Count Number of zeros in an integer using recursion in C++
In this tutorial, you will learn how to count the number of zeros in an integer by using recursion in C++. Counting the number of zeros can be done in different ways recursion is one of the ways of solving it. Then firstly you should know about what is recursion, Recursion is when a function calls itself. And the knowledge of using functions is required. This recursion makes the problem looks easy and makes the code simpler. So, let us see how can we write the code to count the number of zeros.
Program to count the number of zeros using Recursion in C++
In this tutorial, we use recursion to count the number of zeros. Let us take an example to get a clear idea of what should be found out and how can we find the number of zeros. In the code, First, we initialize an integer variable with a value. For example, if we take 10200 as the integer value, then by using recursive functions we get the output value should be three because there are three zeros in that number. So, we have got a basic idea of how to solve the problem and what can be found out.
Program to find the number of Zeros:
#include<iostream> using namespace std; int count(int n) { int largenum = n % 10; int smallnum = n / 10; int c {}; if (largenum == 0) c += 1; if (smallnum == 0) return 0; return count(smallnum) + c; } int main() { int n { 10620 }; cout << count(n); cout << endl; int m { 10300 }; cout << count(m); }
Code Explanation:
- First, we have to initialize an integer variable and assign a value to it. In the above code, we have assigned two values,n is equal to 10620 and m is equal to 10300.
- We create a function named count and pass the integer values to it and using small calculations we can proceed further.
- By using the integer variables and ‘if’ conditional statements to compare whether values are equal to zero or not and if they are equal to zero then count them.
- So in the problem, If we take the value as 10620 and the no of zeroes is 2. If we take the value as 10300 then the number of zeros is 3.
The output of the code is:
2 3
I hope you like the tutorial, Happy learning.
Also read: Count vowels in a string in C++
Leave a Reply