This blog is under construction

Friday, 12 July 2013

C program to increment every digit of the given number by n

Write a C program to increment every digit of the given number by n.


  #include <stdio.h>

  int main() {
        int value, carry = 0, digit, res = 0, incr;

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

        /* increment each digit by incr */
        printf("Increment each digit by :");
        scanf("%d", &incr);

        /* Reverse the number */
        while (value > 0) {
                digit = value % 10;
                res = (res * 10) + digit;
                value = value / 10;
        }

        value = res;

        /*
         * extract the reversed number from LSB to MSB
         * and increment each digit by incr
         */
        printf("Result: ");
        while (value > 0) {
                digit = value % 10;
                printf("%d", digit + incr);
                value = value / 10;
        }

        printf("\n");
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input value:234123
  Increment each digit by :5
  Result: 789678



1 comment:

  1. If the incremented digit is something more than a 10, then the output is wrong. Any updates?

    ReplyDelete