PPS Unit-1.pdf

NenavathSurendhar 2,539 views 152 slides Sep 22, 2022
Slide 1
Slide 1 of 152
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117
Slide 118
118
Slide 119
119
Slide 120
120
Slide 121
121
Slide 122
122
Slide 123
123
Slide 124
124
Slide 125
125
Slide 126
126
Slide 127
127
Slide 128
128
Slide 129
129
Slide 130
130
Slide 131
131
Slide 132
132
Slide 133
133
Slide 134
134
Slide 135
135
Slide 136
136
Slide 137
137
Slide 138
138
Slide 139
139
Slide 140
140
Slide 141
141
Slide 142
142
Slide 143
143
Slide 144
144
Slide 145
145
Slide 146
146
Slide 147
147
Slide 148
148
Slide 149
149
Slide 150
150
Slide 151
151
Slide 152
152

About This Presentation

software


Slide Content

1
Programming For Problem Solving
I B.TechI Semester
BY
Mrs. PavaniB
Assistant Professor
Computer Science and Engineering
MRCET

2
“Unit-I”
IntroductiontoComputing–ComputerSystems,Computing
Environments,ComputerLanguages,Algorithmsand
Flowcharts,StepsforCreatingandRunningprograms.
IntroductiontoC–HistoryofC,FeaturesofC,StructureofC
Program,CharacterSet,CTokens-keywords,Identifiers,
Constants,Datatypes,Variables.Operators,Expressions,
PrecedenceandAssociativity,ExpressionEvaluation,Type
conversion,typedef,enum
ControlStructures:SelectionStatements(DecisionMaking)–if
andswitchstatements,RepetitionStatements(Loops)-while,
for,do-whilestatements,UnconditionalStatements–break,
continue,goto,Commandlinearguments.

Introduction to Computer System
AComputerisanelectronicdevicethatreceivesinput,storesor
processestheinputasperuserinstructionsandprovidesoutputin
desiredformat.
Input-Process-OutputModel
Computerinputiscalleddataandtheoutputobtainedafterprocessing
it,basedonuser’sinstructionsiscalledinformation.

Introduction to Computer System
Acomputerisasystemmadeoftwomajorcomponents.
1.Software
2.Hardware
Hardware:Physicalpartsofcomputerthatwecantouch
calledashardware.
i.e.Monitor,CPU,Keyboard,Mouse,etc.
Software:Itisasetofinstruction/programthattellsthe
computerwhattodo.
i.e.OperatingSystem,MSOffice,etc.

Introduction to Computer System
ComputerHardware:Thehardwarecomponentsofthe
computersystemisdividedinto4majorcomponents
1.InputDevices
2.OutputDevices
3.CPU(CentralProcessingUnit)
4.StorageDevices

6
Components of a Computer System
Input and Output Devices of a Computer System

Components of a Computer System
TheCentralProcessingUnit(CPU)isresponsibleforexecuting
instructionssuchasarithmeticcalculations,comparisonsamongdata,
andmovementofdatainsidethesystem.

Components of a Computer System

Computer Software

Relationship between System and Application Software is shown below

Compiler
Acompilerisacomputerprogramthattranslatescomputercode
writteninoneprogramminglanguage(thesourcelanguage)into
anotherlanguage(thetargetlanguage).

Computing Environments
Intheearlydaysofcomputer,thereisonlyoneenvironment:the
mainframecomputerhiddeninacentralcomputingdepartment.
Withtheadventofminicomputersandpersonalcomputer,the
environmentchanged,resultingincomputersonvirtuallyevery
desktop
1.Personal Computing Environment
2.Time-Sharing Environment
3.Client/Server Environment
4.Distributed Computing

Computing Environments
Personal Computing Environment
Inthepersonalcomputingenvironment,thereisasingle
computersystem.Allthesystemprocessesareavailableonthe
computerandexecutedthere.Thedifferentdevicesthatconstitute
apersonalcomputingenvironmentarelaptops,mobiles,printers,
computersystems,scannersetc.
Time Sharing Computing Environment
Thetimesharingcomputingenvironmentallowsmultipleusersto
sharethesystemsimultaneously.Eachuserisprovidedatime
sliceandtheprocessorswitchesrapidlyamongtheusers
accordingtoit.Becauseofthis,eachuserbelievesthattheyare
theonlyonesusingthesystem.

Fig : Time Sharing Computing Environment

Client Server Computing Environment
Inclientservercomputing,theclientrequestsaresourceandthe
serverprovidesthatresource.Aservermayservemultipleclients
atthesametimewhileaclientisincontactwithonlyoneserver.
Boththeclientandserverusuallycommunicateviaacomputer
networkbutsometimestheymayresideinthesamesystem.

Distributed Computing Environment
Adistributedcomputingenvironmentcontainsmultiplenodesthat
arephysicallyseparatebutlinkedtogetherusingthenetwork.All
thenodesinthissystemcommunicatewitheachotherandhandle
processesintandem.Eachofthesenodescontainsasmallpartof
thedistributedoperatingsystemsoftware.

Computer Languages

Machine Languages/Low Level Languages
Intheearliestdaysofcomputers,theonlyprogramming
languageavailableweremachinelanguages.Eachcomputer
haditsownmachinelanguage,whichwasmadeofstreamsof
0sand1s.
The only language
understood by a
computer is
machine language.

Symbolic Languages
•TheSymboliclanguagesusessymbolsormnemonicsto
representthevariousmachinelanguageinstructionsbut
symboliclanguagewasnotunderstoodbythecomputersoit
mustbetranslatedtothemachinelanguage..
•Aspecialprogramcalledassemblerusedtoconvertinto
machinelanguage.Symboliclanguagesareknownas
Assemblylanguages..
Example
1.mov eax, 10
2.mov ecx, 20
3.add eax, ecx

High-level Languages
•Althoughassemblylanguagesgreatlyimprovedprogramming
efficiency,theystillrequiredprogrammerstoconcentrateon
thehardwaretheywereusing.
•So,Highlevellanguagesaredesignedtorelivethe
programmerfromthedetailsoftheassemblylanguage.These
areportabletomanydifferentcomputers,allowingthe
programmertoconcentrateontheapplicationprogram.
•Overtheyears,variouslanguages,mostnotably
BASIC,COBAL,pascal,Ada,C,C++andjavaweredeveloped
•High-levellanguagesshouldbeconvertedintomachine
language.Thisprocessiscalledcompilation.

Algorithm
•Analgorithmisastepbystepprocesstosolveaproblemusing
afinitenumberofsteps.Algorithmsareusedinmathematical
computingetctocarryoutcalculationsordataprocessing.
•Thealgorithmisdevelopedusingpseudocodewhichcanthenbe
convertedtoacprogram
•Pseudocode:Itisanartificialandinformallanguagethathelps
programmerstodevelopalgorithm.Pseudocodeissimilarto
everydayenglish,itisconvenientanduser-friendly.
•Pseudocodeprogramsarenotexecutedoncomputersbutthey
areusedindevelopingalgorithms

Allthealgorithmsmustsatisfyfollowingproperties
PropertiesofAlgorithms
•Input–thealgorithmmustacceptzeroormoreinputs
•Output-mustproduceatleastoneoutput
•Definiteness-Eachinstructionisclearandunambiguous.
•Finiteness-Analgorithmshouldterminateafterafinite
numberofsteps.Itshouldnotenterintoaninfiniteloop
•Effectiveness–Eachoperationmustbesimpleandshould
completeinafinitetime

Algorithm : Addition of two numbers
Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values into num1 and num2.
Step 4: sum = num1+num2
Step 5: print sum
Step 6: Stop

Algorithm : Area of circle
Step 1: Start
Step 2: Declare variables radius and Area
Step 3: Read value into radius
Step 4: Area = 3.14*radius*radius
Step 5: print Area
Step 6: Stop

Algorithm : Largest among 3 numbers
Step 1: Start
Step 2: Declare variables a,band c.
Step 3: Read variables a,band c.
Step 4: If a > b
If a > c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b > c
Display b is the largest number.
Else
Display c is the greatest number.
Step 5: Stop

Algorithm to print "n" natural numbers
Step 1: Start
Step 2: Declare n, i
Step 3: Assign i=1
Step 4: Read value into n
Step 5: Repeat step 5.1 and 5.2 until i<=n
5.1 Print i
5.2 Compute i=i+1
Step 7: Stop

Algorithm to sum "n" natural numbers
Step 1: Start
Step 2: Declare variables n, sum and i.
Step 3: Initialize variables or Assign
sum = 0
i = 1
Step 4: Read value into n
Step 5: Repeat 5.1 and 5.2 until i <= n
5.1 : sum = sum+i
5.2 : i = i+1
Step 6: Display sum
Step 7: Stop

Flowchart
•Aflowchartisagraphicalrepresentationofanalgorithm.
Flowchartsaredrawnusingcertainspecial-purposesymbols
suchasrectangles,diamonds,ovals,andsmallcirclesasshown
below.
•Thesesymbolsareconnectedbyarrowscalledflowlines.Like
pseudocode,flowchartisusefulfordevelopingand
representingalgorithms.

Flowchart : Addition of two numbers
Step 1: Start
Step 2: Input/Read Number1 and Number2.
Step 3: Sum = Number1+Number2
Step 4: Print Sum
Step 5: Stop

Flowchart : Area of circle
Step 1: Start
Step 2: Read value into Radius
Step 3: Area = 3.14*Radius*Radius
Step 4: Display Area
Step 5: Stop

Flowchart : Largest among two numbers

Flowchart : Largest among three numbers
Read A,B,C
Print B is
largest
Print C is
largest
Print A is
largest
Start
Is
A>B
Is
A>C
Is
B>C
YesNo
No No
YesYes
Stop

Start
Assign i=1
Read n
Is
i<=n
Compute i=i+1
Stop
No
Yes
Flowchart for printing ‘n’ natural numbers
Print i

Start
Assign
Sum=0,i=1
Read n
Is
i<=n
Sum=Sum+i
Compute i=i+1
Stop
No
Yes
Sum of ‘n’ natural numbers
Print Sum

Creating, Compiling and Executing a Program

Creating, Compiling and Executing a Program
Syntax to create a file in linuxoperating system
$ geditfilename.c
Example :
$ geditadd.c
How to Compile a Program?
$ gccadd.c
How to run the program?
$ ./a.out

Features
•Itwasmainlydevelopedasasystemprogramminglanguageto
writeanoperatingsystem.
•ThemainfeaturesofClanguageinclude
•Low-levelaccesstomemory
•Asimplesetofkeywords
•Cleanstyle
•Easy to learn
•Structured language
•It produces efficient programs.
•ThesefeaturesmakeClanguagesuitableforsystemprogramming
likeanoperatingsystemorcompilerdevelopment.

Structure of a C Program

Documentationsection:Toenhancethereadabilityofthe
program,programmerscanprovidecommentsaboutthe
programinthissection.Commentscanbeusedanywherein
theprogrambuttoomanycommentsareavoided.
Example
/*Thisisaexampletochecklargestnumber*/
Headerfile/linksection:Cprogramdependsuponsome
headerfilesforfunctiondefinitionthatareusedinprogram.
Eachheaderfilebydefaultisextendedwith.h.Thefileshould
beincludedusing#includedirective.
#include <stdio.h>
or
#include “stdio.h”

Globaldeclarationsection:Thissectiondeclaressome
variablesthatareusedinmorethanonefunction.These
variablesareknownasglobalvariables.Thesemustbedeclared
outsideofallthefunctions.
Mainprogramsection:EveryprogramwritteninClanguage
mustcontainmain()function.Theexecutionoftheprogram
alwaysbeginswiththefunctionmain().
Theprogramexecutionstartswiththeopeningbrace({)and
endswiththeclosingbrace(}).Betweenthesetwobracesthe
programmershoulddeclarethedeclarationpartandthe
executablepart.

