### Sum of numbers problem..

I got the last part correct and part of the beginning too but i can't get it completely correctly. The question asks "Write a program that asks the user for a positive integer value. The program should use a loop to get the sum of all the integers from 1 up to the number entered. For example, if the user enters 50, the loop will find the sum of 1,2,3,4.......50. input validation: Do not accept and input that is less than 1."

This is what I have so far, I've been trying to get it right on my own but i can't figure it out.

 ``12345678910111213141516171819202122232425262728293031`` ``````#include using namespace std; int main () { int sum = 0, input; cout << "Enter any positive integer.\n"; cin >> input; for (int num = 1; sum += num; num++) if (input > 1) { sum += num; num++; cout << "The sum of numbers 1 - " << input << " " << "is " << sum << endl; break; } else { cout << "\n" << input << " is negative number."; cout << " The program will now terminate.\n"; break; } return 0; } ``````
It's the middle argument in the for loop:
 ``123456789101112131415161718192021222324252627282930`` ``````#include using namespace std; int main () { int sum = 0, input; cout << "Enter any positive integer.\n"; cin >> input; for (int num = 1; num <= input; num++) if (input > 1) { sum += num; num++; cout << "The sum of numbers 1 - " << input << " " << "is " << sum << endl; break; } else { cout << "\n" << input << " is negative number."; cout << " The program will now terminate.\n"; break; } return 0; }``````
I figured out the problem, but now i can't figure out how to validate input. Any help will be much appreciated.
 ``1234567891011121314151617181920212223242526272829303132`` ``````#include using namespace std; int main () { int sum = 0; int num; cout << "Enter a number greater than 0.\n"; cin >> num; for (int counter = 0; counter <= num; counter++) { sum = sum + num; counter++; } cout << "The sum of numbers 1 - " << num << " " << "is " << sum << endl; if (num < 1) //Here is where i am messing up. (I think) { cout << "\n" << num << " is an invalid input."; cout << " The program will now terminate.\n"; } return 0; }``````
Last edited on
Nevermind somehow i made it work... Was there an easier way to do this?

 ``123456789101112131415161718192021222324252627282930313233343536373839`` ``````#include using namespace std; int main () { int sum = 0; int num; cout << "Enter a number greater than 0.\n"; cin >> num; for (int counter = 0; counter <= num; counter++) { sum = sum + num; counter++; } if (num < 1) { cout << "\n" << num << " is an invalid input."; cout << " The program will now terminate.\n"; } else cout << "\nThe sum of numbers 1 - " << num << " " << "is " << sum << endl; return 0; }``````
Topic archived. No new replies allowed.