How do i write a program that computes the sum of all even numbers in a range forexample between 1 and 100

3 Years
Discussion Span
Last Post by TObannion

1) Open program to write code
2) Write code
3) Compile code
4) If you have errors fix them and go to step 3 else continue
5) Run code and make sure you get what you want else go to step 2


You "could" use std::accumulate (if permitted by your homework assignment) with 1 to 100 and pass it a function tell if it's even or not.

Edited by triumphost


For determining which numbers in the range are even, a modulus would work. As for std::accumulate,Most C++ courses now are using namespace std; I believe.
What is your code so far? if you don't post what you've tried, people tend to think you want them to do your homework for you.


I'll give you some hints as to how I would write this:
in main, declare an int sum variable initalized to 0, an int number variable initialized to 1, and an int limit variable initialized to 100.
use a while loop to continually iterate to limit, with a modulus operator inside to check if number is even.


then use a cout to print the sum.
I'm fairly new to C++ and I'm sure there are easier ways to do this, but I am guessing this is either at my level or earlier.

Hope I helped without giving too much away.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.