CodesandTutorials
Next generation website theme is here (black, neon and white color) - Reduces eye strain and headache problems.
You are here - Home > Programming > C > Basics

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

  • /* A client who knows programming or networking with gender female*/
  • #include <stdio.h>
  • #include <conio.h>
  • void main()
  • {
  • int x,y,z;
  • char knows,gender;
  • clrscr();
  • printf("Enter gender (M or F) : ");
  • scanf("%c",&gender);
  • while(1)
  • {
  • printf("Enter option you know \n 1)Programming\n 2)Hardware\n 3)C \n");
  • scanf("%d",&x);
  • switch(x)
  • {
  • case 1:
  • knows='P';
  • break;
  • case 2:
  • knows='H';
  • break;
  • case 3:
  • knows='N';
  • break;
  • default:
  • printf("Wrong option selected, please try again");
  • continue;
  • };
  • break;
  • }
  • if (knows=='P' || knows=='N' && gender!='M')
  • {
  • printf("You are selected");
  • }
  • else
  • {
  • printf("Sorry!, You are rejected.");
  • }
  • getch();
  • }

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.

Tip Box

Operator precedence

Priority Operator
1st &&
2nd ||

Advertisement





Terms of Use | Privacy Policy | Contact Us | Advertise
CodesandTutorials © 2014 All Rights Reserved