The document discusses various operators in the C programming language. It describes arithmetic, assignment, relational, logical, conditional, and type casting operators. It provides examples to demonstrate how each operator works. It also covers decision control structures like if, if-else, nested if, and switch statements that allow conditional execution of code in C based on different conditions.
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
Programming Fundamentals lecture 7
1. BY REHAN IJAZ
07 - Basic C Operators
Operator
Operators are symbolswhichtake one ormore operandsor expressionsandperformarithmeticorlogical
computations.
Types ofoperators available inC are as follows:
1. Arithmeticoperators
2. Assignmentoperators
3. Equalitiesand relational operators
4. Logical/relational
5. Conditional operators
1. Arithmeticoperators
Arithmeticoperators take numerical valuesastheiroperandsandreturna single numerical value.Assume
variable A = 10 and variable B= 20
Operator Description Example
+ Addstwooperands. A + B = 30
− Subtractssecondoperandfromthe first. A − B = 10
∗ Multipliesbothoperands. A ∗ B = 200
∕ Dividesnumeratorbyde-numerator. B ∕ A = 2
% ModulusOperatorand remainderof afteranintegerdivision. B % A = 0
++ Incrementoperatorincreasesthe integervaluebyone. A++ = 11
-- Decrementoperatordecreasesthe integervalue byone. 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 %dn", c );
c = a - b;
printf("Line 2 - Value of c is %dn", c );
c = a * b;
2. BY REHAN IJAZ
printf("Line 3 - Value of c is %dn", c );
c = a / b;
printf("Line 4 - Value of c is %dn", c );
c = a % b;
printf("Line 5 - Value of c is %dn", c );
c = a++;
printf("Line 6 - Value of c is %dn", c );
c = a--;
printf("Line 7 - Value of c is %dn", c );
}
Output
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22
2. Assignmentoperators
The followingtable liststhe assignmentoperatorssupportedbythe Clanguage
Operator Description Example
= Simple assignmentoperator.Assignsvaluesfromright
side operandstoleftside operand
C = A + B will assignthe value of A + B
to C
+= AddAND assignmentoperator.Itaddsthe rightoperand
to the leftoperandand assignthe resulttothe left
operand.
C += A isequivalenttoC = C + A
-= Subtract ANDassignmentoperator.Itsubtractsthe right
operandfromthe leftoperandandassignsthe resultto
the leftoperand.
C -= A isequivalenttoC= C - A
*= Multiply ANDassignmentoperator.Itmultipliesthe right
operandwiththe leftoperandandassignsthe resultto
the leftoperand.
C *= A isequivalenttoC = C * A
/= Divide ANDassignmentoperator.Itdividesthe left
operandwiththe rightoperandandassigns the resultto
the leftoperand.
C /= A is equivalenttoC= C / A
%= ModulusANDassignmentoperator.Ittakesmodulus
usingtwooperandsandassignsthe resultto the left
operand.
C %= A isequivalenttoC= C % A
<<= LeftshiftANDassignment operator. C <<= 2 is same as C = C << 2
>>= RightshiftANDassignmentoperator. C >>= 2 is same as C = C >> 2
&= Bitwise ANDassignmentoperator. C &= 2 issame as C = C & 2
^= Bitwise exclusive ORandassignmentoperator. C ^= 2 issame as C = C ^ 2
3. BY REHAN IJAZ
|= Bitwise inclusiveORandassignmentoperator. 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 = %dn", c );
c += a;
printf("Line 2 - += Operator Example, Value of c = %dn", c );
c -= a;
printf("Line 3 - -= Operator Example, Value of c = %dn", c );
c *= a;
printf("Line 4 - *= Operator Example, Value of c = %dn", c );
c /= a;
printf("Line 5 - /= Operator Example, Value of c = %dn", c );
c = 200;
c %= a;
printf("Line 6 - %= Operator Example, Value of c = %dn", c );
c <<= 2;
printf("Line 7 - <<= Operator Example, Value of c = %dn", c );
c >>= 2;
printf("Line 8 - >>= Operator Example, Value of c = %dn", c );
c &= 2;
printf("Line 9 - &= Operator Example, Value of c = %dn", c );
c ^= 2;
printf("Line 10 - ^= Operator Example, Value of c = %dn", c );
c |= 2;
printf("Line 11 - |= Operator Example, Value of c = %dn", c );
}
Output
Line 1 - = Operator Example, Value of c = 21
Line 2 - += Operator Example, Value of c = 42
Line 3 - -= Operator Example, Value of c = 21
Line 4 - *= Operator Example, Value of c = 441
Line 5 - /= Operator Example, Value of c = 21
Line 6 - %= Operator Example, Value of c = 11
Line 7 - <<= Operator Example, Value of c = 44
Line 8 - >>= Operator Example, Value of c = 11
Line 9 - &= Operator Example, Value of c = 2
Line 10 - ^= Operator Example, Value of c = 0
Line 11 - |= Operator Example, Value of c = 2
4. BY REHAN IJAZ
3. Equalitiesandrelational operators
The 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 bn" );
}
else {
printf("Line 1 - a is not equal to bn" );
}
if ( a < b ) {
printf("Line 2 - a is less than bn" );
}
else {
printf("Line 2 - a is not less than bn" );
}
if ( a > b ) {
printf("Line 3 - a is greater than bn" );
}
else {
printf("Line 3 - a is not greater than bn" );
}
/* 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 bn" );
}
if ( b >= a ) {
printf("Line 5 - b is either greater than or equal to bn" );
5. BY REHAN IJAZ
}
}
When you compile and execute the above program, it produces the following result −
Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to b
Line 5 - b is either greater than or equal to b
4. Logical Operators
Following table shows all the logical operators supported by C language. Assume variable A holds 1 and
variable B holds 0, then −
Operator Description Example
&& CalledLogical ANDoperator.If boththe operands are non-zero,
thenthe conditionbecomestrue.
(A && B) is
false.
|| CalledLogical OROperator.If any of the twooperandsisnon-
zero,thenthe conditionbecomestrue.
(A || B) is
true.
! CalledLogical NOTOperator.Itis usedtoreverse the logical
state of itsoperand.If a conditionistrue,thenLogical NOT
operatorwill make itfalse.
Example
#include <stdio.h>
main() {
int a = 5, int b = 20, int c ;
if ( a && b ) {
printf("Line 1 - Condition is truen" );
}
if ( a || b ) {
printf("Line 2 - Condition is truen" );
}
/* lets change the value of a and b */
a = 0;
b = 10;
if ( a && b ) {
printf("Line 3 - Condition is truen" );
}
else {
printf("Line 3 - Condition is not truen" );
}
if ( !(a && b) ) {
printf("Line 4 - Condition is truen" );
}
6. BY REHAN IJAZ
}
Output
Line 1 - Condition is true
Line 2 - Condition is true
Line 3 - Condition is not true
Line 4 - Condition is true
5. Conditional Operators
Syntax : expression1 ? expression2 : expression3
1. Expression1isnothingbutBooleanConditioni.eitresultsintoeither TRUEor FALSE
2. If resultof expression1isTRUE thenexpression2isExecuted
3. Expression1issaidtobe TRUE if itsresultisNON-ZERO
4. If resultof expression1isFALSEthenexpression3isExecuted
5. Expression1issaidtobe FALSEif its resultisZERO
Example : Even- Odd
#include<stdio.h>
int main()
{
int num;
printf("Enter the Number : ");
scanf("%d",&num);
(num%2==0)?printf("Even"):printf("Odd");
}
7. BY REHAN IJAZ
C - Type Casting
Type 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 : %fn", mean );
}
Output
Value 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 : %dn", sum );
}
Output
Value 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 : %fn", sum );
}
Output
Value of sum : 116.000000
8. BY REHAN IJAZ
DecisionControl structure using if
Decisionmakingstructuresrequire thatthe programmerspecifiesone or more conditions to be evaluated
or tested by the program, along with a statement or statements to be executed if the condition is
determinedtobe true,and optionally, other statements to be executed if the condition is determined to
be false.
C - if statement
The 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 20n" );
}
printf("value of a is : %dn", a);
return 0;
}
Output
a is less than 20;
value of a is : 10
9. 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 200n" );
}
}
printf("Exact value of a is : %dn", a );
printf("Exact value of b is : %dn", b );
return 0;
}
Output
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200
C - if...else statement
An if statementcanbe followedbyanoptional elsestatement,whichexecuteswhenthe Boolean
expressionisfalse.
Example
#include <stdio.h>
int main ()
{
int a = 100;
if( a < 20 )
{
printf("a is less than 20n" );
}
else
10. BY REHAN IJAZ
{
printf("a is not less than 20n" );
}
printf("value of a is : %dn", a);
return 0;
}
Output
a 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
secondtestexpression.If the secondtestexpressionistrue,itexecutesthe statement/sinside the braces{ }
justbelowit.Thisprocesscontinues.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
#i nclude <stdio.h>
i nt mai n(){
i nt numb1, numb2;
pri ntf("Enter two i ntegers to checkn");
scanf("%d %d",&numb1,&numb2);
i f(numb1==numb2)
pri ntf("Result: %d = %d",numb1,numb2);
el se
i f(numb1>numb2)
pri ntf("Result: %d > %d",numb1,numb2);
el se
pri ntf("Result: %d > %d",numb2,numb1);
return 0;
}
Output
Enter two integers to check.
5
3
Result: 5 > 3
11. BY REHAN IJAZ
If...else if...else Statement
An if statementcanbe followed byanoptional elseif...elsestatement,whichisveryuseful totestvarious
conditionsusingsingle 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 10n" );
}
else if( a == 20 ) {
/* if else if condition is true */
printf("Value of a is 20n" );
}
else if( a == 30 ) {
/* if else if condition is true */
printf("Value of a is 30n" );
}
else {
/* if none of the conditions is true */
printf("None of the values is matchingn" );
}
printf("Exact value of a is: %dn", a );
return 0;
}
Output
None of the values is matching
Exact value of a is: 100
12. BY REHAN IJAZ
C - switchstatement
A switch statementallowsavariable tobe testedforequality 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;
case 'B' :
case 'C' :
printf("Well donen" );
13. BY REHAN IJAZ
break;
case 'D' :
printf("You passedn" );
break;
case 'F' :
printf("Better try againn" );
break;
default :
printf("Invalid graden" );
}
printf("Your grade is %cn", grade );
return 0;
}
Output
Well done
Your 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.
14. BY REHAN IJAZ
break statement in C
The 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: %dn", a);
a++;
if( a > 15) {
/* terminate the loop using break statement */
break;
}
}
return 0;
}
Output
value of a: 10
value of a: 11
value of a: 12
value of a: 13