In: Computer Science
Do not use arrays and code a program that reads a sequence of positive integers from the keyboard and finds the largest and the smallest of them along with their number of occurrences. The user enters zero to terminate the input. If the user enters a negative number, the program displays an error and continues. Sample 1: Enter numbers: 3 2 6 2 2 6 6 6 5 6 0 Largest Occurrences Smallest Occurrences 6 5 2 3. Do not use arrays and use C++
#include <iostream>
using namespace std;
int main()
{
//variable declaration
int num, largest, smallest, largOcc=0, smallOcc=0;
//get user input
cout<<"Enter numbers: "<<endl;
cin>>num;
if(num==0)
{
return 0;
}
else if(num<0)
{
cout<<"Please enter only positive
integer."<<endl;
}
smallest = num;
largest = num;
while(1)
{
cin>>num;
if(num==0)
break;
else if(num<0)
cout<<"Please enter only positive
integer."<<endl;
if(num>largest)
{
largest = num;
largOcc = 0;
}
else if(num==largest)
{
largOcc++;
}
if(num<smallest)
{
smallest = num;
smallOcc = 0;
}
else if(num==smallest)
{
smallOcc++;
}
}
smallOcc++;
largOcc++;
//display result
cout<<"Largest = "<<largest<<endl;
cout<<"Smallest = "<<smallest<<endl;
cout<<"Largest occurrence =
"<<largOcc<<endl;
cout<<"Smallest occurence =
"<<smallOcc<<endl;
return 0;
}
OUTPUT:
Enter numbers:
3
2
6
2
2
6
6
6
5
6
0
Largest = 6
Smallest = 2
Largest occurrence = 5
Smallest occurence = 3