codescracker


c

C Program to Print Array Elements present at Even Position



« C Tutorial C Examples »

In this tutorial, we will learn about how to create a program in C that will ask from user to enter some array elements to print all the array elements present at even index number or even positions. Here is the program.

// Write a program in C to read 10 values in an integer
// array and print all value stored at even position
// -----------codescracker.com-----------

#include<stdio.h>
#include<conio.h>
int main()
{
    int arr[10], i;
    printf("Enter any 10 array elements: ");
    for(i=0; i<10; i++)
        scanf("%d", &arr[i]);
    printf("\nValues stored at even position are:\n");
    for(i=0; i<10; i++)
    {
        if(i%2==0)
            printf("%d ", arr[i]);
    }
    getch();
    return 0;
}

As the program was written under Code::Blocks IDE, therefore after successful build and run, here is the first snapshot of the sample run:

c print value stored at even position

As we all knows that the indexing in array starts form 0, therefore here is the second snapshot of the sample run. User has to provide any 10 numbers as 10 array elements for the given array and press ENTER key to see the following output:

print value stored at even position c

Here are the list of some main steps used in above program:

Here is the modified version of the above program. In this program, we have allowed the user to enter the size of the array at run-time:

// Write a program in C to read some values
// (according to user) in an integer array
// and print all the values stored at even
// position (even index number)
// --------codescracker.com---------

#include<stdio.h>
#include<conio.h>
int main()
{
    int arr[100], i, limit;
    printf("How many elements you want to store inside the array: ");
    scanf("%d", &limit);
    printf("Enter any %d array elements: ", limit);
    for(i=0; i<limit; i++)
        scanf("%d", &arr[i]);
    printf("\n\nValues stored at even position (with array and its index) are:\n");
    for(i=0; i<limit; i++)
    {
        if(i%2==0)
            printf("arr[%d] = %d\n", i, arr[i]);
    }
    getch();
    return 0;
}

Here is the final snapshot of the sample run of above program:

print value at even position c

Here are some of the main steps used in above program:


« C Tutorial C Examples »






Tools
Calculator

Quick Links
Signup - Login - Give Online Test