1

I am a newbie in C++ in my first little project is making me a headache.

If I understand the pbolem correctly, I need to cout the sum of the interval [a,b] which should mean: 17 + 18 + 19 + 20 + 21..... + 52 = ? (correct me if I am wrong!) I tried with while, do-while and they both ended up being an endless loop so now I am trying with for loop which gets me to just increasing the value of a until it reaches 52.

#include <iostream>

int main(int argc, char* argv[])
{
    const int a = 17;
    const int b = 52;

    int summe = 0;

  for(summe = a; summe <=b; summe++)

    std::cout << "Summe: " << summe << "\n";

   return 0;
}
1
  • You need two variables: one, the iterator variable, to count the number you're adding, and one to contain the sum so far. Commented Nov 13, 2014 at 16:41

2 Answers 2

6

Your code simply dumps the numbers you are expecting to sum, but you've forgotten to sum up them!

int main(int argc, char* argv[])
{
    const int a = 17;
    const int b = 52;

    int summe, number;

    for(summe = 0, number = a; number <= b; number++)
        summe += number;

    std::cout << "Summe: " << summe << "\n";

    return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

2

or, an easier way: no loops at all!

int a = 17;
int b = 52;
int sum = (a + b) * (b - a + 1) / 2.0

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.