In: Computer Science
Ask the user to input a series of numbers, write a C# program to output the sum, max, and min. Be sure to do error checking if the user input is not a number.
Code:
using System;
class series
{
static void Main()
{
int n,max=0,min=0,sum=0,i,num;/*Declared variables*/
while(true)
{/*infinet while loop*/
try
{
Console.Write("Enter no of numbers you want to enter: ");
n=Convert.ToInt32(Console.ReadLine());
/*here we read the integer from the user
if he entered any charecter this loop iterate again
untill he enter an integer*/
break;
}
catch(Exception e)
{
/*if he enter other than integer we print enter only
integer*/
Console.WriteLine("Enter only integers");
}
}
Console.WriteLine("Enter the numbers: ");
/*Here we ask the user to enter series of numbers*/
for(i=0;i<n;i++)
{/*This loop iterate for 0 to n-1*/
while(true)
{/*infinet while loop*/
try
{
num=Convert.ToInt32(Console.ReadLine());
/*here we read the integer from the user
if he entered any charecter this loop iterate again
untill he enter an integer*/
break;
}
catch(Exception e)
{ /*if he enter other than integer we print enter only
integer*/
Console.WriteLine("Enter only integers");
}
}
if(i==0)
{/*IF the user enter for the first time we make min sum max as the
enterd number*/
min=num;
max=num;
sum=num;
}
else
{
if(num>max)
{
/*If enterd number is greter than the max
then we make the entered number as max*/
max=num;
}
if(num<min)
{
/*If enterd number is less than the min
then we make the entered number as min*/
min=num;
}
sum+=num;
}
}
Console.WriteLine("Sum = "+sum);
Console.WriteLine("min = "+min);
Console.WriteLine("max = "+max);
/*Finally we print min max and sum*/
}
}
Output:
Indentation: