Answer:
The program in Python is as follows:
BCD = ["0001","0010","0011","0100","0101","0110","0111"]
num = input("Decimal: ")
BCDValue = ""
valid = True
for i in range(len(num)):
if num[i].isdigit():
if(int(num[i])>= 0 and int(num[i])<8):
BCDValue += BCD[i]+" "
else:
valid = False
break;
else:
valid = False
break;
if(valid):
print(BCDValue)
else:
print("Invalid")
Step-by-step explanation:
This initializes the BCD corresponding value of the decimal number to a list
BCD = ["0001","0010","0011","0100","0101","0110","0111"]
This gets input for a decimal number
num = input("Decimal: ")
This initializes the required output (i.e. BCD value) to an empty string
BCDValue = ""
This initializes valid input to True (Boolean)
valid = True
This iterates through the input string
for i in range(len(num)):
This checks if each character of the string is a number
if num[i].isdigit():
If yes, it checks if the number ranges from 0 to 7 (inclusive)
if(int(num[i])>= 0 and int(num[i])<8):
If yes, the corresponding BCD value is calculated
BCDValue += BCD[i]+" "
else:
If otherwise, then the input string is invalid and the loop is exited
valid = False
break;
If otherwise, then the input string is invalid and the loop is exited
else:
valid = False
break;
If valid is True, then the BCD value is printed
if(valid):
print(BCDValue)
If otherwise, it prints Invalid
else:
print("Invalid")