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
Compiler used: CodeBlocks C Compiler
code:
Sample Input output on C compiler
C++ simple examples
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
- Pass array to a function
- Swapping array elements
- for loops
- Working with array indexing
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:
- #include <iostream>
- using namespace std;
- void Reverse_Array(int array[],int size)
- { int temp;
- size--;
- int loop_count=0;
- for(int i=0;size>=i;size--,i++)
- {
- loop_count++;// Counts the iterations
- temp=array[i];
- array[i]=array[size];
- array[size]=temp;
- }
- cout<<"Number of Iterations: "<<loop_count<<endl;
- }
- int main()
- {
- int array[5],i;
- cout<<"\nEnter 5 Integer Values in Array\n"<<endl;
- for(i=0;i<5;i++)
- {
- cout<<"Enter Value For Index Number array [ "<<i<<" ] -> ";
- cin>>array[i];
- }
- // Calling Reverse Array Values Function
- Reverse_Array(array,5);
- cout << "\n\n\t\t\tReversed Array Values" << endl;
- for(i=0;i<=4;i++)
- {
- cout<<"\t\t\tarray ["<<i<<"]"<<"= "<<array[i]<<endl;
- }
- return 0;
- }
Sample Input output on C compiler
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
Reverse an Array in C++
ReplyDeleteGood its helpful
awesome
ReplyDelete