Monday, 7 December 2009

for loop in C

Following code has a bug. Can you find that out? Hint: Well, this code is intended to print "hi " **20** times, does it?
   int i, n=20;
   for (i=0; i < n; i--) {        printf("hi ");    }


If you have found the bug, can you now make it print "hi " 20 times by replacing one character.

Well, the answer is too simple (once known :D). Just a hint: Make sure you understand how for loop works, specially at the beginning of the loop.

(Spoiler alert: Solution in comment)

1 comment:

  1. solution:
    1) replace i +)
    2) replace i-- with n-- (i -> n)

    ReplyDelete