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). Here is the program.

// Write a program in C to read 10 values in an integer
// array and print all value stored at odd 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 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). This is the second snapshot of the sample run:

print value at odd position

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

Now let's modify the above program to allow user to decide the length of the array. Here is the modified version of the above program:

// Write a program in C to read some values (according to user)
// in an integer array and print all the values stored at odd
// position
// -----------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("\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 Tutorial C Examples »






Tools
Calculator

Quick Links
Signup - Login - Give Online Test