SlideShare a Scribd company logo
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;
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
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
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" );
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" );
}
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");
}
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
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
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
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
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
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" );
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.
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
BY REHAN IJAZ
value of a: 14
value of a: 15

More Related Content

What's hot (19)

PPT
Mesics lecture 4 c operators and experssions
eShikshak
 
PPTX
Variables, Data Types, Operator & Expression in c in detail
gourav kottawar
 
PPT
Operators and Expressions in C++
Praveen M Jigajinni
 
PPTX
Operators in C Programming
Jasleen Kaur (Chandigarh University)
 
PPT
Operators in c language
Amit Singh
 
PPTX
Basic c operators
dishti7
 
PPT
C operators
GPERI
 
PPTX
Logical and Conditional Operator In C language
Abdul Rehman
 
PPTX
Operators and expressions in c language
tanmaymodi4
 
PPTX
Operators and Expressions
Munazza-Mah-Jabeen
 
PPTX
Lecture 2 C++ | Variable Scope, Operators in c++
Himanshu Kaushik
 
PPT
Types of c operators ppt
Viraj Shah
 
PPTX
Operators
Krishna Kumar Pankaj
 
PPTX
Operator of C language
Kritika Chauhan
 
PPT
CBSE Class XI :- Operators in C++
Pranav Ghildiyal
 
PDF
Types of Operators in C
Thesis Scientist Private Limited
 
PDF
Conditional operators
BU
 
PPTX
Operators and Expression
shubham_jangid
 
PPT
Expressions in c++
zeeshan turi
 
Mesics lecture 4 c operators and experssions
eShikshak
 
Variables, Data Types, Operator & Expression in c in detail
gourav kottawar
 
Operators and Expressions in C++
Praveen M Jigajinni
 
Operators in C Programming
Jasleen Kaur (Chandigarh University)
 
Operators in c language
Amit Singh
 
Basic c operators
dishti7
 
C operators
GPERI
 
Logical and Conditional Operator In C language
Abdul Rehman
 
Operators and expressions in c language
tanmaymodi4
 
Operators and Expressions
Munazza-Mah-Jabeen
 
Lecture 2 C++ | Variable Scope, Operators in c++
Himanshu Kaushik
 
Types of c operators ppt
Viraj Shah
 
Operator of C language
Kritika Chauhan
 
CBSE Class XI :- Operators in C++
Pranav Ghildiyal
 
Types of Operators in C
Thesis Scientist Private Limited
 
Conditional operators
BU
 
Operators and Expression
shubham_jangid
 
Expressions in c++
zeeshan turi
 

Viewers also liked (20)

DOCX
How to make presentation effective assignment
REHAN IJAZ
 
PPT
Trevel presentation
indra Kishor
 
DOC
importance of Communication in business
REHAN IJAZ
 
PPTX
Programming Fundamentals lecture 3
REHAN IJAZ
 
PDF
Career development interviews
REHAN IJAZ
 
PPTX
Programming Fundamentals lecture 6
REHAN IJAZ
 
DOCX
Programming Fundamentals lecture 4
REHAN IJAZ
 
PPTX
Cmp2412 programming principles
NIKANOR THOMAS
 
DOCX
Project code for Project on Student information management system
REHAN IJAZ
 
PPTX
Programming Fundamentals lecture 1
REHAN IJAZ
 
PDF
Everything about Object Oriented Programming
Abdul Rahman Sherzad
 
PPT
Trevel presentation
indra Kishor
 
PPTX
General Programming Concept
Haris Bin Zahid
 
PPTX
Object Orinted Programing(OOP) concepts \
Pritom Chaki
 
PPTX
Introduction to artificial intelligence lecture 1
REHAN IJAZ
 
PPT
Chapter1 - Introduction to Object-Oriented Programming and Software Development
Eduardo Bergavera
 
DOCX
Porposal on Student information management system
REHAN IJAZ
 
PDF
Demystifying Object-Oriented Programming - ZendCon 2016
Alena Holligan
 
PDF
Introduction to Object-Oriented Programming & Design Principles (TCF 2014)
Michael Redlich
 
DOCX
Introduction to programimg
Stn PT
 
How to make presentation effective assignment
REHAN IJAZ
 
Trevel presentation
indra Kishor
 
