[spoiler title=”Lesson Video”]
Direct Download of Video (For mobile / offline viewing)(right click > save target as)
[/spoiler]
[spoiler title=”Lesson Source Code”]
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
|
#include
using namespace std;
int main(){
/*
*
**
***
****
***
**
*
*/
//Allow the user to determine the max size for the output
//Counter starts and ends at 1
//Each time the counter is increasing by 1
//Each time, there is a second counter, counting to the value of the first counter
//Once it hits it's maximum value, it counts down.
int value = 0;
cout << "Please enter a value: ";
cin >> value;
//Count up
for (int i = 1; i <= value; i++){
for (int j = 0; j < i; j++){
cout << "*";
}
cout << endl;
}
//Count down
for (int i = value-1; i >= 1; i--){
for (int j = 0; j < i; j++){
cout << "*";
}
cout << endl;
}
system("PAUSE");
return 0;
}
|
[/spoiler]
Homework: https://beginnerscpp.com/forums/index.php/topic,63.0.html
Nested Loops
In this lesson I threw you guys straight into the deep end. The basic concept of nested loops is the same as a nested if statement, you have an inner loop that will complete all of it’s instructions every time through the outer loop (unless there is a break statement somewhere). Here’s an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
for (int i=0; i<4; i++){
for(int j=0; j<3; j++){
cout << j;
}
cout << endl;
}
The code above will look like this when output:
012
012
012
012
|
As you can see in the example, the inner loop is running fully every time the outer loop iterates.