Please Write a C program that prompts the user to enter an integer, and then pri
ID: 3789628 • Letter: P
Question
Please Write a C program that prompts the user to enter an integer, and then prints out its decimal digits, each one on a separate line, starting with the least significant (rightmost) digit. Each printed line should indicate which of the digits is being printed. Note that the user can input either a positive or a negative integer: the inputs n and n, where n is an integer, should produce exactly the same output.
Here are three sample runs of this program.
-------------------------------
Enter an integer: 512
Digit (1): 2
Digit (2): 1
Digit (3): 5
---------------------------------
Enter an integer: 0
Digit (1): 0
---------------------------------
Enter an integer: -16
Digit (1): 6
Digit (2): 1
-------------------------------------
Hint: You can use the integer division and modulo operators to parse a positive integer into its digits. For example, n%10 produces the least significant digit of n, while n/10 deletes this digit.
Explanation / Answer
#include <stdio.h>
#include <math.h>
int main()
{
int i=0,n;
printf("Enter an integer: ");
scanf("%d", &n);
n = abs(n);
if(n == 0){
printf("Digit (1): %d ", n);
}
else{
while(n > 0){
i++;
int n1= n % 10;
n = n / 10;
printf("Digit (%d): %d ",i, n1);
}
}
return 0;
}
Output:
sh-4.2$ gcc -o main *.c
sh-4.2$ main
Enter an integer: 512
Digit (1): 2
Digit (2): 1
Digit (3): 5
sh-4.2$ main
Enter an integer: 0
Digit (1): 0
sh-4.2$ main
Enter an integer: -16
Digit (1): 6
Digit (2): 1
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.