In this article, we will write a C program to display factors of a number. For example, if the input number is 12, then the program should print numbers 1, 2, 3, 4, 6, 12 as output.
C program to print factors of a number
Let’s write the code that prompts user to enter a positive integer number and prints factors of the input number. The detailed explanation of the logic is provided at the end of the program.
#include <stdio.h>
int main() {
int number, i;
// Input the number
printf("Enter a positive integer: ");
scanf("%d", &number);
// Displaying factors
printf("Factors of %d are: ", number);
for (i = 1; i <= number; ++i) {
// Check if 'i' is a factor of 'number'
if (number % i == 0) {
// If 'i' is a factor, print it
printf("%d ", i);
}
}
return 0;
}
Output:
Enter a positive integer: 12
Factors of 12 are: 1 2 3 4 6 12
For the input number 12, the factors are 1, 2, 3, 4, 6, and 12. These are displayed in the output.
Explanation of the program:
The main part of the program is the logic used inside for loop.
for (i = 1; i <= number; ++i) {
if (number % i == 0) { // Check if 'i' is a factor of 'number'
printf("%d ", i); // If 'i' is a factor, print it
}
}
- Here, we are iterating through all the numbers starting from 1 till the number itself. In our case the number is 12, so the loop iterates from 1 to 12.
- We divide the number by every number from 1 to 12 and check for the remainder, if the remainder is zero, it means that the current number is a factor, the
printf
statement then prints it. - If the remainder is not zero, the if condition returns false and that number doesn’t get printed.
- This way all the number from 1 to 12 are checked and only the factors gets printed.
This loop iterates through all the integer numbers from 1 to the number itself, checking all the numbers if they are factors of the number
. If a number is found factor, it prints the number and checks next number until all the numbers are checked.
Leave a Reply