Sum of 1 to N in C++
By: Grant Braught
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;
}
Archived Comments
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Calculating total based on the given quantity and price in C++
Sorting an array of Strings in C++
Matrix using nested for loops in C++
Compute the square root of the sum of the squares of an array in C++
Calculate average using Two-Dimensional Array in C++
Two-Dimensional Array Manipulation in C++
Compiling and Linking Multiple Source Files in C++
Escape Sequences for Nonprintable Characters in C++
Using the Built-in Arithmetic Types in C++