Home > Net >  Output-values from Loops
Output-values from Loops

Time:01-28

I am trying to what the loops are returning when n = 5, without using any IDE.

int loop1(int n) {
    int x = 0;
    for(int i = 0; i < n; i  ) {
        for(int j = 0; j < n; j  ) x  ;
    }
    return x;
}
int loop2(int n) {
    int x = 0;
    for(int i = 0; i < n; i  ) x  ;
    for(int j = 0; j < n; j  ) x  ;
    return x;
}
int loop3(int n) {
    int x = 0;
    for(int i = 0; i < n; i  ) {
        if (i == n-1) for(int j = 0; j < n; j  ) x  ;
    }
    return x;
}
int loop4(int n) {
    int x = 0;
    for(int i = 0; i < n; i  ) {
        for(int j = i; j < n; j  ) x  ;
    }
    return x;
}

Loop1: 5*5 = 25. My Guess: Both goes up to 5, and in same bracket. IDE Result: 25

Loop2: 5 5 = 10. My Guess: Each for-loop returns 5.. Question: but why do we not count x (2). Should it not be (5 1) (5 1)=12? IDE Result: 10

Loop3: 5 = 5. Reason: Goes up to 5, and is not continuing after the if-statement due to false. IDE Result: 5

Loop4: 5*5 = 25. My Guess: Both goes up to 5, and in same bracket. IDE Result: 15

How should I count on these loops? I've been looking at it for a while, but I'm just having difficult figuring out what's being returned.

Can someone at least explain how loop4 is returning 15 when n = 5 (if you have time please all of them).

CodePudding user response:

Assuming n = 5:

Loop 1: 5 * 5 iterations of incrementing x -> x = 25

Loop 2: 5 5 iterations of incrementing x -> x = 10

Loop 3: if i == 4, then there is another for-loop incrementing x 5 times, so x = 5

Loop 4: 5 4 3 2 1 incrementations of x, since the second for-loop starts at i, which is determined by the outer loop.

  • Related