How to Find Factors of a Number in C: A Step-by-Step Guide

#include <stdio.h>

int main()
{
    // Prompt the user to enter a number
    printf("Enter a number: \n");
    int a, b, c = 0;

    // Read the input number from the user
    scanf("%d", &a);

    // Display message for the search of factors
    printf("Searching for factors: \n");

    // Loop to find factors of the entered number
    for (b = 2; a > b; b++)
    {
        // Check if the number 'a' is divisible by 'b' (where b starts from 2)
        if (a % b == 0 && a != b)
        {
            // If divisible, print the factor
            printf("%d \n", b);
            c++; // Increment the count of factors found
        }
    }

    // Check if factors are found or not
    if (c > 0)
    {
        // If factors are found, display the count
        printf(" \n \n%d factors found \n", c);
    }
    else
    {
        // If no factors are found, display a message
        printf(" \n \nNo factors found \n");
    }

    scanf("%d", &c); // Pause the program before exiting (optional)
    return 0;
}

Comments

Popular posts from this blog

Weird Algorithm || Introductory Problem || CSES