In C++, rewrite the program below by using POINTERS : int main () { int a[MAXSIZ
ID: 3891681 • Letter: I
Question
In C++, rewrite the program below by using POINTERS:
int main ()
{
int a[MAXSIZE];
int n;
int getArray(int a[],int max);
void printArray(const int a [],int n);
void sortArray(int a[] , int n);
n = getArray(a,MAXSIZE);
printf("Before: ");
printArray(a,n);
sortArray(a,n);
printf(" After: ");
printArray(a,n);
return 0;
}
int getArray(int a[], int max)
{
int s, count=0, value;
printf("Enter value ");
while((s=scanf("%d",&value)) !=EOF && count < max)
{
if (s==0)
{
printf("Invalid");
while (getchar()!=' ');
}
else
{
a[count++]=value;
}
}
if(s==1)
printf("Too many value");
return count;
}
//print the array
void printArray(const int a[], int n)
{
int i;
for (i=0; i < n ;i++)
printf("%4i", a[i]);
}
void sortArray( int a[], int n)
{
void swap(int a[], int i, int minIn);
int i ,j , min,minIn;
for (i = 0; i<= (n-2); i++)
{
min = a[i];
minIn = i;
for (j = (i+1); j <= (n-1); j++)
{
if (a[j] < min)
{
min = a[j];
minIn = j;
}
}
swap(a,i,minIn);
}
}
void swap(int a[], int i, int minIn)
{
int temp = a[i];
a[i]= a[minIn];
a[minIn]=temp;
}
The program will help:
1. Read in an undetermined number of array elements
2. Print the array elements (call this function both before and after the elements are sorted)
3. Sort the array elements
4. Swap two elements of an array (this function will be called by your sort function
Run your program using the following sets of input:
1. 5 12 -7 3 0
2. 1 2 3 4 5 7 6
Explanation / Answer
Please find the modified code below.
CODE
====================
# include <iostream>
# define MAXSIZE 5
using namespace std;
int getArray(int *a, int max)
{
int s, count=0, value;
printf("Enter value ");
while((s=scanf("%d",&value)) !=EOF && count < max)
{
if (s==0)
{
printf("Invalid");
while (getchar()!=' ');
}
else
{
a[count++]=value;
}
}
if(s==1)
printf("Too many value");
return count;
}
//print the array
void printArray(const int *a, int n)
{
int i;
for (i=0; i < n ;i++)
printf("%d ", a[i]);
}
void swap(int *a, int i, int minIn)
{
int temp = a[i];
a[i]= a[minIn];
a[minIn]=temp;
}
void sortArray( int *a, int n)
{
int i ,j , min,minIn;
for (i = 0; i<= (n-2); i++)
{
min = a[i];
minIn = i;
for (j = (i+1); j <= (n-1); j++)
{
if (a[j] < min)
{
min = a[j];
minIn = j;
}
}
swap(a,i,minIn);
}
}
int main ()
{
int a[MAXSIZE];
int n;
n = getArray(a,MAXSIZE);
printf("Before: ");
printArray(a,n);
sortArray(a,n);
printf(" After: ");
printArray(a,n);
return 0;
}