Jack P. Oakley Portfolio Game Programmer/Designer

Digit Counter

This is a simple recursive program that determines how many digits are in a given number.

#lang Scheme
;Integer Digit Counter by Jack P. Oakley
;This recursive program takes counts the number of digits in a given integer

;******************************************************************************
; CountDigits function:                                                       *
; PURPOSE: Allow input of an integer of which to count digits                 *
; IN: integer of number to be counted                                         *
; OUT: integer of results of CountDigitsR                                     *
;******************************************************************************
(define (CountDigits num)
	(CountDigitsR num 0)
)

;******************************************************************************
; CountDigitsR function:                                                      *
; PURPOSE: Recursively go through integer and count digits                    *
; IN: integer of number to be counted, integer of number of digits counted    *
;	already                                                               *
; OUT: integer of number of digits counted                                    *
;******************************************************************************
(define (CountDigitsR num digits)
	(if (< num 1)
		digits
		(CountDigitsR (/ num 10) (+ digits 1))
	)
)

;******************************************************************************
; Driving Code:                                                               *
; PURPOSE: Handles input/output and function calls                            *
;******************************************************************************
(display "Digit Counter") (newline)
(display "This program takes a number entered via keyboard and displays the number of digits it has.")
(newline)
(display "Enter a number: ")
(define numEntered (read))
(newline)
(display numEntered)
(display " contains ")
(display (CountDigits numEntered))
(display " digits.") (newline)

;Test Code and Expected Results:
;(CountDigits 5) 				;1
;(CountDigits 22) 				;2
;(CountDigits 386) 				;3
;(CountDigits 248482984898959892358280)   	;24