Learn how to write a C program to replace all occurrences of 0 with 1 in a given number. This guide provides a step-by-step approach to modifying the digits of an integer, using mathematical operations to achieve the desired result. The tutorial includes clear explanations, sample code, and tips for handling different scenarios. Ideal for those looking to manipulate and process numeric data in C.
#include <stdio.h> int main() { int num, remainder, result = 0, multiplier = 1; printf("Enter a number: "); scanf("%d", &num); while (num > 0) { remainder = num % 10; if (remainder == 0) remainder = 1; result += remainder * multiplier; num /= 10; multiplier *= 10; } printf("Number after replacing 0's with 1's: %d\n", result); return 0; }
Inside the main() function:
- Integer variables `num`, `remainder`, `result`, and `multiplier` are declared to store the input number, remainder, result after replacement, and multiplier respectively.
- The user is prompted to enter a number.
- Using a while loop, each digit of the number is extracted from right to left.
- If the digit is 0, it is replaced with 1.
- The result is updated by adding the modified digit multiplied by the corresponding place value.
- Finally, the number after replacing 0's with 1's is printed to the console.