Question over this code! (Please.)

closed account (yR9wb7Xj)
Hi I want to make sure the code is correct and my explanation is correct. Thanks guys!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

/*
Solution from learncpp.com

 * Invert the nested loops example so it prints the following:



5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
 *
 */

#include <iostream>
using namespace std;
int main(){


int outer = 5;

// Since outer is being assign to 5 above the while loop
// The while loop will execute only if it's true, in this case
//  outer is being decremented first by 1 so it's 4, than evaluated
// In the nested while loop, inner is assign to outer, so if
// the inner loop is true it will execute, and evaluate that #
// then decremented by 1
// Once loop or nested loop condition is false, it will exit both of the loops
// and execute the program

while(outer >=1)
{
	int inner = outer;

	while(inner >=1){
		cout << " ";
		cout << inner--;
	}
cout << " \n";
	--outer;
}




	return 0;
}
Last edited on
Try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

int main() {

    int outer = 5;

    int loop_cnt = 0 ;
    while( outer >= 1 && std::cout << "\n\n" << ++loop_cnt << ". while( outer >= 1 ): outer == " << outer << '\n' )
    {
        int inner = outer ;
        std::cout << "    after int inner = outer ; inner == " << inner << '\n' ;

        int inner_lc = 0 ;
        while( inner >=1 && std::cout << "\n    " << ++inner_lc << "> while( inner >= 1 ): inner == " << inner << '\n' ){
            std::cout << "        inner-- == " << inner-- << '\n' ;
            std::cout << "        after inner-- inner == " << inner << '\n' ;
        }
        --outer;
    }
}

http://coliru.stacked-crooked.com/a/2e2469c1c34e8c15
closed account (yR9wb7Xj)
Okay, I will but is my comment explanation of the while loop correct?
> is my comment explanation of the while loop correct?

Run the program, examine its output, and you would be able to answer that question on your own.
closed account (yR9wb7Xj)
I have examined the output, I just wasn't sure if I was explaining it correctly in the comments I made. Thanks :)
Last edited on
Topic archived. No new replies allowed.