0% found this document useful (0 votes)
5 views

Lecture2

Uploaded by

itachiisgenius
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Lecture2

Uploaded by

itachiisgenius
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

CS 101

Computer Programming and Utilization


Autumn 2019
https://www.cse.iitb.ac.in/~cs101

Puru

Lecture 2: Variables, Data Types, and Expressions

Autumn 2019 CS101@CSE IIT Bombay


Recap

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 2


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 Autumn 2019 CS101@CSE IIT Bombay 3


keywords from last class
• logic, syntax, sequence
• simplecpp, c++
• codeblocks
• program
• programming
• main_program, repeat, curly braces, functions

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 4


how to draw an octagon?
#include <simplecpp> • commands seem
main_program{ quite repetitive?
turtleSim();
forward(100); right(45);
• there is a better way!
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);
}

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 5


a better way
#include <simplecpp>
repeat (n) {
main_program {
some commands
turtleSim();
}
repeat(8) {
forward(100);
The instructions within {...} are
right(45);
repeated n times
}
Each round of execution is
} called an iteration

repeating a set of actions is a common action/requirement


as part of logic to do some work
02/08/19 Autumn 2019 CS101@CSE IIT Bombay 6
how to draw a polygon?

#include <simplecpp>
main_program{
turtleSim();
repeat(8){
forward(100);
right(45);
}
}

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 7


how to draw a polygon?
#include <simplecpp> #include <simplecpp>
main_program{ main_program{
turtleSim(); turtleSim();

repeat(8) { repeat(num_sides){
forward(10); forward(10);
right(45); right(360.0/num_sides);
} }
} }

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 8


how to draw a polygon?

#include <simplecpp>
main_program{
turtleSim(); Tell the computer: Reserve space in
your memory where I can store an
integer (int). I will refer to it by the
int num_sides; name num_sides

repeat(num_sides){
forward(10); We need some magic so that
num_sides can have the right
right(360.0/num_sides);
value
}
}
Divide the number 360 by the number stored in the
space named num_sides and pass the result as
an argument to this command
02/08/19 Autumn 2019 CS101@CSE IIT Bombay 9
explanation
#include <simplecpp>

main_program{ Print the sentence within the quotes


on the screen
turtleSim(); cout è “Console out” (display)

int num_sides;

cout << No. of sides? ;


cin >> num_sides; Read the number that the user types
and store it into the space in
memory named num_sides
repeat(num_sides) { cin ç “Console in” (keyboard)
forward(200);
right(360.0/num_sides);
}
Use the integer stored in the space
} in memory which is named
num_sides

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 10


can we improve the program further?

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 11


can we improve the program further?
#include <simplecpp>
Both values for a polygon,
main_program{
turtleSim(); number of sides and
int num_sides;
side length
int side_length;
double exterior_angle;
double sum_exterior = 360; are user inputs.

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 Autumn 2019 CS101@CSE IIT Bombay 12
formatting: indentation, grouping, naming
#include <simplecpp> #include <simplecpp> main_program{
turtleSim(); cout << No. of sides? ;
main_program{ int n; cin >> n; repeat(n) {
turtleSim(); forward(200); right(360.0/n);} }
int num_sides;

cout << No. of sides? ;


cin >> num_sides;

repeat(num_sides) {
forward(200);
right(360.0/num_sides);
}
}

You will lose marks and your sleep for bad formatting
02/08/19 Autumn 2019 CS101@CSE IIT Bombay 13
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

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 14


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 Autumn 2019 CS101@CSE IIT Bombay 15


what does the following program do?

#include <simplecpp>
main_program{
cout << a ;
repeat(5){
cout << b ;
repeat(2){ cout << c ; }
cout << d ;
}
}

abccdbccdbccdbccdbccd
02/08/19 Autumn 2019 CS101@CSE IIT Bombay 16
curly braces group statements
repeat(4){} repeat(4){ repeat(4){
forward(50); forward(50);
forward(50);
right(90); }
right(90); wait(2); right(90);

wait(2); } wait(2);

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 17


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 Autumn 2019 CS101@CSE IIT Bombay 18


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 Autumn 2019 CS101@CSE IIT Bombay 19


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

