PLAY WITH CODING

Home Basic Program If & Else Loops Conversion Pattern logo

Program Based on Loops

Program to print all factors of a number

Input - Output

Input
Enter a number : 8

Output
Factor of 8 are : 1,2,4,8

Input
Enter a number : 15

Output
Factor of 15 are : 1,3,5,15

Algorithm

Step 1: START

Step 2: Enter a number 'num' as input.

Step 3: Start a loop: for(int i=1;i<=num;++i)

  if num % i==0;

  print i;

Step 4:end of loop

step 5: End

CODE


/* Print all factors of a number */

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


/* Print all factors of a number */

#include<iostream>
using namespace std;
int main()
{
      int num;
      cout<<" Enter the number : ";
      cin>>num;
      cout<<" Factors of "<<num<<" are : ";
      for(int i=1;i<=num;++i)
    {
       if(num % i == 0)
        cout<<" "<<i;
    }
    return 0;
}

OutPut

Enter a number : 8

Factor of 8 are : 1,2,4,8