A question I solved [hopefully]

Define a function SwapArray( int [ ], int), that would accept a one dimensional
integer array NUMBERS and its size N. The function should rearrange the array in
such a way that the values of alternate locations of the array are exchanged
(Assume the size of the array to be even)
Example :
If the array initially contains
{2, 5, 9, 14, 17, 8, 19, 16},
then after rearrangement the array should contain
{5, 2, 14, 9, 8, 17, 16, 19}


I wrote:

#include<iostream.h>
#include<conio.h>
#include<math.h>

void main()
{ clrscr();
int n,i,temp;

cout<<" Enter Size of array: ";
cin>>n;

int a[40];
cout<<" Enter values for array: ";
for(i=0; i<n;i++)
{ cout<<" Enter value for a["<<i<<"]";
cin>>a[i];
}

for(i=0;i<n;i+=2)
{ temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;

}

cout<<" Modified value for array: ";
for(i=0; i<n;i++)
{ cout<<a[i];
}

getch();


}

Any suggestion to improve it...Keeping in mind that its for TurboC++ 3.0!

Please suggest if you have anything on mind as it would help me n becoming a good developer or programmer...

Thank you.
Get an newer compiler. Yours is really old. You can download http://www.codeblocks.org/ which will come with one.
You did everything in main. You need to make it a function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include<iostream.h> // use <iostream> instead of <iostream.h>
#include<conio.h> 
#include<math.h> // you don't need this
using namespace std; // You need this line to call cout or cin.  or use std:: everywhere

SwapArray(int a[], int n)
{
  for(i=0;i<n;i+=2) //This is your original unmodified code stuck in the function
  { 
    temp=a[i];
    a[i]=a[i+1];
    a[i+1]=temp;
  }
}

int main() //should be type int
{
  clrscr();  //You don't need this.  It's a console app, no one expects to have the screen cleared.
  int n,i,temp;

  cout<<" Enter Size of array: ";
  cin>>n;
 
  int a[40];
  cout<<" Enter values for array: ";
  for(i=0; i<n;i++)
  { //Proper line formatting and indenting is important.  Keep a line between { and cout
    cout<<" Enter value for a["<<i<<"]";
    cin>>a[i];
  }

  SwapArray(a,n); //You're code is now called by this function header

  cout<<" Modified value for array: ";
  for(i=0; i<n;i++)
    cout<<a[i]; // I took out some unnesesary {...} here


  getch(); //Don't mix conio and iostream.  Use cin.get() or something instead.  THen you don't need the <conio.h> header
  return 0; //You need a return code on main()
}
Last edited on
Actually my couse includes turbo 3.0 so I have to use it. Thank you though.
Thank you Its awesome to see you helping a newbee here.
Topic archived. No new replies allowed.