Maddy Maddy - 1 month ago 16
C Question

I can't predict the output of this program

I have to find value of

x
:

#include<stdio.h>
int main()
{
int x=0,i;
for(i=0;i<10;i++)
{
if(i%4==2)
x+=20;
if(i%2==0)
x+=50;
}
return 0;
}


I have find value of
x
. Could someone briefly elaborate on what is going in this program. As far as I'm concerned in the second
if
-statement
x
will be 0 or 50.

Answer

Code with comments to be easy to understand:

#include <stdio.h>

int main()
{
    int x=0,i;
    for(i=0;i<10;i++) // i = 0 to 9
    {
        if(i%4==2) // rest of i/4 is 2 (2 and 6)
        {
            x+=20;
        }
        if(i%2==0) // rest of i/2 is 0 (0, 2, 4, 6 and 8)
        {
            x+=50;
        }
    printf("Result: %d\n", x); // Prints the result (290)
    return 0;
}
Comments