Write C, C++ Program to print factors of a number. In this program user input a number and we have to print it's factors.
Let's say if user input a number 6. Then it's factor is 1 , 2, 3 and 6. Similarly factors of 24 is 1, 2, 3 ,4 ,6 ,12, 24.
Program to check perfect number
C, C++ Interview Questions
Program to check perfect square
Program Logic to Print Factors of a Number
We Run a loop from i =1 to i <= num and check if i is divisible by num (input number) .
Let's write a code to print factors of a number.
Enter number 6
Factors of 6 is 1 2 3 6
Let's say if user input a number 6. Then it's factor is 1 , 2, 3 and 6. Similarly factors of 24 is 1, 2, 3 ,4 ,6 ,12, 24.
Program to check perfect number
C, C++ Interview Questions
Program to check perfect square
Program Logic to Print Factors of a Number
We Run a loop from i =1 to i <= num and check if i is divisible by num (input number) .
/* Iterate from i=1 to i<=num. */ for(i=1 ;i <= num; i++){ /* if remainder is zero, then it's a factor. */ if(num % i == 0){ printf(" %d ",i); }
Let's write a code to print factors of a number.
C Program to Print Factors of a Number
#include <stdio.h> int main() { int num,i; printf("Enter number \n"); scanf("%d",&num); if(num > 0) { printf("Factors of %d is",num); for(i=1;i<=num;i++){ if(num%i==0){ printf(" %d ",i); } } } else { printf("Enter positive number "); } return 0; }Output :
Enter number 6
Factors of 6 is 1 2 3 6
C++ Program to Print Factors of a Number
#include <iostream> using namespace std; int main() { int num; cout << " Enter a number to find it's factors \n"; cin >> num; /* Run a loop from 1 to num - 1 */ for (int i = 1; i <= num; i++) { /* If remainder is zero then it's a factor */ if (num % i == 0) { cout << i << " "; } } return 0; }
No comments:
Post a Comment