CH-1SYSTEM PROGARMMING (1).pdf programing

hundarat596 21 views 85 slides Jun 02, 2024
Slide 1
Slide 1 of 85
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

About This Presentation

Programing


Slide Content

SYSTEMPROGRAMMING
Faiz Akram (PhD)
Subject and Code: System Programming –SE2044
4
th
Year, BSc. in Software Engineering

INTRODUCTION

INTRODUCTION
SOFTWARE:
Itisageneralteamusedtodescribecollectionofcomputer
programorprocedurewhichperformaspecifictask.
HARDWARE:
Itcanbedescribedasadevicethatisphysicallyconnectedtoa
systemwhichcanbetouched.
PROGRAM:
ApplicationwrittenwiththehelpofaPLisaprogram
(ProgrammingLanguage).
1

Difference between system programming and windows
programming:-
Theonlydifferenceisatechnicalone.
Whilebotharethesame,an'application'is
acomputerprogramlaunchedanddependentuponan
operatingsystemtoexecute."
Whenyouclickonawordprocessor,forexample,itisan
application,asisthathiddenfilethatrunstheprinter
spoolerlaunchedonlybytheOS.
2

Today: …so what is systems programming?
:
Thesystemprogramislikelytobeusedtosupportother
softwareandapplicationsprograms,butmayalsobea
completeapplicationspackageitself.
Itisdesignedforcontinued“production”useratherthana
one-shotsolutiontoasingleapplicationsproblem.
Itislikelytobecontinuouslyevolvinginthenumberand
typesoffeaturesitsupports.
Asystemprogramrequiresacertaindisciplineorstructure,
bothwithinandbetweenmodules(i.e.,“communication”)
,andisusuallydesignedandimplementedbymorethan
oneperson.
5

COMPUTERPROGRAMS
ComputerPrograms:Therearetwotypesofcomputer
programs.
ApplicationProgram
SystemProgram
•ApplicationProgram:Itisdesignedtohelptheuserto
performsomespecifictask,relatedtorealtimeapplication
pointofview.
•SystemProgram:Itisdesignedtooperateandcontrolthe
computerhardwareandalsoprovidesaplatformforrunningthe
application
•Softwareitisrequiresgreaterdegreeofhardwareawareness.
Example:Compiler,Assembler,Macros,InterpreterEtc.
3

Cont….
System Software:
Computercanperformavarietyoftasksuchasediting,linking,
translating,managingresourcesmanaging.I/Odeviceserror
handlingetcwiththehelpofsystemsoftware.
Thus,itiscollectionofsystemprogramstoperformvarious
operations.
ApplicationSoftware:
AnApplicationsoftwareisacomputersoftwaredesignedto
performagroupofcoordinatedfunctions,task,oractivitiesfor
thebenefitoftheuser.
4

Difference between System Software Application Software
1.
Systemsoftwareisusedforoperatingcomputerhardware.
Applicationsoftwareisusedbyusertoperformspecifictask.
2.
Systemsoftwaresareinstalledonthecomputerwhenoperatingsystemis
installed.
Applicationsoftwaresareinstalledaccordingtouser’srequirements.
3.
Ingeneral,theuserdoesnotinteractwithsystemsoftwarebecauseitworks
inthebackground.
Ingeneral,theuserinteractswithapplicationsoftware.
4.
Systemsoftwarecanrunindependently.Itprovidesplatformforrunning
applicationsoftwares.
Applicationsoftwarecan’trunindependently.Theycan’trunwithoutthe
presenceofsystemsoftware.
5.Someexamplesofsystemsoftwaresarecompiler,assembler,debugger,
driver,etc.
Someexamplesofapplicationsoftwaresarewordprocessor,webbrowser,
mediaplayer,etc.
5

Contd…
6

Components of a Programming System
ASSEMBLER:
Ittranslatesassemblylanguageprogram(ALP)withmnemoniccoded
instructionintomachinecodeusingtheinstructionformats,operational
codes(Opcodes)andaddressingmode,etcofthecomputer.
Exampleofassembler
MASM–Macro
TASM-Turbo
NASM-NewmicroASM
LOADER:-
Itisaprogramthatplacesprogramsintotheprimarymemoryandprepares
them
forexecution.Theassembleroutputsthemachinelanguagetranslationof
the
programontoasecondarystoragedeviceandloaderisplacedinthe
primary
memory.
7

Cont….
LINKER:-
Itisaprogramthatlinkstheuserprogramtoanother
programorlibrariestoformasinglemodule.Thetaskofa
linksistolinktwomoreobjectmodulestofromaexecutable
moduleintomemory,preparingforexecutionthemand
executingthem.Itintegratesthenecessaryfunctionrequired
bytheprogram.
MACRO--------------------------------------Startofdefinition
INCR------------------------------------------macroname
Itisanabbreviationofasetofinstruction.
8

Cont….
Needofmacro
(i)Ofteninprogrammingneedtorespectthesamesetof
instructionsagainandagain.
(ii)macrofacilityustowritethedefinitiononce&useitmany
times.
Ex;-#defineprintf(“---------“);p
Itiscalledanywhereinprogram
P;-macrocall
COMPLIER:-
Acomplierisaprogramthatconvertshighlevellanguageto
assemblylanguage.Thecompilercompilestheprogramand
translatesittoassembly.Anassemblerthentranslatesthe
assemblyprogramintomachinecode.
9

PROGRAM DEVELOPMENT CYCLE
1.Analyze-
Programmershouldhaveaclearideaabouttheinputandoutput.
2.Design-
Thesolutionoftheprogramiswritteninastepbystepmethod.
Ex.Algorithm,flowchart
Stepbystepmethod
3.Coding
Thealgothimisconvertedtoaprogram.
4.TestingorDebugging-
Testingmeansfindingtheerror.
Debuggingmeanscorrectingtheerror.
5.Documentation-
Organizealltheinformationtoexplainorunderstandtheprogram.
Program=job=task=process
10

Evaluation of Operating System
Inthelast60yearsoperatingsystemhasgonethoughdifferentPhases.
Wewilldiscusstheevolutionofoperatingsystemasfollows.
1.SerialProcessing–Executionofprogramsisdoneserially
(1afteranother)
Example:-Dos(DiskOperatingsystem)
2.BatchProcessing-Batchmeansagroupofprograms.
Example:-GroupofjavaprogramsanothergroupofCprograms.
Advantage-
(i)Lesstimeforprocessing
(ii)Switchingtimeisless
Oneprogramtoanother
Disadvantage-CPUisidle
11

Cont…..
3.Multiprogramming-Morethanoneprogramareloadedinmemoryatatime.
Here,-contextswitchtakesplace
-contextswitchmeansswitchingfromoneprogramtoanother.
Example:-Cprogramandlisteningmusicatsametime.
SwitchingtakesplaceduringI/ooperation.
(because,duringI/ooperationcpuisidle)
Advantage:-
(i)CPUutilizationismore
(ii)Overalltimeisless,Hence,thesystemisfaster.
memory
12

Cont…..
4. Time Sharing-
It is a special case of multiprogramming. Program is given with
a fixed time. This time is called “Time Quantum”.
5. Real Time OS-
Real time refers to exact time. It guaranteesthat program must
complete in time.
It is two types-
(a) Hard RTOS
(b) Soft RTOS
(a) Hard RTOS:-
-Short time constraint
-No delay in time is allowed.
Ex-Vx works(missile firingsystem, satellite lunching system)
(b) Soft RTOS:-
-Delay in time allowed
Ex-Linux, window Area: browsing internet
13

DistributedSystem
•Itisamultiprocessormorethanonesystem.
•Agroupofcomputerareconnectedtosharedata.
•Eachcomputershasitsownmemory.
Ex.-Internet
LAN=College
MAN=City
WAN=World
Advantages:-
Resourcedatasharing
Reliability
Communication
14

Operating System and Functions
OperatingSystem-
Itisasystemsoftware.Whichisainterfacebetweenuserand
hardware.
FunctionsofOS-
1)ProgramCreation-
•Itprovideseditor,debuggerwhichhelpstheprogrammerto
createprograms.
2)ProgramExecution-
Torunaprogram,aprogramhastobeloadedinRAM(primary
memory).
3)MemoryManagement-
Itallocatesmemorytovariousprogram.
De-allocatememoryafterexecutionofprogramisfinished.
15

Cont….
4)Processmanagement-
•Processisaprogramwhichisexecutingcurrently.
•Osfollowsaschedulingalgorithmtodealwithmanyprocessof
thesystem.
5)ErrorDetection-
Detectdifferenttypesoferrorsandtakeappropriateaction.
Ex:-UnabletoreadthedataduetobadsectorinDVD.
6)Accounting-
Multiusersystemhasmorethanoneusers.
Oskeeptrackofresourcesaccessedbyeachuser.
16

