Understanding Array Initialization and Looping in C with an Example
When learning C programming, arrays and loops are two of the most fundamental topics. Arrays allow you to store multiple values of the same type, and loops help you process these values efficiently. In this post, we’ll explore both concepts with a simple yet effective example program.
What Does the Program Do?
This C program will:
-
Creates an integer array called
fav_numwith 10 elements. -
Initializes the array with values that start at 5 and increase by 3 for each element.
-
Prints the elements of the array in reverse order along with their position numbers.
It’s a great example to understand:
-
Array indexing
-
forloops (forward and backward) -
Basic arithmetic operations
-
The use of
printf()for formatted output
Program
#include <stdio.h>
int main() {
int fav_num[10]; // Array to hold 10 favorite numbers
int first_fav_number = 5; // Starting value
// Forward loop to fill the array
for (int element_index = 0; element_index < 10; element_index++) {
fav_num[element_index] = first_fav_number;
first_fav_number = first_fav_number + 3; // Increase by 3 for next element
}
// Reverse loop to print array values with their index
for (int element_index = 10; element_index > 0; element_index--) {
printf("\n%d\t%d", element_index + 1, fav_num[element_index - 1]);
}
return 0;
}
Explanation
1. Declaring and Initializing Variables
int fav_num[10];
int first_fav_number = 5;
Here, we declare an integer array of size 10 and a variable to store the first number.
2. Filling the Array Using a Loop
for (int element_index = 0; element_index < 10; element_index++) {
fav_num[element_index] = first_fav_number;
first_fav_number = first_fav_number + 3;
}
This loop runs from 0 to 9, filling each index of the array with a value that starts from 5 and increases by 3 every time.
Resulting array after this loop:
5, 8, 11, 14, 17, 20, 23, 26, 29, 32
3. Printing Array Elements in Reverse
for (int element_index = 10; element_index > 0; element_index--) {
printf("\n%d\t%d", element_index + 1, fav_num[element_index - 1]);
}
This loop prints the array in reverse order.
The element_index + 1 part simply adjusts the numbering in the output.
Output
11 32
10 29
9 26
8 23
7 20
6 17
5 14
4 11
3 8
2 5
Points
-
Arrays store multiple values of the same data type.
-
forloops are ideal for iterating through arrays. -
You can easily manipulate the direction of looping (forward or reverse).
-
Simple arithmetic inside loops can generate dynamic sequences of numbers.
No comments:
Post a Comment