Recursive function to count the amount of digits in a number - c++

Is there a way to code a recursive function that prints the number of the digits in a number such that:
-It is a void function
-The "if" condition is if(num==0), return
-The "else" will call the recursion.
I saw 2 different types of codes, one of them is where the "if" condition has the recursive call and the else is for "return". But thats not what I want.
I am pretty bad with recursion and trying to understand it by coding myself, but unsuccessfully.
This is my code(I understand why it prints 122 instead of 3 but I dont really know how code it differently. Help anyone?)
#include <iostream>
#include <string.h>
using namespace std;
void numOfDigits(unsigned int num);
int main(){
int num = 994;
numOfDigits(num);
}
void numOfDigits(unsigned int num)
{
int size = 1;
if (num==0)
return;
else
{
if (num / 10 != 0)
size++;
numOfDigits(num / 10);
}
cout << size;
}

A quick hack that makes this code work is to make size static, that is, change
int size = 1;
to
static int size = 1;
But that only works the first time you call the function.
For a more robust solution, in each call to the function you have to pass the count so far:
void numOfDigits(unsigned int num, int countSoFar = 0) {
if (num == 0)
std::cout << countSoFar << '\n';
else
numOfDigits(num / 10, countSoFar + 1);
}

You have a number of mistakes in the numOfDigits() function.
First, you are declaring a new local variable called size each time the function is called. This has no relation to the 'size' defined in the calling function. To see this, print size after initializing it. To fix this, make size static; it will then use the same static variable each time you call the function.
As you are printing size at the end of the function, it simply gives the value of the size variable after that function is run. Even if you set size as static, you will also print the intermediate values of size. An easy way to fix this is to allow the function to return size, and you would have to simply print the value of the function in the main function.
#include <iostream>
#include <string.h>
using namespace std;
int numOfDigits(unsigned int num);
int main(){
int num = 994;
cout<<numOfDigits(num);
}
int numOfDigits(unsigned int num)
{
static int size = 1;
if (num==0)
return 0;
else
{
if (num / 10 != 0)
size++;
numOfDigits(num / 10);
}
return size ;
}
Make sure to put the case with (num == 0) as you want; in this case it prints 0 as the answer.
PS: Always put a space after printing numbers. Otherwise you might think that 1 2 2 (which are the numbers actually printed) is the number 122.

You can pass a value by reference and make use of it, initialize ans=0 every time you call this function
void recursive(unsigned int num,int &ans){
if(num == 0){
return;
}
else{
ans++;
recursive(num/10,ans);
}
}
See this and this

Without using any global variable, this code works. Just a little note: you declared unsigned int the argument, but the number you give to the function is a signed integer.
#include <iostream>
#include <string.h>
using namespace std;
void numOfDigits(unsigned int num, unsigned int& digits);
int main(){
unsigned int num = 93934;
unsigned int digits = 1;
numOfDigits(num, digits);
cout <<digits <<endl;
return 0;
}
void numOfDigits(unsigned int num, unsigned int& digits) {
if (num==0){
return;
}else{
if (num / 10 != 0){
++digits;
numOfDigits(num / 10, digits);
}
}
}

try declaring size globally because it was intialized every time when the funtion executes
int size = 1;
void numOfDigits(unsigned int num)
{
if (num==0)
return;
else
{
if (num / 10 != 0)
size++;
numOfDigits(num / 10);
}
}
print value of size inside main

#include <iostream>
#include <string.h>
using namespace std;
void numOfDigits(unsigned int num);
void main(){
int num = 994;
int size = 1;
cout << numOfDigits(num, size);
}
void numOfDigits(unsigned int num, int &size)
{
if (num==0)
cout<<size;
else
{
if (num / 10 != 0)
size++;
numOfDigits(num / 10, size);
}
}

I think your misunderstanding is that you assume that size is one single variable. However, in every call of your function, you have a different one. Also, every call of your function will print it again.
The cout in your main does nothing, since it prints a void, which has no content.
Usually, you'd give it a return parameter that is the accumulated number, like
int numOfDigits(unsigned int num);
void main(){
cout << numOfDigits(994) << endl;
}
If you don't want that for some reason, you could do it by reference:
int numOfDigits(unsigned int num, unsigned int& digits);
void main(){
unsigned int digits;
numOfDigits(994,digits);
cout << digits << endl;
}
but that is not that good.
That said, in terms of style, what I would do is either making it a loop (idea is that you want to avoid recursion most times):
unsigned int numOfDigits(unsigned int num){
if(num == 0) { return 1; }
unsigned int size = 0;
while(num != 0){
size++;
num /= 10;
}
return size;
}
which can be also done with a call by reference return value. But again, that is somewhat strange if not necessary.
You might even make it a one-liner by using mathematics, cout << floor(log_10(num)) << endl; (not accounting for the special case if num is zero)
One solution that would also work is to make size a global variable. However, I'd advice against that. Global variables should be avoided in general. Just wanted to mention it if somebody else recommends it.
Lastly, you could go with a class, like DigitsCounter that is usually short lived and does the recursive call on methods, with the size variable being a class member. That is overkill in your case, though.

try this code :
int numOfDigits(unsigned int num)
{
int size = 1;
if (num!=0)
{
if (num / 10 != 0)
size+= numOfDigits(num / 10);
}
return size;
}
use the return value in your main function

The problem with using a void return type on recursive functions is that it's not possible for the nested calls to return any information back to the method which invoked them. If we want to print the value at the first (outer) call, that first call can't gain any information from it's recursive call.
As you've observed, it's not possible to simply print the value as we go, since there isn't a one-to-one mapping from recursive calls to characters of the output (if we use Base 10... see the appendix). If we relax the condition that the if condition must return immediately, we can avoid this problem by passing the information as parameters to the recursive call and then printing the value at the deepest level of recursion. For example:
// The accumulator starts at 0, then increases by 1 for each recursive call
void numOfDigits(unsigned int num, unsigned int accumulator = 0) {
if (num == 0) {
if (accumulator == 0) cout << 1; // Special case: numOfDigits(0) = 1
else cout << accumulator;
} else numOfDigits(num / 10, accumulator + 1);
}
Side-note: This is now a tail-recursive method: it makes the recursive call as its last action. This is useful, since it allows the compiler to reduce the space complexity of the method (see explanation). Essentially, the compiler transforms the method to simple iteration, eliminating the need for accumulating stack frames.
Appendix: The only way I can see to keep constraint (2) is to print the number of digits in Base 1, since each digit taken from the argument corresponds directly to a single character in Base 1). This probably isn't what you meant, but here's a solution:
// The accumulator starts at 0, then increases by 1 for each recursive call
void numOfDigits(unsigned int num) {
if (num == 0) return;
else {
cout << 1
numOfDigits(num / 10);
}
}
N.B. This method will not print anything for numOfDigits(0), which is necessary if we want to keep the line if (num == 0) return;

numOfDigits is a void function
The "if" condition is if(num==0), return
The "else" will call the recursion.
Here:
void numOfDigits(unsigned int num) {
if (num == 0)
return;
// The "else" will call the recursion.
else {
static int size = 1;
if (num / 10 != 0) {
size++;
numOfDigits(num / 10);
}
else {
cout << size << '\n';
size = 1;
}
}
}

Related

remove odd numbers

I need to resolve this problme "Write a recursive function called removeCharge that receives an N number and returns a number that contains only the digits of the original number." I made it but now i don't know how to display the number in the same function.What can I do?
int newNumber=0;
int eliminareCifreImpare(int n){
if(n==0)
return 0;
eliminareCifreImpare(n/10);
int c=n%10;
if(c%2==0)
newNumber=newNumber*10+c;
}
I guess you are using a global variable because you don't properly understand how to return values from functions. You need to get a good understanding of how functions return values and how to use returned values before you try to write recursive functions.
Here's a working version
#include <iostream>
int eliminareCifreImpare(int n) {
if (n == 0)
return 0;
int newNumber = eliminareCifreImpare(n / 10);
int c = n % 10;
if (c % 2 == 0)
newNumber = newNumber * 10 + c;
return newNumber;
}
int main()
{
std::cout << eliminareCifreImpare(12345) << std::endl;
}

When i recurse the following code on function prime the program crashes what is wrong in my code?

Whenever I try to recurse in the function prime, my program crashes at that step. I think the problem is passing the function small as a recursion. What am I doing wrong?
#include <iostream>
using namespace std;
int smallest(int n) {
for( int x = 2 ; x <= n/2 ; x++){
if (n%x==0) {
return x;
}
else {
return 0;
}
}
}
int prime(int n, int(*small)(int)) {
int factor;
if (n == 1){
return 0;
}
else {
factor = n % small(n);
cout << small(n) << endl;
return prime(factor , small);
}
}
int main() {
prime(50 , &smallest);
return 0;
}
As the comments point out, when small returns 0, you continue recursing when you shouldn't. This can be solved with a small update to your base case:
if (n <= 1){
return 0 ;
}
Furthermore, it's worth pointing out that as it stands, your prime function will never call itself more than once. When you call smallest, you are guaranteed to get a prime number!

