For some reason, my numbers aren't adding in correctly and it's taking the -1 sentinel value and adding it into the total.

// worthless testing.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>

using std::cout;
using std::cin;
using std::endl;


int main()
{
int number = 0;
int total = 0;
do
{
	cout<<"Enter a number: ";
	cin>>number;
	total = total + number;
} while (number != -1);

cout<<"Total is:"<<total<<endl;
	return 0;
}

Should I just make it a while statement and forgo the do?

Should I just make it a while statement and forgo the do?

Well, you could simply do the following:

Change:

total = total + number;

To:

if(number != -1) total = total + number;

Edit:: But wouldn't it be better to take 0 as value to end your loop? As zero won't affect your ending result.

Let's build the loop from scratch:
To create this small program, we first need a thorough problem description.

Description:
Well, out of your post I could make up that you have to create a program, which asks the user for entering a valid (integer) number, and when that number is not equal to -1, we will add this number to a variable which holds the sum.

What we're going to need:
To repeatedly let the user enter a number from his keyboard and process it directly after it, we need a loop, in this example I'll guide you on how to achieve it using a do-while loop (as you already started with such a loop).
Also we will take advantage of what's called short-circuiting of the && operator.
In C++, && (and ||) are called short-circuit operators, but what does this exactly mean to us?
Well, this means that when the result of the expression is already sure, the compiler won't let your program waste time to evaluate the other conditions in it.
An example:

// Try running this program
if( false && 5/0 )
    std::cout << "This will never execute..." << std::endl;

We all know that the logical AND operator requires that both its operands are evaluated to true before the result of the expression can become true, the above example illustrates the concept of short-circuiting, you know that a division by zero is not possible, but the program will never perform this division because the first operand is already evaluated to false, as the logical AND operator requires that both its operands are true, and knowing that the first one is already false, the rest won't be evaluated anymore in order to gain efficiency.
I'll be using the same concept in the program below, but I felt that there was need to explain this first to you.

Building the program:
Now we know exactly what the problem is, and what building stones we are going to use in the program, we can start writing the code for it, as with all C++ programs, we first start with the well known skeleton:

#include <iostream>

int main()
{

}

This skeleton as a stand-alone program won't do much, so we'll need to add some features to it, I always start with the variables.
We'll need a variable to hold the value entered by the user (this variable is called tmp in this example), and we need a variable which will hold the sum (which will be called sum in this example).
As you declared both as integer in your code, I'll do the same, so our new code becomes:

#include <iostream>

int main()
{
    int sum = 0;
    int tmp;
}

Please note that there's need to initialize variable sum to zero because otherwise it will contain a garbage value (these are usually incredibly big or incredibly low numbers).

Now that we've added variable definitions to our code, we can move on to the most interesting part: implementing the loop !

Implementing the loop:
As already mentioned earlier in this post, I'm going to demonstrate you how to do it using a do-while loop:

#include <iostream>

int main()
{
    int sum = 0;
    int tmp;
    
    do std::cout << "Enter a number: ";
    while( true );
}

The program as listed above is pretty much useless, because it creates a never ending loop, so we need to add conditions to the loop, in order to let it behave correctly.

Adding conditions to the do-while loop:
The first condition we will add is a condition which reads input from the user (yes you read that correctly), when the input is not a number, the loop will end automatically (because cin will refuse to store a string into an integer variable, technically this is even not possible, so this will immediately catch wrong user input)

#include <iostream>

int main()
{
    int sum = 0;
    int tmp;
    
    do std::cout << "Enter a number: ";
    while( std::cin >> tmp );
}

Now the program does already something more useful, but it still doesn't do what we want it to do, but we can already break out the loop by just entering some text on our keyboard, and pressing ENTER.
In the next step, we'll thankfully make use of the concept of short-circuiting the logical AND operator, to stop the loop when the user inputs -1:

#include <iostream>

int main()
{
    int sum = 0;
    int tmp;
    
    do std::cout << "Enter a number: ";
    while( std::cin >> tmp & tmp != -1 );
}

Now the program is already behaving pretty much like we want, but the program still doesn't do the main activity, where we intended to write it for: making the addition of the number entered on the keyboard, and the variable sum, we're going to do that right now:

#include <iostream>

int main()
{
    int sum = 0;
    int tmp;
    
    do std::cout << "Enter a number: ";
    while( std::cin >> tmp & tmp != -1 && (sum += tmp) );
}