02/08/19
Autumn 2019 CS101@CSE IIT Bombay 20
homework/practice
draw a square with dashed lines

repeat(4){


}

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 21


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 Autumn 2019 CS101@CSE IIT Bombay 22


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 Autumn 2019 CS101@CSE IIT Bombay 23


variable declaration
0
1
2
3
4
5 .......
6
7
8
9

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 Autumn 2019 CS101@CSE IIT Bombay 24
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. reserved


by 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 Autumn 2019 CS101@CSE IIT Bombay 25


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 Autumn 2019 CS101@CSE IIT Bombay 26


the assignment operator
• assignment operator =
exterior_angle = sum_exterior/num_sides;
used to store results of computation into a variable
Form: variable_name = expression;

• expression
a constant (a number) or
a variable name or
a formula involving constants or variables or
a function call

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 27


variable initialization examples

initialization - an INITIAL value is assigned


to the variable
the value stored in the variable at the time of its int i=0;
creation double vx=1.0;
double vy=2.0e5;
variables i, vx, vy are declared and are
initialized
char value = ‘f’;
2.0e5 is how we write 2.0*105
‘f’ is a character constant

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 28


more examples
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;

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 29


more examples
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

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 30


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 cin >> num_sides;

cin >> vx >> vy;


• user expected to type in values consistent
char command;
with the type of the variable into which it is
cin >> command;
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

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 31


printing variables on the screen
• general form: cout << variable; cout << x;

• many values can be printed one cout << x << y;


after another
cout << x << , <<
• need to put “ “ if you want to have gap y;
between successive values
cout << Position: " <<
• to print newline, use endl
x << , << y <<
endl;
• text can be printed by enclosing
it in quotes
char var = G ;
cout << var;

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 32


arithmetic between different types allowed
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 3
s = x*q; // convert to same type,
// then multiply
// Which type?

cout << (360/240) << “ ” << (360.0/240) << “ ” << (360/240.0);

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 33


evaluating varA op varB

• 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

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 34


Integer Division, Evaluation Order
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”

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 35


more examples
int num_sides=100;
int i_angle1, i_angle2;
double d_angle1, d_angle2;

d_angle1 = 360/num_sides + 0.45; // 3.45


i_angle1 = 360/num_sides + 0.45; // 3

d_angle2 = 360.0/num_sides + 0.45 // 4.05


i_angle2 = 360.0/num_sides + 0.45; // 4

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 36


a sample program
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
}

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 37


Re-Assignment
• 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

int p=3, q=4, r;


r = p + q; // 7 stored into r
cout << r << endl; // 7 printed

r = p * q; // 12 stored into r
cout << r << endl; // 12 printed

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 38


in C++ `=‘ is assignment, not equal’
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

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 39


repeat and re-assignment
main_program{
int i=0;
repeat(10){
i = i + 1;
cout << i << endl;
}
}

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 40


another re-assignment example
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

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 41


fundamental idiom
main_program{
int i=0;
repeat(10){
i = i + 1;
cout << i << endl;
}
}
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

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 42


composing two idioms
Write a program to calculate n!

5! = 1 x 2 x 3 x 4 x 5

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 43


composing two idioms
Write a program to calculate n! given n.

main_program{
int n, nfac=1, i=1;
cin >> n;
repeat(n){ Accummulation idiom
nfac = nfac * i;
i = i + 1;
}
cout << nfac << endl;
Sequence idiom
}

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 44


finding remainder
• x % y computes the remainder of dividing x by y
• Bbth x and y must be integer expressions
• Example

int n=12345678, d0, d1;



d0 = n % 10; // 8
d1 = (n / 10) % 10; // 7

• d0 will equal 8 (the least significant digit of n)
• d1 will equal 7 (the second least significant digit of n)

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 45


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 Autumn 2019 CS101@CSE IIT Bombay 46


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 snippet


int 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 Autumn 2019 CS101@CSE IIT Bombay 47


endosaurus

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 48


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 Autumn 2019 CS101@CSE IIT Bombay 49


more nested repeat statements
It will draw a square with dashed lines

repeat(4){
repeat(3){
forward(50); penUp();
forward(50); penDown();
}
right(90);
}

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 50

You might also like