I'm having trouble with a code I need to produce which requires me to get the sum of numbers from 1 to 5, then 1 to 500, then 1 to 4000, then 1 to 22. And if the user inputs a negative number then the output will say "Hey, I said positive". When I run the code the output should be:
Enter a positive, non-zero integer
Sum of numbers from 1 to 5 is //the 5 will change to the above numbers.
Here is what I have so far: Please, any help will be appreciated. Thx!
#include <iostream>
using namespace std;
int main()
{
float x;
int sum = 0, val = 1;
while (val <= 5)
{
sum += val;
++val;
}
cout << "Enter a positive, non-zero integer" << endl;
cout << "Sum of numbers from 1 to 5 is " << sum << endl;
Only once per problem Butch. That's the game. Posting the same problem more than once wastes people's time and effort especially when you can't or won't take the advice.
#include <iostream>
usingnamespace std;
int main()
{
float x; // What is the purpose of this variable?
int sum = 0, val = 1;
cout << "Enter a positive, non-zero integer" << endl;
//User inputs a non-zero integer.
// Use validation to verify the number is not negative. What can you use to validate the user input?
while (val <= 5) // Is there a way to subtitute 5 for any value the user wants to input in the console?
{
sum += val;
++val;
}
cout << "Sum of numbers from 1 to 5 is " << sum << endl;
return 0;
}
@pearlyman I don't think that piece of code is going to help anyone, much less the @OP. It doesn't teach him how to make flexible code (and by flexible I mean dependent on user input, not flexible as in portable).
Also @OP you could basically take @chicofeo's code and run it as your own. A small improvement, aside from putting in user validation (I recommend unsignedint or size_t), is that you can make the lines of
1 2
sum += val;
++val;
into
sum += val++;
This is where postfix incrementing comes into play. Basically you're telling your program to return value, wherever it's at, add it to sum, THEN increment it. Try it out and see what it does compared to when you write sum += ++val;.
@pearlyman I don't think that piece of code is going to help anyone, much less the @OP. It doesn't teach him how to make flexible code (and by flexible I mean dependent on user input, not flexible as in portable).
Address the OP and not criticize the good faith efforts of other contributors please.