-3

I want the dry run of the code for the first 3 iterations to understand. THe output of the code is : abcdbcdbcdbcdbc........(infinte times)

I know how for loop works and put char also.I did not dry run as i was not understand will the third argument in the for loop will increment or not.

#include <stdio.h>
int main()
{
    for (putchar('a');putchar('b');putchar('d'))
    putchar('c');

    return 0;
}
Saumyojit Das
  • 101
  • 1
  • 7
  • `putchar('b')` - this part of the `for` loop should have a condition which should be false (if you want the loop to break). – babon Jun 26 '19 at 09:50
  • 2
    1) have you checked how a `for` loop works? 2) have you checked what `putchar`does? If not, do it. If so, what didn't you understand? – Support Ukraine Jun 26 '19 at 09:58
  • What is your effort so far? Have you tried a dry run yet? What was your result, what is your expected output and how is this different from what you observed? – Gerhardh Jun 26 '19 at 10:22
  • You might want to read [these class notes](https://www.eskimo.com/~scs/cclass/notes/sx3e.html). – Steve Summit Jun 26 '19 at 10:34
  • @4386427 PREVIOUSLY I was not unable to understand how this code was working but now i understood . – Saumyojit Das Jul 24 '19 at 10:01

2 Answers2

2

enter image description here

For your example:

Initial statement : putchar('a')

Condition expression: putchar('b')

Repeat step: putchar('d')

Loop statement : putchar('c')

Now map you code with flow chart above.

Since putchar returns the character it has printed which is b also satisfies the true condition, thus your for loops run infinite time.


Attribution : http://www.equestionanswers.com/c/for-while-do-while-loop-syntax.php

Community
  • 1
  • 1
kiran Biradar
  • 12,700
  • 3
  • 19
  • 44
0

putchar always returns the char that you put. So for instance, putchar('a') returns 'a'. With that in mind, let's have a look at how the for loop works:

for ( init_clause ; cond_expression ; iteration_expression ) loop_statement

The init_clause is putchar('a'). This prints a once, because the init_clause is evaluated once at the beginning of the for loop.

The cond_expression is putchar('b'). This is checked every run through the loop, which is why it always prints b. And as it returns 'b' every time, the loop never stops. The loop would only stop if the cond_expression returned 0 or the loop is exited otherwise, for instance through break.

The iteration_expression is putchar('d'), hence d is printed every time. The loop_statement is putchar('c'), printing c.

The result is printing a once, followed by an infinite amount of bcd. The reason why you get them in this order is because in every run throught the loop, it first checks the cond_expression, executes the loop_statement and then the iteration_expression.

Blaze
  • 16,736
  • 2
  • 25
  • 44