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.
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.