Sunday, March 16, 2014

Factors of a Number


Here is a simple program to get the factors of a given number. A for loop (nested in while) is used which divides number with each number from 2 to that number, and it breaks when the remainder is zero. While loop just divides the number with the factor to get new number for next factor and the process goes on till end.                                                                                                                        

#include <iostream.h>

#include <conio.h>

void main()

 {

  int num, fact, rem;

  cout<< "                  *************    Factors     *************\n\n";

  cout<< "Enter the number:  ";

  cin>>num;                                  //entering the number

  cout<< endl<< "Factors are:  ";

  while (num>=1)

   {

    for (fact=2;fact<=num;fact++)

     {

      rem=num%fact;

      if (rem==0)

       {

        cout<< fact<< "  ";                 //here we get the factor when remainder is 0

        break;

       }

     }

    num=num/fact;                          //reducing the number

   }

getch();

 }

Widgets

 

Copyright @ 2014 CPP Fuzz.