Lesson Overview

Welcome to our final class on C++ loops and conditional statements. This lesson reinforces the concepts of loops (while, do-while, for) and control statements (if, if-else). We will also introduce some advanced topics and illustrate their collective use in problem-solving. Let's proceed, connecting these concepts with practical references for a better understanding.

Refreshing Loops and Conditionals

To start, let's review each type of loop and conditional statement. A while loop iterates until its condition becomes false. A do-while loop ensures at least one execution before evaluating the condition. The for loop is beneficial when we know the exact number of iterations. For conditional statements, if tests a condition and executes statements if the condition is true. The if-else statement enables one block for the true condition and another for the false condition. A switch tests for multiple conditions. These constructs are essential for managing our program's flow.

Combining Loops with Conditionals

We often require the combination of loops and conditional statements for complex scenarios. For example, consider a situation where we calculate the sum of the first n natural numbers, but only even numbers are taken into account. Here's how you may do it:

#include <iostream>

int main() {
   int n = 10;
   int sum = 0;
   for (int i = 0; i <= n; ++i) {
       if (i % 2 == 0) { 
           sum += i;
       }
   }
   std::cout << "Sum is " << sum << std::endl; // This outputs: Sum is 30

   return 0;
}

Here, the for loop iterates from 0 to n, checking if the number is even within the if statement. The expression i % 2 evaluates to the remainder when i is divided by 2, commonly used to determine if i is even (remainder 0) or odd (remainder 1).

Advanced Loop Control with `break` and `continue`

The break and continue statements finely control loop executions in C++. break exits the current loop abruptly, halting the ongoing execution. In contrast, continue skips the remaining code in the current loop iteration, moving to the next iteration.

#include <iostream>

int main() {
   for (int i = 0; i < 10; ++i) {
       if (i > 5) {
           break; // As soon as i > 5, the loop breaks
       }
       std::cout << i << " "; // Prints: 0 1 2 3 4 5
   }
   for (int i = 0; i < 10; ++i) {
       if (i % 2 == 0) {
           continue; // Skips the iteration when i is even
       }
       std::cout << i << " "; // Prints: 1 3 5 7 9
   }

   return 0;
}
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal