Sum of range:

For of my course I programmed a very interesting program to understand the use of “for” loops, and to understand the increment operators and compound assignment operators:

 

The program sums every number in a range given by the user.

 

Lets say the user gave 1 as the first number and 10 as the second number. The program would do the following:

 

0+1+2+3+4+5+6+7+8+9+10=55

 

The program also compares the first and the last numbers and makes reacomodates the first below the last so that the range is correctly calculated.

 

I´ll post a picture of my code.

 

Here notice im using a “For” loop.

First i assing “counter” the value of “first”. This only happens when the loop initializes. Then, For “Counter” is less or equal than “last”, counter is incremented by one. And if the conditional is true, the code inside the loop runs.

 

Sum += counter

 

Which can also be written as: Sum = Sum + counter.

 

When the conditional is no longer true, the program exits the loop and prints the value of “sum”.

 

here it is how it looks on the terminal.

 

Cheers.

 

CC BY 4.0 Sum of range: by Rodrigo Hernández is licensed under a Creative Commons Attribution 4.0 International License.

Comments are closed.