Problem with program that uses a function to convert decimal values to binary values.
The program works fine until I start using 6 digits or more, then I just get the first value of my binary number.
I have the menu part in main because I'm planning on doing all the other conversions in different functions for example octal to hex or binary to hex.
The switch statement is there to reverse the order of the numbers because the least value should be in the end not in the start like it would appear without the switch.
I am grateful for any help I can get in advance ,thank you.
Code:
#include<iostream>
using namespace std;
int decimal_to_binary(int decb)
{
int counterb; //The remainder varaible for the process
int round=0; // To show the program where to put each number
int h[5];
int limit; //To show when the loop should start or end so unused array slots won't be displayed
int i;
while(decb>0)
{
counterb=0;
round++;
if(decb%2!=0) //Where the process of conversion to a binary number happens
{
counterb++;
}
else
{
counterb=0;
}
switch(round) //The process of putting each digit into it's coressponding memory slot
{
case 1:
h[1]=counterb;
limit=1;
break;
case 2:
h[2]=counterb;
limit=2;
break;
case 3:
h[3]=counterb;
limit=3;
break;;
case 4:
h[4]=counterb;
limit=4;
break;
case 5:
h[5]=counterb;
limit=5;
break;
case 6:
h[6]=counterb;
limit=6;
break;
case 7:
h[7]=counterb;
limit=7;
break;
case 8:
h[8]=counterb;
limit=8;
break;
case 9:
h[9]=counterb;
limit=9;
break;
case 10:
h[10]=counterb;
limit=10;
break;
default: cout<<"Error in array memory";
}
if(decb<=1) break;
decb=decb/2;
}
for(i=limit;i>=1;i--) //Displaying the digits form max value to least value e.g 100th 10th and so on
cout<<h[i];
return 1;
}
int main()
{
int choice;
cout<<"Welcome to the value converter"<<endl<<"1.Conversion from decimal to binary ."<<endl; //Menu for the other programs I'm working on
cin>>choice;
switch(choice)
{
case 1:
{
int dec;
cout<<"Enter the number"<<endl;
cin>>dec;
decimal_to_binary(dec);
}
break;
}
return 0;
}
The new shorter code (thanks again guys)
Code:
#include<iostream>
using namespace std;
int decimal_to_binary(int decb)
{
int counterb;
int round=0;
int h[10]; //0-9 means 10 won't forget it again
int limit=0;
int i;
while(1)
{
counterb=0;
if(decb%2!=0)
{
counterb++;
}
else
{
counterb=0;
}
h[round] = counterb; //Replaced the whole switch
limit = round; //No range change was needed
if(decb<=1) break;
decb=decb/2;
round++;
}
for(i=limit;i>=0;i--)
cout<<h[i];
return 1;
}
int main()
{
int choice;
cout<<"Welcome to the value converter"<<endl<<"1.Conversion from decimal to binary ."<<endl;
cin>>choice;
switch(choice)
{
case 1:
{
int dec;
cout<<"Enter the number"<<endl;
cin>>dec;
decimal_to_binary(dec);
}
break;
}
return 0;
}
It works perfectly now!