Adsense 728 * 15

Search

Custom Search

Program to Reverse an Array in C, C++ - Iterative Approach

Write a C, C++ program to reverse an array. Given an input array, we have to write a C, C++ code to reverse an array.

Program to reverse an array using recursion

How to Reverse an Array


1. Take two indexes start and end.

     Initialize start = 0 and end = n - 1; where n is the length of an array

2. Run a loop until start < end. And Swap the values.

C Program to Reverse an Array


#include <stdio.h>

int main() {
 
   int size, i, temp, arr[100], start, end;
 
   printf (" Enter the size of an array (Max 100) \n ");
   scanf (" %d ", &size);
 
   printf (" Enter values in an array \n");
 
   for (i = 0; i < size; i++) {
  
      scanf (" %d ", &arr[i] );
  
   }
 
   start = 0;
   end   = size - 1;
 
   while ( start < end) {
  
     temp       = arr[start];
     arr[start] = arr[end];
     arr[end]   = temp;
  
     start++;
     end--;
   }
 
    printf (" After reversing an array \n ");
 
   for (i = 0; i < size; i++) {
  
      printf (" %d ", arr[i] );
  
   }
 
   return 0;
}


Output of a Program


Enter the size of an array (Max 100)
5

Enter values in an array
2
4
1
6
7

After reversing an array

7     6     1     4     2


Swap two numbers using third variable

Reverse an array using recursion

C++ Program to Reverse an Array


#include <iostream>
using namespace std;

int main() {
 
   int size, i, temp, arr[100], start, end;
 
   cout << " Enter the size of an array (Max 100) \n ";
   cin  >> size;
 
   cout << " Enter values in an array \n";
 
   for (i = 0; i < size; i++) {
  
     cin >> arr[i];
  
  }
 
  start = 0;
  end   = size - 1;
 
  while ( start < end) {
  
    temp       = arr[start];
    arr[start] = arr[end];
    arr[end]   = temp;
  
    start++;
    end--;
  }
 
  cout << " After reversing an array \n ";
 
  for (i = 0; i < size; i++) {
  
     cout << arr[i] << "   ";
  
  }
 
  return 0;
}


No comments:

Post a Comment