C programming language: In this program, you will read an integer from stdin, re
ID: 3666716 • Letter: C
Question
C programming language:
In this program, you will read an integer from stdin, reverse it, and print if back to the user. Keep reading input until a newline is reached.
1. Input Verification: Check that every character entered is either a digit or a
newline character. Check that at least one digit has been entered. You may
assume the integer read is small enough to be represented by int.
2. Constraints:
a. Use getchar to read the string. You may not use any other function to
read input from stdin.
b. If an invalid character is entered or no digits are read, return
EXIT_FAILURE.
c. If the program works as intended, return EXIT_SUCCESS.
4. Be sure to comment (this is part of your 10 points listed above) your code.
i.e.
5. Libraries: ctype.hstdlib.hstdio.h
[prompt]$./reverse_int
Enteranumbertoreverse:103456
654301
[prompt]$./reverse_int
Enteranumbertoreverse:01f3sdk
Error:nondigitcharacterentered
[prompt]$./reverse_int
Enteranumbertoreverse:Error:nodigitshavebeenread.
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int reverse_int()
{
char c;
int cnt=0,num=0,rev=0;
printf("[prompt]$./reverse_int ");
printf("enter the number to be reversed:");//promt
while((c=getchar())!=' ')//read characters until a newline is read
{
if(c<'0'||c>'9') // check if a non digit is read
{
printf("Error:nondigitcharacterentered ");// print error message if non digit is read
return EXIT_FAILURE; // return EXIT_FAILURE as non digit is read
}
num = num*10;// shift the currunt number left by one
num = num+(c-'0'); // add the equivalent value of charecter read to the currunt number
cnt++; //increment the digits read by one
}
if(cnt==0)
{
printf("Error:nodigitshavebeenread. ");// print error if no digits are read
return EXIT_FAILURE; // return EXIT_FAILURE as the number of digits read is 0
}
while(num>0) // while number greater than zero
{
rev = rev*10; // left shist the currunt result by 1 digit
rev = rev + (num%10); // add digit in 1's place of number to rev
num = num /10; // right shift num by one
}
printf("%d ",rev);// print the reversed value of the given number
return EXIT_SUCCESS; // return EXIT_SUCCESS as the program run as intended
}
int main()
{
int n = reverse_int(); // cal the reverse_int function
return n; // return EXIT_SUCCESS or EXIT_FAILURE based on the execution of the program
}
output:
2)
3)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.