+ 1

How can I print the sum of even numbers from a user input ?

if a user inputs 10.how can I print the sum of even numbers from 1 to 10.

15th Oct 2017, 8:04 PM
Nkiruka
Nkiruka - avatar
4 Answers
+ 5
@luka I assume you meant to put the if statement inside the loop 😝. Otherwise your still adding odd numbers. Another way would be to make the for loop include even numbers only. for(int i = 2; i <= input; i += 2)
15th Oct 2017, 8:18 PM
Rrestoring faith
Rrestoring faith - avatar
+ 3
Or you can use math The sum of the first n even numbers = n * ( n + 1 ) If the user enters 10, half of these are odd numbers, so you divide it by 2. ( and round it down if you have to ) 5 * 6 = 30
15th Oct 2017, 8:29 PM
Dennis
Dennis - avatar