Split number into digits in c programming





Extract digits from integer in c language

#include<stdio.h>
int main(){
  int num,temp,factor=1;

  printf("Enter a number: ");
  scanf("%d",&num);

  temp=num;
  while(temp){
      temp=temp/10;
      factor = factor*10;
  }

  printf("Each digits of given number are: ");
  while(factor>1){
      factor = factor/10;
      printf("%d ",num/factor);
      num = num % factor;
  }

  return 0;
}

Sample output:
Enter a number: 123
Each digits of given number are: 1 2 3






7 comments:

  1. sir in this example we are able to extract all integer values except 0, i mean if i choose the number 120 then the output is only 1 2 . it does not display zero.how to remove this error

    ReplyDelete
  2. #include


    int main()
    {
    int r,sum=0,a[100],i=0,num,j;
    printf("enter the number");
    scanf("%d",&num);
    while(num>0)
    {
    i++;
    r=num%10;
    num=num/10;
    a[i]=r;

    }
    printf("each digit of a given number is: ");
    for( j=i;j>=1;j--)
    printf("%d ",a[j]);

    return 0;
    }

    ReplyDelete
  3. This is another solution.

    #include
    main()
    {
    int num, temp, foo = 1;
    scanf("%d",&num);
    temp = num;
    while(num > 9)
    {
    foo *= 10;
    num /= 10;
    }
    while(foo)
    {
    printf("%d ",temp/foo);
    temp %= foo;
    foo /= 10;
    }
    }

    ReplyDelete
  4. #include
    #include
    int main()
    {
    int num,r,a[10],i=0,j;
    clrscr();
    printf("Enter a number:\n");
    scanf("%d",&num);

    while(num)
    {
    r=num%10;
    a[i]=r;
    num=num/10;
    i++;
    }
    printf("After spliting:");
    for(j=i-1;j>=0;j--)
    printf("%d ",a[j]);
    getch();
    return 0;
    }

    ReplyDelete
  5. #include
    #include

    int main()
    {
    int n,c=0,i,num,temp;
    printf("Enter the value of intger:- ");
    scanf("%d",&n);
    num=n;
    for(;n>0;n/=10)
    {
    c++;
    }
    int a[c];
    for(i=0;i=0;i--)
    {
    printf("%d ",a[i]);
    }
    return 0;
    }

    ReplyDelete
  6. Can anyone dry run this this program to explain the logic? Help me please.

    ReplyDelete
  7. #include
    int main ( int argc, char* argv[] )
    {
    printf ( "Enter a Number :\t" ) ;
    int nNumber ;
    scanf ( "%i", &nNumber ) ;

    int nBuffer ;
    while ( nNumber != 0 ) { nBuffer *= 10 ; nBuffer += nNumber % 10 ; nNumber /= 10 ; }
    printf ( "DIGITS SPLITTED :\n" ) ;
    while ( nBuffer != 0 ) { printf ( "%i ", nBuffer % 10 ) ; nBuffer /= 10 ; }
    }

    ReplyDelete