C Program to Display Factors of a Number

Here is a C program that displays the factors of a given number:

#include <stdio.h>

int main() {
    int number;
    
    // Prompt the user to enter a number
    printf("Enter a positive integer: ");
    scanf("%d", &number);
    
    if (number <= 0) {
        printf("Please enter a positive integer.\n");
    } else {
        printf("Factors of %d are: ", number);
        
        // Iterate from 1 to the number and check for factors
        for (int i = 1; i <= number; i++) {
            if (number % i == 0) {
                printf("%d ", i);
            }
        }
        
        printf("\n");
    }
    
    return 0;

This program first asks the user to enter a positive integer. It then checks if the entered number is greater than 0. If it's not, it asks the user to enter a positive integer. If the input is a positive integer, the program proceeds to find and display its factors.

The factors of a number are the integers that can evenly divide the given number without leaving a remainder. To find the factors, we use a loop that iterates from 1 to the given number and checks whether the number is divisible by the current value of the loop variable (i). If it is divisible (number % i == 0), then i is a factor of the given number, and it is printed to the screen.

Here's an example of the program's output:

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

In this example, the factors of 12 are 1, 2, 3, 4, 6, and 12.

Prasun Barua

Prasun Barua is an Engineer (Electrical & Electronic) and Member of the European Energy Centre (EEC). His first published book Green Planet is all about green technologies and science. His other published books are Solar PV System Design and Technology, Electricity from Renewable Energy, Tech Know Solar PV System, C Coding Practice, AI and Robotics Overview, Robotics and Artificial Intelligence, Know How Solar PV System, Know The Product, Solar PV Technology Overview, Home Appliances Overview, Tech Know Solar PV System, C Programming Practice, etc. These books are available at Google Books, Google Play, Amazon and other platforms.

*

Post a Comment (0)
Previous Post Next Post