Modern C++: The Good Parts/Getting loopy

For this chapter, we have a calculator willing to perform more calculations than you are willing to input.

Code edit

#include <iostream>
#include <string>

int main()
{
	std::string input;
	float a, b;
	char oper;
	float result;
	
	// The ultimate truism, this never stops being true.
	while(true)
	{
		std::cout << "Enter two numbers and an operator (+ - * /).\nOr press Ctrl+C to exit.\n";
		
		// Take input.
		std::cin >> input;
		// Parse it as a float.
		a = std::stof(input);

		// Take input.
		std::cin >> input;
		// Parse it as a float.
		b = std::stof(input);

		// Take input.
		std::cin >> input;
		// Get the first character.
		oper = input[0];

		switch (oper)
		{
		case '+':
			result = a + b;
			break;
		case '-':
			result = a - b;
			break;
		case '*':
			result = a * b;
			break;
		case '/':
			result = a / b;
			break;
		}

		std::cout << a << " " << oper << " " << b << " = " << result << "\n";
	}
}

Explanation edit

This program will run until your terminal stops running it (because you press Ctrl+C, or click the X). That's because the while loop, every time control reaches its bottom, jumps back up to the top - if its condition is still true, which it always will be in this case.

If we weren't in a context where the user could easily halt the loop, the while(true) would be a very bad idea. Instead of true, you can put any Boolean expression (like a == b) or bool variable between the parentheses.

Suppose we wanted to allow up to ten iterations (passes through the loop) instead of an unlimited number. We could do this:

int i = 0;
while(i < 10)
{
    //...
    i++;
}

And that would work just fine.

i++ is the same thing as i = i + 1, and results in i being one greater than it was. It's also the same as i += 1.

But C++ provides a prettier way to write that, the for loop:

for(int i = 0; i < 10; i++)
{
    //...
}

For the first iteration, i will have the value 0. For the last iteration, it will have the value 9. It will never (usefully) have the value 10 because, just like with our equivalent while loop above:

  1. the iteration runs;
  2. then i is incremented;
  3. then i < 10 is checked, and if it's false the loop is exited.

Nonetheless, the loop does run 10 times.

Exercises edit

under construction

Vocabulary edit

while loop
continues looping until its condition is false.
iteration
one pass through a loop. Also, the action of looping or "iterating".
for loop
more suited to counting than a while loop is.
Modern C++: The Good Parts
 ← Switching things up Getting loopy At last, functions →