Programming Tutorials

Sum of 1 to N in C++

By: Grant Braught in C++ Tutorials on 2011-01-27  

This sample C++ program accepts a number and prints the sum of all numbers from 1 to the entered number.
#include <iostream>

// Prototype for SumToN function.
int SumToN(int);

// main function is always run first in a
// C++ program.

int main()
{	//Given:   nothing.
	//Results: Accepts a number and
	//		   writes out sum of all ints 1..num.

	int number;
	
	cout << "Enter an integer (>1): ";
	cin >> number;
	
	cout << "Sum of 1..Num = " << SumToN(number) << endl;
	
	// This is more convention than anything.
	return 0;
}

int SumToN(int number)
{	/* 
	Given:   number an integer > 0
	Returns: The sum of all the integers
			 between 1 and number.
	*/
	
	int i,total;
	
	total = 0;		// could use: int total = 0;
	
	for (i=1; i<=number; i++)
	{
		total = total + i;
	}

	return total;	
}
  





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in C++ )

Latest Articles (in C++)