problem...

Discussion in 'C' started by abhijeetptl5, Oct 3, 2012.

  1. abhijeetptl5

    abhijeetptl5 New Member

    Joined:
    Oct 3, 2012
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    int i ;
    for ( i = 4 ; i <= 5 ; i = printf ( "\n%d", i ) ) ;
    i++ ;

    why this code showing output 2 2 2 2 2 2 2 2....infinitely???
     
  2. NewsBot

    NewsBot New Member

    Joined:
    Dec 2, 2008
    Messages:
    1,267
    Likes Received:
    3
    Trophy Points:
    0
    because you have semi colon at the end of your for line.
     
  3. abhijeetptl5

    abhijeetptl5 New Member

    Joined:
    Oct 3, 2012
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    if u run the only for statement ang ignore i++,then also it will give same output......i++ is just for confusion over there....my question is why it is showing 2 2 2 2 2 2....why not any other value????
    as it is initialized to 4 it should show 4...im guesing but why 2????
     
  4. hobbyist

    hobbyist New Member

    Joined:
    Jan 7, 2012
    Messages:
    141
    Likes Received:
    0
    Trophy Points:
    0
    you're assigning i the value of the printf statement, which is 2; 1 for printing the \n plus 1 for printing the %d as the value of i. if you remove the semi after the for loop, it would probably print the value of i after one iteration, but it's a guess.

    it's infinite because i is less than 5 on each test condition since its value is always re-assigned to that of the printf. to fix it, remove the assignment to printf .
     
  5. abhijeetptl5

    abhijeetptl5 New Member

    Joined:
    Oct 3, 2012
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    ohk....thanx buddy...
     
  6. sumedh yadav

    sumedh yadav New Member

    Joined:
    Aug 18, 2012
    Messages:
    17
    Likes Received:
    0
    Trophy Points:
    0
    if I remove the semicolon after the for loop it prints the value '3' infinitely ,it means that it prints the value of i after one iteration.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice