We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now

x

# Base Conversion

on
Medium Priority
555 Views
I need to develop a program that converts a positive number from a given base to another base ranging from 2 to 10. I was initiatially thinking case statements but is there another way? Heres my start:

#include<stdio.h>

int main(void)

{
int num;
int sourcebase;
int targetbase;

//Get num and source base

do {
printf("Enter a positive number/n");
scanf_s("%d",&num);
Prinf("Enter the base of that number");
scan_s("%d" &sourcebase);
if((num<2)||(num>10)){
printf "You number is invalid!!!!!!!/n/n");
}
}
while(((num<2)||(num>10));
if (sourcebase==2)

Comment
Watch Question

## View Solution Only

CERTIFIED EXPERT
Top Expert 2009

Commented:
Note: Since this is probably an assignment, we can only give you pointers and help/support. But you have to find the solution yourself.

Why are you limiting num to 2 ... 10. If I understood your assignment correctly, you should limit sourcebase, and destbase.

I suggest you write two functions :

int from_base_x(char *num, int base);
char *to_base_x(int i, int base);

from_base_x will convert a string in base x to an integer and return it.
to_base_x will convert an integer to a string in base x and return it.

Then you can call these functions as follows :

int tmp = from_base_x(num_str, sourcebase);
char *result = to_base_x(tmp, destbase);
fprint("result : %s\n", result);
free(result);

num_str should be a string of course.

Can you give that a go, and show what code you can come up with for those functions ?
CERTIFIED EXPERT
Top Expert 2009

Commented:
Note the free(result) ... it might not be needed depending on your implementation of to_base_x, but we'll take care of that later ... for now try to come up with some code ...

Commented:
ok but first why are we converting to and from a string? And how do I see that the users source base and destination base are in the range?
CERTIFIED EXPERT
Top Expert 2009

Commented:
>> ok but first why are we converting to and from a string?
You need to have a format that is able to represent numbers in different bases. A string can easily do that.

>> And how do I see that the users source base and destination base are in the range?
In the code you posted, you checked whether num was in the range 2 to 10 ... so, you know how to check whether a number is in a certain range. I don't understand your question ...

Just to make things clearer for you, I'll give you an example of how the program could work :

Enter a positive number : 120
Enter the base of that number (2 to 10) : 3
Enter the target base (2 to 10) : 5
The number in the target base is : 30

The user wanted to convert the base 3 number 120 (= 15 in base 10) to base 5. The result is 30 :

120 (base 3) = 15 (base 10) = 30 (base 5)

What the code does to get to that result is :

num_str = "120"
sourcebase = 3
destbase = 5
tmp = from_base_x(num_str, sourcebase) = from_base_x("120", 3) = 15
result = to_base_x(tmp, destbase) = to_base_x(15, 5) = "30"
// print result

Commented:
so you're saying to convert the number to decimal first? Doesn't that mean that each number in 120 will have to be multiplied by 3 raised to 0 ,1 and 2? how will I do that? This is confusing
CERTIFIED EXPERT
Top Expert 2009

Commented:
Do you know how base conversion works ?

Can you convert 123 in base 4 to base 10 for me ?

Commented:
Ok,I know how base conversionsion works  what i'm asking is how will I represent this procedure in the function for example 1x4^2+2x4^1+3x4^0=27. I was thinking of incrementing the raised power with a for statement. if this is what u mean.
//where i is the  raised power
for (i=0,i>0,++i)

CERTIFIED EXPERT
Top Expert 2009

Commented:
>> I was thinking of incrementing the raised power with a for statement.
That's a good approach.

btw, you can get a given character from a string using num_str[i].
And another thing that might be handy is : subtract '0' from a character between '0' and '9' to get the actual value of the digit.

eg. :

num_str = "123"
num_str[2] - '0' = '3' - '0' = 3

Commented:
heres what I've done but i can't get out of myloop and and getting some data type related warnings any suggestions?

#include<stdio.h>
#include<math.h>
#include<stdlib.h>

int main(void)

{

long double sourcebase;
int targetbase;
int tmp_number;
int* new_number = NULL;

do {
printf("Enter a positive number\n");
scanf_s("%d",&tmp_number);
printf("Enter the base of that number\n");
scanf_s("%d", &sourcebase);
printf("Enter the destination base");
scanf_s("%d",&targetbase);
if((sourcebase<2)||(sourcebase>10)){
printf ("You number is invalid!!!!!!!\n\n");
}

}
while( tmp_number );
int i=0;
int decimal=0;
{
decimal += (tmp_number % 10) * pow( sourcebase, i ) ;
tmp_number /= 10 ;
++i ;
}

while( decimal )
int decimal=0;
{
new_number[i] = decimal % targetbase ;
decimal /= targetbase ;
new_number = (int*) realloc( new_number, i + 2 ) ;
++i ;
}

printf("You number is:%d",new_number);

return 0;
}

CERTIFIED EXPERT
Top Expert 2009

Commented:
1) This should be an int :

long double sourcebase;

Since you're reading it as an int here :

scanf_s("%d", &sourcebase);

And also since there is no reason to make it a double.

2) The do-loop will go on untill you give a 0 as tmp_number :

while( tmp_number );

3) This can't be right :

scanf_s("%d",&tmp_number);

You're reading the number as a DECIMAL (base 10) integer, while that's not necessarily the case. Remember that the base of this number is sourcebase.
I told you earlier that it's a good idea to read the number as a string instead ...

