Example:
Input size: 10
Input elements: 1
2
3
4
5
6
7
8
9
10
Output: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Required knowledge
Basic C programming, For loop, ArrayLogic to input and display array elements
Array uses an index based mechanism for fast and easy accessing of elements. Array index starts from 0 to N - 1 (where N is the total number of elements in the array). Below diagram explains the arrangement of elements in an array.Here, we access the array elements in following manner
array[0] = 10
array[1] = 20
array[2] = 30
...
array[7] = 70
You can replace the index value within the big brackets [ ] with an integer variable. Like the above statements can be replaced by array[i] = some_value; (where i is an integer variable). Let's demonstrate this through a program.
Program to input and display array elements
/** * C program to read and print n elements in an array */ #include <stdio.h> #define MAX_SIZE 1000 //Maximum size of the array int main() { int arr[MAX_SIZE]; //Declares an array of MAX_SIZE int i, N; /* * Reads size and elements in array */ printf("Enter size of array: "); scanf("%d", &N); printf("Enter %d elements in the array : ", N); for(i=0; i<N; i++) { scanf("%d", &arr[i]); } /* * Prints 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 how to print array elements using recursion.
Advance your skills by learning how to print array elements using recursion.
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,
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 ;)
You may also like
- 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.