Topic Overview and Lesson Plan

Welcome to an exciting coding journey! Today's challenge is the while loop, an indispensable tool in C++. The while loop, akin to an endless runner in a video game, runs code repeatedly until a certain condition becomes false. Are you ready to dive in? Let's begin and tackle the structure, syntax, and more about while loops!

Increment and Decrement Operations in C++

When working with loops, understanding how to update conditions is vital. Thus, let's dive into it first. In C++, increment and decrement operators are essential tools for this purpose. Let's break down what these operators do:

Increment Operators:

  1. a += b

    • This shorthand notation is equivalent to a = a + b. It adds the value of b to a and stores the result in a.
    int a = 5;
    int b = 3;
    a += b; // Now a is 8
  2. a++

    • This is the post-increment operator. It increases the value of a by 1. If used in an expression, it returns the value before the increment.
    int a = 5;
    int b = a++; // b is 5, but now a is 6
    • Conversely, ++a is the pre-increment operator that increments the value before returning it.
    int a = 5;
    int b = ++a; // Now both a and b are 6

Decrement Operators: Just like a += b adds b to a, a -= b subtracts b from a. Similarly, a-- and --a decrease the value of a by 1, with a-- being the post-decrement and --a being the pre-decrement.

Understanding "While" Loops

A while loop in C++ executes a block of code repetitively until a specified condition becomes false. Imagine an automatic door system: the door remains open as long as people keep passing through, much like a while loop, which runs as long as the condition is met. Does no one pass through the door? It closes. This mirrors a while loop stopping when the condition becomes false.

C++ "While" Loop Syntax and Structure

A while loop in C++ is structured as follows:

while (condition) {
  // code to be executed
  // condition alteration
}

A while loop comprises two major components: the condition and the loop body. The concept is straightforward: We execute the loop body if the condition is true. Sounds simple, doesn't it? Let's put this into practice:

#include <iostream>

int main() {
   int counter = 1;

   while (counter <= 5) {
     std::cout << "Counter Value: " << counter << std::endl; // will print values from 1 to 5
     counter += 1; // increment the counter by 1
   }

   return 0;
}

The while loop checks if the counter is less than or equal to 5. It then prints the counter value and increments it by 1 each time the loop executes.

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