QBasic Program to Count Number of Digits in a Number

Write a program to count number of digits in a number in QBasic.

For example,

Input
981723
Output
6

Steps

  1. Let N be the input number.
  2. Initialize count = 0.
  3. Initialize num = N.
  4. Repeat the following steps while num > 0
    1. Set count = count + 1.
    2. Set num = num / 10. This step removes the rightmost digit of num.
  5. The number of digits in N is equal to count.

Program Count Number of Digits in a Number

CLS
INPUT "Enter a Number: ", N
num = N
count = 0
WHILE num > 0
    ' increment count
    count = count + 1
    ' remove right most digit of num
    ' Note: We are using '\' for division instead of '/'
    ' '\' returns integer number
    ' whereas '/' returns floating number
    num = num \ 10
WEND
PRINT "Number of Digits in "; N; " = "; count
END

Program Count Number of Digits using Subroutine

DECLARE SUB count_digit(N)

CLS
INPUT "Enter a Number: ", N
count_digit (N)
END

SUB count_digit (N)
    num = N
    count = 0
    WHILE num > 0
        count = count + 1
        num = num \ 10
    WEND
    PRINT "Number of Digits in "; N; " = "; count
END SUB

Program Count Number of Digits using Function Procedure

DECLARE FUNCTION count_digit(N)

CLS
INPUT "Enter a Number: ", N
PRINT "Number of Digits in "; N; " = "; count_digit(N)
END

FUNCTION count_digit (N)
    num = N
    count = 0
    WHILE num > 0
        count = count + 1
        num = num \ 10
    WEND
    count_digit = count
END FUNCTION

Output

qbasic program output

Read

Leave a Comment

Your email address will not be published. Required fields are marked *