QBasic Program to Find Factorial of a Number

Write a program to find factorial of a number in Qbasic.

For example,

Input
4
Output
24
Explanation
4! = 4 * 3 * 2 * 1 = 24

Steps

  1. First, the program asks the user to enter a number – n.
  2. Then we initialize a variable fact = 1.
  3. After that, we use a loop and multiply fact with each number from 1 to n.
  4. The factorial of n is equal to fact.

Factorial Program in QBasic

CLS
INPUT "Enter a Number: ", n
fact = 1
FOR i = 1 TO n
    fact = fact * i
NEXT i
PRINT "Factorial of ";n;" is ";fact
END

Factorial Program in QBasic – Using Subroutine

DECLARE SUB factorial

CLS
factorial
END

SUB factorial
INPUT "Enter a Number: ", n
fact = 1
FOR i = 1 TO n
    fact = fact * i
NEXT i
PRINT "Factorial of ";n;" is ";fact
END SUB

Factorial Program in QBasic – Using Function

DECLARE FUNCTION factorial(n)

CLS
INPUT "Enter a Number: ", n
PRINT "Factorial of ";n;" is ";factorial(n)
END

FUNCTION factorial(n)
fact = 1
FOR i = 1 TO n
    fact = fact * i
NEXT i
factorial = fact
END FUNCTION

Factorial Program in QBasic – With Recursion

DECLARE FUNCTION factorial(n)

CLS
INPUT "Enter a Number: ", n
PRINT "Factorial of ";n;" is ";factorial(n)
END

FUNCTION factorial(n)
IF n = 0 OR n = 1 THEN
  factorial = 1
ELSE
  factorial = n * factorial(n-1)
END IF
END FUNCTION

Output

Enter a Number:   5
Factorial of 5 is 120

Read

Leave a Comment