programming fundamentals lecture 7

21
BY REHAN IJAZ 07 - Basic C Operators Operator Operators are symbols which take one or more operands or expressions and perform arithmetic or logical computations. Types of operators available in C are as follows: 1. Arithmetic operators 2. Assignment operators 3. Equalities and relational operators 4. Logical/relational 5. Conditional operators 1. Arithmetic operators Arithmetic operators take numerical values as their operands and return a single numerical value. Assume variable A = 10 and variable B = 20 Operat or Description Example + Adds two operands. A + B = 30 Subtracts second operand from the first. A − B = 10 Multiplies both operands. A B = 200 Divides numerator by de-numerator. B A = 2 % Modulus Operator and remainder of after an integer division. B % A = 0 ++ Increment operator increases the integer value by one. A++ = 11 -- Decrement operator decreases the integer value by one. A-- = 9

Upload: rehan-ijaz

Post on 15-Apr-2017

56 views

Category:

Engineering


0 download

TRANSCRIPT

Page 1: Programming Fundamentals lecture 7

BY REHAN IJAZ

07 - Basic C Operators

OperatorOperators are symbols which take one or more operands or expressions and perform arithmetic or logical computations.

Types of operators available in C are as follows:

1. Arithmetic operators

2. Assignment operators

3. Equalities and relational operators

4. Logical/relational

5. Conditional operators

1. Arithmetic operatorsArithmetic operators take numerical values as their operands and return a single numerical value. Assume variable A = 10 and variable B = 20

Operator Description Example+ Adds two operands. A + B = 30− Subtracts second operand from the first. A − B = 10∗ Multiplies both operands. A ∗ B = 200∕ Divides numerator by de-numerator. B ∕ A = 2% Modulus Operator and remainder of after an integer division. B % A = 0++ Increment operator increases the integer value by one. A++ = 11-- Decrement operator decreases the integer value by one. A-- = 9

Example

Try the following example to understand all the arithmetic operators available in C −

#include <stdio.h>main() { int a = 21, int b = 10 , int c ; c = a + b; printf("Line 1 - Value of c is %d\n", c );

c = a - b; printf("Line 2 - Value of c is %d\n", c );

Page 2: Programming Fundamentals lecture 7

BY REHAN IJAZ

c = a * b; printf("Line 3 - Value of c is %d\n", c );

c = a / b; printf("Line 4 - Value of c is %d\n", c );

c = a % b; printf("Line 5 - Value of c is %d\n", c );

c = a++; printf("Line 6 - Value of c is %d\n", c );

c = a--; printf("Line 7 - Value of c is %d\n", c );}

Output

Line 1 - Value of c is 31Line 2 - Value of c is 11Line 3 - Value of c is 210Line 4 - Value of c is 2Line 5 - Value of c is 1Line 6 - Value of c is 21Line 7 - Value of c is 22

2. Assignment operatorsThe following table lists the assignment operators supported by the C language

Operator Description Example= Simple assignment operator. Assigns values from right

side operands to left side operandC = A + B will assign the value of A + B to C

+= Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand.

C += A is equivalent to C = C + A

-= Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand.

C -= A is equivalent to C = C - A

*= Multiply AND assignment operator. It multiplies the right operand with the left operand and assigns the result to the left operand.

C *= A is equivalent to C = C * A

/= Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to the left operand.

C /= A is equivalent to C = C / A

%= Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand.

C %= A is equivalent to C = C % A

<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2

Page 3: Programming Fundamentals lecture 7

BY REHAN IJAZ

^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

Example #include <stdio.h>

