Create a program in 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.

Write a function(s) that will Print 2 lines based on number input by user: Line 1- print Switch numbers (1-7); Line 2- print the "ON" or "OFF" state for each switch (assume 1 = ON).

Respuesta :

Answer:

// here is code in C.

#include <stdio.h>

void fun(int num)

{ // array to store binary representation of input number

   int b[7];

   int i,j;

   // convert the number into binary

   for(i=0; num>0; i++)    

       {    

           b[i]=num%2;    

           num= num/2;  

       }  

   // print the switch number and their status

   printf("Switch number:\t 1\t 2\t 3\t 4\t 5\t 6\t 7 \n");

   printf("Switch status:");

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

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

   {

       if(b[j]==1)

           printf("\t ON");

       else

           printf("\t OFF");

   }  

}

// driver function

void main()

{

   int n;

   printf("enter the number between 1-100 only:");

   // read a decimal number

   scanf("%d",&n);

   // validate the input between 1 to 100 only

   while(n<1 ||n>100)

   {

         printf("wrong input:");

           printf("\n enter again :");

           scanf("%d",&n);

           }

  // printf( "input number is: %d \n",n);

  // call the function

  fun(n);

}

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:-1                                                                                                                        

wrong input:                                                                                                                                       ��          

enter again :104                                                                                                                                            

wrong input:                                                                                                                                                  

enter again :68                                                                                                                                              

Switch number:   1       2       3       4       5       6       7                                                                                            

Switch status:   ON      OFF     OFF     OFF     ON      OFF     OFF  

ACCESS MORE