1. You declare all your variables on line 3. That is not inside any function. These are
global variables. This program does not need global variables. Most don't.
First thing, make the variables local:
1 2 3 4 5 6 7
|
#include <iostream>
int main()
{
int base = 1, uno, dos, tres, sum, temp;
std::cout << "Please input an integer greater than or equal to 1: ";
std::cin >> uno;
|
By now we know that base==1 and that uno has whatever value did the user give.
We do not know the value of dos, tres, sum, or temp.
That is now my fault. When they were global, they were all set 0. As local, they are not. I'll fix that:
1 2 3
|
int main()
{
int base = 1, uno {}, dos {}, tres {}, sum {}, temp {};
|
int uno {};
and
int uno = 0;
happen to mean the same.
Wait! What are the dos and tres? They are not used anywhere. If you don't need a variable, then don't have it at all:
1 2 3
|
int main()
{
int base = 1, uno {}, sum {}, temp {};
|
Now we get to the loop. On first time the base==1. Lets assume that uno is at least 1. For example 3.
Thus, on first iteration:
1 2 3
|
sum = base + temp; // sum = 1 + 0, sum=1
base = sum; // base = 1
base = temp; // base = 0
|
Furthermore, the
base++
executes too, so base becomes 1.
Second iteration. The 1 is still less than 3. Lets compute the body again:
1 2 3
|
sum = base + temp; // sum = 1 + 0, sum=1
base = sum; // base = 1
base = temp; // base = 0
|
Obviously, the
base++
executes too, so base becomes 1 (again).
Third iteration. The 1 is still less than 3.
I have an eerie feeling. How about you?
Edit:
Lets try something related:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
#include <iostream>
int main()
{
int uno {};
std::cout << "Please input an integer greater than or equal to 1: ";
std::cin >> uno;
int sum {};
// at this point the sum==0 as it should, for we have added nothing yet
for ( int base = 1; base <= uno; ++base )
{
std::cout << "I should add " << base << " to the sum\n";
}
std::cout << "Total " << sum << '\n'; // this will show 0, for we didn't add anything
return 0;
}
|
That program should show something like:
Please input an integer greater than or equal to 1:
4
I should add 1 to the sum
I should add 2 to the sum
I should add 3 to the sum
I should add 4 to the sum
Total 0 |
Would adding the value of
base
to the
sum
be the right thing to do?