Semester Recap
We’ve Discussed…
• Background knowledge
• Data and calculation
• Input
• Output
• Control
Background Knowledge
• Operating System
• The layer that lies between software applications and hardware
• Executes programs and operate hardware
• Compiler
• A program that translate code to executable machine code
• C++ standard framework
• import libraries necessary
• main function as entry point
OS and Linux
• Provide access to file system
• Able to run programs such as text editor, terminal and text editor
• Terminal: provides command- line interface to operate OS
Keyword - Compiler
• Despite all the work, for OS the text files are just text files
• We need to use the compiler program to translate the C++
code into machine code - a language OS can understand and execute (but of course, not human readable)
Keyword - include & using
• “Libraries” are toolkits other programmers developed and provides us to use, we just
need to tell the computer that we are going to use them
• #include <iostream> tells the computer that we are going to use the library called
‘iostream’
• using namespace std; tells the computer we are
specifically using the section
‘std’
Keyword - function
• The main function is the
special function that marks
the entry point of the program you wrote; there must be one and only one main function
• In this case, the main function (which is also a function)
takes no input and returns a number 0
Keyword - statement
• Rules #1: C++ codes execute line by line, called statements, where each line ends with an semicolon ;
• Rules #2: Keywords, words and values are separated by spaces
• cout is the output method we learned from the iostream library, as well as endl which marks the end of output
• “Hello world!” is the content I wrote to let the program feed to cout for output
• The ‘<<‘ arrow sign is a special
operator used by cout to take inputs;
you’ll see more next week.
• The statement then ends with a semicolon
Declare and Initialization
• Unlike writing down formulas on papers, we have to let the computer know what variables we are going to use
• Declare a variable
• <datatype> <variablename> ;
• int myAge;
• Initialize a variable whilst assigning a value
• <datatype> <variablename> = <value>;
• int myAge = 18;
• Initialize upon declaration is preferred, although not mandatory
• You can only use predefined data types
• (Although you can invent your own data type, we will talk about that later in the semester)
Update Variables
• Use ‘=‘ : assign right hand side value to left hand side variable
• myWeight = 180;
• score = ( midterm + final ) / 2;
• age = age + 1; <— Yes it is legal in C++!
• Variable will keep the latest update value
• Data types must match so that correct operation can be performed
• (More on data types later)
• Of course, you have to declare the variables before you use them
Data - Declare a Variable
• Common types of variables
• int - integer numbers
• float/double - numbers contains fractional part
• char - one single character
• string - multiple characters
• bool - Boolean variable that is either true or false
• Only declare a variable once!
• Correct syntax
int x;
int x = 0;
// Can Only declare same variable once!
• Wrong syntax
int x x;
Data - Use a Variable
• Use +, -, *, / for to calculate
• Use = to assign / update value
• Use ; to end the statement
• Correct syntax
int x = a + b;
x = a * b;
• Wrong syntax
a + b;
x = a + b
Assignment Operator
• =
• means apply RHS value to LHS variable
• Variables only remember the
latest value assigned to them, e.g.
int x = 20; // assign 20 to x x = y + z; // assign y+z to x x = 50; // assign 50 to x
After the last statement, when you use variable x in evaluation, integer value of 50 will be applied.
Arithmetic Operators
• + : addition ⇨ x = 1 + 2 ;
• ++ : LHS variable +1 ⇨ x++ ; ( This means x = x + 1 )
• - : subtraction ⇨ y = 3 - 2 ;
• -- : LHS variable - 1 ⇨ y-- ; ( This means y = y - 1)
• * : multiplication ⇨ a = 6 * 5 ;
• / : division ⇨ b = 6 / 5 ;
• % : modulo, calculate remainder ⇨ c = 6 % 5 ;
• (Some more if you get more advanced)
Comparison Operators
• In addition to arithmetic operators and assignment operator
• Including ==, !=, >, >=, <, <=
• Result is boolean True/False, evaluated from combine logic with LHS and RHS
• More to come later!
Logical Operators
• Provides better flexibility to Boolean logic
• AND - &&
• is true only if both RHS and LHS evaluated to true
• OR - ||
• is true if one of RHS/LHS
conditions evaluated to true, or both are true
• NOT - !
• is false if RHS is true, is true if RHS is false
• Let’s take a look at examples of them
Input
• cin - take input from keyboard
• variable - replace the value with keyboard input
referred by the variable name
• >> - connected by rightward arrow
• end the statement with ;
• Correct syntax
cin >> x;
• Wrong syntax
cin >> “x”;
cin >> x >> endl;
cin x;
cin >> x
Output
• cout - output onto screen
• "…" - output the exact word inside double quote
• variable - output the variable value referred by the variable name
• endl - end current and start a new line
• << - different words/variables should be connected by
leftward arrow
• end the statement with ;
• Correct syntax
cout << “Example one”;
cout << variable << endl;
cout << x+y << endl;
cout << “output:” << variable;
• Wrong syntax
cout << Example one;
cout << "x";
// only print "x", not value of x cout variable;
cout ; variable;
cout << “output:” << endl
Control Flow
• Use another type, bool, for logic operation
• Can use variable to get bool value, e.g. compare values
• Statements included in the
following code block (wrapped up by { } ) will execute when
condition applies
• Use if…else to do certain things under certain conditions
• Use while-loop and for-loop to do things repeatedly under certain conditions
• Correct syntax
if(x > 10 && x > 0){}
if(x != 10) {}
while( a>0 ) {}
for(int x=0; x<10; x++){}
• Wrong syntax
if(x > 10; x > 0;) {}
for(int x=0){}
If - Else Statement
• Execute the code block if the IF condition evaluates to true
• Otherwise execute the ELSE code block
• Let’s take a look at an example
if(*condition*) {
/* Execute this code block if condition evaluates to true */
}
else {
/* Execute this code block if condition is false */
}
If…Else If…Else…
• Execute the code block if the IF condition evaluates to true
• Apply an addition filter each time an 'else if' is used.
• Otherwise execute the ELSE code block
if(*condition A*)
{
// if condition A is true }
else if ( *condition B*)
{
// if condition B is true }
else
{
// all the remain possibilities }
While Loop
• No start condition and iteration statement, just condition
• Means “While condition is true, execute the code”
• End condition better be
achievable, otherwise you will be stuck in the limbo
while(*condition*) {
/* Execute this code block repeatedly until condition is false */
}
For Loop
• A for-loop has the following structure:
• A starting statement that is usually used to initialize a progress counter
• Condition that if evaluates to true, execute the following code block (same as while); end condition should be something you can reach later, otherwise you will be stuck in a infinite loop
• 'Iteration statement' will be
executed once at the end of every cycle; it is usually used to move forward the progress counter
for(
*starting statement*;
*condition*;
*iteration statement)
{
// Execute this code block repeatedly
}
More C++ Gimmicks
•
Comment makes the line(s) visible to only you, and
ignored by the compiler. Note this might create some
bug if you accidentally comment out necessary
statements!
int x = 20; // This comments everything until end of line
/* These comment out everything in between,
Even multiple lines */
More C++ Gimmicks
•
Combine calculation and assignment: +=, -=, *= and /=
x += 10; // is the same as x = x + 10;
y *= x; // is the same as y = y * x;
For Loop <—> While Loop
for(int i = 0; i < 5; i++) {
cout << "i=" << i << endl;
} int i = 0;
while(i < 5) {
cout << "i=" << i << endl;
i++;
}