@lastchance: You could have added rationale for the "exactly 21".
"sum of digits is divisible by 7" means that the sum is 7, 14, 21, 28, 35, ...
(I think that 0 should be omitted in this case.)
Of "numbers upto 1000" the 999 yields the largest sum of digits: 27.
"number itself is divisible by 3" has interesting property: its sum of digits is divisible by 3.
Therefore, only the 21 can be a sum digits of a number that is divisible by 3.
There are two approaches:
1. Brute force; test every number "upto 1000"
2. Use math; you need to test only the numbers that are divisible by 3 (like
tpb suggested) and you can start from the smallest number that has digit sum of 21 (do you know what that is?)
Either way, you need to know how to
test "is divisible", you have to
count the numbers that match and you have to know how to use loops. Using a function is a bonus.
You did try:
1 2 3 4 5 6 7
|
for (int i = 0; i < 1000; i++)
{
if (i / 7)
{
cout << i;
}
}
|
There is a loop. Good.
It checks 1000 different numbers. Close. You check 0, but you don't check 1000.
"upto 1000" includes the 1000, does it not?
You test only one thing
i / 7
. What do we know about integer division?
IF i < 7
THEN i / 7 == 0 and 0 is false
ELSE i / 7 > 0 and that is true |
In other words, your program does same as:
1 2 3 4
|
for (int i = 7; i < 1000; i++)
{
cout << i;
}
|
That is in no way
"test if x is divisible by y".
Furthermore, you had no attempt to "count the matches".