Computer Science, asked by revanthkumar4b6, 1 year ago

Ques. Consider the following code:
for i= m to n increment 2
{ print "Hello!" }
Assuming m < n and (m,n) are either both even or both odd, How many times will Hello be printed?
Op 1: (n - m + 1)/2
Op 2: 1 + (n - m)/2
Op 3: 1 + (n - m)/2 if m is even, (n - m + 1)/2 if m is odd
Op 4: (n - m + 1)/2 if m is even, 1 + (n - m)/2 if m is odd
Op 5: Correct Op : 2

Answers

Answered by QGP
30
Let us consider example cases. That would give us the answer more easily.


m and n are either both even or both odd.

CASE 1: Both even


Let us take m = 2, n = 8
Then our loop would be:

for (i=2; i<=8; i = i+2)
{ print "Hello!" }

The word would be printed for i = 2, 4, 6,8. 
When m=10, the condition i<=8 is broken, and loop does not iterate. 

So, loop iterated four times. 

Which is:

4 = \frac{8-2}{2} + 1 = 1 + \frac{n-m}{2}
Similarly, we can check with other cases. 

Let us take m=4, n=18.

Then loop would iterate for i = 4,6,8,10,12,14,16,18

It again satisfies 1+\frac{n-m}{2}


So, Answer = \textbf{1 + }\frac{\textbf{n-m}}{\textbf{2}}



CASE 2: Both Odd


Let us take:

m=3, n=11

Our loop is:
for(i=3; i<=11 ; i = i+2)
{ print "Hello!" }


The loop will iterate for i = 3,5,7,9,11

When i = 13, the condition i<=11 is unsatisfied, and loop breaks.

The loop iterates 5 times. Which is just:

4 = 1 + \frac{11-3}{2} = 1 + \frac{n-m}{2}

Again, Answer =  \textbf{1 + }\frac{\textbf{n-m}}{\textbf{2}}

____________________________________


Thus, in any case, the Answer is Option 2 or Option 5. Both mention the same thing.

The word will be printed 1+\frac{n-m}{2}  times.

Similar questions