importance of Communication in business
REHAN IJAZ
 
Programming Fundamentals lecture 3
REHAN IJAZ
 
Career development interviews
REHAN IJAZ
 
Programming Fundamentals lecture 6
REHAN IJAZ
 
Programming Fundamentals lecture 4
REHAN IJAZ
 
Cmp2412 programming principles
NIKANOR THOMAS
 
Project code for Project on Student information management system
REHAN IJAZ
 
Programming Fundamentals lecture 1
REHAN IJAZ
 
Everything about Object Oriented Programming
Abdul Rahman Sherzad
 
Trevel presentation
indra Kishor
 
General Programming Concept
Haris Bin Zahid
 
Object Orinted Programing(OOP) concepts \
Pritom Chaki
 
Introduction to artificial intelligence lecture 1
REHAN IJAZ
 
Chapter1 - Introduction to Object-Oriented Programming and Software Development
Eduardo Bergavera
 
Porposal on Student information management system
REHAN IJAZ
 
Demystifying Object-Oriented Programming - ZendCon 2016
Alena Holligan
 
Introduction to Object-Oriented Programming & Design Principles (TCF 2014)
Michael Redlich
 
Introduction to programimg
Stn PT
 
Ad

Similar to Programming Fundamentals lecture 7 (20)

PPTX
PROGRAMMING IN C - Operators.pptx
Nithya K
 
PDF
C Operators and Control Structures.pdf
MaryJacob24
 
PPTX
C - programming - Ankit Kumar Singh
AnkitSinghRajput35
 
PPTX
C Operators and Control Structures.pptx
ramanathan2006
 
PPTX
C operators
Rupanshi rawat
 
PPTX
operators_group_2[1].pptx PLEASE DOWNLOAD
aluffssdd804
 
PPTX
Expressions using operator in c
Saranya saran
 
PPT
6 operators-in-c
Rohit Shrivastava
 
PPTX
COM1407: C Operators
Hemantha Kulathilake
 
PPTX
C operators
AbiramiT9
 
PDF
Programming C Part 02
Raselmondalmehedi
 
PDF
Introduction to programming c and data-structures
Pradipta Mishra
 
PPTX
data type.pptxddddswwyertr hai na ki extend kr de la
LEOFAKE
 
PPTX
introduction to c programming and C History.pptx
ManojKhadilkar1
 
PDF
Introduction to programming c and data structures
Pradipta Mishra
 
PDF
Programming for Problem Solving
Kathirvel Ayyaswamy
 
PPTX
Operators1.pptx
HARSHSHARMA840
 
PPTX
OPERATORS OF C++
ANANT VYAS
 
PDF
Unit ii chapter 1 operator and expressions in c
Sowmya Jyothi
 
DOCX
PPS 2.2.OPERATORS ARITHMETIC EXPRESSIONS/ARITHMETIC OPERATORS/RELATIONAL OPER...
Sitamarhi Institute of Technology
 
PROGRAMMING IN C - Operators.pptx
Nithya K
 
C Operators and Control Structures.pdf
MaryJacob24
 
C - programming - Ankit Kumar Singh
AnkitSinghRajput35
 
C Operators and Control Structures.pptx
ramanathan2006
 
C operators
Rupanshi rawat
 
operators_group_2[1].pptx PLEASE DOWNLOAD
aluffssdd804
 
Expressions using operator in c
Saranya saran
 
6 operators-in-c
Rohit Shrivastava
 
COM1407: C Operators
Hemantha Kulathilake
 
C operators
AbiramiT9
 
Programming C Part 02
Raselmondalmehedi
 
Introduction to programming c and data-structures
Pradipta Mishra
 
data type.pptxddddswwyertr hai na ki extend kr de la
LEOFAKE
 
introduction to c programming and C History.pptx
ManojKhadilkar1
 
Introduction to programming c and data structures
Pradipta Mishra
 
Programming for Problem Solving
Kathirvel Ayyaswamy
 
Operators1.pptx
HARSHSHARMA840
 
OPERATORS OF C++
ANANT VYAS
 
Unit ii chapter 1 operator and expressions in c
Sowmya Jyothi
 
PPS 2.2.OPERATORS ARITHMETIC EXPRESSIONS/ARITHMETIC OPERATORS/RELATIONAL OPER...
Sitamarhi Institute of Technology
 
