An integer number is divisible by 9 if the sum of its digits is divisible by 9.

  1. Write a program that reads a positive integer, finds the number of digits of this integer and using the criteria above, discovers if it is divisible by 9 and then prints out the results.
    Example: if the user enters 57883
    The program displays :
    57883 has 5 digits.
    The sum of digits is : 31
    It is not divisible by 9
  2. Write a program that uses the criteria above to display all the positive integers between 100 and 1000 that are divisible by 9.

Difficulty level
Video recording
This exercise is mostly suitable for students
#include<stdio.h>
int main()
{
	int n, nbdigits, sum, copy;

   	 do{
        	printf("Enter n: ");
        	scanf("%d", &n);
    	}while(n<=0);
	
	copy = n;
	nbdigits = sum=0;
	while(copy)
	{
	    nbdigits++;
	    sum+=copy%10;
	    copy/=10;
	}
	
	printf("%d has %d digits.\n",n,nbdigits);
	printf("The sum of digits is : %d\n",sum);
	if(sum%9)
	    printf("It is not divisible by 9\n");
	else
	    printf("It is divisible by 9\n");
	    
	return 0;
}


#include<stdio.h>
int main()
{
	int n, nbdigits, sum, copy;

	for(n=100;n<=1000;n++)
    	{
	    nbdigits = sum=0;
	    copy = n;
	    while(copy)
	    {
	        nbdigits++;
	        sum+=copy%10;
	        copy/=10;
	    }

	    if(sum%9==0)
	        printf("%d ",n);
    	}
	    
	return 0;
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Sorting using heap-sort algorithm