Input Validation in for loop

// PROBLEM - Use INPUT VALIDATION so number entered is positive. I can't get it to work
#include <iostream>
#include <iomanip>
using namespace std;
int main(int argc, const char * argv[])
{
// SUM OF NUMBERS
// Enter a positive interger
int num;
int total;
cout << "Enter a number: " << endl;
cin >> num;

// Program should use a loop to get the sum of all intergers from 1 up to the number entered.
// Example, user enters 50, look will find sum of 1, 2,...50.

for(int i = num; i; i--)
{
cout << i << endl;
total += i; // Accumulate
cout << total << endl;
}
return 0;
}
Last edited on
You need to initialize total = 0;.
Otherwise it seems to work fine. I would perhaps put the cout << total << endl; outside of the loop, unless you wish to display the sum as it grows for every iteration of the loop.
The loop works, the problem is the INPUT VALIDATION. I shouldn't be able to use negative numbers. Do you suggest a while-loop?
Last edited on
Topic archived. No new replies allowed.