hi, im kinda new to c++ and well programming languages all together as this is my first to learn and only just started learning about 2 days ago.
I started to create some source code in which its aim is to do a sum of equation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
int main()
{
int sum = 0, val = 1, eval = 2, sval= 3;
std::cout << "please enter a start value" << std::endl;
std::cin >> sval;
std::cout << "please enter a end value" << std::endl;
std::cin >> eval;
while (sval <= eval) //keep executing code as long as the val less than or equal to eval
{
sum += sval; // assigns sum + value to sum, so it would split like 1+2 = 3, 3+3 = 6 , 6+4 = 10.
++sval; // this means it has to add 1 to the value after each equation.
}
std::cout << "the sum of " << sval << " to " << eval << " inclusive is " << sum << std::endl;
std::cin.ignore();
std::cin.get();
return 0;
}
however when the console prints the line of "the sum of sval to eval inclusive is" it always adds 1 extra to the value of sval, i can see what the problem is just i dont know how to fix it.
i tried creating a new variable of val and making it equal to sval towards the start of the code and replace sval with val in out put of "the sum...", dont ask why i tried, it i knew it was dumb when i did it, and well, it didnt work aha.
#include <iostream>
int main()
{
int sum = 0, val = 1, eval = 2, sval= 3;
std::cout << "please enter a start value" << std::endl;
std::cin >> sval;
std::cout << "please enter a end value" << std::endl;
std::cin >> eval;
while (sval <= eval) //keep executing code as long as the val less than or equal to eval
{
sum += sval; // assigns sum + value to sum, so it would split like 1+2 = 3, 3+3 = 6 , 6+4 = 10.
++sval; // this means it has to add 1 to the value after each equation.
}
std::cout << "the sum of " <<sum << " to " << eval << " inclusive is " << sum+eval << std::endl;
std::cin.ignore();
std::cin.get();
return 0;
}
Hi @aizlewood40,
The "exit" condition of
your while loop
is that sval must be greater than eval, so the problem it's obvious,
then you can try your first idea;
i tried creating a new variable of val and making it equal to sval towards the start of the code and replace sval with val in out put of "the sum..."
But don't forget
making it equal to sval
val=sval; and
include it in the output statement: "the sum..."
std::cout << "the sum of " << val << " to " << eval << " inclusive is " << sum << std::endl;
or you can use val as an iterator value
1 2 3 4 5
while(val<=eval){
//task
++val;
}
then:
std::cout << "the sum of " << sval << " to " << eval << " inclusive is " << sum << std::endl;