Nearby lessons

51 of 124

C - Arrays

Arrays is one of the foundational topics in C programming. This lesson explains What is an Array?, Declaring an Array and Initializing an Array with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

What is an Array?

An array is a group of variables of the same type, stored one after another in memory, under one name. Each element is reached by its index (position), starting from 0.

In simple words: an array is one row of lockers — the array name is the locker row, and the index is the locker number. In C the lockers are numbered from 0, not 1.
Trainer's Note: Memory trick: index = position − 1. The first element is at index 0, so a 5-element array uses indexes 0 to 4. Forgetting this and using marks[5] goes past the last locker — silent garbage.

Without arrays, storing 100 students' marks means 100 separate variables. With an array, it is just marks[100].

Example01
CCode Cell
1int marks[5]; // an array of 5 integers
2 
3marks[0] = 80; // first element
4marks[1] = 90;
5marks[4] = 75; // last element

Declaring an Array

The size tells C how many elements to reserve. Remember: indexes go from 0 to size-1. So marks[5] has indexes marks[0] to marks[4].

Example02
CCode Cell
1dataType arrayName[size];
2 
3int marks[5]; // 5 integers: marks[0]..marks[4]
4float salaries[10]; // 10 floats
5char name[20]; // 20 characters (a string)

Initializing an Array

If you give fewer values than the size, the remaining elements are filled with 0.

Example03
CCode Cell
1int marks[5] = {80, 90, 75, 60, 88}; // give all values at once
2int a[] = {1, 2, 3, 4}; // size is automatic (4)
3int b[5] = {1, 2}; // rest become 0: {1,2,0,0,0}

Program 6: Two-Dimensional Arrays (Read and Print)

A 2D array is like a table of rows and columns. Use nested loops — the outer loop for rows, the inner loop for columns.

In simple words: a 2D array is a table. The first index picks the row, the second picks the column — like a train seat: m[1][2] means row 1, column 2.
Example04
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int m[2][3], i, j;
6 
7 printf("Enter 6 values: \n");
8 for (i = 0; i < 2; i++) {
9 for (j = 0; j < 3; j++) {
10 scanf("%d", &m[i][j]);
11 }
12 }
13 
14 printf("Matrix:\n");
15 for (i = 0; i < 2; i++) {
16 for (j = 0; j < 3; j++) {
17 printf("%d ", m[i][j]);
18 }
19 printf("\n"); // new line after each row
20 }
21}
Output
Enter 6 values: 1 2 3 4 5 6 Matrix: 1 2 3 4 5 6
📝 Key Takeaways
  • Array = same-type values under one name, accessed by index 0 to size-1.
  • Declare: int marks[5]; Initialize: int a[3]={1,2,3};
  • Use loops to read and print arrays.
  • Separate programs: sum/average, max, min, linear search.
  • 2D array = table; process with nested loops (rows + columns).
  • Matrix addition: c[i][j] = a[i][j] + b[i][j].

🧠 Test Your Knowledge

6 Questions
Progress: 0 / 6