Determine the code below, tell me exactly how many times is
the operation sum++ performed ?
for ( i = 0; i < 100; i++ )
for ( j = 100; j > 100 - i; j--)
sum++;
Answers were Sorted based on User's Feedback
Answer / abdur rab
for ( i = 0; i < 100; i++ )
for ( j = 100; j > 100 - i; j--)
sum++;
first iteration i = 0
j = 100
j loop is executed untill ( 100 - i ) (ie 100 - 0 = 100 )
so output is 0 ( sum is incremented 0 times )
second iteration i = 1
j = 100
j loop is executed untill ( 100 - i ) (ie 100 - 1 = 99 )
so output is 1 ( sum is incremented 1 times )
third iteration i = 2
j = 100
j loop is executed untill ( 100 - i ) (ie 100 - 2 = 98 )
so output is 1 ( sum is incremented 2 times )
0 + 1 + 2 + 3.......+ 99 = ( n (n+1) ) / 2
( 99 (99+1) ) / 2 = 4950
| Is This Answer Correct ? | 15 Yes | 1 No |
Answer / anil
0 times bcoz everytime it enters second loop condition is
not satisfied ,thus comes out of loop.
| Is This Answer Correct ? | 14 Yes | 3 No |
Answer / daniel
(99 * 100)/2 = 4950
The sum++ is performed 4950 times.
| Is This Answer Correct ? | 7 Yes | 7 No |
Answer / santosh
when i=0
j=100 and 100>100-1(false) come out of the loop and the sum
is executed 0 times
| Is This Answer Correct ? | 2 Yes | 2 No |
Answer / lnk
Its quite simple to analyse ...
LOOP i=0: i=0
then enters loop j=o: but it false that always J>100-i;
i.e.., i=0;j=100; 100- i-> 100
so always 100 is not greater than 100
than it comes out no sum++;
Loop i=1; ; j =100 only now 100 - i =99 so j>100 -i
(100>99)
then sum++ is executed ;
i= 1 j=100 j > 100 - i j=99 ;sum ++
i=2 j =99 j> 100 - i j =98 ; sum ++
i=50 j=51 j>100-50 true ( 51>50 ) ; sum++ j=50
i=51 j= 50 j>100-51 true(50>49 ) so no sum++
i = 99 j=2 j>100-i true (2>1) sum ++
so sum++ would be executed 99 times
| Is This Answer Correct ? | 1 Yes | 2 No |
write an algorithm to display a square matrix.
write a program for 7*8 = 56 ? without using * multiply operator ? output = 56
program to find which character is occured more times in a string and how many times it has occured? for example in the sentence "i love india" the output should be i & 3.
What is the difference between local variable and global variable in c?
Why is c so popular?
fun(int x) { if(x > 0) fun(x/2); printf("%d", x); } above function is called as: fun(10); what will it print? }
program for following output using for loop? 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
Toggle nth bit in a given integer - num
Write a program to produce the following output in c language? 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1
If 4 digits number is input through the keyboard, Write a program to calculate sum of its 1st & 4th digit.
How do we open a binary file in Read/Write mode in C?
What are the phases in s/w developed life cycle? wat is the diff b/w stack & queue...where do we use stack