Vishal Sharma Vishal Sharma - 2 months ago 6
C++ Question

Execution of code in else block and after if block

In this code i want to know what is the difference between code executed in else and code executed after if block?

#include <iostream>
using namespace std;

int digits(int number, int value, int times){
int counter = times;
counter++;
int result = number/value;
value=value*10;
if (result != 0){
digits(number,value,counter);
}
return counter;
}

int main() {
int number,no_of_digit;
cout << "Enter the number : ";
cin >> number;
no_of_digit = digits(number, 10, 0);
cout << "No of digits are : " << no_of_digit << "\n";
return 0;
}


This code doesn't work properly. It give value 1.
But if i put
return counter;
in else block it works. Why so?

Answer

you are ignoring the return value of digits function

int counter = times;
counter++;
int result = number/value;
value=value*10;
if (result != 0){
    digits(number,value,counter);
}
return counter;

should say

int counter = times;
counter++;
int result = number/value;
value=value*10;
if (result != 0){
    return digits(number,value,counter);
}
return counter;
Comments