A simple view of code compilation [recap]

1. You type/edit/write/create source code (.cpp files, .h files)
2. The compiler takes your code (and additional code you supply), COMPILES [and links] everything into a single app/binary/runnable/executable/application/program/software
3.The user runs the app/binary/...
This is called the "edit-compile-run ..." cycle. Languages such as C++ and Java require compilation; others such as JavaScript and Python, do not [code in these languages is interpreted, rather than being compiled].
Variables, operators, expressions
These are the building blocks of programs - inside practically every program in every language, all the work gets done by variables (and 'objects') that hold data, operators that modify data, and expressions that aggregate operators.
IT IS ALL DATA MANIPULATION!
At the heart of EVERY useful program (in any language!) is ONE central idea: "data manipulation".
Data can be your bank account balance, a game character's weapons, a piece of music, an email text.. Manipulation can include arithmetic, geometric processing, searching, sorting..
In this class we look at basic data containers and simple manipulation.
Variables (containers)
In programs, data is held in entities called VARIABLES ('objects' are related entities, more on this much later).
A variable is simply a container/holder for a piece of data.
In the real world, there are many 'kinds' of objects (pencils, cars..) which take up different amounts of space. Likewise, in programs we represent different 'kinds' of data (whole numbers, string of letters..) that occupy different amounts of memory (space).
Variables are where/how data gets manipulated (changed). In a sense, programming is ALL ABOUT skillful manipulation of data.
In C/C++, we create a variable like so:
int i;
A variable is created by giving it a NAME ('i') and specifying its (data) TYPE ('int'). Always remember: you need name and type (typename followed by variablename).
Also, in C/C++, such variable "declarations" (where the variable is first named) end with a semi-colon (not so in Python, for example).
Our online coding environment
This is a small detour.. We are going to learn C++ by TYPING IN a lot of small, self-contained, fully working examples, into a code window that looks like this:

