Why do I have to use this while loop here.The code runs perfectly fine without the while loop too.But this gives a error on URI online judge.
#include<stdio.h>
int main()
{
int x,y;
while(1)
{
scanf("%d %d",&x,&y);
if(x==y)
break;
else
{
if(x<y)
{
printf("Increasing\n");
}
else
{
printf("Decreasing\n");
}
}
}
return 0;
}
CodePudding user response:
If there is no while() the code block will execute only a single time. If it is there, then it will execute infinite times until the user inputs the same value for both x and y
CodePudding user response:
The online judge feeds more than one testcase into the program and ends (or expects to end) it with two identical values - and not before.
That is why the code without the loop might seem to work for you (assuming you always try only one pair of values for your tests which seem to show that) but fails the online judge.
CodePudding user response:
I think you just didn't understand what this code is supposed to do. The code receives in a loop in each iteration 2 integers, and prints whether it is an ascending or descending order between them. The loop will stop running when 2 identical numbers are received. This mode of operation cannot be achieved without a loop. If you want to do IF_ELSE you will get another action, only one iteration.
CodePudding user response:
it would be far more readable (and clear/clean) and you will probably understand it better, when written as:
#include <stdio.h>
int main()
{
int x, y;
do {
/* repeat the loop while the input
* numbers are different */
scanf("%d %d", &x, &y);
if(x < y) {
printf("Increasing\n");
} else if (x > y) {
printf("Decreasing\n");
}
} while (x != y);
return 0;
}
without the loop, the program only evaluates and tests one pair of numbers, the loop serves to repeat it as much as you want, until you enter the same number twice.
You probably have not been told, but scanf()
can fail interpreting a number if you actually don't give your program two numbers. You should check that scanf()
actually returns 2 (the actual number of format specifiers satisfied on input, as in case it is not 2, some of the variables ---or both---) will not be initialized at all. This is an error that can lead you to wrong behaviour in case you input alphabetic or punctuation characters.
Something like the following:
int res = scanf("%d %d", &x, &y);
if (res != 2) {
fprintf(stderr,
"one (or both) numbers failed to read\n");
exit(1); /* program failed with exit code 1 */
}
also, the space between both %d
specifiers in the scanf()
call is better if you omit it.