Computing.Net > Forums > Programming > C++ Program Adding Even numbers

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

C++ Program Adding Even numbers

Reply to Message Icon

Name: jem52181
Date: October 1, 2007 at 17:56:17 Pacific
OS: Microsoft Windows XP Pro
CPU/Ram: PIV 2.00 GB
Product: OptiPlex GX280
Comment:

I have to write a code that adds all the even numbers from 1 to 40 except 4 and 10 using a FOR loop or a WHILE loop. This is what I have so far, but I can not figure out how to add them together or exclude 4 or 10.

#include <iostream>
using namespace std;

int main()
{
int i;
double sum = i + i++;

for(i=1; i<=40; i++) {
if(i%2 == 0)

cout << sum;
}

return 0;
}
James Miller



Sponsored Link
Ads by Google

Response Number 1
Name: Razor2.3
Date: October 1, 2007 at 18:32:22 Pacific
Reply:

Ah programming 101. How I miss it.

#include <iostream>

using namespace std;

int main(int argc, char *argv[]) {
int sum = 0;

for (int i = 2; i <= 40; i += 2)
if (i != 4 && i != 10) {
sum += i;
cout << i << ": " << sum << endl;
}

cout << "Grand total: " << sum << endl;
return 0;
}

Or, if you wanted to ignore the looping part of the exercise...

#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
int sum = (40 + 2) * 10 - (4 + 10);
cout << "Grand total: " << sum << endl;
return 0;
}


0
Reply to Message Icon

Related Posts

See More


Know how to edit programs... remove trailing char from...



Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Programming Forum Home


Sponsored links

Ads by Google


Results for: C++ Program Adding Even numbers

Help w/ Simple C Program www.computing.net/answers/programming/help-w-simple-c-program/7850.html

Need help in C program... www.computing.net/answers/programming/need-help-in-c-program/4193.html

C programming help www.computing.net/answers/programming/c-programming-help-/6364.html