Thanks dpitz. Your suggestion was right on target,I missed to spot the obvious, I have changed the statement to in my code and also found that I was printing with the wrong index values.
Instead of printing with index value i, I was printing with index value ndigit in my output loop. Here's my modified code that gives me the right answer.
Code:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int newbase,n,i,ascii,ndigit=0,q,r,zero;
char newrep[100];
char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
printf("Enter the number to be converted");
scanf("%d",&n);
printf("Enter the base between 2 and 36 to which the number is to be converted");
scanf("%d",&newbase);
/* zero=48;*/
q=n;
ndigit=0;
while(q!=0)
{
r=q%newbase;
ndigit+=1;
/* ascii=zero+r;
if(ascii>57)
{
ascii=ascii+7;
}*/
newrep[ndigit] = digits[r];
/* newrep[ndigit]=(char)ascii; */
q=q/newbase;
}
printf("Base %d representation of %d is\n",newbase,n);
i = ndigit;
printf("\ni = %d\n", i);
while (i>=1)
{
printf("%c",newrep[i]);
i--;
}
system("pause");
return 0;
}
Originally Posted by
dpitz
I think you didn't check your while loop after seeing the printed value of i ^^.
If you choose to convert 10 to base 2 (1010), you'll get i=4, since 1010 has 4 digits. What we're trying to say is that your while loop is
Code:
while(i < 1) { ... }
, what doesn't make sense, since i isn't smaller than 1.
I just would like to say that the fact that he hasn't found the error does not mean he didn't try or that he just copy-pasted the code. Some errors are so obvious that we don't see them.
Hope it's clear now.