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

In C programming, finding the product of digits involves extracting each digit from a number and multiplying them together. This is commonly done using loops to repeatedly divide the number by 10 and extract the remainder.

Syntax

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

Method 1: Using For Loop

The for loop approach initializes the product to 1 and continues until all digits are processed −

#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("Product of digits = %d<br>", product);
    return 0;
}
Enter the number: 269
Product of digits = 108

Method 2: Using While Loop

The while loop provides an alternative approach with the same logic −

#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("Product of digits = %d<br>", product);
    return 0;
}
Enter the number: 257
Product of digits = 70

How It Works

  • Step 1: Initialize product to 1 (multiplication identity)
  • Step 2: Extract the last digit using modulo operator (num % 10)
  • Step 3: Multiply the product with the extracted digit
  • Step 4: Remove the last digit by dividing by 10 (num / 10)
  • Step 5: Repeat until no digits remain

Key Points

  • Always initialize product to 1, not 0 (as multiplication with 0 gives 0)
  • The modulo operator % extracts the rightmost digit
  • Integer division by 10 removes the rightmost digit
  • Both for loop and while loop approaches have O(log n) time complexity

Conclusion

Finding the product of digits using loops is a fundamental programming exercise that demonstrates digit manipulation techniques. Both for and while loops work effectively for this purpose.

Updated on: 2026-03-15T13:51:01+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements