I Can't Understand This Logic, HELP

Write a program that asks the user to type all the integers between 8 and 23 (both included) using a for loop.

http://en.wikibooks.org/wiki/C++_Programming/Exercises/Iterations#EXERCISE_2

I read the solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
  #include <iostream>
using namespace std;

int main() {

   int input;
   for(short int i=8; i<=23; i=i+(i==input))
   {
       cout << "Please insert " << i <<": ";
       cin >> input; cout << endl;
   }

    return 0;
}


I get confused from: i=i+(i==input)

I mean, in my mind:

i = 8
if the condition is i=i+(i==input), then 'i' in the cout line, if my input is 8:

i=8+8 so that 'i' is 16.

But everytime i try its always shown 8, 9, 10, consecutively. Why not 16? Can someone help me understand this?
Last edited on
in line 10 you coutnothing
no, not that cout, but this cout cout << "Please insert " << i <<": ";
Last edited on
This is actually a very good example for beginners. If teaches the concept of a boolean expression, of the conversion from bool to int, how the for loop works / the order it proceeds.

i == input is a boolean expression which means it evaluates to true or false. True and false are casted as integers to 1 and 0 respectively. So you are adding 1 if i == input is true, and 0 if not. This way, you keep asking for the same letter until the user enters the correct one.
Last edited on
So, boolean doesnt always have to use _Bool ?
== is a comparison operator. x == y, is a comparison that tests if what is on it's left and right side are equal to each other. This is evaluated to a type bool, true or false. In order to add bool to an int, the bool needs to be converted to an int. The rules are that true is converted as int to 1, and false is converted to 0. It is also important to note that when converting an int to bool, 0 is converted to false, and any other value is converted to true.
Thanks htirwin, if only there is a 'thanks' button :D
Topic archived. No new replies allowed.