Ad

Recently uploaded (20)

PDF
Rapid Prototyping for XR: Lecture 5 - Cross Platform Development
Mark Billinghurst
 
PDF
01-introduction to the ProcessDesign.pdf
StiveBrack
 
PDF
Rapid Prototyping for XR: Lecture 6 - AI for Prototyping and Research Directi...
Mark Billinghurst
 
PPTX
Kel.3_A_Review_on_Internet_of_Things_for_Defense_v3.pptx
Endang Saefullah
 
PDF
PRIZ Academy - Process functional modelling
PRIZ Guru
 
PPTX
Introduction to Python Programming Language
merlinjohnsy
 
PPTX
Comparison of Flexible and Rigid Pavements in Bangladesh
Arifur Rahman
 
PDF
Python Mini Project: Command-Line Quiz Game for School/College Students
MPREETHI7
 
PPTX
Precooling and Refrigerated storage.pptx
ThongamSunita
 
PDF
Designing for Tomorrow – Architecture’s Role in the Sustainability Movement
BIM Services
 
PPTX
CST413 KTU S7 CSE Machine Learning Clustering K Means Hierarchical Agglomerat...
resming1
 
PPSX
OOPS Concepts in Python and Exception Handling
Dr. A. B. Shinde
 
PDF
May 2025: Top 10 Read Articles in Data Mining & Knowledge Management Process
IJDKP
 
PPTX
Tesla-Stock-Analysis-and-Forecast.pptx (1).pptx
moonsony54
 
PDF
How to Buy Verified CashApp Accounts IN 2025
Buy Verified CashApp Accounts
 
PDF
Rapid Prototyping for XR: Lecture 4 - High Level Prototyping.
Mark Billinghurst
 
PPT
FINAL plumbing code for board exam passer
MattKristopherDiaz
 
PDF
تقرير عن التحليل الديناميكي لتدفق الهواء حول جناح.pdf
محمد قصص فتوتة
 
PDF
Generative AI & Scientific Research : Catalyst for Innovation, Ethics & Impact
AlqualsaDIResearchGr
 
PPTX
CST413 KTU S7 CSE Machine Learning Introduction Parameter Estimation MLE MAP ...
resming1
 
Rapid Prototyping for XR: Lecture 5 - Cross Platform Development
Mark Billinghurst
 
01-introduction to the ProcessDesign.pdf
StiveBrack
 
Rapid Prototyping for XR: Lecture 6 - AI for Prototyping and Research Directi...
Mark Billinghurst
 
Kel.3_A_Review_on_Internet_of_Things_for_Defense_v3.pptx
Endang Saefullah
 
PRIZ Academy - Process functional modelling
PRIZ Guru
 
Introduction to Python Programming Language
merlinjohnsy
 
Comparison of Flexible and Rigid Pavements in Bangladesh
Arifur Rahman
 
Python Mini Project: Command-Line Quiz Game for School/College Students
MPREETHI7
 
Precooling and Refrigerated storage.pptx
ThongamSunita
 
Designing for Tomorrow – Architecture’s Role in the Sustainability Movement
BIM Services
 
CST413 KTU S7 CSE Machine Learning Clustering K Means Hierarchical Agglomerat...
resming1
 
OOPS Concepts in Python and Exception Handling
Dr. A. B. Shinde
 
May 2025: Top 10 Read Articles in Data Mining & Knowledge Management Process
IJDKP
 
Tesla-Stock-Analysis-and-Forecast.pptx (1).pptx
moonsony54
 
How to Buy Verified CashApp Accounts IN 2025
Buy Verified CashApp Accounts
 
Rapid Prototyping for XR: Lecture 4 - High Level Prototyping.
Mark Billinghurst
 
FINAL plumbing code for board exam passer
MattKristopherDiaz
 
تقرير عن التحليل الديناميكي لتدفق الهواء حول جناح.pdf
محمد قصص فتوتة
 
Generative AI & Scientific Research : Catalyst for Innovation, Ethics & Impact
AlqualsaDIResearchGr
 
CST413 KTU S7 CSE Machine Learning Introduction Parameter Estimation MLE MAP ...
resming1
 

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
  • 15. BY REHAN IJAZ value of a: 14 value of a: 15