Loops
loop(some_condition)
{
contents_of_the_loop
}
The two most important things you should take away from this pseudocode is the “some_condition” and “contents_of_the_loop”. “some_condition” represents a statement which gets evaluated to either true or false. If it’s true, “contents_of_the_loop” gets executed and the program returns to the “some_condition”. If not, you exit the loop. This is the takeaway point. Unlike if statements, this chunk of code gets repeatedly executed until “some_code” becomes false. For us to further show you the power of loops, we will start with our first loop, the while loop.
While loop
The name says it all: While something is true, execute the code in the loop. The structure of the while loop looks almost identical to the pseudocode:
while(condition)
{
some_statements;
}
Let’s look at a BAD example how we can use this. Imagine you wanted to print every number from 0 to 100 which is divisible by 5. One way you can do it is to increment it by 5, then print it, then increment it by 5 again, then print it again… until your number reaches 100:
#include <iostream>
using namespace std;
int main()
{
int number = 0;
number += 5; // number = 5
cout << number << endl; //endl will move the output cursor to the next line
number += 5; // number = 10
//...
number += 5; // number = 100
cout << number << endl;
}
As you can see, we are doing the exact same task and it’s inefficient. Not only do you need to write all this out, you also need to keep track of the number of times you are doing it. If you wanted to change the maximum number from 100 to 75, you would need to delete a certain number of lines. If then you decide “Hmm, maybe I need up until 170”, you then need to calculate how many more lines you need to add. If finally, for some God-forbidden reason you wanted to change the logic of your code to print all the numbers divisible by 3, you would need to change every second line of your code. This repetitive work can easily be avoided using a while loop:
#include <iostream>
using namespace std;
int main()
{
int number = 0;
while(number <= 100)
{
number += 5;
cout << number << endl;
}
return 0;
}
- Define a variable where we will store the sum (“sum”)
- Define a variable (“number“) which will represent the number we are adding
- While the “number” is less then 10, do the following:
- Add the “number” to the “sum“
- Increment the “number” so it can be the next number we are adding
#include <iostream>
using namespace std;
int main()
{
int sum = 0;
int number = 1;
int N = 10;
while(number <= N)
{
sum += number;
number++;
}
cout << sum << endl;
return 0;
}
Do-while
The do-while loop is relatively similar to the while loop, but with one key difference. In the while loop, the first thing that is done is the check whether the condition is true. If in some special case that was not true, the condition was indeed false and the program will just skip the whole loop, just like that! What if, for some reason you wanted to execute at least one iteration, even if the condition was false? What if you wanted just one iteration and if the condition was true, you continue the same way as with the while loop, but if the condition was false, oh well, at least you got one iteration out of that sucker. That exactly is the structure and logic of a do while loop. In some sense, it looks like a reverse while loop and you’ll see why in the example below:
do
{
do_some_important_work;
}
while(condition);
- At the start, we need to define variables for the current weight, ideal weight, number of kilograms gained from eating, number of kilograms lost from working out per day and the current workout streak which will be incremented every day
- We need to loop through, where each iteration represents a day
- During one iteration, we must calculate the number of kilograms lost/gained
- We need to add that number to the current weight
- Finally, we check if the current weight is below the ideal weight
#include <iostream>
using namespace std;
int main()
{
double current_weight = 78;
double ideal_weight = 75;
int streak = 0;
do
{
streak++;
double weight_gain = 0.01 - 0.01 * streak; /* weight_gain = from_eating - (from_workout * streak)*/
cout << "Current weight: " << current_weight << endl;
cout << "Kilograms to goal: " << current_weight - ideal_weight << endl;
}
while(current_weight > ideal_weight);
return 0;
}
Let’s check the output:
Current weight: 78
Kilograms to goal: 3
Current weight: 78
Kilograms to goal: 3
Current weight: 78
Kilograms to goal: 3
Current weight: 78
Kilograms to goal: 3
Current weight: 78
Kilograms to goal: 3
Current weight: 78
Kilograms to goal: 3
Current weight: 78
Kilograms to goal: 3
Current weight: 78
Kilograms to goal: 3
Current weight: 78
Kilograms to goal: 3
Current weight: 78
Kilograms to goal: 3
Current weight: 78
Kilograms to goal: 3
Current weight: 78
Kilograms to goal: 3
Current weight: 78
Kilograms to goal: 3
Current weight: 78
Kilograms to goal: 3
...
- Don’t be a code monkey – Copying and pasting code blindly will do you more harm than help. Try understanding the code before you run it
- They are left as an exercise – There’s nothing greater in programming than figuring out a problem on your own. If you can come up with a solution on your own, that means that you have understood every step so far and are also starting to develop some crucial problem-solving skills which are very sought after by the industry
For loops
- If for any reason you forgot to initialize your variable, the code might do some strange things (due to the compiler putting some garbage value in the declared variables)
- If you forget to increment your variable, you’ll encounter something called an infinite loop (a loop which does not end and continues running until you forcefully terminate your program)
- After exiting the loop, the variable still exists, even though it served its purpose
- You can declare and initialize a local variable at the start of the for loop so that the variables scope is only inside of the for loop
- If you declare additional local variables in the body of the for loop, they will only exist until the for loop is done
- You can add a statement in the for loop which will be executed after every iteration of the loop
for(local variable declaration/initialization; condition; statement)
{
...
}
Let’s see an example. If we try rewriting the example for the while loop with a for loop, it may look something like this:
#include <iostream>
using namespace std;
int main()
{
int sum = 0;
int N = 10;
// number is defined at the start of the for loop and will only be visible inside the loop
for(int number = 0; number < N; number++ )// number gets incremented after every iteration
{
sum += number;
}
// number does not exist here
cout << sum << endl;
return 0;
}
- number is only needed inside of the loop and we defined it at the start of the loop, so we didn’t need to do any prior declaration.
- Because number is declared at the start of the loop, its scope is just inside of the loop. After the loop is done, number doesn’t exist anymore.
- We were able to supply the increment at the start of the loop, making this a good practice not to forget to increment the number every time
int array[] = {1, 3, 4, 5};
int sum = array[0] + array[1] + array[2] + array[3];
This seems easy enough, but now imagine if the array was a lot bigger, let’s say, 10 elements. If we just changed the number of elements of the array, we would also need to redefine our sum, which seems like a tedious task. Instead, we can notice a pattern. We see that the sum has one thing in common. We’re summing elements of the array where the index gets increased by one and the last index is the (number of elements – 1) in the array (because indexes start from 0). We can exploit this and actually do the summation inside of a for loop like this:
int array[] = {1, 5, 21, 43, 21, 22, 11, 75, 21, 13, 8, 68};
int sum = 0;
int N = 12; // 12 elements in the array
for (int i = 0; i < N; i++)
{
sum += array[i];
}
This seems to do the trick. We go through every element and add it to the sum. More importantly, if we now add a new element to the array, we just need to change the variable N and everything works perfectly!
Table of contents
- Classes and Objects
- Operator Overloading
- Class Inheritance
- Exceptions
- Namespaces
- Templates
- Standard Library
- Additional Problems