4) This is incorrect too :

decimal += (tmp_number % 10) * pow( sourcebase, i ) ;
tmp_number /= 10 ;

For the same reason as the previous point.

5) This is NOT a loop :

{
decimal += (tmp_number % 10) * pow( sourcebase, i ) ;
tmp_number /= 10 ;
++i ;
}

6) I'm sure that this is not what you want to do either :

while( decimal )
int decimal=0;

7) This is not a loop either :

{
new_number[i] = decimal % targetbase ;
decimal /= targetbase ;
new_number = (int*) realloc( new_number, i + 2 ) ;
++i ;
}

8) You can't do this :

new_number[i] = decimal % targetbase ;

because you didn't allocate any memory for new_number yet.

9) This is not right :

printf("You number is:%d",new_number);

since new_number is a POINTER to int and not just an int.

10) Why are you using an array of ints for new_number ?

Commented:
Ok so is there any part of it that is correct? How do I read in the number as a string. I guess I basically have to start over from scratch
CERTIFIED EXPERT
Top Expert 2009

Commented:
>> Ok so is there any part of it that is correct?
Don't take my comments wrong - I just wanted to be as complete as possible.

>> How do I read in the number as a string.
Check out %s with scanf :

http://www.cplusplus.com/ref/cstdio/scanf.html

>> I guess I basically have to start over from scratch
No, just go over my points 1 at a time, and modify your code. Then post it here again.

Commented:
ok i'll do what i can, thanks by the way you're being very patient. btw Num has to be an integer Can I declare as an integer and then convert to a string while reading in?
CERTIFIED EXPERT
Top Expert 2009

Commented:
It doesn't HAVE to be an int. It can be a string representing an integer.

With scanf, there's only 2 ways to read an integer : decimal (base 10) and hexadecimal (base 16). Any other base CANNOT be read in as an integer using scanf. The easiest way to get around that limitation is to read it as a string, and then convert it to an int.

Commented:
I started over doing this the best i could to be completely honest I got some of my previous attempt from someone and i think it threw me off. However this is my honest attempt now so be gentle

#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include <string.h>

int main(void)
{
//initialization section

int sourcebase=0;
int targetbase=0;
char num[50];
int length=0;
int decimal=0;
int new_number=0;

//Get user info

do{
printf("Enter a positive number:");
scanf_s("%s", &num);//wont go any further i'm thinking its the way i read it in
printf("Enter the base of that number:");
scanf_s("%d", &sourcebase);
scanf_s("%d", &targetbase);
if ((sourcebase<2||sourcebase>10)||(targetbase<2||targetbase>10)){
printf("Error your bases are out of range!!!/n/n");

}
} while ((sourcebase<2||sourcebase>10)||(targetbase<2||targetbase>10));

length=strlen(num);

for (int i=0;i<length;i++){

int j=0;
decimal=num[i] * pow( (float)sourcebase, j ) ;//pow won't except two int arguments
j++;
}
new_number=decimal % targetbase;

return 0;
}
ps this is due tomorrow so any major changes i can make are welcome
CERTIFIED EXPERT
Top Expert 2009

Commented:
>> scanf_s("%s", &num);//wont go any further i'm thinking its the way i read it in
When using scanf_s, you need to specify the length of the string too :

scanf_s("%s", num, 49);

