In: Computer Science
Write a program to accept five negative numbers from the user.
(1) Find the average of the five numbers and display the answer to the standard output. Keep the answer two decimal points - 5 points
(2) Output the numbers in ascending order and display the answer to the standard output. - 5 points
1).
Well commented code is given below.
#include<bits/stdc++.h>
using namespace std;
int main()
{
cout<<"Enter the five negative numbers";//Ask user for input.
cout<<endl;
int arr[5];//Array to store user input.
//loop to get input.
for(int i=0;i<5;i++)
cin>>arr[i];
float avg=0;//To store the average.
//Formula to calculate average Sum/5.
avg=(float)(arr[0]+arr[1]+arr[2]+arr[3]+arr[4])/5;
//Output Average up to 2 decimal places.
printf("Average is : %.2f",avg);
}
Here is the output:
2).
Code.
#include<bits/stdc++.h>
using namespace std;
int main()
{
cout<<"Enter the five negative numbers";//Ask user for input.
cout<<endl;
int arr[5];//Array to store user input.
//loop to get input.
for(int i=0;i<5;i++)
cin>>arr[i];
//Using simple bubble sort to sort the numbers.
//Bubble sort- we will compare each number with every other number and move the larger towards the right end.
for(int i=1;i<5;i++)
{
for(int j=0;j<5;j++)
//if first number is greater than second one.
if(arr[j]>arr[i])
{
//if the condition is true swap the numbers.
int temp=arr[j];
arr[j]=arr[i];
arr[i]=temp;
}
}
//Output the numbers in ascending order.
cout<<"The numbers in ascending order :";
cout<<endl;
for(int i=0;i<5;i++)
cout<<arr[i]<<" ";
}
output:
If you like the above information than please do an upvote.