DeclarationPart:Thedeclarationpartdeclarestheentire
variablesthatareusedinexecutablepart.Theinitializationof
variablesalsodonehere.Theinitializationmeansproviding
theinitialvaluetothevariables
ExecutablePart:Thispartcontainsthestatementsfollowing
thedeclarationofthevariables.Thispartcontainsasetof
statements.Thesestatementsareenclosedbetweenthebraces.
User-definedfunction:Thefunctiondefinedbytheuseris
calleduserdefinedfunction.Thesefunctionsaregenerally
definedafterthemain()function.Theycanalsobedefined
beforemain()function.Thisportioninnotcompulsorynow.

/* Program to add two numbers */
#include<stdio.h> /* header file section */
intmain()
{
inta=10,b=20,c; //declaration part
c=a+b; //Executable part
printf("%d",c);
}
OUTPUT : 30
Note : initializing values in program itself

/* Program to add two numbers */
#include<stdio.h>
intmain()
{
inta,b,sum;
printf(“Enter any two values:”);
scanf(“%d %d”,&a,&b);
sum=a+b;
printf("%d",sum);
return 0;
}
OUTPUT : Enter any two values:15 30
45
Note : Taking input through keyboard

C Tokens
TOKENis the smallest
individual unit in a 'C'
program.

Keywords
Keywordsarethosewordswhosemeaningisalreadydefinedby
Compiler.Thereare32KeywordsinC.

Identifiers
Identifiersarethenamesgiventovariables,functionsandarrays
Eachidentifiedvariablestoredinauniqueaddress.Theseidentifierare
definedagainstasetofrules.
RulesforanIdentifier
•Thefirstcharacterofanidentifiercanonlycontainalphabet(a-z,
A-Z)orunderscore(_).
•IdentifiersarealsocasesensitiveinC.Forexamplenameand
NamearetwodifferentidentifiersinC.
•KeywordsarenotallowedtobeusedasIdentifiers.
•Nospecialcharacters,suchassemicolon,period,whitespaces,slash
orcommaarepermittedtobeusedinorasIdentifier.
•Anidentifiershouldnotcontainanywhitespaces.

Variables
Avariableisanameofthememorylocation.Itisusedtostoredata.
Itsvaluecanbechanged,anditcanbereusedmanytimes.
Syntax:
Data_typevariable_list;
Example:
inta;
floatb;
charc;
Here,a,b,carevariables.
Theint,float,chararethedatatypes.

Datatypes
Adatatypespecifiesthetypeofdatathatavariablecanstoresuchas
integer,floating,character,etc.

CharacterDataType:




Characterdatatypeallows avariabletostoreonly onecharacter.
Sizeofcharacterdatatypeis 1 byte(8bits).
“char”keywordis used to refercharacterdata type.
Forexample,‘A’canbestoredusingchardatatype.Youcan’tstore
morethan onecharacterusingchardata type.
Formatspecifier orcontrolstringis %c
Rangeforsignedchar-128 to 127 and unsigned charis0 to 255.


•Example:chargender=‘F’;
Datatypes

IntegerDataType:
•Integerdata typeallows avariable to storenumeric values.
•“int” keywordisusedtoreferintegerdatatype.


Thestoragesizeofintdatatypeis2
Itvariesdependupontheprocessor
areusing16bitprocessor,2byte
allocatedforintdatatype.
or4 or8 byte.
intheCPUthatweuse.Ifwe
(16bit)ofmemorywillbe
•Likewise,4byte(32bit)ofmemoryfor32bitprocessorand
8byte(64bit)ofmemoryfor64bitprocessorisallocatedforint
datatype.
Datatypes

•int(2byte)canstorevalues
int.0 to 65535 forunsigned
from-32,768to+32,767forsigned
int.
•int(4byte) canstorevaluesfrom-2,147,483,648to
+2,147,483,647forsignedint.0to4,29,49,67,295forunsigned
int.
Ifyouwanttousetheintegervaluethatcrossestheabovelimit,
youcangofor“longint”and“longlongint”forwhichthe
limitsareveryhigh.

Note:
•Wecan’t storedecimal values using intdatatype.

Datatypes
Float and double
float and double are used to hold real numbers(decimal values).
For Example : float a=33.6;
Type Storage size Value range PrecisionControl
String
float 4 bytes(32 bits)1.2E-38 to 3.4E+38 6 decimal
places
%f
double 8 bytes(64 bits)3E-308 to 1.7E+30815 decimal
places
%lf
long double10 bytes(80 bits)3.4E-4932 to 1.1E+493219 decimal
places
%Lf

MODIFIERSINC LANGUAGE:
•Modifiersareprefixedwith basicdata typestomodify
(eitherincreaseordecrease)theamountofstoragespace
allocatedtoavariable.
Forexample,storagespaceforintdatatypeis4bytefor32
bitprocessor.Wecanincreasetherangebyusinglongint
whichis8byte.Wecandecreasetherangebyusingshort
intwhichis2byte.

•Thereare5 modifiersavailablein C language. They are,





short
long
signed
unsigned
long long

-2
(n-1)to 2
(n-1)-1Tocalculaterangefor charorintor long
Herenrepresentsnumberofbits

Syntax and Logical Errors
Syntaxerrorsarealsoknownasthecompilationerrorsasthey
occurredatthecompilationtime.
Theseerrorsaremainlyoccurredduetothemistakeswhiletypingor
donotfollowthesyntaxofthespecifiedprogramminglanguage.
Example:
Ifwewanttodeclarethevariableoftypeinteger,
inta;//thisisthecorrectform
Inta;//thisisanincorrectform.
Commonlyoccurredsyntaxerrorsare:
Ifwemisstheparenthesis(})whilewritingthecode.
Displayingthevalueofavariablewithoutitsdeclaration.
Ifwemissthesemicolon(;)attheendofthestatement.

