How to write a recursive function that counts digits of a number in Pascal

2 Answers

0 votes
program CountDigits;

function CountDigitsRecursive(num: Integer): Integer;
begin
    // Base case: If the number is reduced to 0, return 0
    if num = 0 then
        CountDigitsRecursive := 0
    else
        // Recursive case: Divide the number by 10 and add 1
        CountDigitsRecursive := 1 + CountDigitsRecursive(num div 10);
end;

var
    number, result: Integer;
begin
    number := 37910;

    // Handle the case for number 0 explicitly
    if number = 0 then
        result := 1
    else
        // Use the recursive function, taking absolute value to handle negatives
        result := CountDigitsRecursive(Abs(number));

    WriteLn('The number of digits is: ', result);
end.




(*
run:

The number of digits is: 5

*)

 



answered Apr 6, 2025 by avibootz
0 votes
program CountDigits;

function CountDigitsRecursive(num: Int64): Int64;
begin
    // Base case: If the number is reduced to 0, return 0
    if num = 0 then
        CountDigitsRecursive := 0
    else
        // Recursive case: Divide the number by 10 and add 1
        CountDigitsRecursive := 1 + CountDigitsRecursive(num div 10);
end;

var
    number: Int64;
    result: Int64;
begin
    number := 9837106;

    // Handle the case for number 0 explicitly
    if number = 0 then
        result := 1
    else
        // Use the recursive function, taking absolute value to handle negatives
        result := CountDigitsRecursive(Abs(number));

    WriteLn('The number of digits is: ', result);
end.




(*
run:

The number of digits is: 7

*)

 



answered Apr 6, 2025 by avibootz
...