main() {

int a = 21; int c ;

c = a; printf("Line 1 - = Operator Example, Value of c = %d\n", c );

c += a; printf("Line 2 - += Operator Example, Value of c = %d\n", c );

c -= a; printf("Line 3 - -= Operator Example, Value of c = %d\n", c );

c *= a; printf("Line 4 - *= Operator Example, Value of c = %d\n", c );

c /= a; printf("Line 5 - /= Operator Example, Value of c = %d\n", c );

c = 200; c %= a; printf("Line 6 - %= Operator Example, Value of c = %d\n", c );

c <<= 2; printf("Line 7 - <<= Operator Example, Value of c = %d\n", c );

c >>= 2; printf("Line 8 - >>= Operator Example, Value of c = %d\n", c );

c &= 2; printf("Line 9 - &= Operator Example, Value of c = %d\n", c );

c ^= 2; printf("Line 10 - ^= Operator Example, Value of c = %d\n", c );

c |= 2; printf("Line 11 - |= Operator Example, Value of c = %d\n", c );}

OutputLine 1 - = Operator Example, Value of c = 21Line 2 - += Operator Example, Value of c = 42Line 3 - -= Operator Example, Value of c = 21Line 4 - *= Operator Example, Value of c = 441Line 5 - /= Operator Example, Value of c = 21Line 6 - %= Operator Example, Value of c = 11Line 7 - <<= Operator Example, Value of c = 44Line 8 - >>= Operator Example, Value of c = 11Line 9 - &= Operator Example, Value of c = 2Line 10 - ^= Operator Example, Value of c = 0Line 11 - |= Operator Example, Value of c = 2

Page 4: Programming Fundamentals lecture 7

BY REHAN IJAZ

3. Equalities and relational operatorsThe binary relational and equality operators compare their first operand to their second operand to test the validity of the specified relationship. The result of a relational expression is 1 if the tested relationship is true and 0 if it is false. The type of the result is int.

The relational and equality operators test the following relationships:

Operator

Description

< First operand less than second operand> First operand greater than second operand

<= First operand less than or equal to second operand

>= First operand greater than or equal to second operand

== First operand equal to second operand!= First operand not equal to second operand

Example

Try the following example to understand all the relational operators available in C −

#include <stdio.h>main() { int a = 21; int b = 10; int c ;

if( a == b ) { printf("Line 1 - a is equal to b\n" ); } else { printf("Line 1 - a is not equal to b\n" ); }

if ( a < b ) { printf("Line 2 - a is less than b\n" ); } else { printf("Line 2 - a is not less than b\n" ); }

if ( a > b ) { printf("Line 3 - a is greater than b\n" ); } else { printf("Line 3 - a is not greater than b\n" ); } /* Lets change value of a and b */ a = 5; b = 20;

if ( a <= b ) { printf("Line 4 - a is either less than or equal to b\n" ); }

Page 5: Programming Fundamentals lecture 7

BY REHAN IJAZ

if ( b >= a ) { printf("Line 5 - b is either greater than or equal to b\n" ); }}

When you compile and execute the above program, it produces the following result −

Line 1 - a is not equal to bLine 2 - a is not less than bLine 3 - a is greater than bLine 4 - a is either less than or equal to bLine 5 - b is either greater than or equal to b

4. Logical OperatorsFollowing table shows all the logical operators supported by C language. Assume variable A holds 1 and variable B holds 0, then −

Operator Description Example&& Called Logical AND operator. If both the operands are non-zero,

then the condition becomes true.(A && B) is false.

|| Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true.

(A || B) is true.

! Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false.

Example#include <stdio.h>

main() { int a = 5, int b = 20, int c ;

if ( a && b ) { printf("Line 1 - Condition is true\n" ); }

if ( a || b ) { printf("Line 2 - Condition is true\n" ); } /* lets change the value of a and b */ a = 0; b = 10;

if ( a && b ) { printf("Line 3 - Condition is true\n" ); } else { printf("Line 3 - Condition is not true\n" ); }

if ( !(a && b) ) { printf("Line 4 - Condition is true\n" );

Page 6: Programming Fundamentals lecture 7

BY REHAN IJAZ

}

}Output

