Pages

Saturday

Program to Print all the Divisors of a Given Number | C Program

Here’s a C program to print all the divisors of a given number with output and proper explanation. This program uses for loop. 


# include <stdio.h> 
# include <conio.h>
void main() 
{ 
 int i, n ; 
 clrscr() ; 
 printf("Enter the number : ") ; 
 scanf("%d", &n) ; 
 printf("\nThe divisors are :\n\n") ; 
 for(i = 1 ; i <= n ; i++) 
  if(n % i == 0) 
   printf("%d\t", i) ; 
 getch() ; 
}


Output of above program

Enter the number : 21

The divisors are : 1 3 7 21


Explanation of above program 

The integer variable n is the number whose divisors are being calculated and i is the loop variable. 

First, we ask the user to enter a number. Inside the loop, we are checking if the number n is divisible by the current loop variable (i) i.e. if n % i == 0 then we print the value of i but if the number n is not divisible by the current loop variable then the loop will continue with other values until the loop is terminated. In this way all the divisors are calculated. 

Tip: To understand the program you can also take different values of n and try the above process yourself. It will help you to understand the process  much clearly and helps in improving your debugging ability. 
 Also look at:  Program to Find out Multiples of a Given Number.

1 comment:

  1. Hi There,


    Interesting piece! Great to see someone write Program to Print all who is not a fanatic or a complete skeptic.

    How can I access a database ( in Mysql platform, Ubntu, Linux ) using C language ( in gcc platform, Ubuntu, Linux ). I want to add , delete, update any record in any moment using C.


    Once again thanks for your tutorial.


    Kind Regards,
    Cavin

    ReplyDelete