I want to make a program where the user has to input a few positive integers, like: 12345.
Then I want to reverse that to: 54321.
I have to use itoa and atoi, but I am not familiar with the operation of atoi and itoa...
To reverse the digits I have to make use of an iteration function like for, while etc....
Here is my code so far:
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i;
int c;
int d;
int help=0;
char buffer [33];
printf ("Enter numbers: ");
scanf ("%d",&i);
itoa(i,buffer,10);
c=atoi(buffer);
printf("%d",buffer[d]);
getchar();
getchar();
}
Can someone help me with the iteration and reversing the digits.
If I read in the integers and store that in the variable i. Then itoa is going to make a string of those integers. That's all I know about it..
Looks like you're doing it right so far. Line 18 should probably print c rather than the buffer (which is using d, an uninitialized variable).
There are two thoughts about reversing a c-string: 1) create a new buffer and copy the contents of the old into it, but starting from the back. Then copy the new buffer into the old. 2) Initialize variables the first and last index of the buffer. Swap the data at these indecies, increase the first, decrease the last. Repeat until the first is not less than the last ( they will sort of meet in the middle).
while ( 1 )
{
constunsignedint base = 10;
unsignedint x = 0, y = 0;
printf( "Enter a non-negative number (0 - exit): " );
scanf( "%u", &x );
if ( !x ) break;
do { y = base * y + x % base; } while ( x /= base );
printf( "The reverse number: %u\n", y );
}
Not really, kindof. The code you posted would be a swap, something you would need for my #2. The indecies don't make sense though. #1 doesn't need a "help", because your reverse is stored in an entirly new array.
You need a loop for both, can't really post them because that's the thing you're trying to learn :)
#2 is a better approach, I would say:
1 2 3 4 5 6 7 8 9 10 11 12
char buffer[6] = {'1','2','3','4','5','\0'};
int first = 0;
int last = strlen(buffer) - 1;
// To do the entire array, you need a loop
// Where first is increased and last is decreased until first >= last
char store = buffer[first];
buffer[first] = buffer[last];
buffer[last] = store;
printf("%s\n", buffer);