Complementary task for topic: 2
M Nemeth · 2023-08-29 15:21:04.606222'
Loops: while I.
Loops: while I.
Task: Count the number of digits in a positive integer:
Write a C program that prompts the user to enter a positive integer and counts the number of digits in it using a while loop. Display the result using printf()
Hint: inetegr division does not result any remainer, so
401/10=40 leads to 1 less digit. If I do it till the number is 0, I just need to count the steps.
Solution
#include
int main() {
int number;
printf("Enter a positive integer: ");
scanf("%d", &number);
if (number < 0) {
printf("Invalid input. Please enter a positive integer.\n");
return 0;
}
int digitCount = 0;
while (number != 0) {
number /= 10;
digitCount++;
}
printf("The number of digits in %d is %d.\n", number, digitCount);
return 0;
}
Explanation
In this example, the program uses printf() to prompt the user to enter a positive integer. The scanf() function is used to scan the input from the user and store it in the number variable. The program checks if the number is negative. If it is negative, it prints an error message and terminates the program. Otherwise, it initializes the digitCount variable to 0. The while loop continues as long as number is not equal to 0. In each iteration, the number is divided by 10 to remove the rightmost digit, and the digitCount is incremented. Once the number becomes 0, the loop terminates. Finally, it uses printf() to display the result.