-->





Translate

Cpp Tutorial to reverse an array code

2 comments
Write a program which takes some elements as input in integer array then pass this array to a function which reverse its elements using for loop and swapping. 
 Display the reversed array with index number. Loop should execute less than array size. Use any c compiler (codeBlocks recommended).

This tutorial contains the following concepts

Program explanation
  • Program declare an integer array of size five, initialize it using for loop
  • Pass size and array name to function 
  • Function uses for loop and swap array elements with in it
  • A for loop is used to display the final result

Compiler used: CodeBlocks C Compiler
 code:
  1. #include <iostream>
  2. using namespace std;
  3. void Reverse_Array(int array[],int size)
  4. {   int temp;
  5.     size--;
  6.     int loop_count=0;
  7.     for(int i=0;size>=i;size--,i++)
  8.     {
  9.         loop_count++;// Counts the iterations
  10.         temp=array[i];
  11.         array[i]=array[size];
  12.         array[size]=temp;
  13.     }
  14.     cout<<"Number of Iterations: "<<loop_count<<endl;
  15. }
  16. int main()
  17. {
  18.     int array[5],i;
  19.     cout<<"\nEnter 5 Integer Values in Array\n"<<endl;
  20.     for(i=0;i<5;i++)
  21.     {
  22.     cout<<"Enter Value For Index Number array [ "<<i<<" ] -> ";
  23.     cin>>array[i];
  24.     }
  25.     // Calling Reverse Array Values Function
  26.     Reverse_Array(array,5);
  27.     cout << "\n\n\t\t\tReversed Array Values" << endl;
  28.     for(i=0;i<=4;i++)
  29.         {
  30.          cout<<"\t\t\tarray ["<<i<<"]"<<"= "<<array[i]<<endl;
  31.         }
  32.     return 0;
  33. }


Sample Input  output on C compiler
cpp tutorial to reverse an integer array using function and for loop



This tutorial is helpful to understand the array indexing and how to swap the index values. Its is recommended for beginners to edit and do experiment with code. Best of luck for learning cpp programming language.
 Find More Basic Examples here
C++ simple examples

2 comments: