In this blog post, we learn how to write a C Program to find the product of digits of a number?. We will write the C Program to find the product of digits of a number. Write a C program to input a number from the user and calculate the product of its digits. How to display product of digits of a number. How to find a product of digits of a number using loop in C programming. Logic to find a product of digits of a given number in the C program.
Example,
input: 125 output: 10 input: 432 output: 24
Logic to find product of digits of a number:
- Ask the user to enter any number.
- Declare and initialize another variable ‘prod’ with 1, where prod is an integer variable.
- Get the last digit of the given number by performing the modulo division (%) and store the value in last_digit variable, likey last_digit= number % 10.
- Multiply the last digit (last_digit) found above with prod i.e. prod= prod* last_digit.
- Remove last digit by dividing the number by 10 i.e. num = num / 10.
- Repeat steps 3-5 until the number becomes 0. In the last, you will get the product of the digits of the input number.
C Program to find the product of digits of a number using a loop:
The below program ask the user to enter the value. After getting the value from the user it will calculate the product of digits of entered number by using the above-mentioned logic.
#include<stdio.h> int main() { int num, rem, prod = 1; printf("Enter a number: "); scanf("%d", &num); while(num != 0) { rem = num % 10; // get the last-digit prod *= rem; // calculate product of digits num /= 10; // remove the last digit } printf("%d", prod); return 0; }
Output:
Enter a number: 2345
120
C Program to find the product of digits of a number using a function:
The below program ask the user to enter the value. After getting the value from the user it will call a function getProduct() to calculate the product of digits of the entered number. The function getProduct() is using arithmetic operators to calculate the product of digits of an input number.
#include<stdio.h> int getProduct(int num) { int prod = 1,rem; while(num != 0) { rem = num % 10; // get the last-digit prod *= rem; // calculate product of digits num /= 10; // remove the last digit } return prod; } int main() { int num, prod; printf("Enter a number: "); scanf("%d", &num); prod = getProduct(num); printf("%d", prod); return 0; }
Output:
Recommended Articles for you:
- How to access 2d array in C?
- Why is it faster to process sorted array than an unsorted array?
- Best gift for programmers.
- How do you find the missing number in a given integer array of 1 to 100?
- List of some best Laptops for the programmer.
- Best electronic kits for programmers.
- List of some best mouse for the programmer.
- Interview questions on an array.