+ 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.
4 ответов
+ 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)
+ 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