0.1 Conditionals and Loops

Before getting started with loops, let’s briefly go over increments. For our counter \(i\), we can increment or decrement the value, or increase or decrease, by \(1\) with i++ and i--.

For instance if we do the following,

i = 5 
i++

then it is equivalent of the following statements.

i = 5 
i = i + 1 
i = 6

Similarly, i-- is identical to saying i = i - 1. There is also ++i and --i, which first increments or decrements the value before defining, but it is just better to adjust index and use i++ and i-- to avoid confusion unless there is a specific reason to use them.

0.1.1 Conditionals

One more thing to note before we move on is logical operations. Unlike how we would usually write in math, we cannot use \(=\) and \(\neq \) for equal to and not equal to. We also won’t be able to use comparisons \(\geq \) and \(\leq \). Instead, we would be using == for equal to, != for not equal to, <= for less than or equal to, and >= for greater than or equal to. This is crucial when we have to compare two values in different statements. With these in mind, let’s get started with if statements!

If-Else Statements

What if you want to display different statements depending on the user input? Fortunately, we could achieve that through if-else statements without manual human inspections. If, else, if-else statements have the following forms.

if (condition) { 
    body 
} else if (condition) { 
    body 
} else { 
    body 
}

Let’s take a look at a quick example.

Code 0.1.1: CS0201.26051-01

1#include <iostream> 
2 
3int main() { 
4    int a; 
5 
6    std::cout << "Enter a number: "; 
7    std::cin >> a; 
8 
9    if (a > 10) { 
10        std::cout << "Your number is greater than ten!\n"; 
11    } else if (a == 10) { 
12        std::cout << "Your number is ten!\n"; 
13    } else { 
14        std::cout << "Your number is smaller than ten!\n"; 
15    } 
16 
17    return 0; 
18}

In this short example, we compare an input from the user with \(10\). As you can see, we must use a == 10, not a = 10, as it would be declaring \(a\) as ten. We can see that our program works as expected!

Output 0.1.2

$ ./program 
Enter a number: -1 
Your number is smaller than ten! 
 
$ ./program 
Enter a number: 10 
Your number is ten! 
 
$ ./program 
Enter a number: 11 
Your number is greater than ten!

Instead of comparing numbers, we could also use statements for comparing strings.

Code 0.1.3: CS0201.26051-02

1#include <iostream> 
2 
3int main() { 
4    std::string password = "password"; 
5    std::string input; 
6 
7    std::cout << "Enter your password: "; 
8    std::cin >> input; 
9 
10    bool correct = (input == password); 
11 
12    if (correct) { 
13        std::cout << "Correct!\n"; 
14    } else { 
15        std::cout << "Incorrect!\n"; 
16    } 
17 
18    return 0; 
19}

As you can see from the example above we can take in the boolean value. An alternative way would be directly putting input == password in the condition for if without defining a new variable.

Output 0.1.4

$ ./program 
Enter your password: password 
Correct! 
 
$ ./program 
Enter your password: Password 
Incorrect!

If you have fixed options, and you don’t want to type every syntax for if-else statements, we can use switch statements.

Switch Statements

Switch statements have the following structure.

switch (expression) { 
    case case1: 
        block 
    case case2: 
        block 
        break; 
    default: 
        block 
}

Here, break and default are optional, but nice to have. Consider the following example for more intuitive explanation.

Code 0.1.5: CS0201.26051-03

1#include <iostream> 
2 
3int main() { 
4    char input; 
5 
6    std::cout << "Choices for Breakfast:\n" 
7              << "  A. Two Bananas\n" 
8              << "  B. Three Bananas\n" 
9              << "  C. Four Bananas\n" 
10              << "What would you like for breakfast today?\n"; 
11    std::cin >> input; 
12 
13    switch (input) { 
14        case ’A’: 
15            std::cout << "You chose two bananas!\n"; 
16            break; 
17        case ’B’: 
18            std::cout << "You chose three bananas!\n"; 
19            break; 
20        case ’C’: 
21            std::cout << "You chose four bananas!\n"; 
22            break; 
23        default: 
24            std::cout << "Please choose from the options\n"; 
25    } 
26 
27    return 0; 
28}

Here, the program would go through all the options to see if there are any matching cases. If not, it will execute default as the fallback. If you also want to exit from the switch statement after finding the right case, we can do so with the break keyword.

Output 0.1.6

$ ./program 
Choices for Breakfast: 
  A. Two Bananas 
  B. Three Bananas 
  C. Four Bananas 
What would you like for breakfast today? 
B 
You chose three bananas! 
 
$ ./program 
Choices for Breakfast: 
  A. Two Bananas 
  B. Three Bananas 
  C. Four Bananas 
What would you like for breakfast today? 
D 
Please choose from the options

With the basic ideas of conditions in mind, let’s discuss different loops for C++.

0.1.2 Loops

There are many different fundamental loops that we can use in C++. First, let’s start with for loops.

For Loops

For loops retain the following structure.

for (start; condition; update) { 
    body 
}

