How do you write a programme that prints the sum of all the multiples of 3 or 5 below 1000 in c plus plus?

1 answer

Answer

1239022

2026-10-15 09:30

+ Follow

First work out the algorithm for what you want to do and then encode that using the C++ language.

Alternative Answer

In this case, the algorithm will consist of a loop that counts from 1 to 1000, testing each value to see if it can be divided by 3 or 5 without leaving a remainder. If so, it gets added to a running total. When the loop ends, the running total is the final answer.

To determine a remainder in C++, we use the modulo operator (%). That is; 9%5 is 4 because 9 divided by 5 is 1 remainder 4, whereas 9%3 is zero. Therefore if either operation evaluates to zero, the value can be added to the running total.

int DoSum( void )

{

int total=0;

for(int x=1; x<1000; ++x)

if( !(x%3) !(x%5) )

total+=x;

return(total);

}

An alternative (and more efficient) algorithm will perform the same loop twice, first in steps of 3 and then in steps of 5. Since we're no longer testing for invalid values, we simply sum every value.

int DoSum( void )

{

int total=0;

for(int y=0; y<2; ++y)

{

int step=y?5:3; // if y is 0, step is 3, otherwise step is 5

for(int x=step; x<1000; x+=step)

total+=x;

}

return(total);

}

ReportLike(0)ShareFavorite

Copyright © 2026 eLLeNow.com All Rights Reserved.