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

JavaScript must be enabled for certain features to work
* Required information
1000

Comments

No comments yet. Be the first!
(追記) (追記ここまで)
(追記) (追記ここまで)

AltStyle によって変換されたページ (->オリジナル) /