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
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.
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:
- Use 5 separate pages – one page for each student.
- 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.
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.
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
#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
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();
}
}
int[] marks = new int[5];creates an array object with size 5.marks.lengthgives 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
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.
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
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:
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
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.
- 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
- Using index out of range – trying to access
arr[5]when size is 5. Valid indexes are only 0 to 4. - Forgetting that index starts from 0 – many beginners think first element is 1.
- Mixing different data types – arrays should have same type elements.
- Wrong loop condition – using
i <= sizeinstead ofi < size.
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
Post a Comment