Lesson questions:
- repeatedly check to see if certain conditions are met, then preform a function.
- For the statement in the brackets to execute, the information inside the parenthesis must be true. If it is not true, then the code will not execute.
- An infinite loop is a loop where the results are never false, so it continues to iterate.
- An iteration is each time that the loop results return to the top of the loop.
While loop questions:
Question 1:
In the above program, why is variable inner declared inside the while block instead of immediately following the declaration of outer?
The location determines when the function is called. If you move it to another place, it will not run in the way that it should.
Question 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
using namespace std;
int main()
{
char mychar{ ‘a’ };
while (mychar <= ‘z’)
{
std::cout << mychar << ’ ’ << static_cast(mychar);
if(mychar % 4==0)
{
std::cout <<’\n’;
}
++ mychar;
}
return 0;
}
Question 3:
/
#include
int main(int argc, const char * argv[])
{
int outer{5};
while (outer>=1)
{
int inner{outer};
while (inner>= 1)
{
std::cout <<inner-- << ’ ';
}
std::cout<<'\n';
--outer;
}
}
question 4
X X X X 1
X X X 2 1
X X 3 2 1
X 4 3 2 1
5 4 3 2 1
figure out how to make this pattern:
(the solution in the book is missing the “x”)
#include
int main(int argc, const char * argv[])
{
int outer{1};
while (outer<=5)
{
int inner {5};
while (inner>=1)
{
if (inner<=outer)
std::cout <<inner<<' ';
else
std::cout<<"X ";
--inner;
}
std::cout<<'\n';
++outer;
}
}
For loop exercise: print out the even numbers between 1 and 20:
#include
int main(int argc, const char * argv[])
{
for (int grain =0; grain <= 20; grain++)
{
if (grain % 2 == 0)
std::cout<<grain <<' ';
}
}
Add the components of an array 1-5:
{
int myArray [5] {1,2,3,4,5};
int sum =0;
for (int i=0; i<5; i++)
{
sum+=myArray[i];
}
std::cout<<"sum = "<<sum;
}
What’s wrong with this:
1
2
3
// Print all numbers from 9 to 0
for (unsigned int count{ 9 }; count >= 0; --count)
std::cout << count << ’ ';
The loop will continue to run. Because it is unsigned, it will never turn negative.