467 views
1 votes
1 votes
#include<stdio.h>

int main(){

    int x,sum;

    sum=0;

    for(x=0;x<=500;x+=10){

        sum=sum+x;

    }

     printf("%d",sum);

   return 0;

}

 

What is output of above C-program?

 

Actually, Answer when compiled on computer is 12750.

But i want explanation about How for loop is running and what is behaviour of sum value ?

1 Answer

3 votes
3 votes
Iteration 1: s$um=0$ and $x=0$ $\Rightarrow$ $sum = 0+0$ and $x$ increase by $10$

Iteration 2; $sum=0+10=10$ and $x$ increase by $10$ so it becomes $x=20$

Iteration 3: $sum=10+20=30$ and $x$ increase by $10$ so it becomes $x=30$
.
.
.
.

Iteration 51: $sum=12250+500=12750$ and $x$ increase by $10$ so it becomes $x=510$, now the condition $x\leq500$ will become false and it will come out of for loop

so we see that $sum$ is nothing but A.P  $0+10+20+30+…….$, with $n=51, a=0, d=10$

using $S_n=\frac{n}{2}(2a+(n-1)d)$ we will get $12750$

Related questions

1 votes
1 votes
1 answer
1
Purple asked Feb 3, 2016
2,215 views
What is the output of the following program ? void main() { int x=40, y=30, z=80; if(x<y<z) printf(“\n Hello world”); else printf(“\nGood by”);} A] Hello worldB]G...
0 votes
0 votes
1 answer
2
2 votes
2 votes
1 answer
4