The introduction of loops really made our lives easier. One of the reason why we write program is to avoid repetitive tasks and work more efficiently. Say we want to print “I ate six bananas” five times on the screen. Without loops, we may have to use cout five times, which is ridiculous if the number increase to hundreds and thousands. Instead, we can use a for loop.

Code 0.1.7: CS0201.26051-04

1#include <iostream> 
2 
3int main() { 
4    for (int i = 0; i < 5; i++) { 
5        std::cout << "I ate six bananas\n"; 
6    } 
7 
8    return 0; 
9}

When we compile and run, it is telling the computer to print “I ate six bananas” if \(i < 5\) starting from \(i = 0\) where it increments by \(1\) after each pass. As expected, we will get the following result.

Output 0.1.8

I ate six bananas 
I ate six bananas 
I ate six bananas 
I ate six bananas 
I ate six bananas

A more practical use of for loops would be this.

Code 0.1.9: CS0201.26051-05

1#include <iostream> 
2 
3int main() { 
4    for (int i = 2; i <= 6; i++) { 
5        std::cout << "I ate " << i << " bananas\n"; 
6    } 
7 
8    return 0; 
9}

Instead of manually changing the numbers, the loop will display the following.

Output 0.1.10

I ate 2 bananas 
I ate 3 bananas 
I ate 4 bananas 
I ate 5 bananas 
I ate 6 bananas

With this, it is natural to consider for loops inside a for loop. This is called nested loop made with for loops. Consider the following example that generates all possible combinations of my breakfast assuming there exists three distinct bananas and two distinct apple where I must eat exactly one banana and exactly one apple.

Code 0.1.11: CS0201.26051-06

1#include <iostream> 
2 
3int main() { 
4    for (int i = 0; i < 3; i++) { 
5        for (int j = 0; j < 2; j++) { 
6            std::cout << "Banana " << i+1 << " and " 
7                      << "Apple " << j+1 << std::endl; 
8        } 
9    } 
10 
11    return 0; 
12}

This will run the inner loop when \(i = 0\), \(i = 1\), and \(i = 3\). We also have to start from \(i = 1\) and \(j = 1\) or add the displayed number by \(1\), or else we will get Banana \(0\) and Apple \(0\). Compiling and running, we can notice that we get \(3 \cdot 2 = 6\) distinct combinations.

Output 0.1.12

Banana 1 and Apple 1 
Banana 1 and Apple 2 
Banana 2 and Apple 1 
Banana 2 and Apple 2 
Banana 3 and Apple 1 
Banana 3 and Apple 2

Moving on from for loops, let’s discuss while loops.

While Loops

While loops have the following form.

while (condition) { 
    body 
}

There are many things that we can do with while loops. Below are two simple examples.

Code 0.1.13: CS0201.26051-07

1#include <iostream> 
2 
3int main() { 
4    int i = 10; 
5 
6    while (i > 0) { 
7        std::cout << i << " "; 
8        i--; 
9    } 
10    std::cout << std::endl; 
11 
12    return 0; 
13}

The code block inside the while loop will iterate until \(i\) reaches \(1\).

Output 0.1.14

10 9 8 7 6 5 4 3 2 1

Unlike the first example, the second example uses boolean for the condition.

Code 0.1.15: CS0201.26051-08

1#include <iostream> 
2 
3int main() { 
4    int birthdayYear = 9999; 
5    int input; 
6    bool wrong = true; 
7 
8    while (wrong) { 
9        std::cout << "Guess which year I was born in!\n"; 
10        std::cin >> input; 
11 
12        if (input == birthdayYear) { 
13            wrong = false; 
14            std::cout << "Correct!\n"; 
15        } else { 
16            std::cout << ":(\n"; 
17        } 
18    } 
19 
20    return 0; 
21}

This program will ask the user the same question with feedback until the boolean value wrong is false, or the answer is correct. Notice that it is important to put std::cout << ":(\n"; in else to prevent it showing when the answer is correct.

Output 0.1.16

Guess which year I was born in! 
1234 
:( 
Guess which year I was born in! 
5678 
:( 
Guess which year I was born in! 
9999 
Correct!

Lastly, below is an introduction to another loop.

Do/While Loops

Do/While loop is a variation of while loop that always run the first time [CS02-4]. Unlike the traditional while loop that always check the condition first before running, do/while loop run the first time, then check if next run is eligible even if the first pass does not meet the condition. Below is the general structure of do/while loops.

do { 
    block 
} while (condition);

Consider the following example.

Code 0.1.17: CS0201.26051-09

1#include <iostream> 
2 
3int main() { 
4    bool correct = false; 
5 
6    do { 
7        std::cout << "Correct!\n"; 
8    } while (correct); 
9 
10    return 0; 
11}

With the traditional while loop, no outputs are expected. However, do/while loop will give a different result.

Output 0.1.18

Correct!

Notice that even if the condition is false for the first pass, the block still runs anyhow.

This is it for the basics of conditionals and loops! Before discussing fundamental algorithms, let’s discuss more essential topics on functions and references.