Modern C++: The Good Parts/Getting loopy

From Wikibooks, open books for an open world
Jump to navigation Jump to search

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

Code[edit | edit source]

#include <iostream>
#include <string>

int main()
	std::string input;
	float a, b;
	char oper;
	float result;
	// The ultimate truism, this never stops being 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;
		case '-':
			result = a - b;
		case '*':
			result = a * b;
		case '/':
			result = a / b;

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

Explanation[edit | edit source]

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)

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 | edit source]

under construction

Vocabulary[edit | edit source]

while loop
continues looping until its condition is false.
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 →