SRL Archive - C/C++ Help and Tutorials

C Homework help :\


Runescapian321

2008-02-11 21:52:00

I have to 'Write a program in C that displays a reversed number' (if you input 4567 the output should be 7654). I googled this and found that using strings or arrays would make it easy, but I haven't learned how to use those yet so I suppose I'm not supposed to use them. Here is what I have so far…

int main()
{
int num1, reversed, num3, original, num5, lastnum;

printf("Please enter an integer: ");
num1 = GetInteger();
original = num1;
num5 = numdigits(num1); //numdigits is a function that finds the amount of digits
reversed = 0;
lastnum = num1 - ((num1/10)*10);
reversed = lastnum;
while(num5 > 1)
{
num1 = (original / 10) - ((original / 100) * 10);
reversed = (reversed * 10) + num1;
num5 = num5 - 1;
}



printf("The reverse of %d is: %d\n", original, reversed);
}

I'm having trouble with the loop. I'm not doing it for any specific amount of digits, so I can't do this

		while(num5 > 1)
{
num1 = (original / 10) - ((original / 100) * 10);
reversed = (reversed * 10) + num1;
num1 = (original /100) - ((original /1000) * 100);
reversed = (reversed * 100) + num1;
//etc..............
num5 = num5 - 1;
}

I can't figure out how to make it so that it'll work for any amount of digits….

GoF

2008-02-12 08:31:03


int reverse(long num)
{
long result=0,temp=num,k;
int a=0,i;

for(;temp/10!=0;temp/=10) //finds the number or digits
a++;

for(;num/10!=0;num/=10,a--)
{
k=num%10;
for(i=0;i<a;i++)
{
k*=10;
}
result+=k;
}

return result;

}

Found off google, didn't bother to think.. Should help.

Runescapian321

2008-02-12 17:50:46

Ok….Now it works for 2 and 3 digits but not for 4+ digits… I wrote the program out on paper and I got the correct answer with 4 digits (I guess I missed something…). What's making it not work?

int main()
{
int digit, digit2, reversed, original, numofdig, lastnum, num1, num2;

printf("Please enter an integer: ");
original = GetInteger();
digit = original;
numofdig = numdigits(original);
reversed = 0;

lastnum = original%10;
reversed = lastnum;

num1 = 10;
num2 = 100;
digit2 = digit;
while(numofdig > 1) [B][U]
{
digit2 = (original / num1) - ((original / num2) * num1);
reversed = (reversed * 10) + digit2;
digit2 = digit;
num1 = num1*10;
num2 = num2*10;
numofdig-=1;
}




printf(" The reverse of %d is : %d\n", original, reversed);
}