Line 1 - Condition is trueLine 2 - Condition is trueLine 3 - Condition is not trueLine 4 - Condition is true

5. Conditional OperatorsSyntax : expression 1 ? expression 2 : expression 3

1. Expression1 is nothing but Boolean Condition i.e it results into either TRUE or FALSE2. If result of expression1 is TRUE then expression2 is Executed3. Expression1 is said to be TRUE if its result is NON-ZERO4. If result of expression1 is FALSE then expression3 is Executed5. Expression1 is said to be FALSE if its result is ZERO

Example : Even - Odd

#include<stdio.h>int main(){int num;printf("Enter the Number : ");scanf("%d",&num);(num%2==0)?printf("Even"):printf("Odd");}

Page 7: Programming Fundamentals lecture 7

BY REHAN IJAZ

C - Type CastingType casting is a way to convert a variable from one data type to another data type. For example, if you want to store a 'long' value into a simple integer then you can type cast 'long' to 'int'. You can convert the values from one type to another explicitly using the cast operator as follows –

Syntax: (type_name) expression

Example 1

#include <stdio.h>main() { int sum = 17, count = 5; double mean; mean = (double) sum / count; printf("Value of mean : %f\n", mean );}OutputValue of mean : 3.400000

It should be noted here that the cast operator has precedence over division, so the value of sum is first converted to type double and finally it gets divided by count yielding a double value.

Example 2#include <stdio.h>main() { int i = 17; char c = 'c'; /* ascii value is 99 */ int sum;

sum = i + c; printf("Value of sum : %d\n", sum );}

OutputValue of sum : 116

Example 3

#include <stdio.h>main() { int i = 17; char c = 'c'; /* ascii value is 99 */ float sum; sum = i + c; printf("Value of sum : %f\n", sum );}OutputValue of sum : 116.000000

Page 8: Programming Fundamentals lecture 7

BY REHAN IJAZ

Decision Control structure using if

Decision making structures require that the programmer specifies one or more conditions to be evaluated

or tested by the program, along with a statement or statements to be executed if the condition is

determined to be true, and optionally, other statements to be executed if the condition is determined to

be false.

C - if statementThe if statement allows you to control if a program enters a section of code or not based on whether a given condition is true or false. One of the important functions of the if statement is that it allows the program to select an action based upon the user's input. For example, by using an if statement to check a user-entered password, your program can decide whether a user is allowed access to the program. 

Example

#include <stdio.h>int main () { int a = 10; if( a < 20 )

{ printf("a is less than 20\n" );}

printf("value of a is : %d\n", a); return 0;}Outputa is less than 20;value of a is : 10

Page 9: Programming Fundamentals lecture 7

BY REHAN IJAZ

C - nested if statements#include <stdio.h>int main () { int a = 100; int b = 200; if( a == 100 ) { if( b == 200 ) { printf("Value of a is 100 and b is 200\n" ); } } printf("Exact value of a is : %d\n", a ); printf("Exact value of b is : %d\n", b ); return 0;}Output

Value of a is 100 and b is 200Exact value of a is : 100Exact value of b is : 200

C - if...else statementAn if statement can be followed by an optional else statement, which executes when the Boolean expression is false.

Example#include <stdio.h>int main () { int a = 100; if( a < 20 )

{ printf("a is less than 20\n" );}

else

Page 10: Programming Fundamentals lecture 7

BY REHAN IJAZ

{ printf("a is not less than 20\n" );}

printf("value of a is : %d\n", a); return 0;}Outputa is not less than 20;value of a is : 100

C nested if else statement

The nested if...else statement has more than one test expression. If the first test expression is true, it executes the code inside the braces{ } just below it. But if the first test expression is false, it checks the second test expression. If the second test expression is true, it executes the statement/s inside the braces{ } just below it. This process continues. If all the test expression are false, code/s inside else is executed and the control of program jumps below the nested if...else

The ANSI standard specifies that 15 levels of nesting may be continued.

