dhanur sehgal dhanur sehgal - 3 months ago 15
C Question

Interchanging the first and last digits of a number in C

Interchanging the first and last digits of a number in C.
I cracked the question using most basic knowledge of c.
I haven't used any strings or arrays or bit-wise operator, just simple logic. for clearer understanding take an example and see.

#include <stdio.h>

int main()
{
int a,x,y,n=1,b;
printf("enter no");
scanf("%d",&a);
b=a; //used further
if(a>0)
{
y=a%10; //last digit
}
while(a>0)
{
x=a%10;
if(a>0 && a<=9)
{
x=a; //first digit
}
a=a/10;
n=n*10;
}
n=n/10;
printf("%d\n%d\n%d\n%d\n",b,n,x,y); //just to confirm readings
b=(b-y);
b=(b+x);
b=b-(x*n);
b=b+(y*n);
printf("%d",b);
}

Answer

Hope already you know what to fix: printf("%d",&b).

Just for information. You could do it more simply:

int num;
scanf("%d",&num);

char snum[50];

// convert to string
int len = sprintf(snum, "%d", num);

// character swap
char temp = snum[0];
snum[0] = snum[len-1];
snum[len-1] = temp;

// convert to int or use the snum string
int result = atoi(snum);
printf("%d\n", result);
Comments