Yaşar.R
Yaşar.R

Reputation: 19

base conversion in c programming language

Could anyone point out what is wrong with this piece of code? I'm trying to write a simple(without using arrays and stuff like that) program that would convert the base 10 numbers to any other base. I'm a beginner, I've just started coding in C.

PS: As you can see I haven't written anything that would inverse the results, and I didn't receive any outputs from the compiler. It stopped working.

main()
{
    int a,b,c;
    printf("Please enter a number in base 10: ");
    scanf("%d",&a);
    printf("\nPlease enter the base that you want the number to be converted to: ");
    scanf("%d",&b);
    do
    {
        c=a%b;
        printf("%d",c);
        a/=b;
    }while(c!=0);
}

Upvotes: 0

Views: 18423

Answers (2)

Ariel Van Gertos
Ariel Van Gertos

Reputation: 9

Convert any base to base 10:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
main()
{
    char input[23];
    int sum;
    int power;
    int base;
    int val;
    int len;
    gets(input);
    strupr(input);
    scanf("%d",&base);
    len=strlen(input);
    power=len-1;
    for(int x=0;x<len;x++,power--)
    {
        val=input[x]-48;
        if(val>9)
            val-=7; 
        sum+=val*pow(base,power);
    }
    printf("%d",sum);
}

Upvotes: 0

tddguru
tddguru

Reputation: 392

Change your while loop to a != 0. You want to loop until you have reduced the input number to zero. Your code is terminating when the first digit is 0.

Upvotes: 2

Related Questions