C program to find all factors of a number

Write a C program to input a number from user and find all factors of the given number using for loop. How to find factors of a number in C program. Logic to find all factors of a given number in C programming.

Example

Input

Input number: 12

Output

Factors of 12: 1, 2, 3, 4, 6, 12

Required knowledge

Basic C programming, If else, For loop

What is factor of a number?

Factor of any number is a whole number which exactly divides the number into a whole number without leaving any remainder. For example: 2 is a factor of 6 because 2 divides 6 exactly leaving no remainder.

Logic to find all factors of a number

Step by step descriptive logic to find all factors of a number.

  1. Input number from user. Store it in some variable say num.
  2. Run a loop from 1 to num, increment 1 in each iteration. The loop structure should look like for(i=1; i<=num; i++).
  3. For each iteration inside loop check current counter loop variable i is a factor of num or not. To check factor we check divisibility of number by performing modulo division i.e. if(num % i == 0) then i is a factor of num.

    If i is a factor of num then print the value of i.

Learn more - Program to find all prime factors of a number.

Program to find factors of any number

/**
 * C program to print all factors of a number
 */

#include <stdio.h>

int main()
{
    int i, num;

    /* Input number from user */
    printf("Enter any number to find its factor: ");
    scanf("%d", &num);

    printf("All factors of %d are: \n", num);

    /* Iterate from 1 to num */
    for(i=1; i<=num; i++)
    {
        /* 
         * If num is exactly divisible by i
         * Then i is a factor of num
         */
        if(num % i == 0)
        {
            printf("%d, ",i);
        }
    }

    return 0;
}

Output

Enter any number to find its factors: 100

All factors of 100 are:
1, 2, 4, 5, 10, 20, 25, 50, 100,

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>