for Loops- need help

Jun 20, 2014 at 12:00am
Hello. I am taking a beginning C++ class and the teacher is terrible (really. I'm not just saying that.) He wants us to write programs based on material we have not covered. Anyway, I am having trouble with an assignment. Here are the instructions:
**************************************************
Write a program that accepts an integer input from the keyboard and computes the sum of all the integers from 1 to that integer. Example, if 7 were input, the sum: 1 + 2 + 3 + 4 + 5 + 6 + 7 would be computed. Use a while or for loop to perform the calculations. Print out the result after the sum has been calculated. NOTE: if you input a large integer, you will not get the correct results.
**************************************************

My code to //declare and initialize variables is:

float n, i;
cout < "Enter an integer: ";
cin >> n;

My code to print out the integers from 1 to n is:

for (i = 1; i <=n; i++)

What I can't figure out is how to ADD all of the integers together. Any help would be greatly appreciated.
Last edited on Jun 20, 2014 at 12:10am
Jun 20, 2014 at 12:16am
You can add a variable for the total. In the same for loop you can increment each value of i into the total. Make sure you initialize the total variable to 0.

Looks like all the numbers involved are integers, so I'd give them an int type, not float.
Jun 20, 2014 at 1:03am
@wildblue

I still don't know how to put that into code. This is only our second week. This is what I have so far:

//preprocessor directives


int main ()
{
//declare and initialize variables

int n, i;
int total;


//user input

cout << "Enter an integer: ";
cin >> n;


//compute sum of all integers from 1 to n
total=0;

for (i = 1; i <= n; i++)
cout << i;


return 0;
}
Jun 20, 2014 at 1:13am
Each time you go through the loop, you want to add the current value of i to total.

total = total + i or total += i
Jun 20, 2014 at 1:22am
@wildblue- thank you:) it's working.
Topic archived. No new replies allowed.