Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C++ Example - Sum of Natural Numbers

C++ Example - Sum of Natural Numbers

C++ Example C++ Example

Calculate the sum 1+2+3+....+n.

Example

include

<

iostream

using

namespace

std

;

int

main

(

)

{

int

n

,

sum

=

0

;

cout

<<

"

Enter a positive integer:

"

;

cin

n

;

for

(

int

i

=

1

;

i

<=

n

; ++

i

)

{

sum

+=

i

;

}

cout

<<

"

Sum =

"

<<

sum

;

return

0

;

}

The output of the above program is:



输入一个正整数: 50

Sum = 1275

C++ Example C++ Example