Syntax and Logical Errors
Thelogicalerrorisanerrorthatleadstoanundesiredoutput.These
errorsproducetheincorrectoutput.Theoccurrenceoftheseerrors
mainlydependsuponthelogicalthinkingofthedeveloper.
Example.
Manydifferenttypesofprogrammingmistakescancauselogic
errors.Forexample,assigningavaluetothewrongvariablemay
causeaseriesofunexpectedprogramerrors.Multiplyingtwo
numbersinsteadofaddingthemtogethermayalsoproduce
unwantedresults.

Constants
Aconstantisavaluethatcan'tbechangedintheprogram,for
example:10,20,'a',3.4,"cprogramming"etc.

BACKSLASHCHARACTER CONSTANTSINC:
•Therearesomecharacterswhichhavespecialmeaning
inClanguage.
•Theyshouldbeprecededbybackslashsymboltomake
useofspecialfunctionofthem.
•Givenbelowisthelistofspecialcharactersandtheir
purpose.
\n New line
\t Horizontal tab
\v Vertical tab

Variables can be declared as constant using the const keyword
#include <stdio.h>
intmain()
{
inta=10;
a=20;
printf("a=%d", a);
return 0;
}
#include <stdio.h>
intmain()
{
const inta=10;
a=20;
printf("%d", a);
return 0;
}
The const keyword
OUTPUT
a=20
OUTPUT
Error

64
Input / Output Functions
printf()function:
Theprintf()functionisusedforoutput.Itprintsthegivenstatement
totheconsole.
Thesyntaxofprintf()functionisgivenbelow:
Theformatstringcanbe%d(integer),%c(character),%s(string),%f
(float)etc.
scanf()function:
Thescanf()functionisusedforinput.Itreadstheinputdatafromthe
console.
scanf("formatspecifier",variable_list);
printf("formatspecifier",variables_list);

65
Input / Output Functions Example
Programtoprintcubeofgivennumber
#include<stdio.h>
intmain()
{
intnumber;
printf("enteranumber:");
scanf("%d",&number);
printf("cubeofnumberis:%d",number*number*number);
return0;
}

66
Operators in C
•Csupportsrichsetofoperators.
•Anoperatorisasymbolthattellsthecompilertoperformcertain
mathematicalorlogicalmanipulations.
•Operatorsareusedinprogramstomanipulatedataandvariables.

67
Operators in C
Types of ‘C’ operators
1.Arithmetic operators
2.Relational operators
3.Logical operators
4.Assignment operators
5.Increment and Decrement operators
6.Conditional operators
7.Bitwise operators
8.Special operators

68
Arithmetic Operators
Anarithmeticoperatorperformsmathematicaloperationssuchas
addition,subtractionandmultiplicationonnumericalvalues(constants
andvariables).
Operator Meaning of Operator
+ addition or unary plus
- subtraction or unary minus
* multiplication
/ division
% remainder after division( modulo division)
Note:-Modulardivisionoperator%cannotusedonfloating
pointdata

OUTPUT
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder = 1
Example
include <stdio.h>
intmain()
{
inta = 9,b = 4, c;
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder = %d \n", c);
return 0;
}

include <stdio.h>
intmain()
{
inta = 9,b = 4, sum,sub,mul,div,rem;
sum = a+b;
sub = a-b;
mul= a*b;
div = a/b;
rem = a%b;
printf("%d \n",sum);
printf(" %d \n",sub);
printf("%d \n",mul);
printf(“%d\n",div);
printf(“%d \n", rem);
return 0;
}
OUTPUT
13
5
36
2
1

include <stdio.h>
intmain()
{
inta = 9,b = 4;
printf(“sum = %d \n",a+b);
printf(“sub = %d \n",a-b);
printf(“mul= %d \n",a*b);
printf(“div = %d \n",a/b);
printf("Remainder = %d \n", a%b);
return 0;
}
OUTPUT
sum = 13
sub = 5
mul= 36
div = 2
Remainder = 1

72
Operators in C
Relational Operators
Relationaloperatorsareusedtofindtherelationbetweentwo
variables.i.e.tocomparethevaluesoftwovariablesinaCprogram.

If a=20 b=10
a>b it returns 1 (True)
a<b it returns 0 (False)
a<=b it returns 0 (False)
a>=b it returns 1 (True)
a==b it returns 0 (False)
a!=b it returns 1(True)
If a=10 b=10
a==b it returns 1 (True)
a!=b it returns 0 (False)
Relational Operators with Example

74
OUTPUT
0
0
1
0
1
1
Example
#include<stdio.h>
intmain()
{
inti=7,j=1;
printf(“%d \n”,i==j);
printf(“%d \n”,i<j);
printf(“%d \n”,i>j);
printf(“%d \n”,i<=j);
printf(“%d \n”,i>=j);
printf(“%d \n”,i!=j);
return 0;
}

75
Logical Operators
•Allowaprogramtomakeadecisionbasedonmultipleconditions.
•Logicaloperatorsareusedwhenwewanttotestmorethanonecondition.
•Examplea>b&&a>c

76
5>3 && 5<10 returns 1
8>5 && 8<2 returns 0
8>5 || 8<2 returns 1
!(8>5) returns 0

#include<stdio.h>
intmain()
{
printf(“%d \n”,5>3 && 5<10);
printf(“%d \n”,8>5 && 8<2);
printf(“%d \n”,8>5 || 8<2);
printf(“%d \n”,!(8>5));
return 0;
}
output
1
0
1
0

78
Operators in C
Assignment Operators
•Assignment operators are used to assign the result of an
expression to avariable.
•C has a set of ‘shorthand’ assignment
operator:
variable name=expression;
Leftsidemustbeavariablethat
canreceiveavalue
Example
c=a+b;

79
Operatorsin C
Shorthand Assignmentoperators
SimpleAssignment
Operator
ShorthandOperator
a =a+1 a +=1
a =a-1 a -=1
a = a*(m+n) a * =m+n
a = a /(m+n) a / =m+n
a = a%b a%=b

#include<stdio.h>
intmain()
{
inta,b,c;
printf(“Enter any two integer values \n”);
scanf(“%d %d”,&a,&b);
c=a+b;
c+=10;
printf(“ sum=%d”, c);
}
OUTPUT
Enter any two integer values 10 20
Sum=40

81
Increment and Decrement Operators
Incrementoperatorsareusedtoincreasethevalueofthevariable
byoneanddecrementoperatorsareusedtodecreasethevalueof
thevariablebyone.
Syntax:
Increment operator: ++
pre increment : ++var_name;
post increment : var_name++;
Decrement operator: --
pre decrement: ––var_name;
post decrement var_name––;
Example:
Increment operator :++ iandi++ ;
Decrement operator : ––iand i––;

Example
NOTE:
Apostfixoperatorfirstassignsthevaluetothevariableonleft
andthenincrementstheoperand.
Ontheanotherhand,Aprefixoperatorfirstadds1tothe
operandandthenresultisassignedtothevariableonleft.
If x=5
a = x++ ; a=5 x=6
a = ++x;a=6 x=6
a = x––; a=5 x=4
a = ––x;a=4 x=4

83
Example
#include<stdio.h>
intmain()
{
inta=1,b=1;
printf(“%d”,++a);
printf(“ %d ”,b++);
printf(“ %d ”,b);
return 0;
}
OUTPUT
2 1 2
#include<stdio.h>
intmain()
{
inta=1,b=1;
printf(“%d”,--a);
printf(“ %d ”,b--);
printf(“ %d ”,b);
return 0;
}
OUTPUT
0 1 0

84
Operators in C

#include<stdio.h>
main()
{
inta=9,b=9;
a=b++;
b=a++;
b=++b;
printf("%d%d",a,b);
}
a) 9,9
b) 10,10
c) 9,10
d) 10,9
#include <stdio.h>
main()
{
inta,b;
b = 10;
a = ++b + ++b;
printf("%d%d",a,b);
}
a) 24,12
b) 23,12
c) 23,10
d) 24,10

