In: Computer Science
Write a program that asks the user to enter an array of random numbers, then sort the numbers (ascending order), then print the new array, after that asks the user for a new two numbers and add them to the same array and keep the array organization. (c++ ) (using while and do while loops)
#include<iostream>
#include<stdlib.h>
using namespace std;
//method for sort the array using selection sort
void sort(int arr[],int size)
{
int i,j,t;
//loop for selection sort
i=0;
while(i<size)
{
j=i+1;
do //do...while loop for inner
loop
{
if(arr[i]>arr[j])
//condition for swap
{
t=arr[i];
//logic for swap
arr[i]=arr[j];
arr[j]=t;
}
j++;
}while(j<size);
i++;
}
}
//method to print the array
void print(int arr[],int size)
{
int i;
i=0; //initialize i to 0
//loop to print the array elements
while(i<size)
{
cout<<" "<<arr[i];
//print the array elements
i++;
}
}
//driver program
int main()
{
int arr[1000],n,i,a,b;//declare the array
//ask user for number of elements
cout<<endl<<"Enter the number of elements
to input";
cin>>n;
i=0; //initialize i to 0
while(i<n) //loop will continue for n times
{
arr[i]= rand() % 100 +1; //generate a
number between 1 to 100 and assign it to array
i++;
}
//display the array elements before sort
cout<<endl<<"Before sort the array elements are :
\n";
print(arr,n);
sort(arr,n); //call to sort() method.
//display the array elements after sort
cout<<endl<<"After sort the array elements are :
\n";
print(arr,n);
//ask user to input two more elements
cout<<endl<<"Enter two number s to add into the
array";
cin>>a>>b;
//assign the frst number to array
arr[n]=a;
//assign second number to array
arr[n+1]=b;
n=n+2; //update the number of elements
cout<<endl<<"\n*******AFTER ADDING OF TWO
ELEMENTS*****\n";
//display the array elements before sort
cout<<endl<<"Before sort the array elements are :
\n";
print(arr,n);
sort(arr,n);//call to sort() method.
//display the array elements after sort
cout<<endl<<"After sort the array elements are :
\n";
print(arr,n);
}
output