Thread: How does this for-while loop works?

  1. #1
    Registered User
    Join Date
    May 2022
    Posts
    5

    How does this for-while loop works?

    Ok, so I got the following code:

    Code:
    int i,j=1;
    
    for(i=1; i<=3; i++){
      while(j <= i){
        printf("A");
        j++;
      }
      printf("B\n");
      j = 1;
    }
    The output for this is

    AB
    AAB
    AAAB

    My initial expectation for output would be:
    AB
    AB
    AB

    But when I remove j = 1 at the bottom of for loop then I get that result. What does j=1 does to this loop so that I get AB AAB AAAB?

  2. #2
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,111
    Quote Originally Posted by Programmin9 View Post
    Ok, so I got the following code:

    Code:
    int i,j=1;
    
    for(i=1; i<=3; i++){
      while(j <= i){
        printf("A");
        j++;
      }
      printf("B\n");
      j = 1;
    }
    The output for this is

    AB
    AAB
    AAAB

    My initial expectation for output would be:
    AB
    AB
    AB

    But when I remove j = 1 at the bottom of for loop then I get that result. What does j=1 does to this loop so that I get AB AAB AAAB?
    It resets j so that the while loop prints out i number of 'A' then 'B' Without the "j = 1;", j is always one less than i and prints only one 'A'.

    Put some extra printf() statements in the code to see the values of i and j as the program executes, or else us a debugger such as gdb to whatch the values as you step through the program.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 03-28-2015, 08:59 PM
  2. Use c++ to do my works on web
    By mozee in forum C++ Programming
    Replies: 7
    Last Post: 09-18-2010, 09:09 PM
  3. How P2p Works...
    By IndioDoido in forum Networking/Device Communication
    Replies: 1
    Last Post: 12-15-2007, 03:18 PM
  4. Works outside of the loop, not within
    By Decrypt in forum C++ Programming
    Replies: 5
    Last Post: 08-05-2006, 12:22 AM
  5. it never works...
    By Ryce in forum Game Programming
    Replies: 5
    Last Post: 08-30-2001, 07:31 PM

Tags for this Thread