Read a non-negative number and write it reversed
This is the simplest solution:
#include <stdio.h>
int main(void)
{
int n;
printf("Enter a non-negative number\n");
scanf("%d", &n);
if(n < 0) {
printf("*** Error: the number is negative!\n");
return 1;
}
do {
printf("%d", n % 10);
n /= 10; // Equivalent to "n = n / 10"
}
while(n > 0);
return 0;
}
Error messages by convention should be written to standard error, so the statement
printf("*** Error: the number is negative!\n");
should be replaced by
fprintf(stderr, "*** Error: the number is negative!\n");
Commenti
Posta un commento