For N nested loops in C

4

Good morning,

I'm starting very little in C, trying to learn well from the base. I've been thinking about a simple script for too long, since I do not quite understand why its output, which is the following:

*
**
***
****
*****

The script is this:

int main() {
    int i, j;
    for (i=0; i<5; i++) {
        for(j=0; j<=i; j++){
            printf("*");
        }
        printf("\n");
    }
}

I can not understand why from the second iteration the values of j e i move away, when in both cases the increment is +1 for both i and j. Surely it will be the dumbest questions that have been raised by these forums, but really that no matter how many laps I give, I do not understand X)

Greetings and thanks!

    
asked by Oscar Dsflskdflskdfl 28.09.2016 в 11:58
source

2 answers

7

You have two loops:

  • The i loop is used to indicate the maximum number of asterisks to be printed
  • The j loop is used to print the relevant asterisks.

In addition, the loops are nested, that is, for each iteration of the loop i , the loop j will perform a complete path from 0 to the value of i , which could be indicated as [0,i] . This interval can also be expressed as% [0,y+1) (closed on the left and open on the right, which indicates that the value y+1 is not included in the range) and that expression is what I will use later.

Try to solve it with pencil and paper and step by step:

  • First iteration of the loop i : i=0 , then the loop j iterate in the range [0,1) note that the 1 does not enter the range to be an open interval The result is that only one asterisk will be printed: j=0
  • Second iteration of the loop i : i=1 , then the loop j iterate in the range [0,2). This allows you to print two asterisks: j=0 y j=1
  • Third iteration of the loop i : i=2 . The loop j will iterate in the range [0,3) which will print three asterisks: j=0, j=1 y j=2
  • ...

I hope you now understand the logic of the algorithm better.

Greetings.

    
answered by 28.09.2016 / 12:25
source
3

Hello Oscar Dsflskdflskdfl.

What is inside the first for loop is executed with an initial value of i equal to zero, as long as the value of i is less than 5 and at each iteration the value of i is increased by one.

What is inside the second loop is executed for each iteration of i with an initial value of j equal to zero, as long as the value of j is less than or equal to the value of i and every iteration the value of j is increased by one.

Notice that the second for is executed for each iteration of i.

As a result, an asterisk is printed as many times as the value of j can reach, which is limited by i in each iteration of the first for.

Greetings.

    
answered by 28.09.2016 в 12:28