You are on page 1of 53

COL100

Introductionto
ComputerScience

Instructor
ProfK.K.Biswas
DepttofComputerScience&Engineering
Roomno.423,BhartiBuilding
kkb@cse.iitd.ernet.in

CourseContents
IntroductiontocomputerProgrammingusing
Clanguage
Algorithms
Problemsolvingusingcomputers

ReferenceBooks
1. ProgrammingwithC(SchaumsOutlines
Series,)

ByronGottfried,McGrawHill
2. TheCProgrammingLanguage
BrianWKernighan,DennisMRitchie

LabWork
LabswillbeheldinComputerServicesCentre
TAswillbearoundtolookintoyourproblems
Trytovisitthelabatothertimesaswell
Moreyoupractice,betteryouwilllearn
programming
CheatingPolicy

BriefIntroductiontoComputers

WhatdoesaComputerdo?
Computers can perform four general operations,
which comprise the information processing cycle.
Input
ProcessData
Output
Storage(ProgramsandData)

WhyisaComputersoPowerful?
Theabilitytoperformtheinformationprocessing
cyclewithamazingspeed.
Reliability(lowfailurerate).
Accuracy.
Abilitytostorehugeamountsofdataand
information.
Abilitytocommunicatewithothercomputers.

HowdoesaComputerknow
whattodo?
Itmustbegivenadetailedlistofinstructions,
calledacomputeprogram orsoftware,thattells
itexactlywhattodo.
Thecomputerprogramcorrespondingtothatjob
mustbestoredinmemory.
Thecomputercanstarttheoperationby
executingtheprograminstructionsinthe
specifiedsequence.
9

Primary
ComponentsOfA
Computer?

Inputdevices.
CentralProcessing
Unit
Memory.
Outputdevices.
Storagedevices.

DataRepresentation
Dataisstoredinsidethememoryintheform
of1sand0s,Bits(BinaryDigits)asshown
below(ON/OFFpositions)
11000111(referredtoasabyte )
00111111
01011110

UnitsofMemory

1KB(1KiloByte)contains1024Bytes.
1MB(1MegaByte)consistsof1024KB.
1GB(1GigaByte)has1024MB.
1TB(1Terabyte)consistsof1024GB.

SecondaryStorageDevices
Secondarystoragedevicesareusedtostore
datawhentheyarenotbeingusedin
memory.Themostcommontypesof
secondarystorageusedonpersonal
computersPCsare
harddisks
CDROMdrives
FlashDrives(USB,pendrives)

CPU
CentralProcessingUnit(CPU)
itexecutescomputerprograms.
Instructionsintheprogramtelltheprocessorwhenand
whattoreadfromakeyboard;

whattodisplayonascreen;
whattostoreandretrievefromadiskdriveandsoon.

Itcandoarithmetic,comparenumbersand
performinput/output.(readinformationand
displayorstoreit).

CPU
CentralProcessingUnit(CPU)
itexecutescomputerprograms.
Instructionsintheprogramtelltheprocessorwhenandwhatto
readfromakeyboard;

whattodisplayonascreen;
whattostoreandretrievefromadiskdriveandsoon.

Itcandoarithmetic,comparenumbersandperform
input/output.(readinformationanddisplayorstoreit).
Ithasnomagicalpowers.Itisinstructivetobearinmind
thatallcomputerprogramsareconstructedfrom
sequencesofinstructionsbasedonprimitiveoperations

CPUoperation
TheCPUcanreadfromandwritetoaspecifiedmemory
location.
Whilewritingabyteintoagivenlocation,theprevious
bitpatternisdestroyedandthenewcontents(bit
pattern)aresavedforfutureuse.
Whilereadingabytethecontentsofthatlocationare
NOTchanged.
CPUhasnumberofonchipstoragelocationscalled
registers,usually8,16,or32bitslong
Thegreaterthenumber,themorepowerfultheCPU

