# C program to replace all zeros with one in a given integer.

CServer Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

## Problem

Write a program to replace all zeros (0's) with 1 in a given integer.

Given an integer as an input, all the 0's in the number has to be replaced with 1.

## Solution

Consider an example given below −

Here, the input is 102410 and the output is 112411.

## Algorithm

Refer an algorithm given below to replace all the 0’s to 1 in an integer.

Step 1 − Input the integer from the user.

Step 2 − Traverse the integer digit by digit.

Step 3 − If a '0' is encountered, replace it by '1'.

Step 4 − Print the integer.

## Example

Given below is the C program to replace all 0's with 1 in a given integer −

Live Demo

#include<stdio.h>
int replace(long int number){
if (number == 0)
return 0;
//check last digit and change it if needed
int digit = number % 10;
if (digit == 0)
digit = 1;
// Convert remaining digits and append to its last digit
return replace(number/10) * 10 + digit;
}
int Convert(long int number){
if (number == 0)
return 1;
else
return replace(number);
}
int main(){
long int number;
printf("Enter any number : ");
scanf("%d", &number);
printf("After replacement the number is : %dn", Convert(number));
return 0;
}

## Output

When the above program is executed, it produces the following output −

Enter any number: 1056110010
After replacement the number is: 1156111111
Updated on 26-Mar-2021 06:56:47