Monday, May 24, 2010

Write a program in c/c++ to print a new no. by adding one to each of its digit.?

.if a five digit no. is input through the keyboard .write a program in c/c++ to print a new no. by adding one to each of its digit.e.g. 12391 then output must be 23402.

Write a program in c/c++ to print a new no. by adding one to each of its digit.?
You MIGHT think the answer is as simple as adding 11111 to the number, but that would be incorrect, since 12391 + 11111 = 23502 (not 23402)...





Thus, we need to account for the "9" which (according to the specification) must yield a "0" result and not a "10" (i.e. "carry")...





So...


the code fragment for this would look something like this...





int i, digits[5], input=12391;


/* Extract the digits and add 1 to each %26amp; get single digit answer*/





for (i=4; i%26gt;=0; i--) {


digits[i] = (input%10 + 1) %10;


input/=10;


}





/* print the digits in order */


for (i=0; i%26lt;5; i++)


putchar (digits[i] + '0');





}
Reply:Since there are only 10 digits, easiest way is to create an array of that maps number 0 to 9, to its new value, then iterate through input and get the output from the defined mapping array.


No comments:

Post a Comment