What Is an Array in Programming? Simple Explanation with Easy Examples + C, Java, Python, PHP Programs

What Is an Array? Simple Explanation with Easy Programs for Beginners

What Is an Array? Simple Explanation with Easy Programs

In programming we often need to store many values of the same type. For example, marks of 5 students, prices of 10 products, or names of 3 friends. If we use single variables like mark1, mark2, mark3, our program becomes long, boring, and difficult to manage.

To solve this problem, programming languages give us a special data structure called an array. In this article we will understand arrays in a very simple way using real life examples, diagrams and beginner-friendly programs in C, Java, Python and PHP.

Goal of this article: After reading this page you should be able to explain what an array is in one line and you will be able to write simple programs that create, store and print array values on your own.

1. Real Life Example to Understand Arrays

Imagine you are a teacher and you want to store the marks of 5 students in a notebook. You have two options:

  1. Use 5 separate pages – one page for each student.
  2. Use one table on a single page with 5 boxes in a row.

The second option is easier to manage. You can quickly see all marks and you know that all boxes belong to the same test. An array in programming is just like that row of boxes. Each box is called an element of the array.

Index: 0 1 2 3 4 Marks: [ 76 ] [ 81 ] [ 90 ] [ 67 ] [ 72 ]

In this diagram we have an array called marks that can store the marks for 5 students. Each position has a number called the index. Most programming languages start the index from 0, not from 1. So the first element is at index 0, second at 1, and so on.

2. Formal Definition of an Array

A simple beginner-friendly definition is:

Definition An array is a collection of fixed number of elements of the same data type, stored in continuous memory locations, and accessed using an index.

Let us break this definition into smaller parts:

  • Collection – more than one value grouped together.
  • Fixed number – we decide the size of the array when we create it.
  • Same data type – all elements are integers, or all are floats, or all are strings, etc.
  • Continuous memory – elements are stored one after another in memory.
  • Index – position number used to access each element.

3. How Arrays Look in Memory (Simple Diagram)

Think of computer memory as a long street with many houses. Each house has an address such as 100, 104, 108 and so on. When we create an array of 5 integers, the program allocates 5 houses in a row.

Memory Address: 100 104 108 112 116 Array Element: [10] [20] [30] [40] [50] Index: 0 1 2 3 4

If each integer uses 4 bytes, the addresses go 100, 104, 108, 112, 116 etc. The name of the array (for example arr) usually holds the address of the first element.

4. Basic Array Terms You Must Know

Term Meaning Example
Element Single value stored in the array 10, 20, 30 in array arr
Index Position number of an element First element at index 0
Size / Length Total number of elements 5 elements → size = 5
Data Type Type of all elements int, float, String

5. Syntax of Arrays in Different Languages

Here is a quick comparison of how we declare a simple integer array in four popular languages:

Language Syntax (integer array of 5 elements)
C int arr[5];
Java int[] arr = new int[5];
Python arr = [0, 0, 0, 0, 0]   (list used as array)
PHP $arr = array(0, 0, 0, 0, 0);

6. Program 1 – Create and Print an Integer Array in C

Explanation in Simple Words
We will create an array of 5 integers, take input from the user, and then print all the values. This small program helps you understand how to declare, read and display array elements.
#include <stdio.h>

int main() {
    int marks[5];        // array declaration
    int i;

    printf("Enter marks of 5 students:\n");

    // input values
    for (i = 0; i < 5; i++) {
        printf("Student %d: ", i + 1);
        scanf("%d", &marks[i]);
    }

    printf("\nYou entered:\n");

    // output values
    for (i = 0; i < 5; i++) {
        printf("marks[%d] = %d\n", i, marks[i]);
    }

    return 0;
}
    

Step by Step Diagram of the Loop

i = 0 → marks[0] is filled i = 1 → marks[1] is filled i = 2 → marks[2] is filled i = 3 → marks[3] is filled i = 4 → marks[4] is filled i = 5 → loop stops because condition i < 5 is false

7. Program 2 – Create and Print an Integer Array in Java

Now we will write a similar program using Java.

import java.util.Scanner;

public class ArrayExample {
    public static void main(String[] args) {

        int[] marks = new int[5];   // array declaration and object creation
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter marks of 5 students:");

        // input
        for (int i = 0; i < marks.length; i++) {
            System.out.print("Student " + (i + 1) + ": ");
            marks[i] = sc.nextInt();
        }

        System.out.println("\nYou entered:");

        // output
        for (int i = 0; i < marks.length; i++) {
            System.out.println("marks[" + i + "] = " + marks[i]);
        }

        sc.close();
    }
}
    
Important Points from This Program
  • int[] marks = new int[5]; creates an array object with size 5.
  • marks.length gives the size of the array.
  • Indexes are still 0 to 4, same as C.

8. Program 3 – Create and Print an Array (List) in Python

Python does not have a separate built-in array type for simple programs. We generally use a list which behaves like a flexible array.

# create an empty list
marks = []

print("Enter marks of 5 students:")

