Display Factors of a Number in C

Exercise:

Write a C Program to display factors of a number.

Click Here to View the Solution!
#include <stdio.h>
int main() {
    int num, i;
    printf("Enter a positive integer: ");
    scanf("%d", &num);
    printf("Factors of %d are as follows: ", num);
    for (i = 1; i <= num; ++i) {
        if (num % i == 0) {
            printf("%d ", i);
        }
    }
    return 0;
}
Click Here to View the Output!
Enter a positive integer: 6
Factors of 6 are as follows: 1 2 3 6
Click Here to View the Explanation!
  • This program is used to find the factors of a positive number.
  • In main(), the program requests the user to enter a positive integer and stores it in the variable num using the scanf() function.
  • A for loop is initialized that will iterate till i <= num and increment i in each iteration.
  • In each iteration, it will be checked whether num is exactly divisible by i i.e. if i is a factor of num.
  • The return 0 statement is used to exit the program execution.
%d bloggers like this: