Write a program to check if a number is palindrome or not in QBasic.
For example,
Input 12321 Output Palindrone Input 43823 Output Not Palindrome
What is Palindrome number?
A number is palindrome if it is equal to it’s reverse. For example, reverse of 121 is also 121, this implies 121 is palindrome whereas reverse of 123 is 321, this implies 123 is not palindrome.
Logic
The easiest way to check if a number is a palindrome or not is to first convert the input number to a string and then compare ith character from the start and ith character from the end.
Steps
- Let num be the input number.
- Set flag = 1
- Convert num to string and compare ith character from the start and ith character from last using a loop. If any pair of ith character from the start and ith character from the end are not equal then it means that the number is not a palindrome, set flag = 0.
- If the flag is equal to 0 then the input number is not a palindrome. If the flag is not equal to 0 then the input is a palindrome.
QBasic Check if number is Palindrome using for loop
CLS
INPUT "Enter a Number: ", num
'Convert Number to String
num$ = STR$(num)
'flag variable
flag = 1
'Length of input number
n = LEN(num$)
' i: ith number from start
' n-i+1 ith number from last
FOR i = 1 TO n
IF MID$(num$, i, 1) <> MID$(num$, n - i + 1, 1) THEN
flag = 0
END IF
NEXT i
IF flag = 0 THEN
PRINT "NOT PALINDROME";
ELSE
PRINT "PALINDROME";
END IF
END
QBasic Check if number is Palindrome using while loop
CLS
INPUT "Enter a Number: ", num
'Convert Number to String
num$ = STR$(num)
'flag variable
flag = 1
'Length of input number
n = LEN(num$)
' i: ith number from start
' n-i+1 ith number from last
i = 1
WHILE i <= n
IF MID$(num$, i, 1) <> MID$(num$, n - i + 1, 1) THEN
flag = 0
END IF
i = i + 1
WEND
IF flag = 0 THEN
PRINT "NOT PALINDROME";
ELSE
PRINT "PALINDROME";
END IF
END
QBasic Check if number is Palindrome using Subroutine
DECLARE SUB IsPalindrome(num)
CLS
INPUT "Enter a Number: ", num
IsPalindrome(num)
END
SUB IsPalindrome(num)
'Convert Number to String
num$ = STR$(num)
'flag variable
flag = 1
'Length of input number
n = LEN(num$)
' i: ith number from start
' n-i+1 ith number from last
i = 1
WHILE i <= n
IF MID$(num$, i, 1) <> MID$(num$, n - i + 1, 1) THEN
flag = 0
END IF
i = i + 1
WEND
IF flag = 0 THEN
PRINT "NOT PALINDROME";
ELSE
PRINT "PALINDROME";
END IF
END SUB
QBasic Check if number is Palindrome using Function
DECLARE FUNCTION IsPalindrome(num)
CLS
INPUT "Enter a Number: ", num
IF IsPalindrome(num) = 1 THEN
PRINT "PALINDROME";
ELSE
PRINT "NOT PALINDROME";
END IF
END
FUNCTION IsPalindrome(num)
'Convert Number to String
num$ = STR$(num)
'flag variable
flag = 1
'Length of input number
n = LEN(num$)
' i: ith number from start
' n-i+1 ith number from last
i = 1
WHILE i <= n
IF MID$(num$, i, 1) <> MID$(num$, n - i + 1, 1) THEN
flag = 0
END IF
i = i + 1
WEND
IsPalindrome = flag
END FUNCTION
Read