ผู้ใช้ต้องป้อนตัวเลข จากนั้นแบ่งตัวเลขที่กำหนดเป็นตัวเลขแต่ละหลัก และสุดท้าย หาผลคูณของตัวเลขแต่ละหลักโดยใช้ for loop
ตรรกะในการค้นหาผลคูณของตัวเลขที่กำหนด เป็นดังนี้ −
for(product = 1; num > 0; num = num / 10){
rem = num % 10;
product = product * rem;
} ตัวอย่าง1
ต่อไปนี้คือโปรแกรม C เพื่อค้นหาผลคูณของตัวเลขที่ระบุโดยใช้ 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;
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะสร้างผลลัพธ์ดังต่อไปนี้:
enter the number: 269 result = 108 enter the number: 12345 result = 120
ตัวอย่าง2
ลองพิจารณาอีกตัวอย่างหนึ่งเพื่อค้นหาผลคูณของตัวเลขของตัวเลขที่ระบุโดยใช้ 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;
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
enter the number: 257 result = 70 enter the number: 89 result = 72