What can we do with the while statement?
What value needs the statement in the brackets evaluate to in order for the loop to continue?
What is an infinite loop?
if the expression being evaluated to determine if the loop runs always evaluates to true, the while loop will execute forever.
What is an iteration?
one run of the executable code of the loop
Quiz
1) In the above program, why is variable inner declared inside the while block instead of immediately following the declaration of outer?
inner needs to be re-initialized each time the nested loop runs.
2) Write a program that prints out the letters a through z along with their ASCII codes. Hint: to print characters as integers, you have to use a static_cast.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
for (char charVariable = 'a'; charVariable <= 'z'; ++charVariable)
{
std::cout << charVariable << " is ascii " << static_cast<int>(charVariable) << "\n";
}
return 0;
}
3) 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>
#include <iomanip>
using namespace std;
int main()
{
int outer = 1;
while (outer <= 5)
{
int inner = 5;
while (inner >= outer)
{
std::cout << inner << " ";
inner=inner-1;
}
std::cout << "\n";
outer=outer+1;
}
}
-
Now make the numbers print like this:
(reverse of the above)
#include
#include
using namespace std;
int main()
{
//row goes down
//column goes across
int row = 1;
while (row <= 5)
{
// loop between 5 and 1
int column = 5;
while (column >= 1)
{
if (column > row){
std::cout << " ";
} else {
std::cout << column << " ";
}
column=column-1;
}
// start new row
std::cout << "\n";
row=row+1;
}
std::cout << "\n";
return 0;
}