983 views
1 1 vote
#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 ?

2 Answers

3 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$
0 0 votes
Total iterations: ${500 \over 10} + 1 = 51$

Using ap sum formula: $S = {n \over 2}.(2.a + (n - 1).d)$

Here, $a = 0, d = 10, n = 51$

 

answer = ${51 \over 2}.(2.0 + (51 - 1).10) = 12750$
Position:
Show:

Related questions

1 1 vote
1 answers 1 answer
1.4k
1.4k views
abhinowKatore asked Jan 18, 2023
1,429 views
What will be the output of the following program ?answer is 8 but I am getting 5, please explain where I am wrong
2 2 votes
1 1 answer
2.6k
2.6k views
Nishi Agarwal asked Mar 10, 2019
2,559 views
int main() { int m=44; int *p=&m; int &r=m; int n=(*p)++; int *q=p-1; r= *(p)+1; ++*q; printf("m=%d n=%d r=%d",m,n,r); return 0; } Options:$m=44,\ n=46,\ r=45$$m=45,\ n=4...
0 0 votes
0 0 answers
1.4k
1.4k views
Na462 asked Dec 8, 2018
1,352 views