86
Operators in C
Conditional Operators
•Theconditionalexpressioncanbeusedasshorthandforsomeif-else
statements.Itisaternaryoperator.
•Thisoperatorconsistoftwosymbols:thequestionmark(?)andthe
colon(:).

87
Example
intmain()
{
int a ,b, c;
a =10;
b = (a == 1) ? 20:30;
printf( “ Value of b is %d \n ", b ); // 30
c = (a == 10) ? 20 :30;
printf( “ Value of c is %d \n", c); // 20
return 0;
}

Example
intmain()
{
int a =10,b=20;
if(a >b) ? printf(“a is greater”):printf(“b is greater”);
return 0;
}

89
Operators in C
Bitwise Operators
•IntheCprogramminglanguage,operationscanbeperformedona
bitlevelusingbitwiseoperators.
•FollowingarethebitwiseOperators

90
Operators in C
Truth Table

91
Operators in C
ShiftOperator:
LeftShiftOperator(<<):Theleftshiftoperatorwillshift
thebitstowardsleftforthegivennumberoftimes.
inta=2<<1;
printf(“%d”,a);//willprint4
Ifyouleftshiftlike2<<2,thenitwillgivetheresultas8.
Thereforeleftshifting1time,isequaltomultiplyingthe
valueby2.
RightshiftOperator(>>)
Therightshiftoperatorwillshiftthebitstowardsrightfor
thegivennumberoftimes
intb=4>>1
printf(“%d”,b);//willprint2
Rightshifting1time,isequivalenttodividingthevalue
by2.

92
Operators in C
Special Operators
C supports some special operators suchas:
•commaoperator “,” is used to link related expressions together
inta=5,b=6;
•sizeof operator“sizeof()”
•Addressoperator “&”
•pointeroperator “*”
•memberselectionoperator“. and ->”
•Size of operator returns the number of bytes occupied in
memory..theoperand may be variable or constant or data type
qualifier

#include<stdio.h>
intmain()
{
inta;
float b;
char c;
double d;
printf("Size of int: %d bytes\n", sizeof(a));
printf("Size of float: %d bytes\n", sizeof(b));
printf("Size of char: %d bytes\n", sizeof(c));
printf("Size of double: %d byte\n", sizeof(d));
return 0;
}
Size of int: 4 bytes
Size of float: 4 bytes
Size of char: 1 bytes
Sizeofdouble:8byte

Expressions
Anexpressionisacollectionofoperatorsandoperandsthat
representsaspecificvalue.
Whatisanexpression?
ExpressionTypesinC
IntheCprogramminglanguage,expressionsaredividedinto
THREEtypes.Theyareasfollows...
1.InfixExpression–Example:a+b
2.PostfixExpression–Example:a++
3.PrefixExpression–Example:++a

95
Operator Precedence and Associativity
WhatisOperatorPrecedence?
•Operatorprecedenceisusedtodeterminetheorderofoperators
evaluatedinanexpression.Incprogramminglanguageevery
operatorhasprecedence(priority).
•Whenthereismorethanoneoperatorinanexpression,the
operatorwithhigherprecedenceisevaluatedfirstandthe
operatorwiththeleastprecedenceisevaluatedlast.
What is Operator Associativity?
•Operatorassociativityisusedtodeterminetheorderof
operatorswithequalprecedenceevaluatedinanexpression.
•Inthecprogramminglanguage,whenanexpressioncontains
multipleoperatorswithequalprecedence,weuseassociativity
todeterminetheorderofevaluationofthoseoperators.

96
Operator Precedence and Associativity

100
Expression Evaluation
3

101
Type Conversion
ThetypeconversionprocessinCisbasicallyconvertingonetype
ofdatatypetoothertoperformsomeoperation.
Theconversionisdoneonlybetweenthosedatatypeswhereinthe
conversionispossible
example–chartointandviceversa.
Therearetwotypesofconversions:
1.ImplicitTypeConversion
2.ExplicitTypeConversion
ImplicitTypeConversion
Thistypeofconversionisusuallyperformedbythecompiler
whennecessarywithoutanycommandsbytheuser.Thusitisalso
called"AutomaticTypeConversion".

102
Type Conversion

103
Type Conversion

104
Type Conversion
Example 1
int a = 20;
double b = 20.5;
a + b; -----40.5
Example 2
char ch='a';
int x =13;
x + ch; ------110

105
Type Conversion

106
Type Conversion-Example
#include<stdio.h>
intmain()
{
float a = 4.5;
float b = 4.6;
float c = 4.9;
intresult;
result = (int)a + (int)b + (int)c;
printf("result = %d", result);
return 0;
}
Output : 12
#include<stdio.h>
intmain()
{
float a = 4.5;
float b = 4.6;
float c = 4.9;
float result;
result = a + b + c;
printf("result = %d", result);
return 0;
}
Output : 14.000000

107
typedef
typedefis a keyword used in C language to assign alternative names to
existing datatypes.
Its mostly used with user defined datatypes.
Following is the general syntax for using typedef,
typedef <existing_name> <alias_name>
Example:
#include <stdio.h>
int main()
{
typedefint unit;
unit i,j;
i=10,j=20;
printf("Value of i is :%d",i);
printf("\nValueof j is :%d",j);
return 0;
}

Conditional Statements
•ConditionalStatements/Decision-makingstatementsarethe
statementsthatareusedtoverifyagivenconditionanddecide
whetherablockofstatementsgetsexecutedornot,basedonthe
conditionresult.
•Inthecprogramminglanguage,therearetwodecision-making
statementstheyareasfollows.
1.ifstatement
2.switchstatement

if statement in C
ifstatementisusedtomakedecisionsbasedonacondition.Theif
statementverifiesthegivenconditionanddecideswhetherablockof
statementsareexecutedornot,basedontheconditionresult.
Inc,ifstatementisclassifiedintofourtypesasfollows...
•Simpleifstatement
•if-elsestatement
•Nestedifstatement
•else-ifladder

Simple if statement
Syntax:
if(condition)
{
//Statementstoexecute
ifconditionistrue
}
It is used to decide whether a certain
statement or block of statements will be
executed or not

Simple if statement-Example
//CprogramtoillustrateIfstatement
#include<stdio.h>
intmain()
{
inti=10;
if(i>15)
{
printf("10islessthan15");
}
printf("IamNotinif");
}

if-else statement
Syntax:
if(condition)
{
//statementblock1
//conditionistrue
}
else
{
//statementblock2
//conditionisfalse
}
if a condition is true it will execute a
statement block 1 and if the condition is
falseit will executes a statement block 2

//CprogramtoillustrateIf-elsestatement
#include<stdio.h>
intmain()
{
intn;
printf(“enteranynumber”);
scanf(“%d”,&n);
if(n%2==0)
{
printf(“numberiseven”);
}
else
{
printf(“numberisodd”);
}
return0;
}

Nested if-else statement
Syntax:
if(condition1)
{
if(condition2)
{
statement1;
}
else
{
statement2;
}
}
else
{
statement3;
}
Nested ifstatements means anifstatement inside anotherifstatement.

Nested if-else statement-Example
#include<stdio.h>
voidmain()
{
inta,b,c;
printf("Enter3numbers...");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if(a>c)
{
printf("aisthegreatest");
}
else
{
printf("cisthegreatest");
}
}
else
{
if(b>c)
{
printf("bisthegreatest");
}
else
{
printf("cisthegreatest");
}
}
}

else-if ladder statement
Syntax:
if(Condition1)
{
statementblock1;
}
elseif(Condition2)
{
statementblock2;
}
elseif(Condition3)
{
statementblock3;
}
….
else
defaultstatement;

#include<stdio.h>
int main()
{
int s1,s2,s3,s4,s5,sum,avg;
printf("Enter marks of 5 subjects each out of 100 \n ");
scanf("%d %d %d %d %d",&s1,&s2,&s3,&s4,&s5);
sum=s1+s2+s3+s4+s5;
avg = sum/5;
printf("sum=%d average=%d \n",sum,avg);
if(s1<35 || s2<35 || s3<35 || s4<35 || s5<35)
{
printf(" failed");
}

if(avg>=80)
printf("\n\n Your Grade : A+");
else if(avg>=75)
printf("\n\n Your Grade : A");
else if(avg>=60)
printf("\n\n Your Grade : B");
else if(avg>=45)
printf("\n\n Your Grade : C");
else if(avg>=35)
printf("\n\n Your grade : D");
else
printf("\n\n You Are Fail");
return 0;
}
OUTPUT
Enter marks of 5 subjects each out of 100
89 78 65 57 46
sum=335average=67
YourGrade:B

Switch Statement
•Switchstatementisacontrolstatementthatallowsustochoose
onlyonechoiceamongthemanygivenchoices.
•Theexpressioninswitchevaluatesiscomparedtothevalues
presentindifferentcases.
•Itexecutesthatblockofcodewhichmatchesthecasevalue.
•Ifthereisnomatch,thendefaultblockisexecuted(ifpresent).

Switch Statement
switch(expression)
{
casevalue-1:
block-1;
break;
casevalue-2:
block-2;
break;
casevalue-3:
block-3;
break;
casevalue-4:
block-4;
break;
default:
default-block;
break;
}

Switch Statement Rules
1)Theswitchexpressionmustbeofanintegerorcharactertype.
2)Thecasevaluemustbeanintegerorcharacterconstant.
3)Thecasevaluecanbeusedonlyinsidetheswitchstatement.
4)Thebreakstatementinswitchcaseisnotmust.Itisoptional.If
thereisnobreakstatementfoundinthecase,allthecaseswillbe
executedpresentafterthematchedcase.

Switch Statement Example
#include<stdio.h>
intmain()
{
intch,n1,n2;
printf("1.Addition\n");
printf("2.subtraction\n");
printf("3.Multiplication\n");
printf("4.Division\n");
printf(“5.ModularDivision\n");
printf("enteryourchoice:");
scanf("%d",&ch);
printf("Entertwooperands:");
scanf("%d%d",&n1,&n2);
switch(ch)
{
case1:
printf(“sum=%d",n1+n2);
break;
case2:
printf(“sub=%d“,n1-n2);
break;
case 3:
printf(“mul= %d", n1*n2);
break;
case 4:
printf(“division = %d“,n1/n2);
break;
case 5: printf(“rem = %d“,n1%n2);
break;
default:
printf("Error! Select only from 1 to 4");
}
return 0;
}

OUTPUT
1. Addition
2. subtraction
3. Multiplication
4. Division
5.Modular Division
enter your choice : 2
Entertwooperands: 50 30
Sub = 20
OUTPUT
1. Addition
2. subtraction
3. Multiplication
4. Division
5.Modular Division
enter your choice : 6
Entertwooperands: 50 30
Error! Select only from 1 to 5

Switch Statement Example
#include<stdio.h>
intmain()
{
intn1,n2;
charch;
printf("1.Addition\n");
printf("2.subtraction\n");
printf("3.Multiplication\n");
printf("4.Division\n");
printf("enteryourchoice:");
scanf("%c",&ch);
printf("Entertwooperands:");
scanf("%d%d",&n1,&n2);
switch(ch)
{
case‘+’:
printf(“sum=%d",n1+n2);
break;
case‘-’:
printf(“sub=%d“,n1-n2);
break;
case ‘*’:
printf(“mul= %d", n1*n2);
break;
case ‘/’:
printf(“division = %d“,n1/n2);
break;
default:
printf("Error! Enter valid choice");
}
return 0;
}

OUTPUT
1. Addition
2. subtraction
3. Multiplication
4. Division
enter your choice : +
Entertwooperands: 50 30
Sum = 80
OUTPUT
1. Addition
2. subtraction
3. Multiplication
4. Division
enter your choice : &
Entertwooperands: 50 30
Error! Enter valid choice

Iterative Statements/ Loops
Aloopisusedtorepeatablockofcodeuntilthespecifiedcondition
ismet.Usingloopswedonotneedtowritethesamecodeagainand
again.
Cprogramminghasthreetypesofloops:
•whileloop
•do...whileloop
•forloop
Theseloopscontrolledeitheratentryleveloratexitlevelhenceloops
canbecontrolledtwoways:
1.Entry Controlled Loop
2.Exit Controlled Loop

Iterative Statements/ Loops
EntryControlledLoop
Loop,wheretestconditionischeckedbeforeenteringtheloopbody,
knownasEntryControlledLoop.Example:whileloop,forloop
ExitControlledLoop
Loop,wheretestconditionischeckedafterexecutingtheloopbody,
knownasExitControlledLoop.Example:dowhileloop

While Loop
•Thewhileloopisaddressedasentrycontrolledloop/pretestloop.
•Thewhileloopevaluatesthetestexpressioninsidetheparenthesis
().
•Ifthetestexpressionistrue,statementsinsidethebodyofwhile
loopareexecuted.Then,thetestexpressionisevaluatedagain.
•Theprocessgoesonuntilthetestexpressionisevaluatedtofalse.
•Ifthetestexpressionisfalse,theloopterminates(ends).

While Loop
Syntax:
while(testExpression)
{
//bodyoftheloop
}

While Loop-Example
//Printnumbersfrom1to5
#include<stdio.h>
intmain()
{
inti=1;
while(i<=5)
{
printf("%d\t",i);
i++;
}
return0;
}
//Printnumbersfrom1ton
#include<stdio.h>
intmain()
{
inti=1,n;
printf(“Entertherange:”);
Scanf(“%d”,&n);
while(i<=n)
{
printf("%d",i);
i++;
}
return0;
}
OUTPUT
12345
OUTPUT
Entertherange:10
12345678910

do-while Loop
•Thedo...whileloopisaddressedasexitcontrolledloop/posttest
loop
•Thebodyofdo...whileloopisexecutedatleastonce.Onlythen,
thetestexpressionisevaluated.
•Ifthetestexpressionistrue,thebodyoftheloopisexecutedagain
andthetestexpressionisevaluated.
•Thisprocessgoesonuntilthetestexpressionbecomesfalse.
•Ifthetestexpressionisfalse,theloopends.

do-while Loop
Syntax:
do
{
//bodyoftheloop
}
while(testExpression);

//Printnumbersfrom1to5
#include<stdio.h>
intmain()
{
inti=1;
do
{
printf("%d\t",i);
i++;
}while(i<=5);
return0;
}
//Printnumbersfrom1ton
#include<stdio.h>
intmain()
{
inti=1,n;
printf(“entertherange:”);
scanf(“%d”,&n);
do
{
printf("%d\t",i);
i++;
}while(i<=n);
return0;
}
Do-while Example
OUTPUT
12345
OUTPUT
Enter the range: 8
12345678

for Loop
Syntax:
for(initializationStatement;testExpression;updateStatement)
{
//bodyofloop
}

for Loop
•Theinitializationstatementisexecutedonlyonce.
•Then,thetestexpressionisevaluated.Ifthetestexpressionis
evaluatedtofalse,theforloopisterminated.
•However,ifthetestexpressionisevaluatedtotrue,statements
insidethebodyofforloopareexecuted,andtheupdateexpression
isupdated.
•Againthetestexpressionisevaluated.
•Thisprocessgoesonuntilthetestexpressionisfalse.Whenthe
testexpressionisfalse,theloopterminates.

#include<stdio.h>
intmain()
{
inti;
for(i=1;i<=5;i++)
{
printf("%d",i);
}
return0;
}
#include<stdio.h>
intmain()
{
inti,n;
printf(“Entertherange:”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
printf("%d",i);
}
return0;
}
//Printnumbersfrom1to5 //Printnumbersfrom1ton
for Loop-Example
OUTPUT
12345
OUTPUT
Enter the range: 12
1 2 3 4 5 6 7 8 9 10 11 12

Example Programs
//1.factorialofagivennumber
#include<stdio.h>
int main()
{
int i,fact=1,number;
printf("Enter a number: ");
scanf("%d",&num);
for(i=1;i<=num;i++)
{
fact=fact*i;
}
printf("Factorial of %d is: %d",num,fact);
return 0;
}
output
Enter a number: 5
Factorial of 5 is: 120

Example Programs
//2.sumofnnaturalnumbers
output
Enter a positive integer: 10
Sum = 55
#include <stdio.h>
int main()
{
int n, i, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
for (i= 1; i<= n; ++i)
{
sum=sum+i;
}
printf("Sum = %d", sum);
return 0;
}

Example Programs
// 3. Multiplication Table Up to 10
output
Enter an integer: 9
9 * 1 = 9
9 * 2 = 18
9 * 3 = 27
9 * 4 = 36
9 * 5 = 45
9 * 6 = 54
9 * 7 = 63
9 * 8 = 72
9 * 9 = 81
9 * 10 = 90
#include <stdio.h>
int main()
{
int n, i;
printf("Enter an integer: ");
scanf("%d", &n);
for (i= 1; i<= 10; ++i)
{
printf("%d * %d = %d \n", n, i, n * i);
}
return 0;
}

Example Programs
// 4. sum of individual digits of a number
OUTPUT
Enter a number:654
Sum is=15
Enter a number:123
Sum is=6
#include<stdio.h>
int main()
{
int n,sum=0,rem;
printf("Enter a number:");
scanf("%d",&n);
while(n>0)
{
rem=n%10;
sum=sum+rem;
n=n/10;
}
printf("Sum is=%d",sum);
return 0;
}

Weoftencomeacrosssomesituationswherewewanttomakea
jumpfromonestatementtootherstatement,jumpoutofaloopor
tojumptonextiterationoftheloopinstantly,.
Thiscanbeaccomplishedbythestatementslike:
break
continue
goto
Jumps in loops:(unconditional statements)

Breakstatement
Thebreakstatementendstheloopimmediatelywhenitis
encountered.
Syntax:
break;

Breakstatement

Breakstatement-Example
# include <stdio.h>
int main()
{
int i;
for(i=1; i<= 10; i++)
{
if(i==6)
break;
printf("%d",i);
}
}
Output
1 2 3 4 5
# include <stdio.h>
int main()
{
int i=1;
while(i<= 10)
{
if(i==6)
break;
printf("%d",i);
i++;
}
}
Output
1 2 3 4 5

Breakstatement-Example
// Program to calculate the sum of a maximum of 10 numbers
// If a negative number is entered, the loop terminates
# include <stdio.h>
int main()
{
int i;
int number, sum = 0;
for(i=1; i<= 10; i++)
{
printf("Enter number %d: ",i);
scanf("%d",&num);
if(number < 0)
break;
sum = sum+ num;
}
printf("Sum = %d",sum);
}
output
Enter a number 1: 5
Enter a number 2: 6
Enter a number 3: 10
Enter a number 4: 45
Enter a number 5: 26
Enter a number 6: -56
Sum=92

continuestatement
Thecontinuestatementskipsthecurrentiterationoftheloopand
continueswiththenextiteration.
Syntax:
continue;
continue;

continuestatement

continuestatement-Example
# include <stdio.h>
int main()
{
int i;
for(i=1; i<= 10; i++)
{
if(i==6)
continue;
printf("%d",i);
}
}
Output
1 2 3 4 5 7 8 9 10
# include <stdio.h>
int main()
{
int i=0;
while(i<= 10)
{
i++;
if(i==6)
continue;
printf("%d",i);
}
}
Output
1 2 3 4 5 7 8 9 10

continuestatement-Example
// Program to calculate the sum of 10 positive numbers
// Negative numbers are skipped from the calculation
# include <stdio.h>
int main()
{
int i, num, sum = 0;
for(i=1; i<= 10; i++)
{
printf("Enter number%d: ",i);
scanf("%d",&num);
if(number < 0)
continue;
sum = sum+num;
}
printf("Sum = %d",sum);
}
output
Enter a number1 : 10
Enter a number2 : 20
Enter a number3 : 30
Enter a number4 : 40
Enter a number5 : 50
Enter a number6 : -5
Enter a number7 : 10
Enter a number8 : -8
Enter a number9 : 20
Enter a number10 : 30
Sum=210

gotostatement
ThegotostatementisknownasjumpstatementinC.
Thegotostatementallowsustotransfercontroloftheprogramtothe
specifiedlabel.
Syntax:
Thelabelisanidentifier.Whenthegotostatementisencountered,the
controloftheprogramjumpstolabel:andstartsexecutingthecode.

gotostatement-Example
#include <stdio.h>
int main()
{
int sum=0;
for(inti= 0; i<=10; i++)
{
sum = sum+i;
if(i==5)
{
goto addition;
}
}
addition:
printf(“sum =%d", sum);
return 0;
}
Output
sum=15

//program to find reverse of a given number
#include<stdio.h>
intmain()
{
intn,rev=0,rem;
printf("Enter a number:");
scanf("%d",&n);
while(n>0)
{
rem=n%10;
rev=rev*10+rem;
n=n/10;
}
printf(“Reverse of a given number is=%d",rev);
return 0;
}
OUTPUT
Enter a number:987
Reverse of a given number is= 789
Tags