Example#include <stdio.h>int main(){ int numb1, numb2; printf("Enter two integers to check\n"); scanf("%d %d",&numb1,&numb2); if(numb1==numb2) printf("Result: %d = %d",numb1,numb2); else if(numb1>numb2) printf("Result: %d > %d",numb1,numb2); else printf("Result: %d > %d",numb2,numb1); return 0; }

Output Enter two integers to check.53Result: 5 > 3

Page 11: Programming Fundamentals lecture 7

BY REHAN IJAZ

If...else if...else StatementAn if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement.Syntax

if(boolean_expression 1) { /* Executes when the boolean expression 1 is true */}else if( boolean_expression 2) { /* Executes when the boolean expression 2 is true */}else if( boolean_expression 3) { /* Executes when the boolean expression 3 is true */}else { /* executes when the none of the above condition is true */}

Example#include <stdio.h>int main () { /* local variable definition */ int a = 100; /* check the boolean condition */ if( a == 10 ) { /* if condition is true then print the following */ printf("Value of a is 10\n" ); } else if( a == 20 ) { /* if else if condition is true */ printf("Value of a is 20\n" ); } else if( a == 30 ) { /* if else if condition is true */ printf("Value of a is 30\n" ); } else { /* if none of the conditions is true */ printf("None of the values is matching\n" ); } printf("Exact value of a is: %d\n", a ); return 0;}OutputNone of the values is matchingExact value of a is: 100

Page 12: Programming Fundamentals lecture 7

BY REHAN IJAZ

C - switch statement

A switch statement allows a variable to be tested for equality against a list of values. Each value is called a

case, and the variable being switched on is checked for each switch case.

Syntax

The syntax for a switch statement in C programming language is as follows −

switch(expression) { case constant-expression : statement(s); break; /* optional */ case constant-expression : statement(s); break; /* optional */ /* you can have any number of case statements */ default : /* Optional */ statement(s);}

Example#include <stdio.h>int main () { /* local variable definition */ char grade = 'B'; switch(grade) { case 'A' : printf("Excellent!\n" ); break;

Page 13: Programming Fundamentals lecture 7

BY REHAN IJAZ

case 'B' : case 'C' : printf("Well done\n" ); break; case 'D' : printf("You passed\n" ); break; case 'F' : printf("Better try again\n" ); break; default : printf("Invalid grade\n" ); } printf("Your grade is %c\n", grade ); return 0;}OutputWell doneYour grade is B

Benefits of Switch Statement

In some languages and programming environments, the use of a switch-case statement is considered superior to an equivalent series of if else if statements because it is:

Easier to debug

Easier to read

Easier to understand, and therefore

Easier to maintain

Fixed depth: a sequence of "if else if" statements yields deep nesting, making compilation more difficult

Faster execution potential

Limitations of Switch Statement

Switch statement is a powerful statement used to handle many alternatives and provides good

presentation for C program. But there are some limitations with switch statement which are given below:

Logical operators cannot be used with switch statement. For example case k>= 20; is not

allowed.

Switch case variables can have only int and char data type. So float or no data type is allowed.

Page 14: Programming Fundamentals lecture 7

BY REHAN IJAZ

break statement in CThe break statement in C programming has the following two usages −

When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.

It can be used to terminate a case in the switch statement (covered in the next chapter).

If you are using nested loops, the break statement will stop the execution of the innermost loop and start executing the next line of code after the block.

Syntax

break;

Example#include <stdio.h>int main () { /* local variable definition */ int a = 10; /* while loop execution */ while( a < 20 ) { printf("value of a: %d\n", a); a++; if( a > 15) { /* terminate the loop using break statement */ break; }

} return 0;}

Outputvalue of a: 10value of a: 11value of a: 12

Page 15: Programming Fundamentals lecture 7

BY REHAN IJAZ

value of a: 13value of a: 14value of a: 15