In: Computer Science
C language and it has to be a while loop or a for loop.
Use simple short comments to walk through your code.
Use indentations to make your code visibly clear and easy to
follow.
Make the output display of your program visually appealing.
There is 10 points deduction for not following proper submission
structure.
An integer n is divisible by 9 if the sum of its digits is divisible by 9. Develop a program that:
Would read an input from the keyboard. The input should be a
whole positive number.
Then display each digit, starting with the rightmost digit.
At last decide if the number if divisible by 9 or not.
Calculate and display the sum of the digits.
Display whether the input number is divisible by 9 or not. (
Hint: You would need to write a loop that extracts each digit in the number. Use the % operator to get each digit; then use / to remove that digit.
As an example: 154368 % 10 gives 8 and 154368 / 10 gives 15436. The next digit extracted should be 6, then 3 and so on.
Test your program on the following numbers:
n = 154368
n = 621594
n = 123456
Code:
#include<stdio.h>
int main(){
int n, digit, sum = 0;//variable declaration and
initialization
printf("Enter a number: ");//prompt the user to enter a
number
scanf("%d", &n);//take input and store in variable n
printf("Digits are:");//a dialog saying digits are:
//The following while loop executes when n>0
while(n > 0){
digit = n%10;// n%10 is done to extract the last digit of n and is
stored in digit variable
n = n/10;// n/10 is dont to remove the last digit from n and store
the remaining value in n
printf("%d\t", digit);//prints the digit
sum += digit;// adds the digit to the sum and store the total in
sum variable.
}
//checkis if sum of digits is divisible by 9
if(sum % 9 == 0){
printf("\nThe given number is divisible by 9.\n");//if sum is
divisible by 9, this line is executed
}
//if the sum of digits is not divisible by9, the following is
executed.
else{
printf("\nThe given number is not divisible by 9.\n");
}
}
Code in the image:
Output: