Answer to Question #278793 in C++ for Ralph

Question #278793

Write the program that will compute for and display the sum of all numbers divisible by 3 from 1 to 1000.


1
Expert's answer
2021-12-12T12:19:15-0500
#include <iostream>
using namespace std;

int main()
{
    int sum = 0;
    
    // simple approach: traverse all numbers from 1 to 1000
    // and check if current number is divisible by 3
    for (int i = 1; i <= 1000; i++) {
        if (i % 3 == 0) {
            sum += i;
        }
    }
    cout << sum << endl;

    // another approach: we know that having a
    // number divisible by 3, we can find the next
    // number by adding 3 to the current.
    // The first divisible number is 3
    sum = 0;
    for (int i = 3; i <= 1000; i += 3) {
        // no need to check, we only jump on divisible numbers
        sum += i;
    }
    cout << sum << endl;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog