C Program to Display Factors of a Number

Created with Sketch.

Displaying Factors of a Number in C

Introduction

In this blog post, we will explore the concept of factors of a number and demonstrate how to write a C program to display the factors of a given number. We’ll cover the definition of factors, provide an algorithm to find factors, and present C code examples with outputs.

Factors of a Number

Factors of a number are the positive integers that divide the given number exactly without leaving a remainder. For example, the factors of 12 are 1, 2, 3, 4, 6, and 12. Factors always include 1 and the number itself.

Algorithm to Display Factors of a Number

To display the factors of a number:

  1. Take an input number num.
  2. Iterate from 1 to num.
  3. Check if each number in the iteration divides num without a remainder.
  4. If yes, it’s a factor, and display it.

C Program for Displaying Factors of a Number

#include <stdio.h>

void displayFactors(int num) {
    printf("Factors of %d are: ", num);

    for (int i = 1; i <= num; ++i) {
        if (num % i == 0) {
            printf("%d ", i);
        }
    }

    printf("\n");
}

int main() {
    int num;

    // Input: Get the number from the user
    printf("Enter a number: ");
    scanf("%d", &num);

    // Display factors
    displayFactors(num);

    return 0;
}

Output Example

Input: 12

Enter a number: 12
Factors of 12 are: 1 2 3 4 6 12

Input: 20

 
Enter a number: 20
Factors of 20 are: 1 2 4 5 10 20

Input: 7

 
Enter a number: 7
Factors of 7 are: 1 7

Conclusion

In this blog post, we discussed the concept of factors of a number and provided a C program to display the factors of a given number. The algorithm involves iterating through numbers and checking for divisibility. The C code examples demonstrated how to implement this algorithm and obtain the factors of different numbers.

Understanding factors is fundamental in various mathematical and programming contexts. Displaying factors of a number is a common task in coding interviews and competitive programming, making this knowledge valuable for programmers. Feel free to use the provided C program as a reference or incorporate it into your own projects.

Leave a Reply

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