Saturday, December 17, 2011

Somebody HELP me with this C++ program?

I dont know what is wrong it is supposed to convert decimal to binary!


Can I declare Arrays whose number of elements is variable?


How?


This program already output


the binary equivalent but it has extra numbers


#include %26lt;iostream.h%26gt;


void main ()


{


int num,xnum,dgts,counter;


cout%26lt;%26lt;"Enter Number"%26lt;%26lt;endl;


cin%26gt;%26gt;num;


if(num%26lt;=1)


cout%26lt;%26lt;endl%26lt;%26lt;num;


else


{


xnum=num;


dgts=0;


while(xnum%26gt;=1)


{


xnum=xnum/2;


dgts+=1;


}


int bnr[50];


for (counter=0;counter%26lt;dgts;counter++)


{


bnr[counter]=num%2;


num=num/2;


}


cout%26lt;%26lt;endl%26lt;%26lt;"The number entered converted to binary is ";


while(dgts%26gt;=0)


{


dgts=dgts-1;


cout%26lt;%26lt;bnr [dgts];


}


}


}|||Everything is right in the program. Only at the end, while printing the number, you are making a mistake. The while loop should be


"while (dgts%26gt;0)" instead of while(dgts%26gt;=0).


Whats happening is at the end, when dgts = 0;





dgts = dgts -1, will make dgts = -1;


and then you are trying to access bnr[-1], which is illegal.





And certainly you can use a dynamic array, instead of static. Using dynamic arrays you can have whose number of elements is variable.





In above example instead of int bnr[50], you can simply declare int * bnr;


And then when you know how mnay elements you need, you can allocate memory as :





bnr = (int *)malloc(dgts * sizeof(int));


The rest of the program will be as it is.


Here is the entire right program, with dynamic memory.





#include %26lt;iostream.h%26gt;


void main ()


{


int num,xnum,dgts,counter;


cout%26lt;%26lt;"Enter Number"%26lt;%26lt;endl;


cin%26gt;%26gt;num;


if(num%26lt;=1)


cout%26lt;%26lt;endl%26lt;%26lt;num;


else


{


xnum=num;


dgts=0;


while(xnum%26gt;=1)


{


xnum=xnum/2;


dgts+=1;


}


int *bnr;


bnr = (int *)malloc(dgts * sizeof(int));


for (counter=0;counter%26lt;dgts;counte++)


{


bnr[counter]=num%2;


num=num/2;


}


cout%26lt;%26lt;endl%26lt;%26lt;"The number entered converted to binary is ";


while(dgts%26gt;0)


{


dgts=dgts-1;


cout%26lt;%26lt;bnr [dgts];


}


}


}|||OK, I haven't compiled your given code in my compiler, but looking at the code, and assuming that you are getting the binary equivalent, with extra digits means that your array bnr[ ] is printing out ALL the elements in it.


I suggest you first initialize the array before assigning it any value. Then, you can assign a NULL character to index after that last element of the array. This should solve the problem.


Good Luck!

No comments:

Post a Comment