Reverse an Array

Beginner

Introduction

This lab will guide you through the process of reversing an array in C programming.

Note: You need to create the file ~/project/main.c yourself to practice coding and learn how to compile and run it using gcc.

cd ~/project
## create main.c
touch main.c
## compile main.c
gcc main.c -o main
## run main
./main

Declare Variables and Get User Input

In this step, we declare variables and get input from the user.

#include <stdio.h>

int main() {
    int n;
    printf("Enter the size of the array:");
    scanf("%d", &n);

    int arr[n];
    printf("Enter %d integers:\n", n);

    for(int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
}

Reverse The Array

In this step, we reverse the array by swapping elements of the array. The loop stops once we get to mid of the array. Here's the code block:

for(int i = 0; i < n/2; i++) {
        int temp = arr[i];
        arr[i] = arr[n - i - 1];
        arr[n - i - 1] = temp;
    }

Print The Reversed Array

Now we can print the reversed array. The following code block can be used to print the reversed array:

printf("The reversed array is:\n");
    for(int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }

Full code for reversing an array in C:

#include <stdio.h>

int main() {
    int n;
    printf("Enter the size of the array:");
    scanf("%d", &n);

    int arr[n];
    printf("Enter %d integers:\n", n);

    for(int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    for(int i = 0; i < n/2; i++) {
        int temp = arr[i];
        arr[i] = arr[n - i - 1];
        arr[n - i - 1] = temp;
    }

    printf("The reversed array is:\n");
    for(int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}

Summary

Reversing an array in C programming is an important technique. You can use the code provided in this lab to reverse any array. Remember to declare variables, get user input, reverse the array with swapping elements, and print the reversed array.

Other Tutorials you may like