
Brandon T. answered 10/27/21
Experienced Computer Science Tutor
You will be using the modulus operator '%' which will divide one number by another number and return the remainder. If a number mod 3 has a remainder of 0 than it is divisible by 3, if that same number mod 5 has a remainder of 0 then it is also divisible by 5.
We will use conditional statements to check if a number is divisible by 3, 5, both, or none.
1) divisible by 3: (x mod 3 equals 0) and (x mod 5 does not equal 0)
2) divisible by 5: (x mod 5 equals 0) and (x mod 3 does not equal 0)
3) divisible by both: (x mod 3 equals 0) and (x mod 5 also equals 0)
4) any case that is not the 3 listed above
The code will look like this:
for (int i = 1; i < 100; i++) {
if (i % 3 == 0 && i % 5 != 0) {
cout << 'D3';
} else if (i % 5 == 0 && i % 3 != 0) {
cout << 'D5';
} else if (i % 5 == 0 && i % 3 == 0) {
cout << 'D3&5';
} else {
cout << i;
}
}