0

I'm an amateur programmer and is currently trying to learn about recursion. I keep trying to find a website that explains statements such as

public static init sumDigits(int i) {
  return i == 0 ? 0 : i % 10 + sumDigits(i / 10);
}

and that explains what each individual component does, like the semi-colon or question mark. Help.

Itay Maman
  • 30,277
  • 10
  • 88
  • 118
Letta
  • 83
  • 10

3 Answers3

0

? : is a ternary operator. In simple words you can say its an if else statement. Now if the condition before ? is true then the action is the statement written in between ? and :. If the condition before ? is false then the action is the statement written after :.

In your case you are mentioning that if i==0 then return 0 otherwise, return i % 10 + sumDigits(i / 10);

codeLover
  • 2,571
  • 1
  • 11
  • 27
0

Let me now narrate this piece of code:

to compute the sum-of-digits of i first check if i equals 0. If it is, then the result is 0. otherwise the result is the last digit of i plus sum-of-digits of i/10 (rounded down).

  • i == 0 that's "first check if i equals 0"
  • : 0 that's "If it is, then the result is 0"
  • ? that's "otherwise"
  • i % 10 that's "last digit of i`
  • i / 10 that's "i/10 (rounded down)"
  • i % 10 + sumDigits(i / 10) that's "last digit of i plus sum-of-digits of i/10 (rounded down)"
Itay Maman
  • 30,277
  • 10
  • 88
  • 118
0
public static init sumDigits(int i) {
  return i == 0 ? 0 : i % 10 + sumDigits(i / 10);
}

explanation: First of all correct the return type of the method which is written init instead of int.

actually the return statement says that, if the value of i is 0 then return 0 else return i % 10 + sumDigits(i / 10) here ? determines whether the condition (i==0) is true or false. If the condition satisfies(i.e true) then simply return 0 else do some operation with the value of i

It could have been written as below:

public static int sumDigits(int i) {
          if(i==0)
               return 0;
          else
              return i % 10 + sumDigits(i / 10);
    } // that will result the same as above but with less amount of code.
Rashedul.Rubel
  • 3,446
  • 25
  • 36