CS101 Autumn 2019 7/30/19 Autumn 2019 CS101@CSE IIT Bombay 1
CS101Autumn 2019
7/30/19 Autumn 2019 CS101@CSE IIT Bombay
1
CS 101Computer Programming
and UtilizationPuruwith
several CS101 TAs and CSE staff
Course webpage: http://www.cse.iitb.ac.in/~cs101/
Lecture 1: Introduction
Clip art and quote credits: Various sources found through Google Image Search
abouttheseslides
• basedonChapter1ofthebook– AnIntroductiontoProgrammingthroughC++byProf.AbhiramRanade(TataMcGrawHill,2014)
• originalslidesbyAbhiram Ranade– updatesandcontributionsbyVarsha Apte,Uday Khedker,Sunita Sarawagi,Umesh Bellur,OmDamani,GaneshRamakrishnan
7/30/19 Autumn 2019 CS101@CSE IIT Bombay 3
Autumn 2019 CS101@CSE IIT Bombay
somequestions
• whyacomputer?
• whatisacomputer?
• whatisprogramming?
7/30/19 4
Autumn 2019 CS101@CSE IIT Bombay
whycomputer?
7/30/19 5
Autumn 2019 CS101@CSE IIT Bombay
whycomputer?
• yetanotheroptiononthehuman-machineaxis• automationfordoingwork
– efficiently,quickly,newdiscoveries/explanationsetc.
• thecomputer– amachineintheautomationworldthathasinfluencedalmostallaspectsofourexistence
– hassomepropertiesunique/differentfromothermachines
7/30/19 6
Autumn 2019 CS101@CSE IIT Bombay
whatisuniqueaboutacomputer?
7/30/19 7
vs.
what is a computer?
• computer:amachinethatcando(specified)work– …thatcancompute
• compute:perform(elaborate)calculations– combinationofmathematicalandlogicaloperations
• acomputer– isanelectronicdevicewithcomplexcircuitry– isaprogrammable device
7/30/19 Autumn 2019 CS101@CSE IIT Bombay 8
a computercandomanythings
Help book and manage tickets Store and search documents
Help design physical systems: say water networkWeather prediction
Autumn 2019 CS101@CSE IIT Bombay
all of us have already used a computer!
7/30/19 10
– Calculator– ATM– Smartphone
(is a computer)
Autumn 2019 CS101@CSE IIT Bombay
howtodoworkwithacomputer?
• tellitdowork!
• whatwork?andhowtospecify?
whatwork=>logic,calculations,sequenceetc.
howtospecify=>writeaprogramusingaprogramminglanguage
• thiscourse: fromuserstoprogrammers!
7/30/19 11
CS101assessment/grading
• Midtermexam:~20%• 2Quizzes:~10%each• Finalexam:~30%• Labsessions
– Labtests:~20%weightage– Labattendance:~10%weightage
• MandatorytoattendN-1outofNlabs• Everylabsubsequentlymissedwillcost2%
Autumn 2019 CS101@CSE IIT Bombay7/30/19 12
• Lectureslots(SectionS1)Slot11Tuesdays3:30PM– 5:00PM&Fridays3:30PM– 5:00PM(SectionS2)Slot5Wed9:30AM– 11:00AM&Fridays9:30AM– 11:00AM
• LabsessionsTuesdays,WednesdaysandThursdays8PMuntil11PMinSL1,SL2andBasementlab(newCSE building)
• Slidesandvideosonwww.cse.iitb.ac.in/~cs101 andhttp://bodhitree2019.cse.iitb.ac.in
CS101 schedule/logisticshttps://www.cse.iitb.ac.in/~cs101/
7/30/19 Autumn 2019 CS101@CSE IIT Bombay 13
The TA treeCTA
STA
JTAs
Tue lab.batch
STA
JTAs
Wed lab.batch
STA
JTAs
Bodhitree/Web siteLab scheduling
Do not use personal email
Thu lab.batch
7/30/19 Autumn 2019 CS101@CSE IIT Bombay 14
additional help for CS101
• do not hesitate in contacting us if are facing problem due to English
• आप अंग्रेजीकेकारणसमस्याकासामनाकररहेहैंतोहमसेसंपकर् करनेमेंसंकोचनकरें
• there will be one Teaching Assistant for every ~12 students– Help and support can provided in other languages
7/30/19 Autumn 2019 CS101@CSE IIT Bombay 15
Autumn 2019 CS101@CSE IIT Bombay7/30/19 16
let’sstartprogramming!
• whatisaprogram?– logic/concept/idea/calculations…– sequenceofinstructions(thatacomputercanunderstand)thatcapturethelogic
• wealreadydothis…– whichroutetotaketoreachLA001?– whattimetowakeupforclass?– howtobookanola/uber ride?– howtoprepareforanexam?– …
Autumn 2019 CS101@CSE IIT Bombay7/30/19 17
programs
• program =aprecisedescriptionofthecalculationswewantthecomputertoperform
• byfeedingdifferentprogramstoacomputeryoucanmakeitdodifferentcalculations
• thiscoursetellsyouhowtoconstruct(“write”)programs• specialnotationistobeusedtowriteprograms:“ProgrammingLanguage”(C++forthiscourse)
7/30/19 Autumn 2019 CS101@CSE IIT Bombay 18
goal for today
• writesomesmallprogramsusingC++programminglanguage
• theprogramswilldrawpicturesonthescreen• we“drive”a“turtle”onthescreen!
• Turtle hasapen,soitdrawsasitmoves• drawingpicturesmayseembefun,butifyoumasterit,youhavemasteredalotofprogramming
• willusesimplecpp packagedevelopedbyProf. AbhiramRanade,basedonLogo
7/30/19 Autumn 2019 CS101@CSE IIT Bombay 19
programming the turtle to draw
instructions the turtle understands• forward (x): Move forward x pixels
– E.g. forward(50) moves the turtle forward 50 pixels• right (x): turn right by x degrees• left(x): turn left by x degrees • penUp()
– Will not draw while moving• penDown()
– Will draw while moving
7/30/19 Autumn 2019 CS101@CSE IIT Bombay 20
programming a turtle to draw a square
• forward, right, left, penUp, penDown
• With these instructions, make the turtle move in such a way that we will draw a square of length 200
• What facts do we need to know before we can program?
• Note: By default, in the beginning, the turtle faces towards the east, and the pen is down
7/30/19 Autumn 2019 CS101@CSE IIT Bombay 21
The square drawing program
#include <simplecpp>
main_program { turtleSim();forward(200); right(90);forward(200); right (90);forward(200); right(90);forward(200);
}
The square drawing program
#include <simplecpp>
main_program { turtleSim();forward(200); right(90);forward(200); right (90);forward(200); right(90);forward(200);
}
Some magic abracadabra: ignorethe program will use the simplecpp package.
Your commands within these braces {..}.
Start the turtle simulator (open a window)
Move forward 200 units
Turn right 90 degrees
Program exits
General Ideas
#include<simplecpp>
main_program{
turtleSim();
forward(200); right(90);
forward(200); right(90);
forward(200); right(90);
forward(200);wait(10);
}
This sequence of commands in C++ is the program
Commands or statementsterminated by semicolon ";"
Some commands need additional information called arguments• 90 is the argument to the
command right• 200 is the argument to the
command forward
General Ideas (contd)
#include<simplecpp>
main_program{turtleSim();forward(200);right(90);forward(200);right(90);forward(200);right(90);forward(200);wait(10);}
Commands are generally executed from top to bottom, left to right.
how to draw an octagon?
7/30/19 Autumn 2019 CS101@CSE IIT Bombay 26
how to draw an octagon?
• commands seem quite repetitive?
• there is a better way!
#include<simplecpp>main_program{
turtleSim();forward(100);right(45);forward(100);right(45);forward(100);right(45);forward(100);right(45);forward(100);right(45);forward(100);right(45);forward(100);right(45);forward(100);right(45);
wait(10);}
7/30/19 Autumn 2019 CS101@CSE IIT Bombay 27
A Better Way
#include <simplecpp>
main_program{turtleSim(); repeat(8){
forward(100); right(45);
}}
repeat (n) {
some commands
}
The instructions within {...} are repeated n times
Each round of execution is called an iteration
How to Draw a Polygon?
#include <simplecpp>
main_program{turtleSim(); repeat(8){
forward(100); right(45);
}}
7/30/19 Autumn 2019 CS101@CSE IIT Bombay
29
How to Draw a Polygon?
#include <simplecpp>
main_program{turtleSim();
repeat(num_sides){forward(10); right(360.0/num_sides);
} }
#include <simplecpp>
main_program{turtleSim();
repeat(8){forward(10); right(45);
} }
7/30/19 Autumn 2019 CS101@CSE IIT Bombay 30
How to Draw a Polygon?
#include <simplecpp>
main_program{turtleSim();
int num_sides;
repeat(num_sides){forward(10); right(360.0/num_sides);
} }
We need some magic so that num_sides can have the right value
Tell the computer: Reserve space in your memory where I can store an integer (int). I will refer to it by the name num_sides
Divide the number 360 by the number stored in the space named num_sides and pass the result as an argument to this command
7/30/19 Autumn 2019 CS101@CSE IIT Bombay 31
Explanation#include <simplecpp>main_program{
turtleSim();
int num_sides;
cout << “No. of sides?”;cin >> num_sides;
repeat(num_sides) {forward(200);right(360.0/num_sides);
}}
Print the sentence within the quotes on the screencout è “Console out” (display)
Read the number that the user types and store it into the space in memory named num_sides cin ç “Console in” (keyboard)
Use the integer stored in the space in memory which is namednum_sides
Formatting: Indentation, Grouping, Naming
#include <simplecpp>
main_program{turtleSim();int num_sides;
cout << “No. of sides?”;cin >> num_sides;
repeat(num_sides) {forward(200);right(360.0/num_sides);
}}
#include <simplecpp>main_program{turtleSim();cout << “No. of sides?”;int n;cin >> n;repeat(n) {forward(200);right(360.0/n);}}
You will lose marks for bad formatting
Can we improve the program further?main_program{
turtleSim();int num_sides;
cout << “No. of sides?”;cin >> num_sides;
repeat(num_sides) {forward(200);right(360.0/num_sides);
}}
main_program{turtleSim();
int num_sides; int side_length = 200;double exterior_angle;
cout << “No. of sides?”;cin >> num_sides;
exterior_angle = 360.0/num_sides;
repeat(num_sides) {forward(side_length);right(exterior_angle);
}}
Can we improve the program further?Both values for a polygon,
number of sides andside length
are user inputs.
int num_sides; int side_length;double exterior_angle;double sum_exterior = 360;
cout << “No. of sides?”;cin >> num_sides;
cout << “Side length?”;cin >> side_length;
exterior_angle = sum_exterior/num_sides;
repeat(num_sides) {forward(side_length);right(exterior_angle);
}}
language syntax
• syntax =grammatical rulesindicatinghowcommandsmustbewritten
• syntaxofprogramminglanguagesisverystrict,e.g.– “right(90);”cannotbewrittenas“right90;”.– “penUp()”cannotbewrittenas“penup()”oreven“penUp”,i.e.withoutparentheses.
– wewilllaterlearnotherkindsofstatementswhichwillhavetheirownsyntaxwhichmustbeadheredto.
7/30/19 Autumn 2019 CS101@CSE IIT Bombay 36
Nested Repeat Statements
It will draw a square with dashed lines
repeat(4){
repeat(3){
forward(50); penUp();
forward(50); penDown();
}
right(90);
}
7/30/19 Autumn 2019 CS101@CSE IIT Bombay 37
what does the following program do?
#include <simplecpp>
main_program{cout << “a”;repeat(5){
cout << “b”;repeat(2){ cout << “c”; }cout << “d”;
}}
what does the following program do?
#include <simplecpp>
main_program{cout << “a”;repeat(5){
cout << “b”;repeat(2){ cout << “c”; }cout << “d”;
}}
abccdbccdbccdbccdbccd
curly braces group statements
repeat(4){
forward(50); right(90);wait(2);
}
repeat(4)
forward(50); right(90);wait(2);
repeat(4){
forward(50);}right(90);wait(2);
more commands/functions
• sqrt(x) : square root of x
• trigonometric functions,
• x is in radian: sin(x), cos(x), tan(x)
• x is in degree sine(x), cosine(x), tangent(x)
• also for arcsine, arccosine, arctangent etc.
compile and execute this program
1. Raise one of your hands2. Put down your raised hand3. Close your eyes and count loudly up to 104. Loudly say ‘Ha Ha Ha’5. Write the value of Pi ( π ) correct to 3 decimal places6. Loudly say “Thank you” in your mother tongue7. Clap three times8. While executing this program, ignore all earlier
instructions and just raise both hands
Autumn 2019 CS101@CSE IIT Bombay7/30/19 42
running/executing the program
• Compiling a program: translating it into a form that a computer can understand
• the result of compilation: an executable file
• compiler used by us is called s++
running a program on computer
• Type in an editor (say, gedit)• Save the file (say prog.cpp)• Compile (s++ prog.cpp)• It generates a binary file a.out• Execute (./a.out )
• Note that in case compilation fails with some error, existing a.out file is untouched
7/30/19 Autumn 2019 CS101@CSE IIT Bombay 44
The Spirit of The Course
LearnC++statements/conceptsLearnhowtoexpressproblemsyouwanttosolveusingC++
Goal:ifyoucansolveaproblembyhand,possiblytakinganenormousamountoftime,bytheendofthecourse,youshouldbeabletowriteaprogramforit
Learnnewwaysofsolvingproblems!
How to master the course
• Do not be afraid of using the computer
• “What if I write xyz in my program instead of pqr?”
Just do so and find out
• Be adventurous.
• But first write your logic on paper, think about how the computer will execute your instructions, and only then type them up
Why Picture Drawing?
• Picture drawing requires calculatione.g. 360.0/num_sides
• “Draw a triangle with sides of lengths 3, 4, 5 units”
You will need to do trigonometric calculations to find out the angles between the sides
• More interesting calculations will be needed to draw more interesting drawings
A pattern with 36 repetitions. You know enough to write a program to do this! Try it.
End of Lecture
7/30/19 Autumn 2019 CS101@CSE IIT Bombay 49
Compilation and execution summary
CPU RAM Disk Keyboard Display
Operating system (Windows, Linux, Mac OS, …)
C/C++ execution environment
Bashshellio
stre
am
mat
h
strin
g
main() function in a.out
char, short, int, float, double, if, switch, while, …
Source code prog.cpp
iostreammath.hstring
Prec
ompi
led
libra
ries
Head
erfile
s
s++ compiler
7/30/19 Autumn 2019 CS101@CSE IIT Bombay
50
Autumn 2019 CS101@CSE IIT Bombay
PC building blocks: motherboard
CPU withcooling fan
Magneticdisk dataconnectors
Fastelectronicmemory
7/30/19 51
Autumn 2019 CS101@CSE IIT Bombay
Storage and peripheral devices
Rotatingmagneticplatters
Record/playhead on arm
Data cable betweendisk and motherboard
KeyboardDisplay
7/30/19 52
Autumn 2019 CS101@CSE IIT Bombay
CPU
Simplified abstract viewArithmetic
and logic unit
Register 0Register 1Register 2
…
Random accessmemory (RAM)
RAM location 0RAM location 1RAM location 2
…Address
Data Reserved fordisplay
Reserved for keyboard
Program that tells the CPU what to do and
how to do it7/30/19 53