>> for (int i=0;i<length;i++){
Instead of counting up, you'll want to count down (you want to start from the last digit !)

>> decimal=num[i] * pow( (float)sourcebase, j ) ;
A few things here :
(a) you shouldn't use num[i] here, as that will have a value between 0x30 and 0x39 (ASCII values for '0' and '9'). Use (num[i] - '0') instead !
(b) this is a good start, but you're re-assigning to decimal over and over again, while you want to add to it ! Think about what happens. I'm not giving too much away on purpose since you've already proven that you know how to convert between bases - you just need to apply that knowledge here !

>> new_number=decimal % targetbase;
This is not sufficient. You'll have to do something similar as the previous loop, but the other way around.

>> ps this is due tomorrow so any major changes i can make are welcome
I'll stick around for a while ... so post your changes here ...

Another hint once you've got everything working : validate that the num string the user entered contains ONLY digits before using it.
CERTIFIED EXPERT
Top Expert 2009

Commented:
Oh yes, and of course, this :

int j=0;

should not be inside the loop, or you reset the value to 0 for every iteration !

Commented:
int main(void)
{
//initialization section

int sourcebase=0;
int targetbase=0;
char num[50]; //is 50 a suffiencient length for char num
int length=0;
int decimal=0;
int new_number=0;
int j=0;

//Get user info

do{
printf("Enter a positive number:");
scanf_s("%s", num, 49);
printf("Enter the base of that number:");
scanf_s("%d", &sourcebase);
scanf_s("%d", &targetbase);//nothing happens after here
if ((sourcebase<2||sourcebase>10)||(targetbase<2||targetbase>10)){
printf("Error your bases are out of range!!!/n/n");

}
} while ((sourcebase<2||sourcebase>10)||(targetbase<2||targetbase>10));

length=strlen(num);

for (int i=0;i<length;++i){

decimal+= (num[i] - '0') * pow( (float)sourcebase, j ) ;
j++;
}
for (int k=0;k<length;--k)

new_number=decimal % targetbase;// I don't understand u mean by opposite should new num be ana array

printf("Your number is:%d",new_number);//Should i validate by sendin  it though a loop before printing

return 0;
}
CERTIFIED EXPERT
Top Expert 2009

Commented:
>> char num[50]; //is 50 a suffiencient length for char num
more than enough ... an int can only hold 32 binary digits, so that's the max.

>> for (int i=0;i<length;++i){
As I said earlier : you don't want to count up, but down. The last digit has to be treated first.

>> for (int k=0;k<length;--k)
This loop will go on for a LOOONG time (untill k underflows) : you start with k = 0, and on each iteration you subtract one (so k = 0, -1, -2, ...). But you go on for as long as k < length, and every negative integer is smaller than length.
So, this is not what you want.

>> // I don't understand u mean by opposite should new num be ana array
After the first for loop, you have an integer representing the number the user gave.
Try adding a print just after the first loop :

printf("The intermediary state is :%d\n", decimal);

And check whether it's the same as the one the user entered (but in base 10 this time !).

Now, you have to convert that integer to the targetbase. For that you can use a combination of % and /

>> //Should i validate by sendin  it though a loop before printing
I don't know what you mean.

Commented:
>> for (int k=0;k<length;--k)
This loop will go on for a LOOONG time (untill k underflows) : you start with k = 0, and on each iteration you subtract one (so k = 0, -1, -2, ...). But you go on for as long as k < length, and every negative integer is smaller than length.
So, this is not what you want
So increment k?

Another hint once you've got everything working : validate that the num string the user entered contains ONLY digits before using it.

I'm stuck, it simply will not work pass a certain point. Thanks for all your help tho I guess I'll just turn in what i've done and hope to get a few points for trying.
CERTIFIED EXPERT
Top Expert 2009

Commented:
>> So increment k?
For example, but it depends how you're gonna do that part.

I suggest to get it working first - then you can add the check. Btw, that check should happen right after you read the number !

>> I'm stuck, it simply will not work pass a certain point. Thanks for all your help tho I guess I'll just turn in what i've done and hope to get a few points for trying.
Don't give up. Show me your current code, and tell me where you're stuck ...

Commented:
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include <string.h>

int main(void)
{
//initialization section

int sourcebase=0;
int targetbase=0;
char num[50];
int length=0;
int decimal=0;
int new_number=0;
int j=0;

//Get user info

do{
system("cls");
printf("Enter a positive number:");
scanf_s("%s", num, 49);

length=strlen(num);

for(int j=0;j<length;j++)//this to check if it is a positive number but thr loop contiinues without error
if (num[j]<0){
printf("Error number cannot be less than zero");
system("pause");
}
printf("Enter the base of that number:");
scanf_s("%d", &sourcebase);
scanf_s("%d", &targetbase); //After it gets here it tells me theres astackoverflow exception

if ((sourcebase<2||sourcebase>10)||(targetbase<2||targetbase>10)){
printf("Error your bases are out of range!!!\n\n");
system("pause");

}
} while ((sourcebase<2||sourcebase>10)||(targetbase<2||targetbase>10)||(num[j]<0));

length=strlen(num);

for (int i=0;i<length;++i){

decimal+= (num[i] - '0') * pow( (float)sourcebase, j ) ;
j++;
printf("%d",decimal);//This is to check if the number is really in decimal (its not)
}
for (int k=0;k<length;++k)

new_number=decimal % targetbase;

printf("Your number is:%d",new_number);//(the only out put i get is 2)

return 0;
}
This is frustrating
CERTIFIED EXPERT
Top Expert 2009

Commented:
>> if (num[j]<0){
Every ASCII character is positive !!!
What you want to check for is that all characters in the string are between '0' and sourcebase.
So, make this :

if ((num[j] < '0') || (num[j] >= sourcebase + '0')) {

Make sure that you read in sourcebase BEFORE this check, and that sourcebase is maximum 10 !!!

>>   } while ((sourcebase<2||sourcebase>10)||(targetbase<2||targetbase>10)||(num[j]<0));
This will not do what you think, as num[j] will point to the '\0' at the end of the string

It's a better idea to make use of continue and break in the while loop :
1) continue : ends the current iteration, and goes to the next  (do this when you notice a problem)
2) break : ends the loop  (do this when everything is OK, and you've got all data)
That way you can use this :

} while (1);

>>    length=strlen(num);
You've already done this inside the while loop - no need to do it again.

>>   for (int i=0;i<length;++i){
You're still not starting from the last digit. You have to count DOWN from (length - 1) to 0 as I said earlier. That's why you get this :
>> //This is to check if the number is really in decimal (its not)

>> new_number=decimal % targetbase;
You need to do a bit more than that to convert from base 10 to the target base. How would you do it manually ?

>> This is frustrating
It shouldn't be. Just read my comments carefully, and try to make the modifications one at a time. You'll get there !!
And always try to keep in mind what is happening, and what you want to do !

Commented:
Every ASCII character is positive !!!
What you want to check for is that all characters in the string are between '0' and sourcebase.
I included the check because it was specified that num was supposed to be positive like if the user entered -120 base whatever but i don't think it is necessar so i'll take it out

When you say count down is this wha tu mean?
for(int i=0;i,(length-1);i++){//Still not working

>> new_number=decimal % targetbase;
You need to do a bit more than that to convert from base 10 to the target base. How would you do it manually ?
I am thinking that I would divide out by the targetbase until i get to zero but i need a way to store the running remainders in memory perhaps another damn array can i work around this?
CERTIFIED EXPERT
Top Expert 2009

Commented:
>> I included the check because it was specified that num was supposed to be positive like if the user entered -120 base whatever but i don't think it is necessar so i'll take it out
I understand why you did it, but the way you try it doesn't work. You're testing every character for negativity - and as I said, every ASCII character is positive, no matter if the whole string represents a negative number.
If you use the test I gave you in my previous post, it will also give an error when the given number is negative (ie. it contains the character '-') !!

>> When you say count down is this wha tu mean?
>> for(int i=0;i,(length-1);i++){//Still not working
No.
Counting up is : 0, 1, 2, ..., length-1
Counting down is : length-1, ..., 2, 1, 0

To do that with a for loop, you have to get three things :
1) initial value : i = length - 1
2) loop condition : i >= 0
3) in- or decrement : --i

Combine this to get :

for (i = length - 1; i >= 0; --i) { }

>> I am thinking that I would divide out by the targetbase until i get to zero but i need a way to store the running remainders in memory perhaps another damn array can i work around this?
There's a much easier way. I'll show you how I convert the base 10 number 154 to base 5 :

num = 154

next digit of new_num =  (num % 5) = 4
num = num / 5 = 30
(new_num is now = 4)

next digit of new_num =  (num % 5) = 0
num = num / 5 = 6
(new_num is now = 04)

next digit of new_num =  (num % 5) = 1
num = num / 5 = 1
(new_num is now = 104)

next digit of new_num =  (num % 5) = 1
num = num / 5 = 0
(new_num is now = 1104)

STOP because num is = 0

Do you see a pattern ? Can you code that ? Notice that you'll need to store new_num in a string too !!

Commented:
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include <string.h>

int main(void)
{
//initialization section

int sourcebase=0;
int targetbase=0;
char num[50];
int length=0;
int decimal=0;
int new_number[50];
int j=0;
int newnum=0;

//Get user info

do{
system("cls");
printf("Enter a positive number:");
scanf_s("%s", num, 49);

length=strlen(num);

for(int j=0;j<length;j++)
if ((num[j] < '0') || (num[j] >= sourcebase + '0')){//gives me an error a couple  of time and then continues
printf("Error number cannot be less than zero");
system("pause");
}
printf("Enter the base of that number:");
scanf_s("%d", &sourcebase);
scanf_s("%d", &targetbase);

if ((sourcebase<2||sourcebase>10)||(targetbase<2||targetbase>10)){
printf("Error your bases are out of range!!!\n\n");
system("pause");

}
} while ((sourcebase<2||sourcebase>10)||(targetbase<2||targetbase>10));
//do i break here?

for(int i=0;i<(length-1);i++){

decimal+= (num[i] - '0') * pow( (float)sourcebase, j ) ;
j++;
printf("%d",decimal);//still not working
}
for (int k=0;k<length;++k)//heres my crack at it

while(decimal!=0){

newnum=decimal%targetbase;
decimal=decimal/targetbase;
new_number[k]=newnum;

}

//still not working but i can see light at the end of the tunnel

return 0;
}
CERTIFIED EXPERT
Top Expert 2009

Commented:
>> int new_number[50];
Make this a char array

>> if ((num[j] < '0') || (num[j] >= sourcebase + '0')){//gives me an error a couple  of time and then continues
That's because you have to read in sourcebase BEFORE this line !!!

So :
2) check that sourcebase is between 2 and 10
4) check that num is a valid number
6) check that targetbase is between 2 and 10