CPUoperation
TheCPUcanreadfromandwritetoaspecifiedmemory
location.
Whilewritingabyteintoagivenlocation,theprevious
bitpatternisdestroyedandthenewcontents(bit
pattern)aresavedforfutureuse.
Whilereadingabytethecontentsofthatlocationare
NOTchanged.
CPUhasnumberofonchipstoragelocationscalled
registers,usually8,16,or32bitslong
greaterthenumber,themorepowerfultheCPU

Memoryspeeds
onchipregisters Fastest
Mainmemory
Secondarymemory slowest

Software
Softwareisthesetofprogramsandapplicationsthattellthe
computerwhattodo.
Computerprogrammerswritethecodes/instructionsthat
makeupsoftwareapplications/programs.
Programs andDataaresavedinthesamemannerinthe
computer
Setofinstructionsisalsoreferredtoaslinesofcode.

TwoTypesofSoftware

Application
Software

Operating
systemSoftware

OperatingSystemSoftware
Complexsetofprogramswhichdirectsalltheactivitiesand
setsalltherulesforhowthehardwareandsoftwarewillwork
together.
Managesinputdevices,outputdevices,memoryunits,CPU
TheOSisalwayspresentwhenthecomputerisrunning
Responsibleforrunningapplicationprograms
Examples:
WindowsXP,Vista
Solaris
Unix,Linux

ApplicationSoftware
1. Businesssoftware:wordprocessors,spreadsheets,and
databaseprograms.
2. Communicationsoftware:allowscomputerstocommunicate
withothercomputers:faxsoftware,NovellNetWare,AOL,
ModemSoftware.
3. Graphicssoftware:softwarethatallowsuserstocreateand
manipulategraphics...Photoshop,PrintShop,etc.

4.EducationandReferencesoftware:Programsthathelpteach
newmaterialandideas,andprogramsthatcanbeusedto
findinformation
5. EntertainmentandLeisuresoftwaregames
6. Scientificsoftware:Programstosolvescientificproblems

IntroductiontoCProgramming

Variables
Veryimportantconceptforprogramming
Anentitythathasavalueandisknowntotheprogrambya
name
Canstoreanytemporaryresultwhileexecutingaprogram
Canhaveonlyonevalueassignedtoitatanygiventime
duringexecution
Thevalueofavariablecanbechangedduringthe
execution

26

Contd.
Variablesstoredinmemory
Rememberthatmemoryisalistofstorage
locations,eachhavingauniqueaddress
Avariableislikeabin
Thecontentsofthebinisthevalue ofthevariable
Thevariablenameisusedtorefertothevalueofthe
variable
Avariableismappedtoalocation ofthememory,called
itsaddress
27

Exampleofvariables
#include<stdio.h>
voidmain()
{
intx;
inty;
x=1;
y=3;
printf("x=%d,y=%d\n",x,y);
}
28

VariablesinMemory
Instruction executed

Memory location allocated


to a variable X

X = 10
T
i
m
e

10

X = 20
X = X +1
X = X*5

29

VariablesinMemory
Instruction executed

Memory location allocated


to a variable X

X = 10
T
i
m
e

20

X = 20
X = X +1
X = X*5

30

VariablesinMemory
Instruction executed

Memory location allocated


to a variable X

X = 10
T
i
m
e

21

X = 20
X = X +1
X = X*5

31

VariablesinMemory
Instruction executed

X = 10
T
i
m
e

Memory location allocated


to a variable X

105

X = 20
X = X +1
X = X*5

32

Variables(contd.)
X = 20
Y=15

20

X = Y+3

Y=X/6

33

Variables(contd.)
X = 20
Y=15

20

X = Y+3

15

Y=X/6

34

Variables(contd.)
X = 20
Y=15

18

X = Y+3

15

Y=X/6

35

Variables(contd.)
X = 20
Y=15

18

X = Y+3

Y=X/6

36

Data Types
Eachvariablehasatype,indicateswhattypeof
valuesthevariablecanhold
FourcommondatatypesinC
int canstoreintegers(usually4bytes)
float canstorefloatingpointnumbers(54.27,
0.05,etc.)
double canstoredoubleprecisionfloatingpoint
numbers
char canstoreacharacter(1byte)
37

Contd.
Mustdeclareavariable(specifyitstype andname)
beforeusingitanywhereinyourprogram
Allvariabledeclarationsshouldbeatthebeginning

38

VariableNames
Sequenceoflettersanddigits
Firstcharactermustbealetteror_
Nospecialcharactersotherthan_
Noblanks inbetween
Namesarecasesensitive (max,MAX andMax are
differentnames)
Examplesofvalidnames:

krank1MAXmaxMinclass_rank

Examplesofinvalidnames:
asclassrank2sqrootclass,rank
39

MoreValidandInvalidIdentifiers
Valididentifiers
X
abc
simple_interest
a123
LIST
stud_name
Empl_1
Empl_2
avg_empl_salary

Invalididentifiers
10abc
myname
hello
simpleinterest
(area)
rate%

CKeywords
UsedbytheClanguage,cannotbeusedas
variablenames
Examples:
int,float,char,double,main,ifelse,for,while.do,
struct,union,typedef,enum,void,return,signed,
unsigned,case,break,sizeof,.
Thereareothers,seetextbook

Constants
Integerconstants
Consistsofasequenceofdigits,withpossiblyaminussign
beforeit

Floatingpointconstants
Twodifferentnotations:
Decimalnotation:25.0,0.0034,.84,2.234
Exponential(scientific)notation
3.45e23,0.123e12,123e2
e means 10 to the power of

42

#include <stdio.h>
int main(void) {
printf(My name is Kanad Biswas.")
return 0;
}

Compiler
A "translator" which converts a program written
in a highlevel computer language
into machine language, 001101001010
understood by the computer.

1) Edit your program


2) Compile your program
3) Execute your program
4) Go to step 1, if you are not satisfied with
your results.

#include <stdio.h>
int main(void) {
printf(My name is Kanad Biswas.");
return 0;
}

Execution:
My name is Kanad Biswas

UNDERSTANDINGAPROGRAM
LINEBYLINE

#include <stdio.h>
A directive to include a standard C header file. There are some
pre-written functions in C that we commonly use.
All the functions that control standard input and output are
included in the file stdio.h.
When we include this file, we are allowed to use these functions.
These functions allow us to print information to the screen and
read in information from the user.
All of your programs will include this line.

int main(void) {
All code in C resides in functions.
This line signifies the beginning of the function main.
main is a special function.
A program may be made up on many functions, but the computer
only DIRECTLY executes main.

int main(void) {
printf(My name is Kanad Biswas.")
return 0;
}
Main calls other functions.
All functions are signified by
-a return type, (which is int for this function),
-a name (which is main for this function)
-a parameter list in parentheses (void here)
-curly brace { signifies the beginning of the function.
curly brace } ends the definition of the function.

printf(My name is Kanad Biswas.")

This line calls a function printf which resides in stdio.h.


It prints out any string contained in between
two sets of double quotes.
Some special characters are also used in printf.
All such characters start with a backslash: \
The code

\n stands for a newline character.

This simply tells the computer to advance the cursor to the new
line.

/* My 1st C Program */

COMMENT STATEMENT

#include <stdio.h>
int main(void) {
printf("This is my first C Program.");
printf( My name is Kanad Biswas.");
return 0;
}

This is my first C Program. My name is Kanad


Biswas

/*

My 2nd C Program using new line*/

#include <stdio.h>
int main(void) {
printf("This is my first C Program.\n");
printf( My name is Kanad Biswas.\n");
return 0;
}

This is my first C Program.


My name is Kanad Biswas.

You might also like