Write a C program to declare, initialize, input elements in array and print array. How to input and display elements in an array using for loop in C programming. C program to input and print array elements using loop.
Example
Input
Input size: 10 Input elements: 1 2 3 4 5 6 7 8 9 10
Output
Output: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Required knowledge
Basic Input Output, For loop, Array
How to input and print array elements?
Array uses an index for accessing an element. Array index starts from 0 to N-1
(where N is the number of elements in array).
To access any an array element we use.
array[0] = 10
array[1] = 20
array[2] = 30
array[9] = 100
Since array index is an integer value. Hence, rather hard-coding constant array index, you can use integer variable to represent index. For example,
int i = 0;
array[i] = 10; // Assigns 10 to first array element
Program to input and print array elements
/**
* C program to read and print elements in an array
*/
#include <stdio.h>
#define MAX_SIZE 1000 // Maximum array size
int main()
{
int arr[MAX_SIZE]; // Declare an array of MAX_SIZE
int i, N;
/* Input array size */
printf("Enter size of array: ");
scanf("%d", &N);
/* Input elements in array */
printf("Enter %d elements in the array : ", N);
for(i=0; i<N; i++)
{
scanf("%d", &arr[i]);
}
/*
* Print all elements of array
*/
printf("\nElements in array are: ");
for(i=0; i<N; i++)
{
printf("%d, ", arr[i]);
}
return 0;
}
Note: Using i < N
is equivalent to i <= N-1
.
Advance your skills by learning this using recursive approach.
Learn more – Program to print array elements using recursion.
The above method uses array notation to print elements. You can also use pointer notation to access an array in C. The statement arr[i]
is equivalent to *(arr + i)
.
Output
Enter size of array: 10 Enter 10 elements in the array : 10 20 30 40 50 60 70 80 90 100 Elements in array are : 10, 20, 30, 40, 50, 60, 70, 80, 90, 100,
Happy coding 😉
Recommended posts
- Array and Matrices programming exercises index.
- C program to print all unique elements of a given array.
- C program to print all negative element of a given array.
- C program to insert an element in an array at any given position.
- C program to delete an element from array at any specified position.
- C program to find maximum and minimum elements in a given array.