With regards to break and continue :

do {
if (errorcondition) {
// print error message
continue;
}
// do something else
break;
} while (1);

The continue in the above code, will skip the rest of the loop, and go back to the "do", and start over.
The break will exit the loop (put this at the end when you're sure that everything was read in fine !!).

>> for(int i=0;i<(length-1);i++){

>> for (int k=0;k<length;++k)//heres my crack at it
drop this line

>>        while(decimal!=0){
>>           newnum=decimal%targetbase;
>>           decimal=decimal/targetbase;
>>           new_number[k]=newnum;
>>        }
This is a very good start ! The only problem is that  k will not be incremented !
And you have to make sure that you fill in the LAST digit first (remember, a number starts from the back !!).
And also make sure that you fill in the characters '0' through '9' instead of just the values 0 through 9. So, use ('0' + newnum) instead.

>> //still not working but i can see light at the end of the tunnel
Yep, it's coming :) Just go over my comments carefully, and try to understand them. If there is something you don't understand, then PLEASE ask me, and I'll be glad to explain it. You HAVE to understand the code you're writing, or you're gonna have a difficult time getting it to work !!

Commented:
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include <string.h>

int main(void)
{
//initialization section

int sourcebase=0;
int targetbase=0;
char num[50];
int length=0;
int decimal=0;
char new_number[50];
int j=0;
int newnum=0;

//Get user info

do{
system("cls");
printf("Enter a source base:");
scanf_s("%d", &sourcebase);

if((sourcebase<2||sourcebase>10)){
printf("Error your sourcebase is out of range!!!\n\n");
system("pause");
}continue;//this is a strange one , when i press enter the number gets erased
printf("Enter a positive number:");
scanf_s("%s", num, 49);

length=strlen(num);

for(int j=0;j<length;j++){
if ((num[j] < '0') || (num[j] >= sourcebase + '0')){
printf("Error number cannot be less than zero");
system("pause");
}continue;
}
scanf_s("%d", &targetbase);

if ((targetbase<2||targetbase>10)){
printf("Error your targetbase is out of range!!!\n\n");
system("pause");
}continue;
break;
} while (1);//So while (1) is the condition that everthing is true?

for (int i = length - 1; i >= 0; --i) {

decimal+= (num[i] - '0') * pow( (float)sourcebase, j ) ;
j++;
printf("%d",decimal);

}
for (int k=0;k<length;++k)//drop which line?

while(decimal!=0){

newnum=decimal%targetbase;
decimal=decimal/targetbase;
new_number[k]=newnum;

// The only problem is that  k will not be incremented !
//why not?
//And you have to make sure that you fill in the LAST digit first (remember, a number starts from the back !!).
//I don't understan what you mean by that.How?
//And also make sure that you fill in the characters '0' through '9' instead of just the values 0 through 9. So, use ('0' + newnum) instead.
//so new_number[k]=('0' + newnum);

}

return 0;
}
CERTIFIED EXPERT
Top Expert 2009

Commented:
>>           }continue;//this is a strange one , when i press enter the number gets erased
You need to put it INSIDE the if block of course. It can only be executed if a problem occurs.
The same applies to the other continue's !!!

>>  for(int j=0;j<length;j++){
>>    if ((num[j] < '0') || (num[j] >= sourcebase + '0')){
>>      printf("Error number cannot be less than zero");
>>      system("pause");
>>    }continue;
>>  }
In this case, the continue will apply to the for loop, not to the while loop !!
So, you have to do it slightly differently :

for(int j=0;j<length;j++){
if ((num[j] < '0') || (num[j] >= sourcebase + '0')){
printf("Error number cannot be less than zero");
system("pause");
break;  // if we notice something wrong in the string we jump out of the for loop ...
}
}
if (j < length) continue; // if we didn't reach the end of the string, that means a problem was encountered, so we continue ...

>>   } while (1);//So while (1) is the condition that everthing is true?
Indeed. So, the loop will go on untill the break is reached which will stop the loop. And the break is only reached when all entered values are valid.

