C Program for replacing one digit with other


Given a number n, we have to replace a digit x from that number with another given number m. we have to look for the number whether the number is present in the given number or not, if it is present in the given number then replace that particular number x with another number m.

Like we are given with a number “123” and m as 5 and the number to be replaced i.e. x as “2”, so the result should be “153”.

Example

Input: n = 983, digit = 9, replace = 6
Output: 683
Explanation: digit 9 is the first digit in 983 and we have to replace the digit 9 with 6 so the result will be 683.
Input: n = 123, digit = 5, replace = 4
Output: 123
Explanation: There is not digit 5 in the given number n so the result will be same as the number n.

The approach used below is as follows

  • We will look up for the number by starting from the unit place
  • When we found the digit which we want to replace then add result to the (replace * d) where d should be equal to 1.
  • If we don’t found the number just simply keep the number as it is.

Algorithm

In function int digitreplace(int n, int digit, int replace)
   Step 1-> Declare and initialize res=0 and d=1, rem
   Step 2-> Loop While(n)
      Set rem as n%10
      If rem == digit then,
         Set res as res + replace * d
      Else
         Set res as res + rem * d
         d *= 10;
         n /= 10;
      End Loop
   Step 3-> Print res
      End function
In function int main(int argc, char const *argv[])
   Step 1-> Declare and initialize n = 983, digit = 9, replace = 7
   Step 2-> Call Function digitreplace(n, digit, replace);
Stop

Example

 Live Demo

#include <stdio.h>
int digitreplace(int n, int digit, int replace) {
   int res=0, d=1;
   int rem;
   while(n) {
      //finding the remainder from the back
      rem = n%10;
      //Checking whether the remainder equal to the
      //digit we want to replace. If yes then replace.
      if(rem == digit)
         res = res + replace * d;
      //Else dont replace just store the same in res.
      else
         res = res + rem * d;
         d *= 10;
         n /= 10;
   }
   printf("%d
", res);       return 0; } //main function int main(int argc, char const *argv[]) {    int n = 983;    int digit = 9;    int replace = 7;    digitreplace(n, digit, replace);    return 0; }

If run the above code it will generate the following output −

783

Updated on: 21-Oct-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements