This blog is under construction

Thursday 11 July 2013

C program to extract digits of a number

Write a C program to extract digits of a number.


  #include <stdio.h>
  int main() {
        int value, i = 1, rem, rev = 0;

        /* get the input value from the user */
        printf("Enter your input value: ");
        scanf("%d", &value);

        /* reverse the given number */
        while (value > 0) {
                rem = value % 10;
                rev = (rev * 10) + rem;
                value = value / 10;
        }

        value = rev;

        /* extract digits from LSB to MSB in reversed no */
        while (value > 0) {
                rem = value % 10;
                /* print the digits */
                printf("Digit %d: %d\n", i, rem);
                value = value / 10;
                i++;
        }

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/cpgms/lab_pgms/02_control_flow$ ./a.out
  Enter your input value: 123456
  Digit 1: 1
  Digit 2: 2
  Digit 3: 3
  Digit 4: 4
  Digit 5: 5
  Digit 6: 6



No comments:

Post a Comment