Now we will see how we can calculate the number of digits in an integer using C programming. The integer will be entered at the run time by the User.
Count the Number of digits using Loops in C
In this method, we will use a loop to count the number of digits. you can use either for or while loop approach will be the same.
#include<stdio.h>#include<conio.h>int main(){int num, digits = 0;printf("Enter the number \n");scanf("%d",&num);while(num>10){num = num/10;digits++;}digits = digits+1;printf("Number of Digits in %d are : %d", num , digits);return 0;}
Count the Number of digits using Recursion in C
In this method, we will create a recursion function and try to count the number of digits in an integer.
#include<stdio.h>#include<conio.h>int digCount(int n);int main(){int num, digits = 0;printf("Enter the number \n");scanf("%d",&num);digits = digCount(num);printf("Number of Digits in %d are : %d", num , digits);return 0;}int digCount(int n ){static int count = 0;if(n>0){count++;digCount(n/10);}return count;}
Bottom line
There are a lot of ways through which you can write a C program that will count the number of digits in an integer for example you can use loops, functions, recursion function and even you can calculate the number of digits without using loops only using log method provided to you in the math.h header file.
ThankYou!! For coming please feel free to comment down your queries we will respond to each one !!
0 Comments