We'll use other (similar) coding enviroments in future classes.
Launch the online code environment ("oce" from now on) by clicking this link (it will open in a new tab). Clean out (select and delete) existing contents.
Copy and paste the following TINY C++ program into the oce, and click 'Run' - that will cause the code to be compiled and run:
// smallest possible valid C++ program!
int main(){}
The above shows a barebones C++ program, all 6 of its pieces are required: int main ( ) { }
Cool! Now we can practice creating variables..
Vars: creation
Run this (c&p) in the oce (empty it out first):
int main() {
int i; // a var called 'i', of type 'int'
}
Note that // signifies the START of a comment - the compiler will ignore (not process) comments; comments are for humans (yourself, your colleagues, others) to read.
The above program runs, but does nothing useful. A variable called 'i' gets created (capable of holding integers), and when the program is done running, 'i' gets destroyed (the memory it occupied is reclaimed by the OS).
Let us next create TWO vars, both int type, called i and j:
int main() {
int i;
int j;
}
Rather than type in two similar lines, we can use the 'comma' operator to do this instead why? Because programmers are [LAZY :)]:
int main() {
int i,j; // create i and j, of type 'int'
}
Types (TYPEs)
We learned that 'int' is a (data)type, for holding integers (usually -2,147,483,648 to 2,147,483,647). Likewise, 'float' is a type for creating "floating point" (decimal) holders:
int i;
// j can hold values between
// 1.175494351 E -38
// and 3.402823466 E +38.
float j;
// note the naming convention!
float roomTemp, tirePressure;
'Type' (aka datatype) is one of the BIGGEST concepts in coding!
Vars [cont'd]
What if we wanted to hold even bigger ints, even bigger floats? We need to use the long and double types respectively:
int main() {
int i,j;
float x,y,z;
long particleCount;
double jointAngle;
}
Exercise (informal): Google to find out the capacities (limits for long and double types).
We can also create vars of type boolean, where, such vars can only hold 'true' or 'false'.
int main() {
int maxLevels;
bool maxLevelReached;
}
Types, again
To repeat - TYPE is one of the most important concepts in programming. EVERY piece of data is of a certain TYPE. Types we have seen so far:
• int
• float
• long
• double
• bool
Later we'll see that WE CAN CREATE OUR OWN TYPES! Eg. there can be a BankAccount type, ToDoList type, scene type, vector type.. User-created types are called classes.
Values (contents of variables)
OK, so we can create vars of specific types (eg int i;). NOW WHAT? How to store a VALUE inside a var? Answer: just "assign" the value to the var!
int main() {
int i;
i = 2015;
}
The assignment operator (=) is what is used for assigning a VALUE (on the RHS of the = sign) into a var (on the LHS).
Assignment can be pictured like so:

Remember: receiving vars are ALWAYS on the left of =, literal values and value producers (expressions, and functions too) are ALWAYS on the right! In other words we can NEVER have 2015=i; for example.
Rather than declare a var and THEN assign a value into it in the very next line, we can do both in one step (laziness, again!):
int main() {
int i=52, j=6;
float pi=3.1415, e=2.718;
bool maxReached=false;
}
OK, so we know how to create vars of several types, and assign values into them. How can we MANIPULATE (change) the values in those vars?
Data manipulation
Easiest/only way to modify a var's value: just overwrite it!
int main() {
int i=12;
i = 13; // 13 OVERWRITES 12
}
Once 13 is stored in i, 12 is DISCARDED FOREVER (no backup, no undo!!!!!).
In real programs, we won't overwrite values explicitly, like we did above. Instead, we'd use vars on the RHS, and we'll use operators too.
In the following, the value of i is COPIED into j:
int main() {
int i=12, j=15;
i = j; // j's value is copied into i
}
When a var (eg j) appears on the RHS of the = sign, we use its value. THE VARIABLE STANDS FOR ("TURNS INTO") ITS VALUE!! This is a big, important idea..
In the above, it's not like we "transfer" j's value into i! j will still continue to contain 15 after the i=j; statement runs. A variable can NEVER be "emptied out".
String: another basic (and USEFUL) datatype
Before we go further, let us introduce another fundamental and important datatype, the 'string' type. A string type variable can hold strings, which are collections of letters and numbers. "USC", "Hello World", "firstWheel_Radius", "aVEryG00dPa$$Wo__rd" are all examples of strings, and can be stored in string-type vars:
#include <string>
int main() {
// create and initialize a string var called gr8Passwd
std::string gr8Passwd="aVEryG00dPa$$Wo__rd";
}
Note that the string type has to be "imported" (via #include), and referred to as std::string (instead of just 'string').
Simple output
So far we've created vars, and assigned values to them. How can we print out a var's content (its held value)? Answer: use 'cout':
#include <iostream>
int main() {
std::cout << "Hello!" << std::endl;
}
Using a string var:
#include <iostream>
#include <string>
int main() {
std::string greeting = "Hola!!";
std::cout << greeting << std::endl; // print var's val
}
Note: we've been using (and will continue to use) 'Courier', which is a "non-proportional" (fixed-width, monospace) typeface, for code.. Why?
Inputs from the user
#include <iostream>
using namespace std; // this lets us say cout instead of std::cout
int main() {
cout << "Enter a number: " << endl;
int n;
cin >> n; // RECEIVE from user, a value for (into) n
cout << "You entered: " << n << endl; // echo back to user
}// main()
cout (with << arrows pointing towards it) writes (prints) to the screen, ie. it generates output.
cin (with >> arrows pointing away from it) gets values from the user, and assigns them to variables, ie. it accepts input. This allows us to have the user provide values for vars.
Operators
We can perform math on numbers, using vars on the RHS of the = sign. Code on the RHS of = is called an expression. AN EXPRESSION PRODUCES A VALUE, WHICH GET ASSIGNED TO A VARIABLE - this is the essence of programming :)
#include <iostream>
#include <string>
int main() {
int numApples = 4, numOranges=12;
int numFruits = numApples + numOranges; // var's VALUES on the RHS
std::cout << "Total fruit count: " << numFruits << std::endl;
}
The + sign is an 'arithmetic' operator that does addition on ints, floats, doubles, longs. Likewise we have - (subtraction), * (multiplication), / (division).
Average of two numbers
Run this:
#include <iostream>
#include <string>
int main() {
int x=4, y=6;
int av = x+y/2;
std::cout << "Av: " << av << std::endl;
}
Oh no! 7 is NOT what we should have gotten. What happened was this: x+y/2 became x plus y/2, ie. 4 plus 3. In other words, y/2 "went first" (because / has a higher operator precedence than +). We needed x+y to happen first, THEN the division. How to force such an [or any] eval order?
Do this:
#include <iostream>
#include <string>
int main() {
int x=4, y=6;
int av = (x+y)/2;
std::cout << "Av: " << av << std::endl;
}
That worked: (x+y) makes the addition happen as intended, the / happens after the sum is computed.
Use parentheses whenever you want to specify the order of calculations - that is the way to override built-in operator precedence!
What about this:
#include <iostream>
#include <string>
int main() {
int x=5, y=6;
int av = (x+y)/2;
std::cout << "Av: " << av << std::endl;
}
Why does av not contain 5.5 (we see 5 being output)? Our first guess is this - we think it is because av is of type int, we need it to be a float instead (so that the 5.5 floating point result can be stored without getting truncated).
Let's try again, with a float av:
#include <iostream>
#include <string>
int main() {
int x=5, y=6;
float av = (x+y)/2; // will THIS work?
std::cout << "Av: " << av << std::endl;
}
We STILL get 5 instead of 5.5!! That is because (x+y)/2, even before it is assigned to 'av', works out to be 5. Why? Because / is dividing an int (11) by another int (2), THAT PRODUCES AN INT RESULT (5). 11/2=5. The / is operating in 'integer mode' (say this fast, 5 times :) : "int slash int results in int").
Our problem is that we are performing integer division - if the numerator and/or denomenator becomes a float, / will do the right thing (switch to float-mode division). There are at least two ways to achieve this (multiply by 1.0, "type cast" to float):
#include <iostream>
#include <string>
int main() {
int x=5, y=6;
float av1 = (1.0*(x+y)) / 2;
std::cout << "Av: " << av1 << std::endl;
float av2 = ((float)(x+y)) / 2;
std::cout << "Av again: " << av2 << std::endl;
}
Worked both ways!
modulus ("mod") operator
Another arithmetic operator is mod - it computes the remainder ("excess") of a division.
#include <iostream>
#include <string>
int main() {
int t = 15 % 12; // remove 12s from 15
std::cout << t << std::endl;
// the following will FAIL because % expects ints to operate on
float frac = 37.4053 % 1.0; // remove 1.0s
std::cout << frac << std::endl;
}
% only works on an int numerator and int denomenator.. So to get the equivalent of 37.4053%1.0, we need to do instead, 'fmod(37,4053, 1.0)' [where fmod() is a library FUNCTION].
#include <iostream>
#include <cmath> // for fmod and LOTS of other math functions
int main() {
int t = 15 % 12; // remove 12s from 15
std::cout << t << std::endl;
// use fmod(), not %, for modulus ops involving floats or doubles
float frac = fmod(37.4053,1.0); // NOT 37.4053 % 1.0;
std::cout << frac << std::endl;
}// main()
+=, -=, *=, /= (and %=)
These arithmetic operators offer more ways to be lazy!
#include <iostream>
#include <string>
int main() {
int frameNumber=25;
frameNumber = frameNumber + 2; // increment by 2
std::cout << frameNumber << std::endl;
frameNumber += 2; // increment by 2 again
std::cout << frameNumber << std::endl;
}
The rather dyslexic += operator means "increment by". -=, *= and /= behave similarly. And, there's also %=.
++, --
Ultimate laziness! Rather than say +=1 to increment by 1, we can just say ++ (likewise for --):
#include <iostream>
#include <string>
int main() {
int playerScore=300;
playerScore = playerScore+1; // noob!
std::cout << playerScore << std::endl;
playerScore += 1; // not bad..
std::cout << playerScore << std::endl;
playerScore++; // bingo!
std::cout << playerScore << std::endl;
}
playerScore++ does not even need the = assignment operator! In other words, the ++ does increment. We use this a LOT (eg. to step through a list of friends, players, grocery list items, cars..).
Comparison (relational) operators
These 6 operators COMPARE (they do not COMPUTE anything) two values, and result in a true ("yes") or false ("no") result:
==, !=, <, >, <=, >=.
Examples (don't run these - they are incomplete snippets):
5 == 6; // is 5 equal_to 6?
2 != 3; // is 2 not_equal_to 3?
4 < 5.8; // is 4 less_than 5.8?
9 > 4.5; // is 9 greater_than 4.5?
10 <= 10; // is 10 less_than_or_equal_to 10?
5 >= 12; // is 45 greater_than_or_equal_to 12?
In each case above, the result of the comparison is either true, or false.. AND NOTHING ELSE!
Run this:
#include <iostream>
#include <string>
int main() {
int score = 102;
int levelUp = (score > 100);
std::cout << levelUp << std::endl;
}
As you can see, we 'receive' (assign) the result of a comparison, to an 'int' variable. 'true' will result in a 1 being generated, and 'false' will result in a 0. C++ treats any positive number as 'true' and 0 as 'false'.
AND, OR, NOT: 'logical' operators
To round out our operators tour (for now), we look at && (AND), || (OR) and ! (NOT), which work with comparison operators (== != < <= > >=).
&& || ! also result in a true or false value.
&& considers two comparisons, and outputs 'true' ONLY IF BOTH comparisons are themselves true. Eg.
int validEdge = (x>5) && ((x+y)<20);
int greatMatch = lovesMusic && isNerdy;
|| considers two tests, and outputs 'true' IF EITHER test is true (or both tests are true).
int badPlayer = lowScore || slowResponses;
int possibleDonor = (income>1000000) || (ZIPCode == 90210);
The ! operator takes a single test and FLIPS (inverts) it:
int riskyLoan = !(creditScore > 700);
&& and || are 'binary' operators (they operate on two inputs), whereas ! is a 'unary' operator.
&& || ! (aka Boolean operators) have cool connections with mathematical set theory and with fundamental logic circuits :)
&& is equivalent to set intersection, and the 'AND' gate.
|| is equivalent to set union, and to the OR gate.
! is equivalent to set complement, and to the NOT gate.
Operators: summary
We looked at three groups of operators: arithmetic, comparison, logical. We SKIPPED "bitwise" operators <<, >>, ^, ~, & and |.
Operators form the bread and butter of computing. Without them, data would be perpetually stuck in variables and would never get manipulated (modified)!
Here is a page that discusses all the operators.
Expressions, statements
We noted earlier that on the LHS of a = is always a variable, eg.
x = 5 + y;
The piece of code on the RHS of a = is called an 'expression'. Eg in the above, 5+y is the expression.
An expression always gets evaluated to a result, ie. turns into a value (which can be assigned to the var on the LHS of the =).
(a*a + b*b) is another example of an expression.
The entire "line", LHS = RHS, is a 'statement'. Statements end with a semi-colon, in C/C++ (and Java, etc.).
Summary
In this lecture, we discussed:
• DATA
• types
• variables
• operators
• expressions, statements
Next time we'll look at control structures - how to LOOP, how to BRANCH.