Loops How to repeat code - while
Video
Key Takeways
There are 2 techniques we can use to repeat code:
- while loops
- for loops
While Loops
Lets focus on while
loops. Lets say we have the following code:
void PrintNumbers() {
std::cout << 1 << std::endl;
std::cout << 2 << std::endl;
std::cout << 3 << std::endl;
std::cout << 4 << std::endl;
std::cout << 5 << std::endl;
}
Using a while
loop we could write the same code as:
void PrintNumbers() {
int number = 1;
while (number <= 5) {
std::cout << number << std::endl;
number++;
}
}
The while
loop has almost the same structure as an if
statement.
while(expr) {
// body
}
The only difference is that unlike an if
statement which simply either executes the body or skips the body, the while
statement continuously executes the body as long as expr
is true. In the PrintNumbers
example, we would excute the body of the code 5 times.
- when
number == 1
since1 <= 5
is true. - when
number == 2
since2 <= 5
is true. - when
number == 3
since3 <= 5
is true. - when
number == 4
since4 <= 5
is true. - when
number == 5
since5 <= 5
is true. - when
number == 6
, we skip to after thewhile
loop since6 <= 5
is false.
Go ahead, try and walk through PrintNumbers
in a memory table and see what happens.
Variable Termination
The convinient thing about loops is they enable you to do something you haven’t been able to do yet: Execute code a varible number of times. Lets say the goal of the program is to ask the user for input. Then print out all numbers less than that number starting from 1. Without loops that seems like an impossible task! However with one quick modification to our PrintNumbers
function, it becomes easy!
void PrintNumbers(int limit) {
int number = 1;
while (number < limit) {
std::cout << number << std::endl;
number++;
}
}
By changing the condition of the while
from number <= 5
to number < limit
, we allow the code to execute as many times as the condition is true. Go ahead, try and use this code with various inputs in a REPL to get used to it.
Infinite Loops
One of the most common bug encountered with loops will be infite loops. An infite loops is when your loop never has a termination clause. For example:
while(true) {
std::cout << "Hi!" << std::endl;
}
std::cout << "Lets Start!" << std::endl;
Can you spot why this is an infinite loop?
Answer
This code would never print Lets Start!
as the while
loop expression would always be true and hence always execute the body.
Another example of an infinite loop could be something like:
int counter = 1;
while (counter < 10) {
std::cout << "My number is: " << counter << std::endl;
}
Can you spot why this is an infinite loop?
Answer
The variable counter
is never changing! So the counter < 10
will always be true.
Assignment
- For each code sample 0 - 2 below:
- Summarize what this code is doing?
- Can you improve this code?
- For each code sample 3 - 4 below:
- Can you identify how to code is broken?
- Can you fix this code?
- Can you improve this code?
- Solve the following problems:
- Write a function which finds out the number of factors for a number X. It doesn’t need to identify what the prime factors are.
- For example, 12 has 6 factors (1, 2, 3, 4, 6, 12). 35 has 4 factors (1, 5, 7, 35).
- Write a function to determine if a number is a prime number.
- Write a function which prints out (exactly as is). Try using loops.
1 2 3 4 5 1 2 3 4 1 2 3 1 2 1
- Write a function which finds out the number of factors for a number X. It doesn’t need to identify what the prime factors are.
- Update your calculator to use while loops.
- Write a calculator which first takes in a number N. Then your calculator should ask for N numbers and (N - 1) operators. For example, if the user enters 5, it should produce the same output as your 5 number 4 operator calculator.
Code Samples
Sample 0
int Function(unsigned int number) {
int counter = 0;
while (number > 0) {
counter++;
number = number / 10;
}
return counter;
}
int main() {
int x;
std::cout << "Enter a number: ";
std::cin >> x;
int result = Function(x);
std::cout << "Fun Fact: " << result << std::endl;
return 0;
}
Sample 1
bool isValid(int y) {
return (z < 5) && (z >= 0);
}
int number() {
int x = -1;
while (!isValid(x)) {
std::cout << "Enter a number: ";
std::cin >> x;
}
return x;
}
char TryThis(int a) {
if (a == 0) {
return 'a';
} else if (a == 1) {
return 'e';
} else if (a == 2) {
return 'i';
} else if (a == 3) {
return 'o';
} else {
return 'u';
}
}
int main() {
int X = number();
char B = TryThis(X);
std::cout << "CHAR at: " << X << " is: " << B << std::endl;
return 0;
}
Sample 2
int main() {
int Y = GetUserInput();
int Z = GetUserInput();
int i = 1;
int j = 1;
while (i <= Y || j <= Z)
{
if (i % j == 0) {
std::cout << i << " " << j << std::endl;
}
i++;
j++;
}
}
Sample 3
int Calculate(int X) {
int R = 1;
while X <= 0) {
R *= X;
X--;
}}
return R;
}
int main() {
int number = GetUserInput();
long long f = Calculate(X);
std::cout << "Factorial of " << number << " is " << f << std::endl;
return 0;
}
Sample 4
void TryThis(int X) {
int counter = 0;
while (counter < X) {
std::cout << counter << " ";
}
}
int main() {
int number = GetUserInput();
int counter = 0;
while (counter < number) {
counter++;
int result = TryThis(counter);
}
return 0;
}
End of Assignment Checklist
- I finished all the assignments.
- I shared my assignments with others.
- I provided feedback for assignments of at least 2 others.
- I addressed the feedback from others and thanked them for the review.