Shabnam Sheikhha Shabnam Sheikhha - 1 month ago 10
C Question

why is the output wrong from what i calculate on paper based on my code?

I've written this code for a class project:

#include<stdio.h>
int main()
{
int n = 0, i = 1, c = 0, d = 0, a = 0, b = 0, j = 1;
scanf("%d", &n);
while (i <= n)
{
b = a;
scanf("%d", &a);
if (a >= b)
{
i++;
}
if (a == b)
{
j++;
}
if (a < b)
{
i++;
break;
}
}
while ((i <= n) && (i != j + 2))
{
b = a;
scanf("\n%d", &a);
if (a < b)
{
i++;
}
if (a > b || a == b)
{
i++;
c = 1;
break;
}
}
if (c == 1)
{
while (i <= n)
{
scanf("\n%d", &a);
i++;
}
printf("No");
}
while (i <= n)
{
b = a;
scanf("\n%d", &a);
if (a <= b)
{
i++;
}
if (a > b);
{
i++;
break;
}
}
while (i <= n)
{
b = a;
scanf("\n%d", &a);
if (a > b)
{
i++;
}
if (a < b || a == b)
{
i++;
d = 1;
break;
}
}
if (d == 1)
{
while (i <= n)
{
scanf("\n%d", &a);
i++;
}
printf("No");
}
if (c != 1 && d != 1)
{
printf("Yes");
}
}


and I expect the output for this income:
6
4 4 3 2 3 2

to be "No". But instead, it's "Yes". I go through all of the steps in my code on paper, and the answer i get on my own is correct. But when i run the program it's not. Can someone please explain why?

Answer

Here you have an error in your code, the semicolon is ending the instruction

while (i <= n)
{
    b = a;
    scanf("\n%d", &a);
    if (a <= b)
    {
        i++;
    }
    if (a > b); // remove this semicolon
    {
        i++;
        break;
    }
}

EDIT: Just for clarity, is ending the "if" instruction, it's like an empty "if" like:

if ( a > b ) { }

so the

i++;
break;

get executed as the next instructions

Comments