for i in range(5):
    value = int(input(f"Student {i + 1}: "))
    marks.append(value)

print("\nYou entered:")

for i in range(len(marks)):
    print(f"marks[{i}] = {marks[i]}")
    

Diagram of Python List Growth

Start: [ ] After 1st: [ 76 ] After 2nd: [ 76, 81 ] After 3rd: [ 76, 81, 90 ] After 4th: [ 76, 81, 90, 67 ] After 5th: [ 76, 81, 90, 67, 72 ]

9. Program 4 – Create and Print an Array in PHP

<?php
$marks = array();   // empty array

echo "Enter marks of 5 students:\n";

// in real PHP web page, you would get values from form.
// here we assume the values are already known:
$marks = array(76, 81, 90, 67, 72);

echo "You entered:\n";

for ($i = 0; $i < count($marks); $i++) {
    echo "marks[$i] = " . $marks[$i] . "\n";
}
?>
    

10. Accessing Elements of an Array

Once an array is created, we use the array name and index in square brackets to access any element.

Example: Access 3rd student mark

If array name is marks, index of 3rd student is 2.

  • C / Java / C++ : marks[2]
  • Python list : marks[2]
  • PHP : $marks[2]

Diagram: Accessing One Element

Index: 0 1 2 3 4 Marks: [ 76 ] [ 81 ] [ 90 ] [ 67 ] [ 72 ] ^ | marks[2] = 90

11. Updating Elements in an Array

We can change the value at any index by assigning a new value to it.

// C example
marks[2] = 95;   // change 3rd student's mark

// Java example
marks[2] = 95;

// Python example
marks[2] = 95

// PHP example
$marks[2] = 95;
    

After this line, the diagram becomes:

Index: 0 1 2 3 4 Marks: [ 76 ] [ 81 ] [ 95 ] [ 67 ] [ 72 ]

12. Simple Array Program – Sum and Average of Marks

Let us take a very common exam-style question: “Write a program to read marks of N students into an array and find their sum and average.”

C Program

#include <stdio.h>

int main() {
    int n, i;
    int marks[100];
    int sum = 0;
    float avg;

    printf("How many students? ");
    scanf("%d", &n);

    printf("Enter marks of %d students:\n", n);

    for (i = 0; i < n; i++) {
        printf("Student %d: ", i + 1);
        scanf("%d", &marks[i]);
        sum = sum + marks[i];
    }

    avg = (float)sum / n;

    printf("\nTotal = %d\n", sum);
    printf("Average = %.2f\n", avg);

    return 0;
}
    

Logic Diagram

sum = 0 i = 0 → read marks[0] → sum = sum + marks[0] i = 1 → read marks[1] → sum = sum + marks[1] ... i = n-1 → read marks[n-1] → sum = sum + marks[n-1] avg = sum / n

13. Why Arrays Are So Important

  • They make programs shorter because we do not need many separate variables.
  • They are easy to use with loops for repeating tasks.
  • They are the foundation for many other data structures like lists, stacks, queues, matrices, etc.
  • They help in writing programs that handle large amounts of data.
Real World Uses of Arrays
  • Storing all pixel values of an image.
  • Storing daily temperatures for one month.
  • Storing stock prices for several days.
  • Storing characters of a word or sentence.

14. Common Beginner Mistakes with Arrays

  1. Using index out of range – trying to access arr[5] when size is 5. Valid indexes are only 0 to 4.
  2. Forgetting that index starts from 0 – many beginners think first element is 1.
  3. Mixing different data types – arrays should have same type elements.
  4. Wrong loop condition – using i <= size instead of i < size.
Correct loop: for (i = 0; i < size; i++) Wrong loop: for (i = 0; i <= size; i++) // last index will be out of range

15. Practice Questions Based on Arrays

Here are some simple tasks you can try after understanding the above code.

  • Read N numbers into an array and print them in reverse order.
  • Read N numbers and find the largest and smallest using an array.
  • Count how many numbers are even and how many are odd in the array.
  • Read marks of 5 students and display the roll number of the student with highest mark.
  • Read 10 integers and search whether a given number is present in the array (linear search).

16. Summary in Very Simple Words

Let us quickly repeat the main points so that they stay in your mind:

  • An array is a collection of many values of the same type stored together.
  • Each value in an array is called an element, and its position is called an index.
  • The first index is usually 0.
  • Arrays are stored in continuous memory locations.
  • We can easily access elements using arrayName[index].
  • Arrays work very well together with loops.
  • Understanding arrays is the first big step towards learning data structures.

Now you know what an array is and how to write basic programs to create and use arrays in different languages. When you become comfortable with these simple examples, you will find it much easier to learn advanced topics like multi-dimensional arrays, strings, matrices, sorting and searching algorithms.

Next Step: Try to write your own small program that uses an array without looking at the code above. Even if you make mistakes, you will learn very fast.

Comments

Popular posts from this blog

For Loop vs While Loop – Easy Explanation with Real-Life Examples and Beginner Programs in C, Java, Python & PHP

How to Learn HTML in One Day – Complete Beginner Coding Tutorial