History of C language
Itisastructured,high-level,machineindependentlanguage.
Itallowssoftwaredeveloperstodevelopprogramswithout
worryingaboutthewheretheywillbeimplemented.
UNIXisoneofthemostpopularnetworkoperatingsystems
inusetodayandtheheartoftheinternetdatasuperhighway.
Today,Cisrunningunderavarietyofoperatingsystemand
hardwareplatforms.
17

Cont….
18

Importance of C
•Itisarobustlanguagewhoserichsetofbuilt-infunctions.
•Operatorscanbeusedtowriteanycomplexprogram.
•ProgramwritteninCareefficientandfast.
•Itsvarietyofdatatypesandpowerfuloperators.
Ex-Aprogramtoincrementavariablefrom0to15000takesaboutone
secondinCwhileittakesmorethan50secondsinaninterpreterBASIC.
Cishighlyportable.
Cprogramswrittenforonecomputercanberunonanotherwithlittleor
nomodification.
Clanguageiswellsuitedforstructuredprogramming.
Thismodularstructuremakesprogramdebugging,testingand
maintenanceeasier.
ImportantfeatureofCisitsabilitytoextenditself.
ACprogramisbasicallyacollectionoffunctionsthataresupportedby
theClibrary.
ContinuouslyaddourfunctionstoClibrary.Theprogrammingtask
becomessimple.
19

Some Sample C Programs and Analyze
PROGRAM 1: PRINTNG A MESSAGE
Main()
{
/*…..printing begins…….*/
printf(“I see, I remember”);
/*…..printing ends…….*/
}
Program is mainand the execution begins at this line.
The main() is a special function used by the C system to tell
the computer where the program starts.
BY using more than one function compiler can not understand
which one marks the beginning of the program.
The opening brace “{” in second line mark the beginning of the
functionmainand the closing brace “}” in the last line indicates
the end of the function.
20

Contd…
All the statements between these two braces form the function body.
Function body contains a set of instructions to perform the given
task.
The line beginning with /* and ending with */ are known as
comment lines.
The comment line /* = = = =*/ = = = =*/ = = =*/ is not validand
therefore results in an error.
printf()functiononlyexecutablestatementoftheprogram
printf(“Isee,Iremember”);
printf()isapredefinedstandardCfunctionforprintingoutput.
Predefinedmeansthatitisafunctionthathasalreadyhave
writtenandcompiledandlinkedtogetherwithourprogramat
thetimeoflinking.
Theprintffunctioncauseseverythingbetweenthestartingandthe
endingquotationmarkstobeprintedout.Inthiscase,theoutput
willbe:
I see, I remember
21

Cont…
EverystatementinCshouldendwithasemicolon(;)mark.
supposewewanttoprinttheabovequotationintwolinesas
Isee,
Iremember!
Theinformationcontainedbetweentheparenthesesiscalled
theargumentofthefunction.
ThisargumentofthefirstPrintffunctionisIsee,/n’’andthe
secondisIremember!”.
Theseargumentaresimplystringsofcharactertobeprinted
out.
printfcontainsacombinationoftwocharacters\andnatthe
endofthestring.
\ncollectivelycalledthenewlinecharacterandinstructthe
computertogotothenext(new)line.
Nospaceisallowedbetween\andn.
22

Contd…
Possible to produce two or more lines of output by one printf
statement with the use of newline character at appropriate places.
e.g. printf(“I see,\n I remember !”);
Will print
I see,
I remember !
while the statement
printf(“I\n.. See, \n… …. ….I\n… … … … remember !”);
will print
I
.. See,
… … … I
… … … … remember !
23

Contd…
Some authors recommend the inclusion of the statement
#include<stdio.h>
At the beginning of all programs that use any input/output
library function
This is not necessary for the function printf and scanfwhich
have been defined as a part of C language.
•C makes a distinction between uppercase and lowercase
letters.
•printf and PRINTF are not the same.
•In C everything is written in lowercase letter.
•Uppercaseletters are used for symbolic names representing
constants.
24

Contd..
General format of simple program and all C program
need a main function.
25

The main function()
Cpermitsdifferentformsofmainstatement.
Followingformsareallowed
main()
intmain()
voidmain()
main(void)
voidmain(void)
intmain(void)
Theemptypairofparenthesisindicatesthatthefunctionhasno
arguments.
Keywordvoidmeansthatthefunctiondoesnotreturnanyinformationto
theoperatingsystem
intmeansthatthefunctionreturnsanintegervaluetotheoperating
system
Whenintisspecified,thelaststatementintheprogrammustbe“return
0”
26

