Reputation: 423
I am creating a small program which uses a while loop to ask user to enter number(s) bigger than 0. When the program runs only the loop works, but I don't see the biggest number. Here is the code:
#include <stdio.h>
int main(void) {
int num1;
int biggestValue = 0;
printf("Enter a number: ");
scanf("%d", &num1);
while (num1 != 0) {
printf("Enter a number (0 to exit): ");
scanf("%d", &num1);
biggestValue = num1;
if (biggestValue > num1) {
printf("Biggest value is: %d \n", biggestValue);
}
}
}
Upvotes: 3
Views: 12013
Reputation: 153547
Do not set biggestValue
until it is shown to be greater.
Change compare order @Zaman
// biggestValue = num1;
if (num1 > biggestValue) {
biggestValue = num1; // move here
printf("Biggest value is: %d \n", biggestValue);
}
A sample complete solution:
#include <limits.h>
#include <stdio.h>
int main(void) {
int biggestValue = INT_MIN;
const char *prompt = "Enter a number: ";
for (;;) {
fputs(prompt, stdout);
int num1;
if (scanf("%d", &num1) != 1) break;
if (num1 > biggestValue) {
biggestValue = num1;
}
prompt = "Enter a number (or 'q' to exit): ";
}
printf("Biggest value is: %d \n", biggestValue);
return 0;
}
Upvotes: 1
Reputation: 5741
Use this code
#include <stdio.h>
int main(void)
{
int num1;
int biggestValue = 0;
printf("Enter a number: ");
scanf("%d", &num1);
while (num1 != 0)
{
if (biggestValue < num1)
{
biggestValue = num1;
}
printf("Enter a number (0 to exit): ");
scanf("%d", &num1);
}
printf("Biggest value is: %d \n", biggestValue);
}
Explanation:
num1
is greater than biggestValue
or not.num1
is greater than biggestValue
then biggestValue=num1
.biggestValue
remain unchanged.biggestValue
.Upvotes: 1
Reputation: 4454
The printing should be just after the while loop,and don't write biggestValue = num1;
before the comparison.
#include <stdio.h>
int main(void)
{
int num1;
int biggestValue = 0;
while (num1 != 0)
{
printf("Enter a number (0 to exit): ");
scanf("%d", &num1);
if (biggestValue < num1)
{
biggestValue = num1;
}
}
printf("Biggest value is: %d \n", biggestValue);
}
Upvotes: 0
Reputation: 2933
Since you're setting biggestValue = num1;
and then immediately checking if biggestValue > num1
, biggestValue
can never be bigger than num1
. They'll always be equal.
I think what you want is:
if (biggestValue < num1) {
biggestValue = num1;
}
And then outside of the while loop you'd place:
printf("Biggest value is: %d \n", biggestValue);
Upvotes: 0