In the above example, you can see that I've added another logical AND operation, with on it's right side the expression: (sum += tmp) .
I want to mention that this expression must be surrounded by parentheses because of the rules of precedence: the logical AND operator has a higher precedence than the += operator, if you wouldn't have surrounded sum += tmp by parentheses, the expression would become: [B][... && sum][/B] += tmp , and if you try compiling this, your compiler will start complaining about a left value, and he's right, because sum (and only sum) now is the logical AND's right operand, so there would be a lack of a left value (most of the times left values are variables), and because the += operator requires requires such a left value, you won't be able to compile this without adding parentheses.
(Now everything within the square brackets will be evaluated from left to right)

But ok, enough explanation for now, let's finish the whole program:

#include <iostream>

int main()
{
    int sum = 0;
    int tmp;
    
    do std::cout << "Enter a number: ";
    while( std::cin >> tmp & tmp != -1 && (sum += tmp) );
    
    std::cout << "Sum = " << sum << std::endl;
}

As you can see, I've added the last line, to make this program fulfill your wish: an instruction which prints out the result on your screen.

Author's note: I hope you've learnt something from this quite large post, and that you didn't skip over all my explanation and just took the code to finish your assignment.

For some reason, my numbers aren't adding in correctly and it's taking the -1 sentinel value and adding it into the total.

// worthless testing.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>

using std::cout;
using std::cin;
using std::endl;


int main()
{
int number = 0;
int total = 0;
do
{
	cout<<"Enter a number: ";
	cin>>number;
	total = total + number;
} while (number != -1);

cout<<"Total is:"<<total<<endl;
	return 0;
}

to answer the OP's question, here's why the total is being affected in a way that you don't think it should. Go through your loop and see what's happening sequentially:
1. tell the user to enter a number
2. get the number
3. add the number to the total (regardless of what it is)
4. exit if the number is -1

simple fix (that utilizes 99% of your original code ;) ) :

total = total + number; //change this to:

if(number != -1) //this
     total += number //with this

now here's what's happening:
1. tell the user to enter a number
2. get the number
3. add the number to the total if it's not -1
4. exit if the number is -1

hopefully that's helpful as well, while it pales to tux's thesis :P

there is another way of doing it (for completeness sake) with a conditional break inside of the loop, but can't say it's the preferred method:

do
{
	cout<<"Enter a number: ";
	cin>>number;

        if(number == -1)
                break;

	total = total + number;
} while (true);
commented: Yes, this post is also valuable in this thread :) +13

I wanted to provide the OP with two solutions:

  • The easy fix
  • The one in my "thesis" :P

He may choose the one he thinks that will suit him the best, personally I prefer the method described in my "thesis" (that's why I tried to describe it so thoroughly), but opinions differ, and under no circumstances I want to obligate him to follow way I did it, but of course he's completely free to choose what he wants :)

I just see that I've made a nasty typo in my "thesis": while( std::cin >> tmp & tmp != -1 && (sum += tmp) ); this has to be: while( std::cin >> tmp [B]&[/B]& tmp != -1 && (sum += tmp) ); of course.

(I made this typo once in the beginning, and because since then, I copied and modified the code snippets, the typo still exists in the final code)

What if the numeric input can contain negative values other than -1 such that sum becomes zero before the end of numeric input occurs?

[I'm not a fan of forcing "supercompression" at the expense of readability and/or correctness, as it sometimes happens to instigate.]

commented: Oh yes, good catch :) +13

@Dave
I too was thinking about this catch; later only I read your post.
The solution would be this:

do std::cout << "Enter a number: ";
    while( std::cin >> tmp && tmp != -1 && (1 || (sum += tmp)) );

but as you said, neither me is a fan of squeezing Line of Codes; so I would do my job like this:

int main()
{
    int sum = 0;
    int tmp;
    while(std::cout << "Enter a number: "&&std::cin >> tmp)
    {
        if (tmp==-1) break;
        sum+=tmp;
    
    }
    std::cout << "\rSum     =       "<< sum << std::endl;
}

@Tux:
Great Tutorial. I liked it when you covered short-circuit operators.

Hey Siddhant, you made a mistake according to the concept of short circuiting here:

The solution would be this:

do std::cout << "Enter a number: ";
    while( std::cin >> tmp && tmp != -1 && (1 || (sum += tmp)) );

The mistake is here: ([B]1[/B] || (sum += tmp)) .
Because 1 will always be evaluated to true, and because the logical OR operator || is a short circuit operator, the instruction (sum += tmp) will never be executed in this example, resulting in the fact that sum will always have the value 0 at the end of the program.

So the solution would be to simply swap the places of 1 and (sum += tmp), so that it becomes: ((sum += tmp) || 1) .

:)

True.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.