Programming

How to display factors of a number in C Program [Solved]

In this blog post, you learn how to find and C Program to display the factors of a number with a C Programming language with the given user input.

What is a factor of a number?

The Factor of a Number is a number that can be divisible by the original number evenly/precisely without any remainder, which is called a factor number.

Example:

4 divided by 2 gives 2,

6 divided by 3 gives 2.

Program to display factors of a number in C Programming Language

In this Program, we write a C Program to display the Factors of a Number with the given user input.

#include <stdio.h>

int main()
{
    int number;
    printf("Please enter a positive number: ");
    scanf("%d", &number);

    printf("The Factors of a given number %d are: \n", number);
    for (int i = 1; i <= number; i++)
    {
        if (number % i == 0)
        {
            printf("%d\n", i);
        }
    }
    return 0;
}

Output:

Please enter a positive number: 50

The Factors of a given number 50 are: 
1
2
5
10
25

The Step by step Explanation of factors of a number in the C Program:

This Program takes a number from user input and displays Factors of a Number.

The following Steps of the program execution:

    int number;
    printf("Please enter a positive number: ");
    scanf("%d", &number);
  • The variable “number” is declared as an integer as follows,
  • Then we asked the user to enter the positive integer using the “printf” function.
  • Following the function, “scanf” wait for the user to enter the value then the “number” variable stores the value we declared in the first step.
    printf("The Factors of a given number %d are: \n", number);
  • Then the “printf” function prints the string to the user about the Factors number that follows after this statement.
    for (int i = 1; i <= number; i++)
    {
        if (number % i == 0)
        {
            printf("%d\n", i);
        }
    }
  • This step “for loop” is initialized with the Integer “i” variable of value one and incremented on each loop till the number the user provided in step 3.
  • In this loop, using the “If” statement, we check the condition, the modulus of “number” with the “i” variable is zero is the Factors number because the modulus is the remainder of the division we don’t want the integer that has the remainder. 
  • In the if statement, we got only the factors number, then displayed the Factors of a number on the user’s screen using the print function with the “\n” newline character.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button