//This is a code that prints all the numbers below 1000 that are divisible by 3.
#include <iostream>
usingnamespace std;
void divide()
{
for (int i = 0; i <= 1000; i++)
{
if (i % 3 == 0)
{
cout << i << endl;
}
}
}
int main()
{
int num;
divide();
system("pause");
return 0;
}
You can simply count up from 3 in 3's to ensure your number is divisible by 3.
There are many different ways to sum digits:-
- pick the digits off one by one with %10 (modulo operation) followed by integer-dividing the number by 10 to move to the next;
or ...
- take a string representation and add up the integer equivalents of the individual characters;
or ...
etc.
#include <iostream>
#include <numeric>
#include <string>
usingnamespace std;
int sumDigits1( unsignedlonglong n ) // Recursive version using modulus and division (my preference)
{
return n ? sumDigits1( n / 10 ) + n % 10 : 0;
}
int sumDigits2( unsignedlonglong n ) // Non-recursive version using modulus and division (while loop)
{
int sum = 0;
while ( n )
{
sum += n % 10;
n /= 10;
}
return sum;
}
int sumDigits3( unsignedlonglong n ) // Non-recursive version using modulus and division (for loop)
{
int sum = 0;
for ( ; n; n /= 10 ) sum += n % 10;
return sum;
}
int sumDigits4( unsignedlonglong n ) // Via string characters
{
int sum = 0;
for ( char c : to_string( n ) ) sum += c - '0';
return sum;
}
int sumDigits5( unsignedlonglong n ) // Using std::accumulate()
{
string str = to_string( n );
return accumulate( str.begin(), str.end(), 0, []( int sum, char c ){ return sum + ( c - '0' ); } );
}
int main()
{
int n = 1234321;
cout << "Input n: "; cin >> n;
cout << sumDigits1( n ) << '\n';
cout << sumDigits2( n ) << '\n';
cout << sumDigits3( n ) << '\n';
cout << sumDigits4( n ) << '\n';
cout << sumDigits5( n ) << '\n';
}