codescracker
c

C Program to Print Array Elements present at Odd Position



« C Tutorial C Examples »

In this tutorial, we will learn about how to create a program in C that will read array elements and then will print all the array elements present at odd position (index-wise). The question is, write a program in C to read 10 values in an integer array and print all value stored at odd position. Here is its answer:

#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 odd positions are:\n");
    for(i=0; i<10; i++)
    {
        if(i%2!=0)
            printf("%d ", arr[i]);
    }
    getch();
    return 0;
}

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

c print value at odd position

Supply any 10 numbers or elements for the array and press ENTER key to see the value stored at odd position (odd index position):

print value at odd position

Program Explained

Allow User to Define Array Size

Now let's modify the above program to allow user to decide the length of the array:

#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("\nValues stored at odd 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:

print value stored at odd position c

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

C Online Test


« C Tutorial C Examples »



© Copyright 2021. All Rights Reserved.

CodesCracker