Logical Operators


Description

C language allows two types of logical operators - logical AND (&&) and logical OR (||) . These logical operators allows you to logically combine boolean (true/false) values of two or more regular expressions.

Eg. Selecting a female client, who knows programming or networking.

By using two variables client and knows, the condition statement for this problem becomes as if ( client != 'male' && knows == 'programming' || knows == 'networking'

Source code

  1. /* A client who knows programming or networking with gender female*/
  2. #include <stdio.h>
  3. #include <conio.h>
  4. void main()
  5. {
  6. int x,y,z;
  7. char knows,gender;
  8. clrscr();
  9. printf("Enter gender (M or F) : ");
  10. scanf("%c",&gender);
  11. while(1)
  12. {
  13. printf("Enter option you know \n 1)Programming\n 2)Hardware\n 3)C \n");
  14. scanf("%d",&x);
  15. switch(x)
  16. {
  17. case 1:
  18. knows='P';
  19. break;
  20. case 2:
  21. knows='H';
  22. break;
  23. case 3:
  24. knows='N';
  25. break;
  26. default:
  27. printf("Wrong option selected, please try again");
  28. continue;
  29. }
  30. break;
  31. }
  32. if (knows=='P' || knows=='N' && gender!='M')
  33. {
  34. printf("You are selected");
  35. }
  36. else
  37. {
  38. printf("Sorry!, You are rejected.");
  39. }
  40. getch();
  41. }

Program working steps

  • First 5 lines of the program are basic about comment, preprocessor directive statements and void main function.
  • 6th and 7th line is the declaration of integer and character variables and then clearing of the screen using clrscr() function.
  • Printf statement prints the double quoted text and scanf stores the character value in variable gender.
  • While(1) statement is used here to repeat switch case loop, if the user enters invalid input using continue statement.
  • Program prompts the user to enter the option you know 1,2 or 3 for programming hardware and networking.
  • Switch case loop traverses the cases till the match is found, if not then default case will be implemented.
  • Case implementation stops when it reaches break or continue statement in this program.
  • After the break of switch case loop, while(1) loop also terminates as it is followed by break statement.
  • If condition expression on line no.33 is true it will print 'You are selected' else 'Sorry, you are rejected'.
  • Getch() function to avoid closing of program immediately as it takes input from the user and doesn't prints on the screen.