PROGRAM 2: ADDING TWO NUMBER
Below C program is for addition of two number and displays
result.
/* program addition
Main()
{
int number;
float amount;
number=100;
amount=30.75+75.35;
printf(“%d\n”, number);
printf(“%5.2f”,amount);
}
Output
100
106.10
27

Contd…
number and amount are variable name and what types
of data they hold.
int number;
float amount;
Tells the compiler that number is an integer(int) and
amount is a floating(float) point number.
The word intand floatare called the keywords and can
not used as a variable name.
number=100;
amount=30.75+75.35;
are called the assignment statementsand have a
semicolonat the end.
28

Contd…
Outputstatementthatprintsthevalueofnumber.The
printstatement
printf(“%d\n”,number);
Containstwoargument.Thefirstargument“%d”tells
thecompilerthatthevalueofsecondargument
numbershouldbeprintedasdecimalinteger.
Printf(“%5.2f”,amount);printsoutthevalueofamount
infloatingpointformat.%5.2ftellsthecompilerthat
theoutputmustbeinfloatingpointwithfiveplacesin
allandtwoplacestotherightofthedecimalpoint.
29

PROGRAM3:INTEREST CALCULATION
Calculatethevalueofmoneyattheendofeachyearofinvestment,assumingan
interestrateof11percentandprintstheyearandcorrespondingamount,intwo
columns.
Assumingforaperiodof10yearwithinitialinvestmentof5000.00
/*Investmentproblem*/
#definePERIOD=10;
#definePRINCIPAL=5000.00;
/*MAINPROGRAMBEGINS*/
Main()
{/*DECLARATIONSTATEMENTS*/
intyear;
floatamount,value,inrate;
//ASSIGNMENTSTATEMENTS
amount=PRINCIPAL;
inrate=0.11;
year=0;
30

Contd…
//COMPUTATION USINGwhileloop
while(year<=PERIOD){
printf("%2d%8.2f\n",year,amount);
value=amount+inrate*amount;
year=year+1;
amount=value;
}/*WhileLOOPENDS*/
}/*PROGRAMENDS*/
31

Contd…
A#defineinstructionsdefinesvaluetoasymbolicconstantfor
useintheprogram.
Wheneverasymbolicnameisencountered,thecompiler
substitutesthevalueassociatedwiththenameautomatically.
Tochangethevalue,wehavetosimplychangethedefinition.
Thesevaluesremainconstantthroughouttheexecutionofthe
program.
A#definelinesshouldnotendwithasemicolon.
A#defineinstructionsareusuallyplacedatthebeginning
beforethemain()function.
Thedefinedconstantsarenotvariables.
Wemaynotchangetheirvalueswithintheprogrambyusing
anassignmentstatement.
Ex.PRINCIPAL=10000.00;
Isillegal
32

Contd…
Theycanalsobedeclaredas
floatamount;
floatvalue;
floatinrate;
When two or more variables are declared in one statement,
they are separated by a comma.
While is a mechanism for evaluating respectively or a
statement/group of statements.
33

SAMPLE PROGRAM 4:USE OF SUBROUTINES
Illustrate the use of user-defined function and math function through
sample program
A very simple program that using a user defined function i.e. mul()
function.
/*---program using function*/
int mul(int a, int b); /*----declaration ---*/
/*------Main program begins------*/
main()
{
int a, b, c;
a=5;
b=10;
c=mul( a, b);
printf(“multiplication of %d and %d is %d”, a, b,c);
}
/*----Main program ends
Mul() function starts----*/
34

Contd…
int mul(int x, int y)
{
int p;
p=x*y;
return(p);
}
/* Mul() function ends*/
Themulfunctionmultipliesthevaluesofxandyandthe
resultisreturnedtothemain()functionwhenitiscalled
inthestatement.
c=mul(a,b);
Themul()hastwoargumentxandythataredeclaredas
integer.Thevalueaandbarepassedontoxandy
respectivelywhenthefunctionmul()iscalled.
35

SAMPLE PROGRAM 5:USE OF MATH FUNCTION
•MathematicalfunctionsaredefinedandkeptasapartofC
mathlibrary.
•Beforeusingthesemathematicalfunctionwemustaddan
#includeinstructionintheprogram.
•Like#defineitisalsoacompilerdirectivethatinstructsthe
compilertolinkthespecifiedmathematicalfunctionfrom
thelibrary.
•Theinstructionisoftheform
#include<math.h>
math.histhefilenamecontaingtherequiredfunction.
•Belowprogramillustratetheuseofcosinefunctionand
programcalculatecosinevaluesforangles0,10,20……..180
36

