Skip to content

Commit 9de7ec1

Browse files
committed
Decimal convertion done
1 parent caacdaf commit 9de7ec1

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

For loop/51. Octal to decimal.c

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ The equivalent Decimal Number : 485
1212
+ 1.5 Input
1313
+ 2. Pow function
1414
+ 3. Function to count amount of digits
15-
4. Write function to iterate over digits and return sum of powers
15+
+ 4. Write function to iterate over digits and return sum of powers
1616
+ 5. Invalid input
1717
6. Test
1818
7. Cpplint test
@@ -30,17 +30,30 @@ int input_octal(int *octal);
3030
void print_invalid_input();
3131
int power(int base, int exponent);
3232
int find_number_of_digits(int octal);
33+
int find_decimal(int octal, int number_of_digits);
3334

3435
int main() {
3536
int octal = 0;
3637
if (input_octal(&octal)) {
37-
printf("%d\n", find_number_of_digits(octal));
38+
int number_of_digits = find_number_of_digits(octal);
39+
printf("%d", find_decimal(octal, number_of_digits));
3840
} else {
3941
print_invalid_input();
4042
}
4143
return 0;
4244
}
4345

46+
int find_decimal(int octal, int number_of_digits) {
47+
int decimal = 0, temp_octal = octal, power_of_ten;
48+
for (int i = number_of_digits; i > 0; --i) {
49+
power_of_ten = power(10, number_of_digits - 1);
50+
decimal += temp_octal / power_of_ten * power(8, number_of_digits - 1);
51+
temp_octal -= temp_octal / power_of_ten * power_of_ten;
52+
--number_of_digits;
53+
}
54+
return decimal;
55+
}
56+
4457
int find_number_of_digits(int octal) {
4558
int counter = 0;
4659
for (int i = octal; i > 0; i /= 10) {

0 commit comments

Comments
 (0)