CS 101 Computer Programming and Utilizationcs101/2019.1/lectures/Lecture2.pdf · Autumn 2019...
Transcript of CS 101 Computer Programming and Utilizationcs101/2019.1/lectures/Lecture2.pdf · Autumn 2019...
Autumn 2019 CS101@CSE IIT Bombay
CS 101Computer Programming and Utilization
Autumn 2019https://www.cse.iitb.ac.in/~cs101
Puru
Lecture 2: Variables, Data Types, and Expressions
Autumn 2019 CS101@CSE IIT Bombay
programming is like riding a cycle
• try• fall / fail• try again• get hurt / program crashes• get help from friends• try again• try• try • try• ... fly
02/08/19 3
Autumn 2019 CS101@CSE IIT Bombay
keywords from last class• logic, syntax, sequence• simplecpp, c++• codeblocks• program• programming• main_program, repeat, curly braces, functions
02/08/19 4
Autumn 2019 CS101@CSE IIT Bombay
how to draw an octagon?• commands seem quite repetitive?
• there is a better way!
502/08/19
#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);}
Autumn 2019 CS101@CSE IIT Bombay
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
repeating a set of actions is a common action/requirementas part of logic to do some work
02/08/19 6
Autumn 2019 CS101@CSE IIT Bombay
how to draw a polygon?
02/08/19 7
#include <simplecpp>
main_program{
turtleSim();
repeat(8){
forward(100);
right(45);
}
}
Autumn 2019 CS101@CSE IIT Bombay
how to draw a polygon?
802/08/19
#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);
} }
Autumn 2019 CS101@CSE IIT Bombay
how to draw a polygon?
902/08/19
#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
Autumn 2019 CS101@CSE IIT Bombay
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
02/08/19 10
Autumn 2019 CS101@CSE IIT Bombay
can we improve the program further?
Both values for a polygon,
number of sides andside length
are user inputs.
#include <simplecpp>
main_program{turtleSim();
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);
}}
02/08/19 12
Autumn 2019 CS101@CSE IIT Bombay
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 and your sleep for bad formatting02/08/19 13
Autumn 2019 CS101@CSE IIT Bombay
language syntax• syntax = grammatical rules indicating how
commands must be written• syntax of programming languages is very strict,
e.g.– right(90);cannot be written as right(90)penUp() cannot be written as penup()or even penUp, i.e., without parentheses
– all statements, instructions, keywords of a language have a format and have to adhered to
1402/08/19
Autumn 2019 CS101@CSE IIT Bombay
what does the following program do?
#include <simplecpp>main_program{
cout << �a�;repeat(5){
cout << �b�;repeat(2){ cout << �c�; }cout << �d�;
}}
02/08/19 15
Autumn 2019 CS101@CSE IIT Bombay
what does the following program do?
#include <simplecpp>main_program{
cout << �a�;repeat(5){
cout << �b�;repeat(2){ cout << �c�; }cout << �d�;
}}
abccdbccdbccdbccdbccd02/08/19 16
Autumn 2019 CS101@CSE IIT Bombay
curly braces group statementsrepeat(4){
forward(50); right(90);wait(2);
}
repeat(4){}
forward(50);
right(90);
wait(2);
repeat(4){
forward(50);}right(90);wait(2);
02/08/19 17
Autumn 2019 CS101@CSE IIT Bombay
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.
02/08/19 18
Autumn 2019 CS101@CSE IIT Bombay
running/executing the program• Compiling a program:
– translating it into a form that a computer can understand– high level language to machine instructions
• the result of compilation: an executable file
• compiler used by us (for simplecpp code) is called s++
• g++ compiler for vanilla C++ programs
02/08/19 19
Autumn 2019 CS101@CSE IIT Bombay
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
2002/08/19
Autumn 2019 CS101@CSE IIT Bombay
homework/practicedraw a square with dashed lines
2102/08/19
repeat(4){
…
}
Autumn 2019 CS101@CSE IIT Bombay
Outline
• How to store data in the memory of a computer
• How to perform arithmetic
• How to read numbers into the memory from the keyboard
• How to print numbers on the screen
• Many programs based on all this
02/08/19 22
Autumn 2019 CS101@CSE IIT Bombay
variable declaration
a general statement of the form
data_type_name variable_name;
creates and declares variables (named space in memory to store data)
earlier example …
int sides;
int : name of the data type. Short form for integer. Says reserve space for storing integer values
sides : name given to the reserved space, or the variable created
02/08/19 23
Autumn 2019 CS101@CSE IIT Bombay
variable declaration0123456789
.......
32 bits
int sides;Results in a memory location being reserved for this variable. The program will refer to it by the name sides
02/08/19 24
Autumn 2019 CS101@CSE IIT Bombay
variable names: identifiers• sequence of letters, digits & the underscore �_� character
• case matters. ABC, Abc and abc are distinct identifiers
• should not begin with a digit
• some words such as int cannot be used as variable names. reservedby C++ for its own use
• Which of these are valid variable names:sides, #sides, 3rd_cousin, third cousin, tele_number, x, third_cousin,
02/08/19 25
Autumn 2019 CS101@CSE IIT Bombay
naming practices
• use meaningful names, describing the purpose for which the variable will be used
exterior_angle = sum_exterior/num_sides;
• never use single letter variable name unless appropriate in the context. Example:
u*t+1/2*a*t*t
e = s/n
02/08/19 26
Autumn 2019 CS101@CSE IIT Bombay
the assignment operator• assignment operator =
exterior_angle = sum_exterior/num_sides;used to store results of computation into a variableForm: variable_name = expression;
• expressiona constant (a number) ora variable name ora formula involving constants or variables ora function call
02/08/19 27
Autumn 2019 CS101@CSE IIT Bombay
initialization - an INITIAL value is assigned to the variable
the value stored in the variable at the time of its creation
variables i, vx, vy are declared and are initialized
2.0e5 is how we write 2.0*105
‘f’ is a character constant
int i=0;double vx=1.0;double vy=2.0e5;
char value = ‘f’;
variable initialization examples
02/08/19 28
Autumn 2019 CS101@CSE IIT Bombay
int x=2, y=3, p=4, q=5, r, s, t;
x = rt;
x = r*s;
r = x*y + p*q;
s = x*(y+p)*q;
t = x – y + p – q;
more examples
02/08/19 29
Autumn 2019 CS101@CSE IIT Bombay
int x=2, y=3, p=4, q=5, r, s, t;
x = rt; // syntax error!
x = r*s; // disaster! r, s undefined
r = x*y + p*q; // r becomes 2*3 + 4*5 = 26
s = x*(y+p)*q; // s becomes 2*(3+4)*5 = 70
t = x – y + p – q; // equal precedence, // so evaluated left to right,// t becomes (((2-3)+4)-5 = -2
more examples
02/08/19 30
Autumn 2019 CS101@CSE IIT Bombay
reading values into variables
• can read value of a variable from the terminal• can read into several variables one after another• int, char etc. can be read
• user expected to type in values consistent
with the type of the variable into which it is
to be read
• whitespaces (i.e. space characters, tabs, newlines)
typed by the user are ignored
• newline/enter key must be pressed after values are typed
cin >> num_sides;
cin >> vx >> vy;
char command;
cin >> command;
02/08/19 31
Autumn 2019 CS101@CSE IIT Bombay
printing variables on the screen• general form: cout << variable;
• many values can be printed one after another
• need to put “ “ if you want to have gap between successive values
• to print newline, use endl
• text can be printed by enclosing it in quotes
cout << x;
cout << x << y;cout << x << �, � << y;
cout <<�Position: " << x << �, � << y << endl;
char var = �G�;cout << var;
02/08/19 32
Autumn 2019 CS101@CSE IIT Bombay
int x=2, y=3, z, w;double q=3.1, r, s;r = x; // representation changed
// 2 stored as a double in r "2.0"z = q; // store with truncation
// z takes integer value 3s = x*q; // convert to same type,
// then multiply// Which type?
cout << (360/240) << “ ” << (360.0/240) << “ ” << (360/240.0);
arithmetic between different types allowed
02/08/19 33
Autumn 2019 CS101@CSE IIT Bombay
• e.g. x*q
if varA, varB have the same data type: the result will have same
data type
• if varA, varB have different data types: the result will have more
expressive data type
• int/short/unsigned int are less expressive than float/double
• shorter types are less expressive than longer types
• we will only use int and double in this course
evaluating varA op varB
02/08/19 34
Autumn 2019 CS101@CSE IIT Bombay
int x=2, y=4, p=3;
double u;
u = x/p + y/p;
cout << u << (x+y)/p;
• x/p : both are int. So truncation. Hence 0
• y/p : 4/3 after truncation will be 1
• So the output is “1 2”
Integer Division, Evaluation Order
02/08/19 35
Autumn 2019 CS101@CSE IIT Bombay
int num_sides=100;int i_angle1, i_angle2;double d_angle1, d_angle2;
d_angle1 = 360/num_sides + 0.45; // 3.45i_angle1 = 360/num_sides + 0.45; // 3
d_angle2 = 360.0/num_sides + 0.45 // 4.05i_angle2 = 360.0/num_sides + 0.45; // 4
more examples
02/08/19 36
Autumn 2019 CS101@CSE IIT Bombay
main_program{
double centigrade, fahrenheit;
cout << “Give temperature in Centigrade: ”;
cin >> centigrade;
fahrenheit = centigrade * 9.0 / 5.0 + 32;
cout << “In Fahrenheit: ” << fahrenheit
<< endl; // newline
}
a sample program
02/08/19 37
Autumn 2019 CS101@CSE IIT Bombay
int p=3, q=4, r;r = p + q; // 7 stored into rcout << r << endl; // 7 printed
r = p * q; // 12 stored into rcout << r << endl; // 12 printed
• Same variable can be assigned a value again• When a variable appears in a statement, its value at the
time of the execution of the statement gets used
Re-Assignment
02/08/19 38
Autumn 2019 CS101@CSE IIT Bombay
int p=12;p = p+1;
See it as: p p+1; // Let p become p+1
rule for evaluation: • FIRST evaluate the RHS and THEN store the result into the
LHS variable• 1 is added to 12 (the value of p)• the result, 13, is then stored in p• thus, p finally becomes 13
p = p + 1 is false in mathematics “=” in C++ is different from “=” in mathematics
in C++ `=‘ is assignment, not equal’
02/08/19 39
Autumn 2019 CS101@CSE IIT Bombay
main_program{int i=0;
repeat(10){i = i + 1;cout << i << endl;
}}
repeat and re-assignment
02/08/19 40
Autumn 2019 CS101@CSE IIT Bombay
main_program{int term, s = 0;
repeat(10){cin >> term; s = s + term;
}cout << s << endl;
}
• values read are summed into s• we could have used other binary operators too, say
multiplication, or gcd or max or min
another re-assignment example
02/08/19 41
Autumn 2019 CS101@CSE IIT Bombay
sequence generation
• can you make i take values 1, 3, 5, 7, …?
• can you make i take values 1, 2, 4, 8, 16, …?
• both can be done by making slight modifications to
above program
fundamental idiom
02/08/19 42
main_program{int i=0;repeat(10){i = i + 1;
cout << i << endl;}
}
Autumn 2019 CS101@CSE IIT Bombay
Write a program to calculate n!
5! = 1 x 2 x 3 x 4 x 5
composing two idioms
02/08/19 43
Autumn 2019 CS101@CSE IIT Bombay
Write a program to calculate n! given n.
main_program{int n, nfac=1, i=1;cin >> n;repeat(n){
nfac = nfac * i;i = i + 1;
}cout << nfac << endl;
}
Accummulation idiom
Sequence idiom
composing two idioms
02/08/19 44
Autumn 2019 CS101@CSE IIT Bombay
finding remainder
• x % y computes the remainder of dividing x by y• Bbth x and y must be integer expressions• Example
•
•• d0 will equal 8 (the least significant digit of n)• d1 will equal 7 (the second least significant digit of n)
int n=12345678, d0, d1;d0 = n % 10; // 8d1 = (n / 10) % 10; // 7
02/08/19 45
Autumn 2019 CS101@CSE IIT Bombay
concluding Remarks
• variables are regions of memory which can store values• variables have a type, as decided at the time of creation
• choose variable names to fit the purpose for which the variable is defined
• the name of the variable may refer to the region of memory (if the name appears on the left hand side of an assignment), or its value (if the name appears on the right hand side of an assignment)
• operators have an ordering (* / before + -)
02/08/19 46
Autumn 2019 CS101@CSE IIT Bombay
more practice• What is the result of evaluating the expression (3+2)/4?
• What is printed by this code snippet …float f=6.022E23; float r=f+2-f; cout<<r;
• What is printed by this code snippetint t=10; repeat(2){t=t-1.2;} cout<<t;
• What is printed by this code:int i=2, j=3, k=4; i=j; j=k; k=i; cout << (i*j*k);
02/08/19 47
Autumn 2019 CS101@CSE IIT Bombay
we have labs on 3 days of the week --- Tue, Wed, Thu 8 pm to 11 pm
check for student to lab section mapping• three lab sections L1, L2, L3• students from both sections will be mixed across sections• labs for sections will be held on different days of the week• you will be assigned a fixed seat
for lab related logistics, please visit the web page, every week … Lab section to day of the week may change
02/08/19 49