-
Notifications
You must be signed in to change notification settings - Fork 21
/
ex15.c
71 lines (59 loc) · 1.45 KB
/
ex15.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
* 15. Modify Program 7.14 so that the user is asked again to type in the value
* of the base if an invalid base is entered. The modified program should
* continue to ask for the value of the base until a valid response is given.
*
* By Faisal Saadatmand
*/
#include <stdio.h>
#include <stdbool.h>
#define SIZE 64 /* see chapter 14. The #define Statement */
/* globals */
int gConvertedNumber[SIZE];
long int gNumberToConvert;
int gBase;
int gDigit = 0;
/* functions */
void getNumberAndBase(void);
void convertNumber(void);
void displayConvertedNumber(void);
void getNumberAndBase(void)
{
printf("Number to be converted? ");
scanf("%li", &gNumberToConvert);
while (true) {
printf("Base? ");
scanf("%i", &gBase);
if (gBase >= 2 && gBase <= 16) /* break if base is withing range */
break;
printf("Invalid base - must be between 2 and 16\n");
}
}
void convertNumber(void)
{
do {
gConvertedNumber[gDigit] = gNumberToConvert % gBase;
++gDigit;
gNumberToConvert /= gBase;
} while (gNumberToConvert != 0);
}
void displayConvertedNumber(void)
{
const char baseDigits[16] =
{ '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
int nextDigit;
printf("Converted number = ");
for (--gDigit; gDigit >= 0; --gDigit) {
nextDigit = gConvertedNumber[gDigit];
printf("%c", baseDigits[nextDigit]);
}
printf("\n");
}
int main(void)
{
getNumberAndBase();
convertNumber();
displayConvertedNumber();
return 0;
}