Please solve this problem: Is a given number divisible by 3?
In your group or as a class, come up with an algorithm or several algorithms to solve this problem. After deciding on a single algorithm, write the necessary C code to solve the problem. Some questions that you might need to think about include the following: How will the number be entered? How will you display the answer to the question above? What numbers will you allow to be entered?
Re-write the problem formally, specifying the input and the output.
Note: When writing the C code to solve the problem, be sure to
include comments so that a reader of your code can understand how you're
solving the problem.
Divide the number by 3 and check to see if the remainder is 0. If the remainder is 0, then print "Divisible by 3". If the remainder is not equal to 0, then print "Not Divisible by 3".
Add up the integers of the number. See if this total is divisible
by 3 by dividing the number and checking the remainder.
(Example: 12435 -> total of integers is 1 + 2 + 4
+ 3 + 5 = 15 -> 15 divided by 3 is equal to 5 remainder 0, so 12435
is divisible by 3)
(Note: This algorithm would need a loop to implement in C, so
the students should write C code for the simpler algorithm described above.)
Possible C code:
/* read a number and report whether it is or is not divisible by
3 */
#include <stdio.h>
int main(void){
int num;
/* input number by user */
int rem;
/* remainder after division by 3 */
/* get number from user and store into num */
printf("Please enter a number: ");
scanf("%d", &num);
/* calculate remainder and report whether it
is or is not divisible by 3 */
rem = num % 3;
if (rem == 0){
printf("Is divisible
by 3\n");
}
else{
printf("Is NOT divisible
by 3\n");
}
/* terminate program */
return 0;
}