C program to input and print n elements in an array

Previous Program Next Program
Write a C program to read elements in an array and print array. How to input and display elements in an array using for loop in C programming. Logic to implement array using loop.

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, Array

Logic 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.
Element of 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.


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 ;)


Previous Program Next Program
Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment