Write a C program to count number of digits in a number. Using do-while loop
Question
Write a C program to count number of digits in a number. Using do-while loop
Solution
Sure, here is a simple C program that uses a do-while loop to count the number of digits in a number:
#include <stdio.h>
int main() {
int num;
int count = 0;
printf("Enter a number: ");
scanf("%d", &num);
do {
count++;
num /= 10;
} while (num != 0);
printf("Number of digits: %d", count);
return 0;
}
Here's how it works:
- The program first includes the standard input/output header file (
stdio.h). - It then defines the
mainfunction where the program execution starts. - Inside the
mainfunction, it declares two integer variables:num(to store the user input) andcount(to keep track of the number of digits). - It prompts the user to enter a number and stores the input in
num. - It then enters a do-while loop. Inside the loop, it increments
countby 1 and dividesnumby 10. This effectively removes the last digit fromnum. - The loop continues as long as
numis not equal to 0. Whennumbecomes 0, it means there are no more digits left to count. - Finally, it prints the number of digits stored in
countand returns 0 to indicate successful program execution.
Similar Questions
Write a C program to calculate sum of digits of a number. – using while loop
123456789#include <stdio.h> int main() { int count = 0; for (int i = 100; i >= 0; i -= 10) { count++; } printf("%d", count); return 0; }
Alex is teaching his younger sister how to count the number of digits in an integer. He wants to write a program that takes an integer n as input and counts the number of digits using a do-while loop. Company Tags: CapgeminiInput format :The input consists of a single integer n.Output format :The output prints a single integer representing the count of digits in the given number.Refer to the sample output for formatting specifications.Code constraints :1 ≤ n ≤ 107Sample test cases :Input 1 :1Output 1 :1Input 2 :1000Output 2 :4Input 3 :54782Output 3 :5
write a program to print integer no, from 1 to n where n is the input from the user using do while loop in c language use getch
#include<stdio.h> int main(){ int number,sum=0,digit; printf("Enter an integer : "); scanf("%d",&number); while (number != 0){ digit=number%10; sum += digit; number /= 10 } printf("The sum of digits of the given number "%d" = %d",number,sum); return 0; }
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.