C/C++ Program to remove all zeros from a number

Write a program to remove all zeros from a integer number in C/C++.

For example,

Input
809210003
Output
89213

Steps

  1. Take input from the user. Let it be N.
  2. Set num = 0. num will store the output.
  3. Repeat the following steps while N > 0
    • Set R = N % 10. This step stores the right-most digit of N in R.
    • Set N = N / 10. This step removes the right-most digit of N.
    • If R !=0, Set num = num*10 + R
    • If R==0, Do nothing
  4. The final answer is stored in num but it is reversed. So, we need to reverse num to get the answer.
#include<stdio.h>
#include<math.h>

int remove_zeros(int n)
{
	
	int r, num = 0;
	// removing zeros from n and storing the number in num
	while(n > 0)
	{
		r = n % 10;
		n = n / 10;
		if(r!=0)
		{
			num = num*10 + r;
		}
	}
	
	// we need to reverse num to obtain final answer since the above loop
	// stores digits in num in reverse order
	n = num;
	num = 0;
	while(n>0)
	{
		r = n % 10;
		n = n / 10;
		num = num*10 + r;
	}
	
	return num;
	
}

int main()
{
	int n;
	printf("Enter a Number: ");
	scanf("%d", &n);
	printf("Number after removing zeros = %d", remove_zeros(n));
}

Output

Enter a Number: 103230023
Number after removing zeros = 132323

Read

Leave a Comment

Your email address will not be published. Required fields are marked *