Value assignment into array c++

I'm trying to create a array of prime numbers done by calculation. As a project to learn coding. Ultimately to build my own math library so this is something I can add onto at a variety of levels as I learn to code c++.
The following is code that works great for printing prime numbers to the screen based on the search range, but my totalPrimes iterator is stuck at 1. So each time it places the last prime found in the PrimeNumbers[1] position.
Any advice would be awesome.
#include <iostream>
#include <array>
std::array<long, 10000000> PrimeNumbers={0};
void isPrime(long x);
int main() {
for (long i = 1; i < 10; i++) {
isPrime(i);
}
for(int h = 0; h < 10; h++) {
std::cout << "\nSecond Prime is : " << PrimeNumbers[h];
}
}
void isPrime(long x) {
int count(0), totalPrimes(0);
for (long a = 1; a < x; a++) {
if ((x % a) == 0) {
count += 1;
}
}
if (count == 1) {
++totalPrimes;
std::cout << '\n' << x << " is a Prime number";
PrimeNumbers[totalPrimes] = x;
}
}
You're initializing totalPrimes to 0 every time the function runs. You would need to have totalPrimes as a global variable, or better yet (because global variables can become problematic), set it equal to the first available member of PrimeNumbers before you do anything else in that function.
Keep track of a position along with your PrimeNumbers array.
size_t nLastPos=0;
...
for(size_t x = 0; 1000 > x; ++x)
{
if(isPrime(x))
{
PrimeNumbers[nLastPos++] = x;
}
}
for(size_t i = 0; nLastPos > n; ++n)
{/* print out number PrimeNumbers[n] */ }
It looks like you're having some trouble with variable scoping. The reason for your problem (as I noted in the comment) is that totalPrimes is local, so you're creating a new integer variable and setting it to 0 every time the function is called.
However, you've made PrimeNumbers global and are having the isPrime function modify it, which doesn't look like good practice.
All of this can be fixed with a little restructuring to make the code nicer:
#include <iostream>
#include <array>
bool isPrime(long x);
int main() {
std::array<long, 10000000> PrimeNumbers={0};
int totalPrimes = 0;
for (long i = 1; i < 10; i++) {
if (isPrime(i)) {
std::cout << '\n' << i << " is a Prime number";
PrimeNumbers[totalPrimes++] = i;
}
}
for(int h = 0; h < 10; h++) {
std::cout << h << " Prime is : " << PrimeNumbers[h] << std::endl;
}
}
bool isPrime(long x) {
int count(0);
for (long a = 1; a < x; a++) {
if ((x % a) == 0) {
count += 1;
}
}
return count == 1;
}
Your program can be re-structured little bit to make it easier to follow and debug.
Don't put things in isPrime other than the logic to decide whether a number is prime. Make sure it returns a bool. This will make the function a bit simpler and easier to debug.
Use the return value of isPrime in the calling function to perform other bookkeeping tasks.
The logic you have used to check whether a number is prime is incorrect. That needs to be fixed.
Here's an updated version of your posted code.
#include <iostream>
#include <array>
#include <cmath>
std::array<long, 10000000> PrimeNumbers={0};
bool isPrime(long x);
int main()
{
int totalPrimes = 0;
for (long i = 1; i < 10; i++)
{
if ( isPrime(i) )
{
std::cout << i << " is a Prime number" << std::endl;
PrimeNumbers[totalPrimes] = i;
++totalPrimes;
}
}
}
bool isPrime(long x) {
// 1, 2, and 3 are primes.
if ( x <= 3 )
{
return true;
}
// Even numbers are not primes.
if ( x % 2 == 0 )
{
return false;
}
// Check the rest.
long end = (long)std::sqrt(x);
for (long a = 3; a < end; a += 2) {
if ((x % a) == 0)
{
return false;
}
}
return true;
}
and its output:
1 is a Prime number
2 is a Prime number
3 is a Prime number
5 is a Prime number
7 is a Prime number
9 is a Prime number
Everybody is talking about how your totalPrimes variable is reset each time the function is called, and this is obviously true. You could return the value from the function and increment it from main, you could use global variables having the variable being defined outside of the function so that it's not reset each time inside the function or you could use
A static variable!
Take a look at this simple case. I have a function called up_two which increases the value of by two each time the function is called. The static variable int value has a memory of each time the function up_two() is called which increments value by two each time. If I were to use a just an integer it would always reset the value and have it be zero, which is what I initially defined it to be.
The advantage of using a static variable is that I can count how many times a function has been called, and I can keep my counter specific to a particular function.
#include <iostream>
using namespace std;
void up_two();
int main()
{
for(int i = 0; i < 10; i++)
{
up_two();
}
return 0;
}
void up_two()
{
static int value = 0;
cout << value << endl;
value += 2;
}
This program doesn't solve the particular problem that you want to solve, but if you figure out how the static variable is working, it should make your workflow easier.
The magic line here is this:
static int value = 0;
With it like this my program prints the following:
0
2
4
6
8
10
12
14
16
18
Without the static declaration, you just get 10 lines of zeroes
which is troublesome.
Hope that helps you optimize your program the way you want it to be.

