While loops

Syntax for a while loop:

while ( someBooleanExpressionHere) {
    // Put code that you want to execute in here
}

What this does:

  1. Check the Boolean Expression. If it's true, go to step (2). If false, quit looping and go on to the next part of the program.
  2. Execute the code, then go to step (1).

Do-while loops

Syntax for a do-while loop:

do {
    // Put code that you want to execute in here.
} while ( someBooleanExpressionHere)

What this does:

  1. Execute the code, then go to step (2).
  2. Check the Boolean Expression. If it's true, go to step (1). If false, quit looping and go on to the next part of the program.

In other words, a do-while loop is almost the same as a while loop. Instead of checking the condition first, it executes the code inside the loop first. So the only real difference between the two is that the do-while loop is guaranteed to run the code at least once, whereas a while loop may run the code zero times.

Examples:

// Example 1
#include<iostream>
using namespace std;

int main() {

    int a = 5;
    int b = 0;
    
    while (b < a) {
        b = b+1;
    }

    cout << b << endl;
    return 0;
}
// What does this code do?
// What if we changed it to a do-while loop?



// Example 2
#include<iostream>
using namespace std;

int main() {

    int a = 5;
    int b = 0;
    
    while (a < b) {
        b = b+1;
    }

    cout << b << endl;
    return 0;
}
// What if we changed it to a do-while loop?




// Example 3

#include<iostream>
using namespace std;

int main() {

    int a = 5;
    int b = 0;
    
    while (b < a) {
        a = a+1;
    }

    cout << b << endl;
    return 0;
}
// What if we changed it to a do-while loop?

Longer Example:

Loops are SUPER useful. We can do a lot of cool things with them. Here's a program that inputs a name from the user and outputs their initials:

#include<iostream>
#include<string>
using namespace std;

int main() {

    // Input full name from user
    string name;
    cout << "Please input your full name:\n";
    getline(cin,name);

    // Set up string initials to store initials.
    string initials = "";
    unsigned pos=0;
    initials = initials + name[pos]; // Store first initial into string
    pos = name.find(" ");

    while(pos < name.length()) {
        // After each space character we get another initial
        initials = initials + name[pos+1];
        pos = name.find(" ",pos+1);
    }

    cout << "Your initials are " << initials << ".\n";
    return 0;
}

For Loops

A for loop is a slightly different kind of loop. It is generally more useful when you know how many times you want to go through a loop.

Syntax:

for ( initialState; booleanExpression; thingToDoWhenLooping) {
    Code to execute here.
}

Examples

// Example 1

#include<iostream>
using namespace std;

int main() {
    for (int i=0; i<6; i++)
        cout << i;
    cout << endl;
    return 0;
}

/* What this does:
   (1) At the beginning of the loops, we initialize a variable i=0;
   (2) Check that i<6 (if true, execute code. If false, loop is finished)
   (3) Execute code  (cout << i;)
   (4) Run the line i++, then go to step (2)
*/



// Example 2

#include<iostream>
using namespace std;

int main() {
    cout << "Please input two integers. The first one must be non-negative.\n";
    int a,b;
    cin >> a >> b;
    
    int result = 0;
    for(int i=0; i<a; i++) {
        result = result + b;  // We could also write "result += b;" to mean the same thing
    }
    
    cout << result << endl;
    return 0;
}

Aside: i++ versus ++i

Check out the following example code-segments:

// Example 1
int a = 0;
int b = 0;
a = a+1;
b = a;
cout << "a is " << a << '\n';
cout << "b is " << b << '\n';

// Example 2
int a = 0;
int b = 0;
b = a++;
cout << "a is " << a << '\n';
cout << "b is " << b << '\n';

// Example 3
int a = 0;
int b = 0;
b = ++a;
cout << "a is " << a << '\n';
cout << "b is " << b << '\n';

The lines a++ and ++a both increment a by one. However, the order of operations is different between the two. Writing ++a first increments a, then uses the new value in any further calculations. Writing a++ will increment a, but it will use the original (un-incremented) value if there are more calculations on that same line.

Aside #2: Scopes and Loops

Similar to if-statements, if you declare a variable inside a loop, the scope of that variable is limited to that loop. Once the program exits the loop, your variable will be destroyed.

// Example:

#include <iostream>
using namespace std;

int main() {
    for(int i=0; i<5; i++) {
        int count = 3;
        count += i;
    }
    cout << count << '\n';   // This will give an error.
                             // The variable 'count' does not exist at this point
                             // in the code
    return 0;
}

Code-Reading Exercises

For each code-segment below, what is the output?

// Segment 1
int count = 3;
while (count > 0)
{
    cout << count << " ";
    count = count-1;
}







// Segment 2
int x = 10;
while (x > 10)
{
    cout << x << endl;
    x = x - 3;
}








// Segment 3
int x = 10;
while (x < 20)
{
    cout << x << endl;
    x = x - 3;
}






// Segment 4
for (int count = 1; count < 5; count++)
    cout << (2 * count) << " ";








// Segment 5
for (int n = 10; n > 0; n = n - 2)
{
    cout << "Hello ";
    cout << n << endl;
}


Writing Exercises

Exercise 1

Rewrite the following as a for loop

int i = 1;
while (i <= 10)
{
    if (i < 5 && i != 2)
        cout << 'X';
    i++;
}

Exercise 2

Rewrite the following as a while loop

for (int i = 1; i <= 10; i = i + 3)
    cout << 'X';

Exercise 3

Write a program that inputs an integer from the user (via cin), and outputs (via cout) that many stars. Example input/output:

How many stars would you like to print? 10
Okay here you go!
**********

Exercise 4

Extend your program from the previous exercise so that it now prints a square of stars. Example input/output:

How big of a square do you want? 10
Alright here it is!
**********
**********
**********
**********
**********
**********
**********
**********
**********
**********

Exercise 5

Write a program that inputs a string from the user (use getline), then goes through the string one character at a time and changes every 'a' to a '!'. Example input/output:

Please input a string: The rain in Spain stays mainly on the plain.
Here is your edited string:
The r!in in Sp!in st!ys m!inly on the pl!in

What would you do if I also wanted to change every 'A' to a '!'?

Also, completely unrelated, this movie stinks.

More reading exercises

// What does this program do?

#include<iostream>
#include<string>
using namespace std;

int main() {
    string myString;
    cout << "Please input a string:\n";
    getline(cin, myString);

    int pos = 0;
    int numVowelsFound = 0;
    int vowel1 = 0;
    int vowel2 = 0;

    while (pos < myString.length() && numVowelsFound < 2) {
        if (myString[pos] == 'a' || myString[pos] == 'e' || myString[pos] == 'i' ||
            myString[pos] == 'o' || myString[pos] == 'u') {
            numVowelsFound++;
            if (numVowelsFound == 1)
                vowel1 = pos;
            else
                vowel2 = pos;
        }
        pos++;
    }

    cout << "I found " << numVowelsFound << " vowels in your string.\n";
    if (numVowelsFound >= 1)
        cout << "The first vowel was '" << myString[vowel1] << "' at position " 
             << vowel1 << ".\n";
    if (numVowelsFound == 2)
        cout << "The next vowel was '" << myString[vowel2] << "' at position " 
             << vowel2 << ".\n";

    return 0;
}

// Check out the find_first_of method from the string class for another way to do the same thing.

One last code-writing problem

Write a program that inputs a string from the user and removes all space-characters from the string. After you're done removing the spaces, output the result to the console.


Example input/output:
Please input a string: Frankly my dear, I don't give a damn.
Output: FranklymydearIdon'tgiveadamn.