Click here to Skip to main content
15,886,806 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have to calculate the sum of two-digit even numbers and i have done it but i want to find a shorter way possible to do it. If anyone can help.

What I have tried:

#include <iostream>
using namespace std;

int main(){
    int counter = 0, sum = 0;
    

   do{
   	
        if(counter != 0 && counter != 2 && counter != 4 &&counter != 6 && counter != 8){
            cout<<"\n" <<counter;
            sum += counter;
        }
    } while ((counter += 2) <= 50);
    cout<<"\n sum of even numbers:"<< sum;
    
    return 0;
}
Posted
Updated 7-Nov-17 15:04pm
Comments
Peter_in_2780 7-Nov-17 18:35pm    
start with
int counter = 10;
then throw out the "if"
Rick York 7-Nov-17 18:38pm    
Peter_in_2780 is on the right track. Also consider what the range of two-digit numbers is. Aren't there some beyond 50?

There is a formula for that, fo there is no need for a for loop but you can also do that (C# code though):
    int num = 50;
    int sum = 0;
    for (int i = 0; i < num+1; i += 2)
        sum += i;

    int sum2 = GetEvenSum(num);
}

static int GetEvenSum(int UpperNumber)
{
    if (UpperNumber % 2 != 0)
         UpperNumber -= 1;

    int HalfLimit = UpperNumber / 2;

    return HalfLimit * (1 + HalfLimit);
}
 
Share this answer
 
v2
Comments
Rick York 7-Nov-17 19:10pm    
I think it is best to let people do their own homework.
Quote:
i have done it but i want to find a shorter way possible to do it.

are you sure 2 digits numbers stops at 50 ?

You start counter at 0 and then do a test to remove 0, 2, 4, 6, 8.
You are lucky you were not requested to counter 4 digits even numbers!
Think about it, what is the reason why your counter starts ar 0 ?

You do ... while loop is a little complicated, why don't you use the syntax especially made for loops with counters ?

Have read on this, it can apply to your problem with a little adaptation.
1 + 2 + 3 + 4 + ⋯ - Wikipedia[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900