1. What can we do with the while statement?
A while statement allows a block of code to be repeatedly executed while a certain condition is met.
2. What value needs the statement in the brackets evaluate to in order for the loop to continue?
The statement in the brackets needs to evaluate to a boolean expression that returns either true or false.
3. What is an infinite loop?
An infinite loop is a loop that has no way to exit, such as no incrementing counter for example. If the conditional statement always evaluates to true, the code in the loop body will continue to execute indefinitely unless you provide a way to stop the conditional statement from being true (or break out of the loop - using a break statement for example).
4. What is an iteration?
An iteration is an occurrence of the body of the loop executing. If the conditional statement is true and the program reaches the end of the loop body, an iteration has occurred (and subsequently loops back to the start to see if the conditional statement still evaluates to true and continues looping if it is, in turn causing another iteration)
Section 2:
1. When is it a good idea to use a for statement (do a for loop) instead of the while loop we learned previously?
For loops are a good idea if you know how many iterations of the loop you require. For example, if you wanted to print 10 lines of something or wanted to count up in 3âs exactly 50 times, etc. Personally, I usually consider a while loop as exactly that - a while statement (while âxâ is true do âyâ), whereas I consider a for loop almost as an until statement (keep doing âyâ until âxâ is no longer true). This is not always the case, but most of the time it helps wrap my head around what I want to achieve and then define it accordingly.
2. How would you write a for-loop in code?
int treats = 5;
for (int jellybeans = 1; jellybeans <= treats; jellybeans++){
cout<<"You have not found all the jellybeans"<<"\n";
cout<<"You must continue on your quest to find the remaining jellybeans"<<endl;
cout<<"\n";
if (jellybeans = treats)
{
cout<<"Well done, you have found all "<<jellybeans<<" jellybeans!!! .....mmmm, jellybeans"<<endl;
}
}
3. What is an off-by-one error?
An off by one error usually occurs during the < or <= part of a loop (or > or >= if decrementing the count). Quite often, new programmers (or distracted seasoned programmers) might end up using the wrong combination of start points and operators (for counting) for example they want to count 10 numbers and either start from 0 and use <= 10 and end up counting eleven numbers or they might start from 1 and just use the < operator before 10 and end up counting only 9 numbers.