Contd…
•Program using cosine function
#include <stdio.h>
#include <math.h>
#define PI 3.1416
#define MAX 180
main()
{
int angle;
float x, y;
Angle=0;
Printf(“ Angle Cos(angle)\n\n”);
while (angle <= MAX)
{
x=( PI/ MAX )* angle ;
y= cos (x); //Use of cosinefunction
printf ("%15d %13 . 4 f\n”, angle ,y);
angle = angle +10;
}
}
37

Contd…
Output:
Angle Cos(angle)
0 1.0000
10 0.9848
20 0.9397
and so on….
#include instruction required is
#include<stdio.h>
stdio.hrefers to the standard I/O header file containing
standard input and output functions.
38

The #include Directive
Cprogramsaredividedintomodulesorfunctions.
somefunctionarewrittenbyuserandstoreintheC
library.
Libraryfunctionsaregroupedcategorywiseandstoredin
differentfilesknownasheaderfiles.
Toaccessthefunctionsstoredinlibrary,necessarytotell
thecompileraboutthefilestobeaccessed.
#include<filename>
•filenameisthenameoflibraryfilethatcontainsthe
requiredfunctiondefinition.
•Preprocessordirectivesareplacedatthebeginningofa
program.
39

BASIC STRUCTURE OF C PROGRAMS
AnyCprogramisconsistsof6main
sections.
Cprogramcanbeviewedasagroupof
buildingblockscalledfunctions.
Afunctionisasubroutinethatmayinclude
oneormorestatementsdesignedtoperform
aspecifictask.
40

Contd…
41

Contd…
42

Contd…
VarioussectionandUse
Documentation:Consistsofcomments,somedescription
oftheprogram,programmernameandanyotheruseful
pointsthatcanbereferencedlater.
Link:Consistsoftheheaderfilesofthefunctionsthatare
usedintheprogram.Providesinstructiontothecompilerto
linkfunctionfromthelibraryfunction.
Definition:Consistsofsymbolicconstantsormacros
Globaldeclaration:Canbeusedanywhereintheprogram.
Consistsoffunctiondeclarationandglobalvariables.
43

Contd…
main(){}:EveryCprogrammusthaveamain()
functionwhichisthestartingpointoftheprogram
executionandcontainstwoparts,declarationand
executablepart.Thedeclarationpartdeclaresallthe
variablesthatareusedinexecutablepart.Mustbe
writteninbetweentheopeningandclosingbracesend
withasemicolon(;).
variabledeclaration:InCprogrammingwecannot
createvariableanywherelikec++orjavasoneedto
declarevariablebeforebodyofprogram.
Subprogramsorfunction:Userdefinedfunctions
thatareusedtoperformaspecifictask.Theseuser
definedfunctionsarecalledinthemain()function.
44

Contd…
Different sections of the above code
Documentation:/*This section contains a multi line
comment or name of program.description: program to
call function add();*/
In C, we can create single line comment using two forward
slash // and we can create multi line comment using /*
*/.Comments are ignored by the compiler and is used to
write notes and document code.
Link:Thissection includes header file.
#include <stdio.h>
#include<conio.h>
We are including the stdio.h input/output header file from
the C library.
45

Contd…
Definition: This section contains constant.
#define max 10
In the above code we have created a constant max and
assigned 10 to it.
The #define is a preprocessor compiler directive which
is used to create constants. We generally use uppercase
letters to create constants.
The #define is not a statement and must not end with
a ; semicolon.
Global Declaration: This section contains function
declaration.
void add();
int x=10;
We have declaredan add function which print Hello
add .
main( ) function
46

Contd…
This section contains the main() function.
int main(){
int a=10;
printf("Hello Main");
return 0;
}
This is the main() function of the code. Inside this function
we have created a integer variable a and assigned 10 to it.
Then we have called the printf() function to print Hello
Main.
Subprograms or Function
This section contains a subprogram or function i.eadd( ) or
any no of user defined function .
void add() {
void add(){
printf(" Hello add ") ;
}
47

Programming style
Alsoknownascodestyle,isasetofrulesorguidelines
usedwhenwritingthesourcecodefora
computerprogram
Itisdesignedtoprovideinformationonhowto
effectivelyuseindentation,comments,andother
elementsthatwillmakeyourCcodemorereadable.
48

Character set of C
Character:-Itdenotesanyalphabet,digitorspecialsymbol
usedtorepresentinformation.
Use:-Thesecharacterscanbecombinedtoformvariables.C
usesconstants,variables,operators,keywordsand
expressionsasbuildingblockstoformaBasiccprogram
Characterset:-Thecharactersetisthefundamentalraw
materialofanylanguageandtheyareusedtorepresent
information.
49

Contd…
The characters in C are grouped into the
followingtwocategories:
1.Source character set
a.Alphabets
b.Digits
c.Special Characters
d.White Spaces
2.Execution character set
a.Escape Sequence
Source character set
1. ALPHABETS
Uppercase letters A-Z
Lowercase letters a-z
2. DIGITS 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
50

Contd…
3.Special Characters
~ tilde
%percent sign
| vertical bar
@ at symbol
+ plus sign
< less than
& ampersand
$ dollar sign
* asterisk \back slash ,etc.
51

Contd…
4.White space Characters.
\b blank space
\t horizontal tab
\v vertical tab
\r carriage return
\f form feed
\n new line
\\Back slash
\’ Single quote
\" Double quote
\? Question mark
\0 Null
\a Alarm (Audible Note)
52

Contd…
Execution Character Set:
Executioncharacterssetarealwaysrepresentedbya
backslash(\)followedbyacharacter.
Theyareusedinoutputstatements.Escapesequence
usuallyconsistsofabackslashandaletterora
combinationofdigits.
Eachoneofcharacterconstantsrepresentsone
character,althoughtheyconsistoftwocharacters.
Thesecharacterscombinationsarecalledasescape
sequence.
53

Contd…
Character ASCIIvalueEscape Sequence Result
Null 000 \0 Null
Alarm (bell) 007 \a Beep Sound
Back space 008 \b Moves previous position
Horizontal tab 009 \t Moves next horizontal tab
New line 010 \n Moves next Line
Vertical tab 011 \v Moves next vertical tab
Form feed 012 \f Moves initial position of nextpage
Carriage return 013 \r Moves beginning of the line
Double quote 034 \" Present Double quotes
Single quote 039 \' Present Apostrophe
Question mark 063 \? Present Question Mark
Back slash 092 \\ Present back slash
54

C program to print all the characters of C character Set
#include<stdio.h>
#include<conio.h>
int main()
{
int i;
clrscr();
printf("ASCII ==> Character\n");
for(i = -128; i <= 127; i++)
printf("%d ==> %c\n", i, i);
getch();
return 0;
}
55

Tokens in C
In a C program smallest individual unitsare known as C tokens
A C program consists of various tokens
Token is eithera keyword, an identifier, a constant, a string
literal, or a symbol.
For example, the following C statement consists of six type of
tokens −
56

C TOKENS EXAMPLE PROGRAM:
intmain()
{
intx, y, total;
x = 10, y = 20;
total = x + y;
printf("Total = %d \n", total);
}
where,
main –identifier
{,}, (,) –delimiter
int –keyword
x, y, total –identifier
main, {, }, (, ), int, x, y, total –tokens
57

Keyword and Identifiers
Keywords:Everycwordisclassifiedaseitherakeywordoranidentifier.
Allkeywordshavefixedmeaningsandthesemeaningcannotbechanged.
Keywordsarepredefined,reservedwordsusedinprogrammingthathave
specialmeaningstothecompiler.
Keywordsserveasbasicbuildingblockforprogramstatements.
Allkeywordsmustbewritteninlowercase.
Underscorecharacterisalsoanidentifierandusedasalinkbetweentwo
wordsinlongidentifiers.
ANSI C Keyword
58

Contd…
Identifier:
ACidentifierisanameusedtoidentifyavariable,
function,oranyotheruser-defineditem.
AnidentifierstartswithaletterAtoZ,atoz,oran
underscore'_'followedbyzeroormoreletters,anddigits
(0to9).
Cdoesnotallowpunctuationcharacterssuchas@,$,and
%withinidentifiers.
Cisacase-sensitiveprogramminglanguage.
Thus,Manpowerandmanpoweraretwodifferent
identifiersinC.
Herearesomeexamplesofacceptableidentifiers−
mohd zara abcmove_name
myname50 _temp j a23b9
retVal a_123
59

Contd…..
Rules for naming identifiers
First character must be an alphabet(or underscore)
A valid identifier can have letters (both uppercase and
lowercase letters), digits and underscores.
Only first 31 characters are significant.
Can not use a keyword.
Must not contain white space.
60

Constants
Constant in c refer to fixed values that do not change
during execution of a program.
Constants are like a variable
Value remains the same during the entire execution of
the program.
Constants are also called literals.
Constants can be any of thedata types.
It is considered best practice to define constants using
onlyupper-casenames.
Syntax:
const type constant_name;
61

HOW TO USE CONSTANTS IN A C PROGRAM?
By “const” keyword: when you try to change constant values after defining in
C program, it will through error.
EXAMPLE PROGRAM USING CONST KEYWORD IN C:
#include<stdio.h>
voidmain()
{
constintheight = 100; /*int constant*/
constfloatnumber = 3.14; /*Real constant*/
constcharletter = 'A'; /*char constant*/
constcharletter_sequence[10] = "ABC"; /*string constant*/
constcharbackslash_char = '\?'; /*special char const*/
printf("value of height :%d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence);
printf("value of backslash_char : %c \n", backslash_char);
}
OUTPUT:
value of height : 100
value of number : 3.140000
value of letter : A
value of letter_sequence : ABC
value of backslash_char : ?
62

EXAMPLE PROGRAM USING #DEFINE PREPROCESSOR DIRECTIVE IN C
#include <stdio.h>
#define height 100
#define number 3.14
#define letter 'A'
#define letter_sequence "ABC"
#define backslash_char '\?'
voidmain()
{
printf("value of height : %d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n",letter_sequence);
printf("value of backslash_char : %c \n",backslash_char);
}
Output:
value of height : 100
value of number : 3.140000
value of letter : A
value of letter_sequence : ABC
value of backslash_char : ?
63

Variables
Variable is a data name that used to store a data value.
Variable may take different values at different times
during execution.
Variables are memory locations(storage area) in the C
programming language.
The primary purpose of variables is to store data in
memory for later use.
Unlikeconstantswhich do not change during the
program execution, variables value may changeduring
execution.
If you declare a variable in C, that means you are asking
to the operating system for reserve a piece of memory
with that variable name.
64

Contd…
Syntax:
type variable_name; OR
type variable_name, variable_name, variable_name;
Variable definition and initialization:
int width,
height=5;
char letter='A';
float age, area;
double d;
/* actual initialization */
width = 10;
age = 26.5;
int i,j,k; char c,ch; float f,salary;double d;
Thelineinti,j,k;declaresanddefinesthevariablesi,j,andk;which
instructthecompilertocreatevariablesnamedi,jandkoftypeint.
65

Variable assignment
It is a process of assigning a value to a variable.
Example:
int width = 60;
int age = 31;
Rules on choosing variable names:
A variable name can consist of Capital letters A-Z, lowercase
letters a-z, digits 0-9, and the underscore character.
The first character must be a letter or underscore.
Blank spaces cannot be used in variable names.
Special characters like #, $ are not allowed.
C keywordscan not be usedas variable names.
Variable namesare case sensitive.
Values of the variables can be numeric or alphabetic.
Variable typecan be char, int, float, double or void.
66

C Program to Print Value of a Variable
Example:
#include<stdio.h>
void main()
{
/* c program to print value of a variable */
int age = 33;
printf("I am %d years old.\n", age);
}
Program Output:
I am 33 years old.
67

Example:
Variables have been declared at the top, but they have been defined and initialized inside the main
function
#include <stdio.h>
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main ()
{
/* variable definition: */
int a, b;
int c;
float f;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf("value of c : %d \n", c);
f = 70.0/3.0;
printf("value of f : %f \n", f);
return 0;
}
Output:
value of c : 30
value of f : 23.333334
Use the keywordexternto declare a
variable at any place.
In this example variables have been
declared at the top, but they have
been defined and initialized inside
the mainfunction.
68

Variable…contd
Variable name Valid? Remark
First_tag Valid
Char Not valid Char is a keyword
Price$ Not valid Dollar sign is illegal
group one Not valid Blank space is not
permitted
avevge_number Valid First eight characters are
significant
int_type Valid Keyword may be part of
name
Examples of variable names
69

Data Types
C language is rich in its data types.
ANSCI C supports three classes of data types:
Primary(or fundamental) data types:
void,int,char,doubleandfloat.
Derived data types:Array,References, andPointers.
User-defined data types:Structure,Union,
andEnumeration.
All C compilers support five fundamental data types,
namely integer(int),character(char),floating
point(float),double-precision floating point(double)
and void.
•Also extended data types such as long int, long double.
70

Contd…
71

Operator expression
An operator is a symbol that tells the computer to perform
certain mathematical or logical manipulation.
Operators are used in program to manipulate data and
variables.
Operators, functions, constants and variables are
combined together to form expressions.
Consider the expressionA + B * 5. where, +, *are operators,
A, B are variables, 5is constantand A + B * 5 is an
expression.
Types of c operators:
C language offers many types of operators. They are:
1.Arithmetic operators
2.Assignment operators
3.Relational operators
4.Logical operators
72

Contd…
5.Bit wise operators
6.Conditional operators (ternary operators)
7.Increment/decrement operators
8.Special operators
Arithmetic operators:
CArithmeticoperatorsareusedtoperformmathematical
calculationslikeaddition,subtraction,multiplication,division
andmodulusinCprograms.
73

Example for Arithmetic operators:
#include <stdio.h>
intmain()
{
inta=40,b=20, add,sub,mul,div,mod;
add = a+b;
sub = a-b;
mul= a*b;
div = a/b;
mod = a%b;
printf("Addition of a, b is : %d\n", add);
printf("Subtraction of a, b is : %d\n", sub);
printf("Multiplication of a, b is : %d\n", mul);
printf("Division of a, b is : %d\n", div);
printf("Modulus of a, b is : %d\n", mod);
}
Output:
Addition of a, b is : 60
Subtraction of a, b is : 20
Multiplication of a, b is : 800
Division of a, b is : 2
Modulus of a, b is : 0
74

Show the use of integer arithmetic to convert a given
number of days into months and days.
#include<stdio.h>
int main()
{
int months,days;
printf("Enter days\n");
scanf("%d",&days);
months=days/30;
days=days%30;
printf("Months=%d Days=%d", months,days);
getch();
}
Output:
Enter days
265
Months=8 Days=25
75

Increment and decrements operator
Increment Operatorsare used to increased the value of the
variable by one andDecrement Operatorsare used to decrease
the value of the variable by one in C programs.
Syntax
++ // increment operator
--// decrement operator
And can not apply on constant
x= 4++;
// gives error, because 4 is constant
Type of Increment Operator
pre-increment
post-increment
pre-increment (++ variable)
In pre-increment first increment the value of variable and then
used inside the expression (initialize into another variable).
Syntax: ++ variable;
76

Example
#include<stdio.h>
#include<conio.h>
int main()
{
int x,i;
i=10;
x=++i;
printf("x: %d\n",x);
printf("i: %d\n",i);
getch();
}
Output:
x: 11
i: 11
In above program first increase the value of i and then used value of i into
expression.
77

Contd…post-increment (variable ++)
In post-increment first value of variable is used in the expression
(initialize into another variable) and then increment the value of
variable.
Syntax: variable ++;
#include<stdio.h>
#include<conio.h>
int main()
{
int x,i;
i=10;
x=i++;
printf("x: %d\n",x);
printf("i: %d\n",i);
getch();
}
Output:
x: 10
i: 11
In above program first used the value of i into expression then increase value of i
by 1.
78

Decrement Operator
Type of Decrement Operator
pre-decrement
post-decrement
Pre-decrement (--variable)
In pre-decrement first decrement the value of variable and then used inside the
expression (initialize into another variable).
Syntax: --variable;
#include<stdio.h>
#include<conio.h>
int main()
{
int x,i;
i=10;
x=--i;
printf("x: %d\n",x);
printf("i: %d\n",i);
getch();
}
Output:
x: 9
i: 9
In above program first decrease the value of i and then value of i used in expression.
79

Contd…post-decrement (variable --)
In Post-decrement first value of variable is used in the expression
(initialize into another variable) and then decrement the valueof
variable.
Syntax: variable --;
#include<stdio.h>
#include<conio.h>
int main()
{
int x,i;
i=10;
x=i--;
printf("x: %d\n",x);
printf("i: %d\n",i);
getch();
}
In above program first used the value of x in expression then decrease value of i
by 1.
Output:
x: 10
i: 9
80

Example of increment and decrement operator
#include<stdio.h>
#include<conio.h>
int main()
{
int x,a,b,c;
a = 2;
b = 4;
c = 5;
x = a--+ b++ -++c;
printf("x: %d",x);
getch();
}
Output:
x: 0
81

THANK YOU