In: Computer Science
This is a C++ assignment
The necessary implementations:
Requirements to meet:
Write a program that asks the user to enter 5 numbers. The numbers will be stored in an array. The program should then display the numbers back to the user, sorted in ascending order.
Include in your program the following functions:
Main calls each function once, in turn and passes the array and it's size to each function. Creates the array. Does not interact with the user itself.
Note: You must implement the sorting algorithm yourself, either selection sort or bubble sort
CODE:
#include<iostream>
using namespace std;
//function fillArray
void fillArray(int arr[],int size){
//asking the user to enter the elements
for(int i=0;i<size;i++){
cout<<"Enter element "<<(i+1)<<": ";
cin>>arr[i];
}
}
//sortArray method
void sortArray(int arr[], int size){
//using selection sort
for(int i=0;i<size;i++){
//after every ith loop the ith position
//gets its final number
int min = arr[i];
int minIndex = i;
for(int j=i;j<size;j++){
if(arr[j] < min){
min = arr[j];
minIndex = j;
}
}
//swapping
int temp = arr[i];
arr[i] = min;
arr[minIndex] = temp;
}
}
//printArray function
void printArray(int arr[], int size){
//printing the array elements
cout<<"Array elements: "<<endl;
for(int i=0;i<size;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
}
//main method
int main(){
//declaring the array
int *arr = new int[5];
//calling the fillArray function
fillArray(arr,5);
//calling the sortArray function
sortArray(arr,5);
//calling the printArray function
printArray(arr,5);
return 0;
}
______________________________________________
CODE IMAGES:
__________________________________________
OUTPUT
_________________________________________
Feel free to ask any questions in the comments section
Thank You!