>>   for (int k=0;k<length;++k)//drop which line?
This line :) You don't need this for statement !!

>> // The only problem is that  k will not be incremented !
>>           //why not?
Because you never do it.

>> //And you have to make sure that you fill in the LAST digit first (remember, a number starts from the back !!).
>>          //I don't understan what you mean by that.How?
Check my earlier example again :

I'll show you how I convert the base 10 number 154 to base 5 :

num = 154

next digit of new_num =  (num % 5) = 4
num = num / 5 = 30
(new_num is now = 4)

next digit of new_num =  (num % 5) = 0
num = num / 5 = 6
(new_num is now = 04)

next digit of new_num =  (num % 5) = 1
num = num / 5 = 1
(new_num is now = 104)

next digit of new_num =  (num % 5) = 1
num = num / 5 = 0
(new_num is now = 1104)

STOP because num is = 0

Do you notice how I fill in the LAST digit (4) first, then the next to last (0), then the second (1), and finally the first (1). Do you understand why I do it that way ?

>>      //so new_number[k]=('0' + newnum);
Yes. Now all you have to do is make sure that k has the correct value.

You'll have to change this too, because new_number is a string and not an integer.

Commented:
for(int j=0;j<length;j++){
if ((num[j] < '0') || (num[j] >= sourcebase + '0')){
printf("Error number cannot be less than zero");
system("pause");
break;
}
}
if (num[j] < length){continue;//error definition from the for loop is ignored; the definition from the enclosing scope is used
}

