An integer n is divisible by 9 if the sum of its digits is d
An integer n is divisible by 9 if the sum of its digits is divisible by 9. Develop a program that uses this method to determine whether or not a number is divisible by 9. Test it on the following numbers: n = 154368 n = 621594 n = 123456 Use the % operator to get each digit; then use/to remove that digit. So, 154368 % 10 gives 8 and 154368/10 gives 15436. The next digit extracted should be 6, then 3 and so on. On the next page is a screen shot of a working solution with the loops missing. After you write your loops and get the program running, you can test it by hitting run, then hitting the halt button. Examine memory at PORT B to see if it worked. PORT B is at address 01 in the memory window. Starter code for Program 3a://your name//Programming Assignment 3a #include /* common defines and macros * #include \"derivative. h\"/* derivative-specific definitions * void main(void) {long number = 153368; unsigned char i. sum = 0; unsigned char digits [6]; DDRB = 0xFF;//make PORTB an output//write a for loop to store the digits in the array//write a while loop to add up all the digits//ver. could have done this in the first loop, but we\'re practicing//check if divisible by 9 if (sum % 9 = = 0) PORTB = 1; else PORTB = 0. while(1);}
Solution
Here is the code for you:
// Your name
// Programming Assignment 3a
#include <hidef.h> /*Common defines and macros*/
#include \"derivative.h\" /*Derivative-specific definitions*/
int main()
{
long int number = 153368;
unsigned int i, sum = 0;
unsigned int digits[6];
DDRB = 0xFF; //Make PORTB an output.
//Write a for loop to store the digits in the array.
for(int i = 0; i < 6; i++) //This loop runs for 6 times.
{
digits[i] = number % 10;
number /= 10;
}
//Write a while loop to add up all the digits.
//We could have done this in the first loop, but we\'re practicing!
i = 0;
while(i < 6)
{
sum += digits[i];
i++;
}
//Check if divisible by 9.
if(sum % 9 == 0)
PORTB = 1;
else
PORTB = 0;
}
