i have to create a code that will take the sum of the numbers between 0 and any number. example 0 to 5 = 15. my code is saying that i is not initialized.
#include <iostream>
usingnamespace std;
int main()
{
int num = 1;
int val;
int sum;
cout << "Enter an integer: ";
cin >> val;
while(val != 0)
{
int i = num, i <= val, ++i;
cout << "The sum from 0 to " << val << " is " << sum;
sum += ++i;
}
cout << sum << endl;
cout << "Goodbye! " << endl;
return 0;
}
#include <iostream>
usingnamespace std;
int main()
{
int val;
int sum = 0;
int i = 1;
cout << "Enter an integer: ";
cin >> val;
while(val != 0)
{
sum += ++i;
cout << "The sum from 0 to " << val << " is " << sum;
cout << sum << endl;
}
cout << "Goodbye!" << endl;
return 0;
}
#include <iostream>
int main()
{
std::cout << "Enter an integer: ";
int val = 0;
std::cin >> val;
int sum = 0;
int i = 0;
while( ??? ) // hint: there's a variable which stores a value that is
{ // supposed to grow up to the one given by the user
sum += i++;
std::cout << "The sum from 0 to " << i << " is " << sum << '\n';
}
std::cout << "Goodbye!\n";
return 0;
}
SO now it does the math right. it just displays all the values. example
The sum from 0 to 5 is 1
The sum from 0 to 5 is 3
The sum from 0 to 5 is 6
The sum from 0 to 5 is 10
The sum from 0 to 5 is 15.
when its only suppose to display the last line for the value 15. and the program doesnt exit and it just stays open
#include <iostream>
usingnamespace std;
int main()
{
int val;
int sum = 0;
int i = 1;
cout << "Enter an integer: ";
cin >> val;
while(val != 0)
{
while(i <= val)
{
sum = sum + i;
i++;
cout << "The sum from 0 to " << val << " is " << sum << endl;
}
}
cout << "Goodbye!" << endl;
return 0;
}
So I only changed two things from your most recent code(see bold text). I changed your outer while to an if then just pulled your cout, outside the while loop. If the cout is inside the loop it'll print every time the while loop is executed, if its outside it'll print just once while still using the data gathered from the while loop itself. I hope I am explaining this well, and I hope this helps!
#include <iostream>
usingnamespace std;
int main()
{
int val;
int sum = 0;
int i = 1;
cout << "Enter an integer: ";
cin >> val;
if (val != 0)
{
while (i <= val)
{
sum = sum + i;
i++;
}
}
cout << "The sum from 0 to " << val << " is " << sum << endl;
cout << "Goodbye!" << endl;
return 0;
}