logical and conditional operator in c language

Post on 11-Jan-2017

156 Views

Category:

Education

1 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Topic:

Logical Operators and Conditional Operator

Presented by:Abdul Rehman (BSSE09151014)

Three Logical Operators

1. && (Logical AND)2. | | (Logical OR)3. ! (Logical NOT)

Logical Operators

In this operator, the condition is true if both conditions are true.

if ( gender == 1 && age >= 65 ) senior++;

&& (Logical AND)

Table of Logical AND

Operand 1 Operand 2 Resultsx y x&&y0 0 00 Non-Zero 0

Non-Zero 0 0Non-Zero Non-Zero 1

• Use the AND operator on the bit patterns 10011000 and 00101010.

Example

Example Program

Example

In this operator , the program is executed if any one of the two conditions is true.

if (semesterAvg >= 90 || finalExam >=90 ) printf("Student grade is A“);

| | (Logical OR)

Operand 1 Operand 2 Resultx y x | | y0 0 00 Non-Zero 1

Non-Zero 0 1Non-Zero Non-Zero 1

Table of Logical OR

Use the OR operator on the bit patterns 10011001 and 00101110.

Example

Example Program

Int x,y,z;

if (x<y | | x<z)

printf(“x is small”);

Example

 If a condition is true then Logical NOT operator will make false and vice versa.

if ( !( grade == 20 ) ) printf(“hello world“);

Alternative:if ( grade != 20 ) printf(“hello world“);

! (Logical NOT)

Operand 1 Operand 2 Result Resultx y !x !y0 0 1 10 Non-Zero 1 0

Non-Zero 0 0 1Non-Zero Non-Zero 0 0

Table of Logical NOT

Use the NOT operator on the bit pattern 10011000.

Example

Example Program

Ternary operator are used to reduce the code the in a short form.

Conditional Operator

General form is, (expression 1 ? expression 2 : expression 3);

Conditional operators ? and : are sometimes called ternary operators

if expression 1 is true, then the value returned will be expression 2, otherwise the value returned will be expression 3

Syntax

Nested conditional operator(expression 1 ? expression 2 : expression 3);

Single condition

or compound condition

(expression 1 ? expression 2 : expression 3);

(expression 1 ? expression 2 : expression 3);

Example program

main( ) { float sal ; printf ("Enter the salary" ) ; scanf ( "%f", &sal ) ; ( (sal < 40000 && sal > 25000) ? printf ( "Manager" ) : (( sal < 25000 && sal > 15000 ) ? printf ( "Accountant") :

printf ( "Clerk" ) )); }

Any Question???

top related