retagged by
1,284 views

2 Answers

3 votes
3 votes

Mathematically the result of the above program can be written as follows

$$\sum_{i=0}^{98}\sum_{j=1}^{46}\sum_{k=1}^{3}1$$

Explanation:

The inner most loop controlled by the value of $k$ breaks out of loop when its value reaches 4. Thus, the increment in the inner most loop is performed for only $3$ time.

The middle level loop controlled by the value of $j$ will continue until it reaches $49$. Therefore, it can be said that the iteration will run for $48$ times (loop terminated when $j == 49$). However, out of those $48$ iterations, two of them are ineffective because of second if condition which simply continues with the loop for $j == 20$ and $j == 40$. Thus, we are adding the result of innermost iteration for $46$ time

Similar argument can be given for the outer most loop and hence the summation proposed above correctly represents the program.

Solution:

$$\sum_{i=0}^{98}\sum_{j=1}^{46} 3 = \sum_{i=0}^{98}46*3 = 99*46*3 = 13662$$


The given program can be rewritten as follows

The lines from original code are commented and replaced by lines just below them.

#include <stdio.h>

int main(void) {
	int i, j, k;
	int s = 0;
	
	for(i = 0; i <= 100; i++)
	{
		if(i == 25 || i == 30)
			continue;
		
		// for(j = 1; j <= 100; j++)
		for(j = 1; j <= 48 ; j++)
		{
			// if(j == 49)
			// 	break;
			
			if(j == 20 || j == 40)
				continue;
			
			// for(k = 1; k <= 10; k++)
			for(k = 1; k <= 3; k++)
			{
				// if(k == 4)
				// 	break;
					
				s = s+1;
			}
		}
	}
	
	printf("%d", s);
	return 0;
}

HTH

0 votes
0 votes
1> First loop(Outer loop) will iterate completely 99 times.( leaving for i=25 and 30 )

2> Second loop(nested 2nd loop)  will iterate completely 99 *46 times.(leaving for j=20 and 30 & break at j=48)

3> 3rd loop(inner loop) will iterate (99*46*3)=13662 times (break at k=4).

Thus S=13662 since s is increasing by one on each iteration in the 3rd inner loop.

Related questions