1- we can repeat a statement in the braces of a while loop as long as the expression in the parentheses would evaluate to true.
2- As long as the expression in the parenthesis evaluates to true,the loop will continue.
3- If the expression always evaluates to true, the while loop will execute forever. This is called an infinite loop.
4- Each time a loop executes, it is called an iteration.
Quiz)
1- If we put the inner variable outside the outer while loop,the result would be like this :
1
2
3
4
5
so, we put it inside the outer loop and define it right above the inner loop.Every time the outer loop iterates the inner variable should be reset to 1 in order to get the true result.
2-
int x=97;
while(x<123)
{
cout<<char(x)<< " “<<x <<endl;
++x;
}
3-
int outer=1;
int count=0;
while(outer<=5)
{
int inner=5-count;
while(inner>=outer-count)
{
cout<<inner–<<” ";
}
cout<<"\n";
++outer;
++count;
}
4-
#include
using namespace std;
int main()
{
int outer=1;
while(outer<=5)
{
int inner=5;
while(inner>outer)
{
cout<<" “<<” “;
–inner;
}
int mid=outer;
while(mid>0)
{
cout<<mid–<<” ";
}
cout<<"\n";
++outer;
}
return 0;
}
Part2 :
1- The for statement (also called a for loop) is ideal when we know exactly how many times we need to iterate, because it lets us easily define, initialize, and change the value of loop variables after each iteration.
2- A for statement is evaluated in 3 parts:
-
The init-statement is evaluated. Typically, the init-statement consists of variable definitions and initialization. This statement is only evaluated once, when the loop is first executed.
-
The condition-expression is evaluated. If this evaluates to false, the loop terminates immediately. If this evaluates to true, the statement is executed.
3)After the statement is executed, the end-expression is evaluated. Typically, this expression is used to increment or decrement the variables declared in the init-statement. After the end-expression has been evaluated, the loop returns to step 2. For example:
for(count=0;count<10;++count)
{
The statement;
}
3- Off-by-one errors occur when the loop iterates one too many or one too few times. This generally happens because the wrong relational operator is used in the conditional-expression (eg. > instead of >=).
Quiz)
1-
for(int iii=0;iii<=20;++iii)
{
if(iii%2==0)
cout<<iii<<" ";
}
2-
int sumTo(int s)
{
int sum=0;
for(int iii=1;iii<=s;++iii)
{
sum+=iii;
}
return sum;
}
3-
// Print all numbers from 9 to 0
for (unsigned int count=9; count >= 0; --count)
std::cout << count << " ";
I think this loop will iterate forever,because the count variable is defined as unsigned, so it never
be a negative integer and the count>=0 always will evaluate to TRUE value.