Collection of Similar Data Type Elements (Array)


Explanation

An array is a collection of elements of the same data type stored in contiguous memory locations. Each element in an array is identified by its index number, which starts from 0. In this program, an integer array named r stores five values. A for loop is then used to display all the elements of the array one by one.

How It Works?

  • Step 1: Declare an integer array r[5] and an integer variable k.
  • Step 2: Store five integer values in the array using indexes 0 to 4.
  • Step 3: Initialize the for loop with k = 0.
  • Step 4: Continue the loop until k <= 4.
  • Step 5: Print the array element using r[k].
  • Step 6: Increase the value of k by 1 after each iteration.
  • Step 7: Repeat the process until all array elements are displayed.

Example Program


#include <stdio.h>
#include <conio.h>

main()
{

    int r[5];
    int k;

    clrscr();

    r[0] = 10;
    r[1] = 9;
    r[2] = 12;
    r[3] = 42;
    r[4] = 19;

    for(k = 0; k <= 4; k++)
    {

        printf("\n %d", r[k]);

    }

    getch();

}

Output

10
9
12
42
19

Practice Exercises

Task 1: Write a C program to store 6 integer values in an array and display all the elements using a for loop.

Goal: Learn how to declare an array, store values using array indexes, and display all array elements using a for loop.

💡 Hint: Declare an array of size 6. Store values in indexes 0 to 5. Use a for loop from 0 to 5 and print each element using r[k].
💡 Show Solution

#include <stdio.h>
#include <conio.h>

main()
{

    int r[6];
    int k;

    clrscr();

    r[0] = 15;
    r[1] = 22;
    r[2] = 8;
    r[3] = 41;
    r[4] = 30;
    r[5] = 17;

    for(k = 0; k <= 5; k++)
    {

        printf("\n %d", r[k]);

    }

    getch();

}

Output
15
22
8
41
30
17
Explanation: The program declares an integer array of size 6 and stores six values using array indexes 0 to 5. A for loop accesses each element one by one using r[k] and displays all the values on the screen.