15.7k views
5 votes
Create a program in c/c++ which accepts user input of a decimal number in the range of 1 -100. Each binary bit of this number will represent the ON/OFF state of a toggle switch.

1 Answer

4 votes

Answer:

// here is code in C++.

#include <bits/stdc++.h>

using namespace std;

void switch_fun(int input)

{

//array to store binary of input number

int bin[7];

// convert the number into binary

for(int i=0; input>0; i++)

{

bin[i]=input%2;

input= input/2;

}

// print the switch number and their status

cout<<"Switch number:\t 1\t 2\t 3\t 4\t 5\t 6\t 7 \\";

cout<<"status: ";

for(int j=6;j>=0;j--)

{

// if bit is 1 print "ON" else print "OFF"

if(bin[j]==1)

cout<<"\t ON";

else

cout<<"\t OFF";

}

}

int main()

{

int n;

cout<<"enter the number between 1-100 only:");

// read a number in decimal

cin>>n

// validate the input

while(n<1 ||n>100)

{

cout<<"wrong input!! Input must be in between 1-100:"<<endl;

cout<<"enter the number again :";

cin>>n;

}

// call the function with input parameter

switch_fun(n);

return 0;

}

Step-by-step explanation:

Read a decimal number from user. If the number is not between 1 to 100 the it will again ask user to enter the number until the input is in between 1-100.Then it will call the fun() with parameter n. First it will convert the decimal to binary array of size 7.Then print the status of switch.If bit is 1 then print "ON" else it will print "OFF".

Output:

enter the number between 1-100 only:-5

wrong input!! Input must be in between 1-100:

enter the number again :125

wrong input!! Input must be in between 1-100:

enter the number again :45

Switch number: 1 2 3 4 5 6 7

Status: OFF ON OFF ON ON OFF ON

User ZAT
by
8.8k points