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")
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
<em> valid = False</em>
<em> break;</em>
If otherwise, then the input string is invalid and the loop is exited
<em> else:</em>
<em> valid = False</em>
<em> break;</em>
If valid is True, then the BCD value is printed
<em>if(valid):</em>
<em> print(BCDValue)</em>
If otherwise, it prints Invalid
<em>else:</em>
<em> print("Invalid")</em>