Introduction to Programming (CS 101)
Spring 2024
Lecture 2:
- Variables, data types, operators
- cout/cin Instructor: Preethi Jyothi
- Based on material developed by Prof. Abhiram Ranade
Recap
#include <simplecpp>
main_program{
turtleSim();
Pick the closest emoji that the following int nsides = 40;
repeat(nsides){
piece of code will draw.
forward(400.0/nsides);
right(360.0/nsides);
}
A
forward(5); right(90);
B penUp();
forward(50); right(90); forward(10);
penDown(); forward(20); right(180);
C
penUp(); forward(30); forward(10);
penDown(); forward(20);
D
hide();
getClick();
}
Variables, data types and operators
• Recall:
#include <simplecpp>
main_program { = is the assignment operator
turtleSim();
A variable called "nsides" int nsides = 4;
whose value can be set repeat(nsides) {
and modi ed later
forward(100);
right(90);
The type of the variable
} is int: short for integer
getClick();
}
• We will cover four data types today (and more later): char, int, float and double
fi
Variables
• A variable occupies a region of memory (in a computer) into which you can store a value
Simpli ed View of a
CPU (Central Processing Unit)
ALU
INPUT Control OUTPUT
Unit
Variables Main
are stored
here
Memory
fi
Variables and data types
• A variable occupies a region of memory (in a computer) into which you can store a value
• Create variables of a particular data type by giving each variable a name, to refer to in
the rest of the program
• A variable declaration is as follows:
data-type variable-name;
• Several variables of the same data type can be de ned in a single statement:
data-type variable-name-1, variable-name-2, variable-name-3;
fi
Variables and data types
• A variable occupies a region of memory (in a computer) into which you can store a value
• Create variables of a particular data type by giving each variable a name, to refer to in
the rest of the program
• A variable declaration is as follows:
data-type variable-name;
where data-type is one of:
Data type Possible values Used for
char -128 to 127 Characters
More data types such as bool -2147483648 to Standard size
int
will be covered in later lectures 2147483647 Integers
About 7 digits
float Real numbers
of precision
About 15 digits
double Real numbers
of precision
Variable names
• Variable names or identifiers can consist of letters, digits, and the underscore character "_"
• Reserved words in C++ (e.g., int, char, etc.) cannot be used as variable names
• Not recommended to start a name for an ordinary variable with "_"
• A variable name cannot start with a digit. E.g., 2ndname
• Case (lowercase vs. uppercase) is important and distinguishes variable names from one
another. E.g., coursetotal is different from CourseTotal
char (short for character)
• char data type is most commonly used to store a single character
• Use single quotes around the character. Example of usage: char grade = 'A';
• An integer value is stored in char variables, referred to as ASCII values (ranging from 0 to
127). ASCII integer value to character mapping is at [1]. E.g., ASCII value of 'A' is 65.
• char j = 'A'; and char j = 65; are equivalent
• a-z, A-Z, 0-9 → all have consecutive ASCII codes Ans: Prints out the upper case letter
corresponding to the one in in_char
What does this code segment do?
char in_char = ‘c’, out_char;
out_char = in_char + 'A' - 'a'
Assume only lower case letters in in_char
[1] https://en.cppreference.com/w/cpp/language/ascii
char (short for character)
• char data type is most commonly used to store a single character
• Use single quotes around the character. Example of usage: char grade = 'A';
• An integer value is stored in char variables, referred to as ASCII values (ranging from 0 to
127). ASCII integer value to character mapping is at [1]. E.g., ASCII value of 'A' is 65.
• char j = 'A'; and char j = 65; are equivalent
• a-z, A-Z, 0-9 → all have consecutive ASCII codes
• Escape sequences: Special characters such as ', ", \, etc. can be written as they are with an
escape sequence.
char j = '''; throws an error but char j = '\''; does not
[1] https://en.cppreference.com/w/cpp/language/ascii
int (short for integer) and float/double (short for oating-point)
int
• int represents integers in the range -2147483648 to 2147483647
• If you know you are only dealing with non-negative integers, use the data type unsigned int
that represents numbers in the range 0 to 4294967295
• Other avours of int that we will learn later (short int, etc.)
float/double
• float/double are both used for decimals with 7 and 15 decimal digits precision, respectively.
Magnitude ranges are 1.17549 x 10-38 to 3.4028 x 1038 and 2.22507 x 10-308 to 1.7977 x 10308
• Typically use double unless you know you are dealing with small oating-point numbers
• Scienti c notation: float i = 2E-3f that stands for 2 x (10-3)
Note the suf x 'f' that denotes the value is oat
fl
fi
fi
fl
fl
fl
int (short for integer) and float/double (short for oating-point)
int
• int represents integers in the range -2147483648 to 2147483648
• If you know you are only dealing with non-negative integers, use the data type unsigned int
that represents numbers in the range 0 to 4294967295
• Other avours of int that we will learn later (short int, etc.)
float/double
• float/double are both used for decimals with 7 and 15 decimal digits precision, respectively.
Magnitude ranges are 1.17549 x 10-38 to 3.4028 x 1038 and 2.22507 x 10-308 to 1.7977 x 10308
• Typically use double unless you know you are dealing with small oating-point numbers
• Scienti c notation: float i = 2E-3f and double i = 2E-3
• Floating point arithmetic has many subtleties that we will cover in a later class
fl
fi
fl
fl
Assignment operation
Assignment operator
• Syntax:
variable = expression
• Semantics (Meaning): Evaluate expression and then store in the result in variable
• Examples:
int nsides = 4; Here, expression is a constant (i.e., 4)
int i = 1;
Here, expression is a simple arithmetic operation on i (i.e., i + 1)
i = i + 1;
int i = 1; Here, expression is another arithmetic operation on i with two
i = (i * i) + 2; operators '*' and '+'
Illustrating assignment
• What does this program do?
#include <simplecpp>
main_program {
turtleSim();
int x = 5; • int x = 5: x is assigned an initial value of 5 or
repeat(100) { x is initialized with the value 5
forward(x); right(90);
x = x + 5;
• x = x + 5: Add 5 to x and then store this
} value back into x
hide();
getClick();
}
Arithmetic operations
• Variables can be manipulated using arithmetic operations, much like in algebra
• Common arithmetic operators: +, - , *, / E.g.: x = (a / d) + (b * c)
• Preference order of operators:
• Multiplication and division have the same precedence, which is higher than ...
• ... addition and subtraction that have the same precedence
• Among operators of the same precedence, we go left-to-right
int x = 6 * 2 + 3; Here, x will evaluate to 15
int x = 6 / 3 * 2; Here, x will evaluate to 4
int x = 6 - 3 / 3 + 2; Here, x will evaluate to 7
Order of assignment vs. arithmetic operators
• With arithmetic operators, evaluation order is left-to-right
• With multiple assignment operators, the rightmost assignment is evaluated rst i.e. the order is
right-to-left
int x = 1, y = 2, z = 3; What are the values of x, y, z?
x = y = z = 4; Ans: x = 4 , y = 4, z = 4
int x = 1, y = 2, z = 3; What are the values of x, y, z?
x = y = z = x + z;
Ans: x = 4 , y = 4, z = 4
int x = 1, y = 2, z = 3; What are the values of x, y, z?
x = y = z = x - z + y;
Ans: x = 0 , y = 0, z = 0
fi
Relational operators
• Relational operators are used to compare two variables or expressions
• Returns either false (zero) or true (non-zero) value
• Operators include:
• Greater than (>): sum > 10
• Greater than or equal to (>=): i >= 5
• Less than (<): sum < 10
• Less than or equal to (<=): i <= 5
• Equal to (==): a == 1 Note this is different from the assignment = operator
• Not equal to (!=): 1 != 2
Compound assignment operators
• A compound assignment is as follows:
variable += expression
• This is short-hand for:
variable = variable + expression
• Also exists for other arithmetic operators: -=, *=, /=
Input / Output
CS 101, 2025
Recall code to draw a square
• Recall:
#include <simplecpp>
main_program {
turtleSim();
int nsides = 4;
repeat(nsides) {
forward(100);
right(90);
}
getClick();
}
• What if I want to
• ask the user for their choice of nsides?
• print that number to the screen?
Input/output: cin/cout operators
• Recall:
#include <simplecpp>
main_program {
turtleSim();
cout << "How many sides?";
Print "How many sides?"
to the screen int nsides;
cin >> nsides;
repeat(nsides) { Read from keyboard
forward(100); into the variables nsides
right(90);
}
getClick();
}
Input/output: cin/cout operators
• Standard input (cin) and output (cout) streams: Get input (from a keyboard) and
produce output (on screen)
• cout used with insertion operators <<
• Multiple insertion operations (<<) may be chained in a single statement...
•
cout << "How many sides " << "in the polygon?";
... also with variables to print out their values:
cout << "There are " << nsides << " in the polygon" << endl;
• Note: cout typically ends with an endl so that the statement appears in the order of execution
Input/output: cin/cout operators
• cin used with extraction operators >>
• Syntax:
int x;
cin >> x;
• Multiple extraction operations (>>) may be chained in a single statement...
•
cin >> a >> b;
• Any kind of space (space, tab, newline) can separate consecutive input operations
Coding Hygiene
CS 101, 2025
Comments
• Comments are very useful in helping the reader understand the code
• Single-line comments using //:
int n = 4; // n refers to the number of sides in a polygon
• Multi-line or block comments:
/* The code below computes the sum of n numbers
Input: Reads n numbers - i_1,i_2,...,i_n
Output: Prints out i_1 + i_2
*/
repeat(n) {
• Text between // and end of line, or between /* and */ is ignored by the compiler
Image from: https://xkcd.com/1513/
A few good coding styles/practices (e.g., [1])
• Common to use spaces and not tabs for indentation
• Use blank lines to separate sections within a le
• Choose one of the following styling of braces, and use consistently:
repeat(n)
repeat(n) {
{
body OR
body
}
}
• Variable names must be meaningful (as far as possible); multiple word variables typically
separated by "_" (e.g., light_on)
• Typically initialize (if at all) variables as part of de nition, and not as a separate statement.
That is, int i = 5; preferred over int i; i = 5;
• Or, ignore style guides and write obfuscated C code! [2]
[1] https://google.github.io/styleguide/cppguide.html
[2] https://www.ioccc.org/
fi
fi
Going from program statement to code
CS 101, 2025
Problem statements
Q. Write C++ code to calculate sin(x) using the Taylor series expansion (where x is in radians):
3 5 7
x x x
sin(x) = x − + − +…
3! 5! 7!
Ask for x (in degrees) from the user and use a xed number of terms. You can use PI
(offered by simplecpp) to access the value of π.
1 1 1 1
[Easier Q]. Write C++ code to calculate the following series: 1 − + − + − …
2 3 4 5
HW fi
Next class: Variables, Operators, Data types
CS 101, 2025