In: Computer Science
Statistics are often calculated with varying amounts of input data. Write a program that takes any number of non-negative integers as input, and outputs the average and max. A negative integer ends the input and is not included in the statistics.
Please refer to the comments of the program for more clarity.
#include<bits/stdc++.h>
using namespace std;
int main() // Starting of the main method
{
int arr[100000]; // Declaring an array to store the incoming non-negative values
//Here I have taken the maximum size of the array for safety
// Here length represent the current length/size of the array
int input, length = 0; // Initializing the length of the array as 0
// Initialized an infinite loop. It will run till it gets a negative value
while(1)
{
cin >> input; // Taking number as input
if(input<0)
{
// When number is negative, calculating the average, sum and breaking/terminating the program
double average;
int sum=0;
// Initialized the max value with the first element of the array
int max_value = arr[0];
// Traversing the array
for(int i=0; i<length; i++)
{
sum = sum + arr[i];
// Finding the maximum value from the array
if(arr[i] > max_value)
{
max_value = arr[i];
}
}
// Finding the average
average = (double)sum / length;
// Printing the average and the max
cout << "\nAverage: " << average << endl;
cout << "Max: " << max_value << endl;
break;
}
else
{
// When number is non negative, storing the input to the array and increasing the size
arr[length] = input;
length++;
}
}
return 0;
}
Sample Input-Output/Code-run:
Please let me know in the comments in case of any confusion. Also, please upvote if you like.