I was trying to wap to obtain every single digit of a number in order to manipulate a given number.
I think my code is right still it’s not working. Pls help me figure out the flaw.The Code goes as:
#include <stdio.h>
void main()
{
int k,r,n,i;
int ar[10];
k=0;i=0;
printf(“Enter any number”);
scanf("%d",&n);
while(n)//To get the number of digits
{
r=n%10;
n=n/10;
k++;
}
for(i=0;n!=0&&i<k; i++,n=n%10) //To store every digit in int array
{
r=n%10;
ar[i]=r;
}
for(i=0;i<k;i++)
{ printf(" %d",ar[i]);
printf(" ");
}
printf("The number of digit in the following no is%d",k);
}
while(n)//To get the number of digits
{
r=n%10;
n=n/10;
k++;
ar[k]=r;
}
for(i=0;i<k;i++)
{ printf(" %d",ar[i]);
printf(" ");
}
printf(“The number of digit in the following no is%d”,k);
1 Like
Thnk u…i m really feeling foolish after seeing ur code
one more ques…
the array is storing the number in reverse order…(input:123;output:3 2 1)
if we want to do it straight how should we do?
Instead of doing all this integer manipulation, what you can simply do is take the integer in the form of a string. Then by just taking care of ASCII codes, you can get whichever digit you like in whichever order you want.!
k = 0;
while(n > 0){
a[k++] = n%10;
n /= 10;
}
for(i = 0;i<k/2;i++){
temp = a[i];
a[i] = a[n-i-1];
a[n-i-1] = temp;
}
This is the short code to get the array of digit of a number.
1 Like
first loop is to store the digits of a number in an int array…
what’s the second loop for?
You can take an char array of MAX_NO_OF_DIGITS and then do index each digit by subtracting ‘0’ from it.
char s[10001]
scanf("%s",&s);
for(int i=0;s[i]!=’\0’;i++)
printf("%d",s[i]-‘0’);
2 Likes
^exactly what i wanted to convey!