Skip to content

Commit 6c5b4f2

Browse files
committed
Fixed 8-9 number invalid input
1 parent e6029c9 commit 6c5b4f2

File tree

1 file changed

+25
-6
lines changed

1 file changed

+25
-6
lines changed

For loop/51. Octal to decimal.c

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ The equivalent Decimal Number : 485
1414
+ 3. Function to count amount of digits
1515
+ 4. Write function to iterate over digits and return sum of powers
1616
+ 5. Invalid input
17+
+ 5.5 Fix "using digit 0 - 7"
1718
+ 6. Test
1819
+ 7. Cpplint test
1920
+ 8. Add and push
@@ -36,7 +37,7 @@ void print_invalid_input();
3637
int power(int base, int exponent);
3738
int find_number_of_digits(int octal);
3839
int find_decimal(int octal, int number_of_digits, int sign);
39-
void output_decimal(int decimal);
40+
void output_decimal(int octal, int decimal);
4041
void test(int octal, int expected_result, int test_number);
4142
void run_tests();
4243

@@ -48,7 +49,7 @@ int main() {
4849
octal *= IS_NEGATIVE;
4950
sign = IS_NEGATIVE;
5051
}
51-
output_decimal(find_decimal(octal, find_number_of_digits(octal), sign));
52+
output_decimal(octal, find_decimal(octal, find_number_of_digits(octal), sign));
5253
} else {
5354
print_invalid_input();
5455
}
@@ -87,8 +88,9 @@ void test(int octal, int expected_result, int test_number) {
8788
}
8889
}
8990

90-
void output_decimal(int decimal) {
91-
printf("%d\n", decimal);
91+
void output_decimal(int octal, int decimal) {
92+
printf("The Octal Number: %d", octal);
93+
printf("The equivalent Decimal Number: %d\n", decimal);
9294
}
9395

9496
int find_decimal(int octal, int number_of_digits, int sign) {
@@ -123,13 +125,30 @@ int power(int base, int exponent) {
123125
}
124126

125127
void print_invalid_input() {
126-
printf("n/a");
128+
printf("n/a\n");
129+
}
130+
131+
int is_valid_octal(int octal, int number_of_digits) {
132+
int digit = 0, temp_octal = octal, power_of_ten, is_valid = TRUE;
133+
for (int i = number_of_digits; i > 0; --i) {
134+
power_of_ten = power(10, number_of_digits - 1);
135+
digit = temp_octal / power_of_ten * power(8, number_of_digits - 1);
136+
temp_octal -= temp_octal / power_of_ten * power_of_ten;
137+
--number_of_digits;
138+
if (digit >= 8 && digit <= 9) {
139+
is_valid = FALSE;
140+
break;
141+
}
142+
}
143+
return is_valid;
127144
}
128145

129146
int input_octal(int *octal) {
147+
printf("Input an octal number (using digit 0 - 7):\n");
130148
int is_valid = TRUE;
131149
char endline = '\0';
132-
if (!scanf("%d%c", octal, &endline) || endline != '\n') {
150+
if (!scanf("%d%c", octal, &endline) || endline != '\n' ||
151+
is_valid_octal(*octal, find_number_of_digits(*octal) == FALSE)) {
133152
is_valid = FALSE;
134153
}
135154
return is_valid;

0 commit comments

Comments
 (0)