I have this problem where the user must input a list of integers, and find which is the largest amongst the list of integers and count how many times that largest number was inputted.
This is my source code:
int main()
{
int i, numberOfIntegers, listOfIntegers, largest = 0, occurrence = 0;
p("\n How many integers do you want to enter? ");
s("%i", &numberOfIntegers);
p("\n Input %i number of integers: ", numberOfIntegers);
for (i = 1; numberOfIntegers == listOfIntegers; i )
{
s("%i", &listOfIntegers);
if (listOfIntegers > largest)
{
largest = listOfIntegers;
}
if (listOfIntegers == largest)
{
occurrence ;
}
}
p("\n \n The largest value is %i and the number of occurrence is %i", largest, occurrence);
return 0;
}
And my problem is my program won't let the user input numbers. And if the user can't input any numbers, the program can't read the largest and the number of occurrences of the largest number.
My program's output looks like this:
How many integers do you want to enter? 13
Input 13 number of integers:
The largest value is 0 and the number of occurrence is 0
The correct output should be:
How many integers do you want to enter? 13
Input 13 number of integers: 5, 2, 15, 3, 7, 15, 8, 9, 5, 2, 15, 3, 7
The largest value is 15 and it was entered 3 times.
Is the problem in the loop?
I have problems when it comes to looping, so it would be very helpful if someone could point out where did my program go wrong.
CodePudding user response:
Some issues:
guess p/s is printf/scanf ?
for loop condition, "numberOfIntegers == listOfIntegers" Infact this should be i < numberOfIntegers.
Even above is corrected program will not work . For e.g take the input 1,3 ,5, 7, your answer will compute the correct max, but number of instances of max will be incorrect. (you need to reset occurence, when new max is found)
if (listOfIntegers > largest)
{
largest = listOfIntegers; occurence=1 ;
}
else if (listOfIntegers == largest)
{
occurrence ;
}