Program to reverse an array

0 Suresh Chand June 2, 2021

In this example, We will learn a program to reverse an array. For this, we must have knowledge in following topics

Download Application: Learn C Programming with Live Compiler

Algorithm

This is the algorithm of this program

Step 1: Start
Step 2: Initialize variables c, d, n, a and b
Step 3: Take input from user and stored in n
Step 4: Assign c = 0
Step 5: Repeat this step until c < n
        Take input from user and store in c index of a i.e a[c]
        Increase c by 1
Step 6: Assign c = n-1 and d = 0
Step 7: Repeat this step unitl c >= 0
        Copy the value of a[c] to b[d]
        Decrease c by 1 and Increase d by 1
Step 8: Assign c = 0
Step 9: Repeat this step until c < n
        Copy the value of b[c] to a[c]
        Increase c by 1
Step 8: Assign c = 0
Step 10: Repeat this step until c < n
        Print a[c]
        Increase c by 1
Step 11: End

Flowchart

This is the flowchart of this program

Flowchart : Program to reverse an array

CODE: Program to reverse an array

Now, We will see the code to reverse an array.

#include<stdio.h>

int main(){
    
    int c, d, n, a[100], b[100];
    printf("\nEnter number of elements in array :");
    scanf("%d", &n);

    printf("\nEnter %d elements\n", n);
    for(c = 0; c < n; c++)
        scanf("%d", &a[c]);

    /*
        temporarily storing elements into array b 
        starting from end of array a
    */
    for(c = n-1, d = 0; c >= 0; c--, d++)
        b[d] = a[c];

    /*
        copying reversed array into original.
        Here we are modifying original array to reverse it.
    */
    for(c = 0; c < n; c++)
        a[c] = b[c];


    printf("\n Resultant array is: ");
    for(c = 0; c < n; c++)
        printf("%d\t", a[c]);
        

    return 0;
}

The output of above program is

Enter number of elements in array :5

Enter 5 elements
1
2
3
4
5

 Resultant array is: 5  4       3       2       1
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Join Our Newsletter Now

Get the latest tutorials, examples and projects updates.

Ads Block Detector Powered by codehelppro.com

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Disable Ad Block

Want Same System