20 March, 2012

C++ Program For Swapping Of Two Arrays.

This Post Contains A C++ Program For Swapping Of Two Arrays With Correct Source Code & Output. This Program Is Written, Compiled & Executed At TurboC3.0 Compiler & Will Help You To Understand The Concept Of 'Arrays' & 'For-loop' From C++ Language. It Is A Well-Structured Program With Proper Comments Which Provides Step-By-Step Description Of Various Features Of The Language In A Simple & Easy-To-Understand Way.


When It Comes To Arrays, Most Of Us Get Confused & Hence Some Of Us Find Or Thinks That This Particular Concept Is Complicated As Well As Tricky. But The Following Code Will Make It Really Simple For You To Understand.

# Note : You Can Simply Copy-Paste The Following Program Or Code Into Compiler For Direct Result.

  
C++ Program For Swapping Of Two Arrays.

/* Declaration Of Header Files */
# include <iostream.h>
# include <conio.h>

/* Start Of Main Program */
void main()
{
   /* Declaration Of Variables */
   int a[10], b[10], f, p;
   clrscr();
 
   /* Asking For The Input From User */
   cout << " Enter Dimension : ";
   cin >> f;
   cout << " Enter " << f << " Values For Array A: ";
   for ( p = 0; p < f; p++ )
   {
     cin >> a[p];
   }

   /* Asking For The Input From User */
   cout << " Enter " << f << " Values For Array B: ";
   for ( p = 0; p < f; p++ )
   {
     cin >> b[p];
   }
 
   /* Printing The Values Of Array A */
   cout << " Values For Array A: ";
   for ( p = 0; p < f; p++ )
   {
     cout << a[p] << " ";
   }

   /* Printing The Values Of Array B */
   cout << " Values For Array B: ";
   for ( p = 0; p < f; p++ )
   {
     cout << b[p] << " ";
   }
 
   /* Source Code For Swapping Of Two Arrays */
   for ( p = 0; p < f; p++ )
   {
     a[p] = a[p] + b[p];
     b[p] = a[p] - b[p];
     a[p] = a[p] - b[p];
   }

   /* Printing The Output On The Screen/Console */
   cout << " \n After Swapping : \n ";
   cout << " Values For Array A: ";
   for ( p = 0; p < f; p++ )
   {
     cout << a[p] << " ";
   }
   cout << " Values For Array B: ";
   for ( p = 0; p < f; p++ )
   {
     cout << b[p] << " ";
   }
  
   getch();
}
/* End Of Main Program */

Output  :

Enter Dimension  :  3

Enter 3 Values For Array A  :  1  2  3

Enter Dimension  :  3

Enter 3 Values For Array B  :  4  5  6

Values Of Array A  :  1  2  3

Values Of Array B  :  4  5  6

After Swapping  :

Values Of Array A  :   4  5  6

Values Of Array B  :   1  2  3



  




No comments:

Post a Comment

Subscribe To:

Most Commonly Asked Programs In 'C' & 'C++' Language.