Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,884 questions

51,810 answers

573 users

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
...