Program example to print array in C. Two simple examples will be demonstrated for printing array element in C programs i.e. in forward and reverse direction both using for loop.
- Create an int array.
- Run for loop from index 0 to less than array length. e.g if array length is 5 then loop will run from 0 to 4 index.
- Retrieve array element using expression arr[index], where arr is your array name and index you have declared to retrieve elements.
Program to print array in C
/*
* Example to print array in C
*/
#include<stdio.h>
int main(){
int len = 0;//for length of array
int index =0;//to fetch array elements
int arr[5] = {2,4,6,8,9};
//find length of the array or hard code with 5
len = sizeof(arr)/sizeof(int);
//Run the for loop from index 0 to 4,
//to get all 5 elements
for(index =0; index < len; ++index){
//fetch element using arr[index] statement
printf("%d ",arr[index]);
}
return 0;
}
Output:
2 4 6 8 9
C program to print array in reverse order
Printing array elements in reverse order is also easy.Here are steps.
- Initialize index to length of the array – 1 ( point to last index and move back up to start of the array location). loop we want to run for index 4 to 0, hence, set index to array length-1, if array length is 5.
- Check the condition in for loop for index >= 0, and decrement the index in for loop.
- Retrieve array elements using arr[index] statement.
Source code to print array in c in reverse order
/*
* Example to print array in C
*/
#include<stdio.h>
int main(){
int len = 0;
int index =0;
int arr[5] = {2,4,6,8,9};
len = sizeof(arr)/sizeof(int);
//Run the for loop from last index 4 to 0,
//to get all 5 elements in reverse order
for(index =len-1; index >= 0; --index){
printf("%d ",arr[index]);
}
return 0;
}
Output:
9 8 6 4 2