Recursive/iterative functions

I'm having a bit of a hard time creating a function, using iteration and recursion to find the sum of all even integers between 1 and the number the user inputs. The program guidelines require a function to solve this three ways:
a formula
iteration
recursion
This is what I have so far:
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
void formulaEvenSum(int num, int& evenSum)
{
evenSum = num / 2 * (num / 2 + 1);
return;
}
void loopEvenSum(int num, int& evenSum2)
{
}
int main()
{
int num, evenSum, evenSum2;
cout << "Program to compute sum of even integers from 1 to num.";
cout << endl << endl;
cout << "Enter a positive integer (or 0 to exit): ";
cin >> num;
formulaEvenSum(num, evenSum);
loopEvenSum(num, evenSum2);
cout << "Formula result = " << evenSum << endl;
cout << "Iterative result = " << evenSum2 << endl;
system("PAUSE");
return 0;
}
Using iteration to find the sum of even number is as given below.
void loopEvenSum(int num, int &evenSum2)
{
evenSum2=0;
for (i=2;i<=num;i++)
{
if(i%2==0)
evenSum2+=i;
}
}
The following code though not the most efficient can give you an idea how to write a recursive function.
void recursiveEvenSum(int num,int &evenSum3,int counter)
{
if(counter==1)
evenSum3=0;
if(counter>num)
return;
if(counter%2==0)
evenSum3+=counter;
recursiveEvenSum(num,evenSum3,counter+1);
}
Now you can call recursiveEvenSum(...) as
int evenSum3;
recursiveEvenSum(num,evenSum3,1);
You should be able to build an iterative solution using a for loop without too much problem.
A recursive solution might take the form:
f(a)
if(a>0)
return a+f(a-1)
else
return 0
f(user_input)
You have to differentiate between a case where you "dive deeper" and one wherein you provide an answer which doesn't affect the total, but begins the climb out of the recursion (though there are other ways to end it).
An alternative solution is a form:
f(a,sum,total)
if(a<=total)
return f(a+1,sum+a,total)
else
return sum
f(0,0,user_input)
The advantage of this second method is that some languages are able to recognise and optimize for what's known as "tail recursion". You'll see in the first recursive form that it's necessary to store an intermediate result for each level of recursion, but this is not necessary in the second form as all the information needed to return the final answer is passed along each time.
Hope this helps!
I think this does it Don't forget to initialize the value of evenSum1, evenSum2 and evenSum3 to 0 before calling the functions
void loopEvenSum(int num, int& evenSum2)
{
for(int i = num; i > 1; i--)
if(i%2 == 0)
evenSum2+=i;
}
void RecursiveEvenSum(int num, int & evenSum3)
{
if(num == 2)
{
evenSum3 + num;
return;
}
else
{
if(num%2 == 0)
evenSum3+=num;
num--;
RecursiveEvenSum(num, evenSum3);
}
}
void loopEvenSum(int num, int& evenSum2)
{
eventSum2 = 0;
for(int i = 1 ; i <= num; i++){
(i%2 == 0) eventSum += i;
}
}
void recurEvenSum(int num, int& evenSum3)
{
if(num == 1) return;
else if(num % 2 == 0) {
eventSum3 += num;
recurEvenSum(num-1, eventSum3);
}
else recurEvenSum(num-1, eventSum3);
}
btw, you have to initialize evenSum to 0 before calling methods.
the recursive method can be much simpler if you return int instead of void
void iterEvenSum(int num, int& evenSum2)
{
evenSum2 = 0;
if (num < 2) return;
for (int i = 0; i <= num; i+=2)
evenSum2 += i;
}
int recurEvenSum(int num)
{
if (num < 0) return 0;
if (num < 4) return 2;
return num - num%2 + recurEvenSum(num-2);
}
To get the sum of all numbers divisible by two in the set [1,num] by using an iterative approach, you can loop through all numbers in that range, starting from num until you reach 2, and add the number of the current iteration to the total sum, if this is divisible by two.
Please note that you have to assign zero to evenSum2 before starting the loop, otherwise the result will not be the same of formulaEvenSum().
void loopEvenSum(int num, int& evenSum2)
{
assert(num > 0);
evenSum2 = 0;
for (int i=num; i>=2; --i) {
if (0 == (i % 2)) {
evenSum2 += i;
}
}
}
To get the same result by using a recursive approach, instead of passing by reference the variable that will hold the sum, i suggest you to return the sum at each call; otherwise you'll need to hold a counter of the current recursion or, even worse, you'll need to set the sum to zero in the caller before starting the recursion.
int recursiveEventSum(int num)
{
assert(num > 0);
if (num == 1) {
return 0;
} else {
return ((num % 2) ? 0 : num) + recursiveEventSum(num-1);
}
}
Please note that, since you get an even number only if you subtract two (not one) from an even number, you could do optimisation by iterating only on those numbers, plus eventually, the first iteration if num was odd.