while(decimal!=0){

newnum=decimal%targetbase;
decimal=decimal/targetbase;
new_number[k]=newnum; //How do I get the new num values in the array so it reads up if I dont use a for statement? I'm not very good at manipulating arrays so i try to avoid them

//is this how we print it?
CERTIFIED EXPERT
Top Expert 2009

Commented:
>>        if (num[j] < length){continue;
Compare this with what I wrote in my last post - there's an important difference !

>>           new_number[k]=newnum; //How do I get the new num values in the array so it reads up if I dont use a for statement?
You're already in a loop : the while loop !

>> I'm not very good at manipulating arrays so i try to avoid them
You will have to learn though :) It's not very difficult - you just have to think of an array as several elements stored one after the other. And you can easily access them by their index.

>> //is this how we print it?
%c is for one character. We want to print a whole string, so we use %s

Commented:

do{
system("cls");
printf("Enter a source base:");
scanf_s("%d", &sourcebase);

if((sourcebase<2||sourcebase>10)){
printf("Error your sourcebase is out of range!!!\n\n");
system("pause");
continue;
}
printf("Enter a positive number:");
scanf_s("%s", num, 49);

length=strlen(num);

for(int j=0;j<length;j++){
if ((num[j] < '0') || (num[j] >= sourcebase + '0')){
printf("Error number cannot be less than zero");
system("pause");
break;
}
}
if (j < length) continue;//still starting over what am i doing wrong?

scanf_s("%d", &targetbase);

if ((targetbase<2||targetbase>10)){
printf("Error your targetbase is out of range!!!\n\n");
system("pause");
}
break;
} while (1);

for (int i = length - 1; i >= 0; --i) {

decimal+= (num[i] - '0') * pow( (float)sourcebase, j ) ;
j++;
printf("%d",decimal);

}

while(decimal!=0){

newnum=decimal%targetbase;
decimal=decimal/targetbase;
new_number[k]=('0' + newnum);
--k;//Will this work?

}

CERTIFIED EXPERT
Top Expert 2009

Commented:
>>           if (j < length) continue;//still starting over what am i doing wrong?
What is the complete output you get ?
add this line just before the if :

printf("j = %d\n", j);

>>             if ((targetbase<2||targetbase>10)){
>>             printf("Error your targetbase is out of range!!!\n\n");
>>              system("pause");
>>             }
You forgot the continue !!

>>        for (int i = length - 1; i >= 0; --i) {
Before this, you need to add the line :

j = 0;

because you need to re-set j to 0.

>>            --k;//Will this work?
Yes, but you need to initialize k correctly BEFORE the loop !! Otherwise you're gonna count down like this :

0, -1, -2, -3, ...

Commented:
What is the complete output you get ?
using 123 base 4 j=3

Commented:
so k should be initialized k=-1?
CERTIFIED EXPERT
Top Expert 2009

Commented:
>> What is the complete output you get ?
>> using 123 base 4 j=3
I meant the complete output, starting with :

Enter a source base:
...

>> so k should be initialized k=-1?
If you initialize k to -1, you're gonna count down like this :

-1, -2, -3, ...

That's not what you want either.

You want to index into the array. The indexes of the array go from 0 to 48. So you NEVER want a negative number !
You have to determine the length of the resulting number in the targetbase, and start from that index !!

Commented:
update  I added a break after the target base was read in

length=strlen(number);

for(int i=0;i<length;i++){
if((number[i]<'0')||(number[i]>=sourcebase+'0')){
printf("Error!!! number cannot be less than zero.\n\n");
system("pause");
break;
}
}
if (i < length) continue;

printf("Enter a target base between 2 and 10:");
scanf("%d",&targetbase);
if((targetbase<2||targetbase>10)){
printf("Invalid!!!Your target base must be between 2 an 10\n\n");
system("pause");
continue;
}
break;//Added break to end the looping(figured that out by myself Yippee I'm learning!!!
}while(1);

//the program moves forward but the decimal i get is incorrect or it is correct....
for (int j=length-1; j>=0;--j){
decimal+=(number[j]-'0')*pow((float)sourcebase,power);
power++;
printf("Decimal=%d",decimal);
}//yeilds Decimal=3Decimal=11Decimal=27 so where do the 3 and 11 come from?
CERTIFIED EXPERT
Top Expert 2009

Commented:
>>           break;//Added break to end the looping(figured that out by myself Yippee I'm learning!!!
didn't we already have that ? :)

>>      }//yeilds Decimal=3Decimal=11Decimal=27 so where do the 3 and 11 come from?
The 3 and 11 are just the progress of the calculation in the loop. Only the last one counts !

123 in base 4 = 27 in base 10

Now, just finish the part that converts the decimal to the targetbase ...

Commented:
didn't we already have that ? :) Oh well, so much for progress...:(

lentgth=strlen(newnumber);
k=length-1;

Commented:
printf("Your number is:%s\n\n",new_number);//Is this how you print the entire array?
return 0;
CERTIFIED EXPERT
Top Expert 2009

Commented:
>> lentgth=strlen(newnumber);
>> k=length-1;
That won't work as the newnumber string is not yet created.

Based on the targetbase, and the decimal number, can you calculate how long the newnumber will be ?

>> printf("Your number is:%s\n\n",new_number);//Is this how you print the entire array?
Yes :)

Commented:
Based on the targetbase, and the decimal number, can you calculate how long the newnumber will be ?
No, am I supposed to know that?
CERTIFIED EXPERT
Top Expert 2009

Commented:
Try to find out how long 27 in base 10 would be if you'd represent it in base 3.

Commented:
I'm getting 4. So you're saying k=4?
CERTIFIED EXPERT
Top Expert 2009

Commented:
>> I'm getting 4. So you're saying k=4?
The number will not always be 27, and the targetbase will not always be 3.

I'm saying that you should calculate the length the same way you got the 4.

Commented:
Seriously, I'm not following you so int k=decimal%targetbase
CERTIFIED EXPERT
Top Expert 2009

Commented:
How did you know that it was 4 ?
Explain step by step how you came to the number 4, then code that !

Commented:
thats what i said k=decimal%targetbase
CERTIFIED EXPERT
Top Expert 2009

Commented:
27 % 3 = 0

So that can't be it :)

Commented:
do I need another aray to store the remainder
values and then calcualte the length of the array? Is theire an easier way to add the numbers to newnumber?
CERTIFIED EXPERT
Top Expert 2009

Commented:
You can do it any way you like :

1) you calculate the length, and then start from the back
2) you start from the front, but need to keep track of all progress

Whichever you like best.

In any case, you're gonna code it exactly the same way you do it in your head or on paper.

Commented:
i still don't understand :(

remainder=decimal%targetbase;
decimal=decimal/targetbase;
new_number[k]=('0' + remainder);
--k
//This isn't working How to I initialize k so the remainder is added to the newnumber array
CERTIFIED EXPERT
Top Expert 2009

