Sum Of Number

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Includes
#include "stdafx.h"
#include <iostream>
#include <conio.h>
#include <stdio.h>
using namespace std;

// Main Function
int main()
{
	int n = 0;		//counter
	int num;	//input: user enters number
	int sum = 0;	//output:  display sum of only positive numbers

	cout << "This program will add 1 to the number entered.\n\n";

	//start loop
	while (n != 1) 
	{
		cout << "\n\nEnter number: " << endl;
		cin >> num;

		if (num > 0) 
    	                sum += num;
		else 
    	              n++;

	        cout << "\n\nThe sum is: "<< sum << endl;
	}
	_getch();

	return 0;
}


My coding on this program is wrong, i know that, its not even doing what i want it too. I am trying to make a loop that allows the user to enter a number, and the program will add the number from 1- to the number entered. Example: if the user enters 5 it will add 1+2+3+4+5 and then stop after 5 because the usser entered 5. I need some help.
Last edited on
1
2
3
4
5
6
//step 1: Enter number > num.
//step 2: For/While index less than or equal to number entered. (goto 3)
//step 3: sum +=1(on first iteration)...
//            sum +=2(on second iteration)...
//            sum +=n(on nth iteration)...  see the pattern?
//step 4: until index is no longer less than or equal to number entered. 


Now put that into code

Good luck.
Last edited on
oh wow, i cant believe i didnt think of that first, thank you.
closed account (o1vk4iN6)
Or you can just do

sum = n * (n + 1) / 2;
Topic archived. No new replies allowed.