Computer >> Computer tutorials >  >> Programming >> C programming

How to find the product of given digits by using for loop in C language?


The user has to enter a number, then divide the given number into individual digits, and finally, find the product of those individual digits using for loop.

The logic to find the product of given digits is as follows −

for(product = 1; num > 0; num = num / 10){
   rem = num % 10;
   product = product * rem;
}

Example1

Following is the C program to find the product of digits of a given number by using for loop −

#include <stdio.h>
int main(){
   int num, rem, product;
   printf("enter the number : ");
   scanf("%d", & num);
   for(product = 1; num > 0; num = num / 10){
      rem = num % 10;
      product = product * rem;
   }
   printf(" result = %d", product);
   return 0;
}

Output

When the above program is executed, it produces the following result −

enter the number: 269
result = 108
enter the number: 12345
result = 120

Example2

Consider another example to find the product of digits of given number by using while loop.

#include <stdio.h>
int main(){
   int num, rem, product=1;
   printf("enter the number : ");
   scanf("%d", & num);
   while(num != 0){
      rem = num % 10;
      product = product * rem;
      num = num /10;
   }
   printf(" result = %d", product);
   return 0;
}

Output

When the above program is executed, it produces the following result −

enter the number: 257
result = 70
enter the number: 89
result = 72