-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path85_while_loop.txt
More file actions
126 lines (83 loc) · 1.46 KB
/
85_while_loop.txt
File metadata and controls
126 lines (83 loc) · 1.46 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
Section 09: while Loop
-----------------------------------------------------------------
while Loop
- Example of a pre-test loop
General Example
while (expression)
statement;
while (expression) {
statement1;
statement2;
...
statement3;
}
Example 1
int i {1};
while (i <= 5) {
cout << i << endl;
++1; // important!
}
output
-------
1
2
3
4
5
Example 1 - even numbers
int i {1};
while (i <= 10) {
if (i % 2 == 0)
cout << i << endl;
++i;
}
output
-------
2
4
6
8
10
Example 2 - array example
int scores[] {100, 90, 87};
int i {{0};
while (i < 3) {
cout << scores[i] << endl;
++i;
}
output
-------
100
90
87
Example 3 - input validation 1
int number {};
cout << "Enter an integer less than 100: ";
cin >> number;
while (number >= 100) { //!(number < 100)
cout << "Enter an integer lses than 100: ";
cin >> number;
}
cout << "Thanks" << endl;
Example 4 - input validation 2
int number {};
cout << "Enter an integer between 1 and 5: ";
cin >> number;
while (number <= 1 || number >= 5) {
cout << "Enter an integer between 1 and 5: ";
cin >> number;
}
cout << "Thanks" << endl;
Example 5 - input validation - boolean flag
bool done {false};
int number {0};
while (!done) {
cout << "Enter an integer between 1 and 5: ";
cin >> number;
if (number <= 1 || number >=5) {
cout << "Out of range, try again" << endl;
} else {
cout << "Thanks!" << endl;
done = true;
}
}