Problem with sentinel...

Hi everyone :)

I'm trying to make a program but I'm having a hard time getting the sentinel right. The programs runs without the sentinel just fine, but I need to add a sentinel for homework. Can someone help me here?

This is my code.


#include "stdafx.h"
#include <iostream>
using namespace std;


int main()
{
int number = 0, counter, sum = 0;

cout << "Type a positive number " << endl;
cin >> counter;

while (counter != -1);
{
while ((counter < 1) || (counter > 100));
{
while (counter > 0)
{
sum++;
number = sum + number;
counter--;
}

}
cout << number << endl;
cin >> number;
}



return 0;
}



Write just *one* while loop. And put all the checks in that.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

int main()
{
    int number = 0 ;
    int sum = 0 ;

    while( std::cout << "Type a positive number (1-100): "
            && std::cin >> number // a number has been entered
            && number>0 // and the number is +ve
            && number<101 // and the number is not greater than 100
          )
    {
        sum += number ;
    }

    std::cout << "sum: " << sum << '\n' ;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
while (counter != -1);
{	
while ((counter < 1) || (counter > 100));
{	
while (counter > 0)
{
sum++;
number = sum + number;
counter--;
}

}
cout << number << endl;
cin >> number;
}


First of all, remove all the semicolons after the while loops. Semicolons only go after statements, so while (something); means do an empty statement while something is true.

After you have done this, continue reading.

This code is saying:
While counter is not equal to -1
While counter is less than one or greater than 100
While counter is greater than 0
Do a bunch of other stuff.

This means that the while loops will only go through if the counter is greater than 100. I believe you meant for the second while loop:

while ((counter > 1) || (counter < 100)) {
O_O
I completely forgot about that, thank you, both.
Topic archived. No new replies allowed.