Ive got a assignment that requires us to do multiple things with two user inputted integers. I'm a little stuck on the third part and was wondering if anyone could look over that part of the code. The point of the code is to show the sum of the integers between the inputted integers. I dont want someone to re do it but instead point me in the right direction. thanks. (also please excuse my use of { and } its just to get me into the flow of using them.)
1 2 3 4 5 6 7 8
sumOfVar = 0;
while(int x=firstVar + 1; x< secondVar; x++)
{
sumOfVar += x;
}
cout << endl
<<"Part C:" << endl
<<"The sum of the integers between " << firstVar << " and " << secondVar << " are: " << sumOfVar <<endl;
Please excuse my use of { and } its just to get me into the flow of using them.
There's nothing wrong with using braces.
A for-loop is the best choice for this problem. You have written the proper for-loop, except that you mistakenly used the word while instead of for.
1 2 3 4
for(int x = firstVar + 1; x < secondVar; ++x)
{
sumOfVar += x;
}
The equivalent while loop is longer and more error-prone:
1 2 3 4 5 6
int x = firstVar + 1;
while (x < secondVar)
{
sumOfVar += x;
x++;
};
A do-while loop is not suitable for this problem. We could make it work, but it would be silly.
I do have two stylistic suggestions for you:
First, indent your code. This makes your program easier to understand and change for the same reasons that a bulleted outline is easier to understand and change than a single large textwall.
Second, don't use noise words when naming things: you need not put "var" in the name of every variable you create.
adding just a little more: with some supporting code and creativity, every loop type can do every loop in c++.
your choice is really just which one fits better.
int x;
... code
x = 0;
while(x!= 0)
cin >> x;
is messy.
do-while eliminates the x=0 stray statement:
do
cin >> x;
while (x!= 0)
rather than set it to a default that forces the condition, you read it first and then check the condition after here, see?