Commented:
You're approaching this the wrong way.

Take the base 10 number 35. Now, how would you find out its base 3 representation ? Write down all steps, and I mean ALL of them. Write down your complete thinking process. And post that here. To get a good overview, write it down in steps : step 1, step 2, ...

Commented:
divide 35 by 3 store the remainder divide the quotient by three until we get zero read up the remainders for the numbers. How do you store each remainder in a separate array index?
CERTIFIED EXPERT
Top Expert 2009

Commented:
Now do the same step-by-step description of how you calculate the length of that base 3 number

Commented:
I don't know
CERTIFIED EXPERT
Top Expert 2009

Commented:
Then how did you come to the value 4 earlier ? Don't tell me you just guessed :)

Commented:
I just said you divde by the targetbase till you get a zero i got four remainders
CERTIFIED EXPERT
Top Expert 2009

Commented:
So, just code that the same way, and you've got the length !

Commented:
how do i do that? I'm not seeing how that would work
CERTIFIED EXPERT
Top Expert 2009

Commented:
If you can do it in your head or on paper, you can also do it in code :) In this case it's not very difficult ... Think about it for 5 seconds ...

Commented:
I got it finally

int k=0;

while(decimal>0){

/* Convert to Target Base*/

remainder=decimal%targetbase;
decimal=decimal/targetbase;
new_number[k]=('0' + remainder);
++k;

}
/* Display Converted Number*/

int string_length = strlen( new_number ) ;

for( int l = string_length - 1; l >= 0; --l ){

}
return 0;
}
It would have been nice If could have printed the reversed string in one line but this is good enough.
Thanks for all your help and patience:)
CERTIFIED EXPERT
Top Expert 2009

Commented:
That's another way to approach it :) Nice solution !

Commented:
ok last question I swear
1) Why am I repeatedly getting my error message even when my number isn't negative

}
printf("Enter a positive number:");
scanf("%s",number,49);
length=strlen(number);

for(int i=0;i<length;i++){
if((number[i]<'0')||(number[i]>=sourcebase+'0')){
printf("Error!!! number cannot be less than zero.\n\n");

break;
}
if (i<length) continue;
2) I added a quit while statement and its given me an error on execution
do{
//conversion

printf("Enter Q to quit, C to continue >");
scanf("%c", quit);
}
}while ((quit != 'Q') && (quit != 'q'));
return 0;

}
CERTIFIED EXPERT
Top Expert 2009

Commented:
>> 1) Why am I repeatedly getting my error message even when my number isn't negative
Which sourcebase do you enter and which number ?

>> 2) I added a quit while statement and its given me an error on execution
First of all, I see a } that doesn't match.
What's "//conversion" supposed to do ?
What do you want to achieve by this quit loop ?

Commented:
1)Say I enter 5 for the sourcebase and positive 345the error comes up but the progrma moves forward. I  thought thr error was only supposed to report negative numbers why are numbers the are numbers >=sourcebase+'0' also invalid?

2)Quit offers the option to exit or start over so I wrapped it around the entire program

do{

do {
/* Get user information*/
system("cls");
printf("Enter a source base between 2 and 10:");
scanf("%d",&sourcebase);
if((sourcebase<2||sourcebase>10)){
printf("Invalid!!!Your source base must be between 2 an 10\n\n");

continue;
}
printf("Enter a positive number:");
scanf("%s",number,49);
length=strlen(number);

for(int i=0;i<length;i++){
if((number[i]<'0')||(number[i]>=sourcebase+'0')){
printf("Error!!! number cannot be less than zero.\n\n");

break;
}

if (i<length) continue;
}
printf("Enter a target base between 2 and 10:");
scanf("%d",&targetbase);
if((targetbase<2||targetbase>10)){
printf("Invalid!!!Your target base must be between 2 an 10\n\n");

continue;
}
break;
/* Validate User Data*/
}while(1);
/* Convert to Decimal*/
for (int j=length-1; j>=0;--j){
decimal+=(number[j]-'0')*pow((float)sourcebase,power);
power++;

} int k=0;

while(decimal>0){

/* Convert to Target Base*/

remainder=decimal%targetbase;
decimal=decimal/targetbase;
new_number[k]=('0' + remainder);
++k;

}
/* Display Converted Number*/

int string_length = strlen( new_number ) ;

for( int l = string_length - 1; l >= 0; --l ){

printf("Enter Q to quit, C to continue >");
scanf("%c", quit);

}
}while ((quit != 'Q') && (quit != 'q'));
return 0;

}
CERTIFIED EXPERT
Top Expert 2009

Commented:
>> 1)Say I enter 5 for the sourcebase and positive 345
345 is an invalid base 5 number. Base 5 numbers can only contain digits between 0 and 4 (0, 1, 2, 3, 4)

>> the error comes up
That's whay the error is shown

>> but the progrma moves forward.
The program moves forward because you put this line :

if (i<length) continue;

inside the for loop. It has to be put just AFTER the for loop.

>> I  thought thr error was only supposed to report negative numbers why are numbers the are numbers >=sourcebase+'0' also invalid?
As I said above, 345 is an invalid base 5 number. Errors will be reported for EVERY invalid sourcebase number. So, if you put in any other character than the allowed digits, an error will be reported. And that includes negative numbers.

>> 2)Quit offers the option to exit or start over so I wrapped it around the entire program
OK, let's look at your code then :

