Computer Science Of Engineering

Simple and practical computer science tutorials, programming guides, and engineering concepts for students and beginners.

Breaking

Friday, April 18, 2025

Write a program to reverse an array in C

 



#include <stdio.h>


int main() {

    int arr[100], n, i, temp;


    // Get the size of the array

    printf("Enter the number of elements in the array: ");

    scanf("%d", &n);


    // Get array elements from the user

    printf("Enter %d elements:\n", n);

    for(i = 0; i < n; i++) {

        scanf("%d", &arr[i]);

    }


    // Reverse the array in-place

    for(i = 0; i < n / 2; i++) {

        temp = arr[i];

        arr[i] = arr[n - i - 1];

        arr[n - i - 1] = temp;

    }


    // Print the reversed array

    printf("Reversed array:\n");

    for(i = 0; i < n; i++) {

        printf("%d ", arr[i]);

    }

    printf("\n");


    return 0;

}



Output:


No comments:

Post a Comment