ch4-Print decimal

Chapter_4     Exercise_4-11 Quick_sort     Exercise_4-12







Note:  In C and other Procedural_programming_languages, recursion should be used with care. See the discussion on Recursion_versus_iteration, Imperative_programming, and Functional_programming. Check also recursion pros and cons online.




printd.c     K&R, p. 87         download


#include <stdio.h> // for printf(), scanf(), putchar()

void printd(int); // print int in decimal

int main()
{
int n;

printf("Type an integer, [+-]?[0-9]+\n");
scanf("%d", &n);

if (n < 0) {putchar('-');}
printd(n);
putchar('\n');

return 0;
}

void printd(int n) // print n in decimal
{
int sign = 1;

if (n < 0) {sign = -1;}

if (n / 10) // if (n / 10 != 0)
{printd(n / 10);} // recursive call

putchar((n % 10) * sign + '0');
}
/*
gcc printd.c -o printd
./printd
Type an integer, [+-]?[0-9]+
0
0

./printd
Type an integer, [+-]?[0-9]+
+0
0

./printd
Type an integer, [+-]?[0-9]+
-0
0

./printd
Type an integer, [+-]?[0-9]+
123
123

./printd
Type an integer, [+-]?[0-9]+
+123
123

./printd
Type an integer, [+-]?[0-9]+
-123
-123

./printd
Type an integer, [+-]?[0-9]+
-1
-1

./printd
Type an integer, [+-]?[0-9]+
2147483647 // INT_MAX // limits.h
2147483647

./printd
Type an integer, [+-]?[0-9]+
-2147483648 // INT_MIN
-2147483648

./printd
Type an integer, [+-]?[0-9]+
2147483648 // INT_MAX + 1 (overflow)
-2147483648 // INT_MIN // modulo 2 arithmetic

./printd
Type an integer, [+-]?[0-9]+
2147483649 // INT_MAX + 2 (overflow)
-2147483647 // INT_MIN + 1

./printd
Type an integer, [+-]?[0-9]+
-2147483649 // INT_MIN - 1 (underflow)
2147483647 // INT_MAX

./printd
Type an integer, [+-]?[0-9]+
-2147483650 // INT_MIN - 2 (underflow)
2147483646 // INT_MAX-1
*/





Notes:

The regular_expression [+-]?[0-9]+ means an integer with at least 1 digit and an optional sign.
We print the minus sign in main() to be able to use negative numbers inside printd() or else we could not treat the case of overflow (and print the integer limit INT_MIN). See also Exercise_3-4.









Chapter_4     Exercise_4-11 BACK_TO_TOP Quick_sort     Exercise_4-12



Comments

Popular posts from this blog

Contents

Blogger Page Margins in Contempo