1) before this line :

>>        int string_length = strlen( new_number ) ;

put this line :

new_number[k] = '\0';

to terminate the string with a null - this is to make sure that strlen will work correctly !

2) This :

for( int l = string_length - 1; l >= 0; --l ){

printf("Enter Q to quit, C to continue >");
scanf("%c", quit);

}

is not what you want to do. It's gonna give you this output :

Enter Q to quit, C to continue >

Enter Q to quit, C to continue >

Enter Q to quit, C to continue >

And you want it to show :

Enter Q to quit, C to continue >

So, replace it with this code :

for( int l = string_length - 1; l >= 0; --l ){
printf("%c",new_number[l]);
}
printf("\n\n");
printf("Enter Q to quit, C to continue >");
scanf("%c", quit);

Commented:
I'm still getting an unhandled exception error on execution saying i was trying to write to a corrupted part of memory

for( int l = string_length - 1; l >= 0; --l ){
printf("%c",new_number[l]);
}
printf("\n\n");
printf("Enter Q to quit, C to continue >");
scanf("%c", quit);

}while ((quit != 'Q') && (quit != 'q'));
CERTIFIED EXPERT
Top Expert 2009

Commented:
Show me the complete code.

Commented:
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include <string.h>

int main(void)
{
/* Initialization section*/

char number[50]={ '\0' };
char new_number[50]={ '\0' };
int sourcebase=0;
int targetbase=0;
int length=0;
int decimal=0;
int power=0;
int remainder=0;
char quit={'0'};

do{

do {
/* Get user information*/
system("cls");
printf("Enter a source base between 2 and 10:");
scanf("%d",&sourcebase);
if((sourcebase<2||sourcebase>10)){
printf("Invalid!!!Your source base must be between 2 an 10\n\n");

continue;
}
printf("Enter a positive number whose digits are less than source base:");
scanf("%s",number,49);
length=strlen(number);
int i=0;
for( ;i<length;i++){
if((number[i]<'0')||(number[i]>=sourcebase+'0')){
printf("Error!!! number cannot be less than zero.\n\n");

break;
}
}
if (i<length) continue;

printf("Enter a target base between 2 and 10:");
scanf("%d",&targetbase);
if((targetbase<2||targetbase>10)){
printf("Invalid!!!Your target base must be between 2 an 10\n\n");

continue;
}
break;
/* Validate User Data*/
}while(1);
/* Convert to Decimal*/
for (int j=length-1; j>=0;--j){
decimal+=(number[j]-'0')*pow((float)sourcebase,power);
power++;

} int k=0;

while(decimal>0){

/* Convert to Target Base*/

remainder=decimal%targetbase;
decimal=decimal/targetbase;
new_number[k]=('0' + remainder);
++k;

}
/* Display Converted Number*/

int string_length = strlen( new_number ) ;

for( int l = string_length - 1; l >= 0; --l ){
printf("%c",new_number[l]);
}
printf("\n\n");
printf("Enter Q to quit, C to continue >");
scanf("%c", quit);

}while ((quit != 'Q') && (quit != 'q'));
return 0;

}
CERTIFIED EXPERT
Top Expert 2009

Commented:
>> I'm still getting an unhandled exception error on execution saying i was trying to write to a corrupted part of memory
Where do you get the error ? With which input ? What's the exact error message (complete) ?

Commented:
On program execution after
Enter Q to quit, C to continue > iis displayed
a window pops up saying the solution has encountered an error and needs to close
Then I see Unhandled exception:System.AccessVoilationException: Attempted to read write protected memory. This is often an indiction that other memory is corrupt.
at scanf(SByte*)
at main() in baseconvertor.cpp line 90
CERTIFIED EXPERT
Top Expert 2009

Commented:
The only thing I see wrong after quickly scanning the code is your initialisation of "quit" :

char quit={'0'};

Make that :

char quit='0';

Other than that ... what compiler are you using ?

Commented:
visual C++ 2005 express

Commented:
okay i'll take it out but thanks again for everything :)
CERTIFIED EXPERT
Top Expert 2009

Commented:
There must be something in your project settings - are you sure you made a C project for a command-line executable ?

Commented:
well i used a clr empty project
CERTIFIED EXPERT
Top Expert 2009

Commented:
You probably want a Win32 console application instead

Commented:
now i'm getting the just in time debugger

Commented:
Unhandled exception at 0x102a3aa0 in hgjhg.exe: 0xC0000005: Access violation writing location 0x00000030.
CERTIFIED EXPERT
Top Expert 2009
Commented:
I watched your code a bit closer, and you have a mistake in the scnaf statement :

scanf("%c", quit);

should be :

scanf(" %c", &quit);

notice the & and the extra space before the %c

Not the solution you were looking for? Getting a personalized solution is easy.

Commented:
Now it isn't waiting for either a c or a q to be entered its  just starting over again
CERTIFIED EXPERT
Top Expert 2009

Commented:
Don't forget the space before the %c !!

Commented:
It Works! In the end its the little things. Thanks for not giving up on me!
CERTIFIED EXPERT
Top Expert 2009

Commented:
No problem :) I hope you learned something !
##### Thanks for using Experts Exchange.

• View three pieces of content (articles, solutions, posts, and videos)
• Ask the experts questions (counted toward content limit)
• Customize your dashboard and profile