Sum of 1 to N in C++

By: Grant Braught Viewed: 169 times  Printer Friendly Format    


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

// 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;	
}
  


Most Viewed Articles (in C++ )

Latest Articles (in C++)

Comment on this tutorial