Tuesday, 26 August 2014

Filled Under: ,

C program to Display Factors of a Number

Share
C program to Display Factors of a Number : This program takes a positive integer from an user and displays all the factors of that number.


C program to Display Factors of a Number


C program to Display Factors of a Number



#include <stdio.h>
int main()
{
  int n,i;
  printf("Enter a positive integer: ");
  scanf("%d",&n);
  printf("Factors of %d are: ", n);
  for(i=1;i<=n;++i)
  {
      if(n%i==0)
         printf("%d ",i);
  }
  return 0;
}



Output

Enter a positive integer:50
Factors of 50 are: 2 5 5

Explanation

In this program, an integer entered by user is stored in variable n. Then, for loop is executed with initial condition i=1 and checked whether n is perfectly divisible by i or not. If n is perfectly divisible by i then, i will be the factor of n. In each iteration, the value of i is updated(increased by 1). This process goes not until test condition i<=n becomes false,i.e., this program checks whether number entered by user is perfectly divisible by all numbers from 1 to n and all displays factors of that number.