A Recursion function in C++

If I have this recursive function:
int mystery(int n) {
if ( n == 0 || n == 1 || n == 2) return n ;
return (mystery(n-1) + mystery(n-2) + mystery(n-3)) ;
}
I am working with finding mystery(20).
How can I find out how many addition operations are carried out when calculating the function and how many invocations of mystery() there are in order to calculate mystery(20)?
I tried adding some cout statements like:
int mystery(int n) {
if ( n == 0 || n == 1 || n == 2) {
cout << n << endl;
return n ;
}
cout << n << endl;
return (mystery(n-1) + mystery(n-2) + mystery(n-3)) ;
}
But I couldn't really make sense of it since there were over a thousand numbers outputted. And I don't believe those cout statements do much in the way of telling me how many addition operations are carried out and how many invocations of mystery() there are in order to calculate mystery(20)?
Thanks for any and all help!
The easiest way to do is to increment a global (or static global) variable.
Something like to get the number of mystery call:
int nb_of_invok = 0;
int mystery(int n)
{
nb_of_invok++;
...your code here...
}
And this to get the number of additions:
int nb_of_invok = 0;
int nb_of_add = 0;
int mystery(int n)
{
nb_of_invok++;
if(...)return n;
nb_of_add++;
return(...);
}
If I'm understanding you correctly... you can use a static counter variable and increment that every time you call the method. Alternatively, you can pass around a reference to the counter and just increment that.
This is possible to figure out with math. But if you wanted to measure it empirically, you could use a static counter in the function. This logic is easy to extend to counting the number of additions as well.
int mystery(int n) {
static int invocations = 1;
cout << "mystery has been invoked " << invocations++ << " times.\n";
if ( n == 0 || n == 1 || n == 2) {
return n ;
}
return (mystery(n-1) + mystery(n-2) + mystery(n-3)) ;
}
You could also use a global variable. I don't like either of those solutions though. They make multi-threading hard, and they violate some important design principles. As a one-off to answer this question and then remove from your code they're fine, but what I would do if I wanted this as a permanent feature is this:
#include <iostream>
class counted_mystery {
public:
counted_mystery() : invocations_(0), additions_(0) { }
unsigned int getInvocations() const { return invocations_; }
void resetInvocations(unsigned int newval = 0) { invocations_ = newval; }
unsigned int getAdditions() const { return additions_; }
void resetAdditions(unsigned int newval = 0) { additions_ = newval; }
operator ()(int n) {
++invocations_;
counted_mystery &mystery = *this;
if ( n == 0 || n == 1 || n == 2) {
return n ;
}
// The code is about to perform two additions.
additions_ += 2;
return (mystery(n-1) + mystery(n-2) + mystery(n-3));
}
private:
unsigned int count_, additions_;
};
int main(int argc, char *argv[])
{
using ::std::cout;
counted_mystery mystery;
mystery(20);
cout << "mystery was called " << mystery.getCount() << " times for n == 20\n";
return 0;
};
Figuring this out with math is an interesting problem, but likely not too hard. I think it will turn out to be exponential.
BTW, don't use endl unless that's what you mean to use. It's very slow since it forces a buffer flush whenever you use it. Use '\n'.
Another option is to make this is method of a class which would allow use of a member variable rather than a global, and at the same time keeps the int mystery(int) interface clean.
Declare two different static int variables to keep track of number of times invoked and number of addition operations.
Use (and increment) a global variable. http://www.cplusplus.com/doc/tutorial/variables/
I would type an example but I've got a hand injury.