0% found this document useful (0 votes)
11 views36 pages

Lecture7

This document provides an introduction to programming concepts in C++ compared to Python, highlighting differences in variable declaration, data types, and input/output operations. It covers basic programming constructs such as operators, if-statements, loops, and their syntax in C++. The document serves as a guide for transitioning from Python to C++ programming.

Uploaded by

ryyjyg9p2r
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views36 pages

Lecture7

This document provides an introduction to programming concepts in C++ compared to Python, highlighting differences in variable declaration, data types, and input/output operations. It covers basic programming constructs such as operators, if-statements, loops, and their syntax in C++. The document serves as a guide for transitioning from Python to C++ programming.

Uploaded by

ryyjyg9p2r
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Introduction to Algorithms &

Programming
Steve James
Lecture 7
Python to C++

RECAP
Summary so far
• C++ is compiled
– Python is interpreted
• C++ variables have fixed types (static)
– Python variables can change types (dynamic)
• Whitespace in C++ is not important
– Indentation is important in Python
• C++ starts executing code in the main function
– Python executes the first line of code it sees
Type Examples
Python
Values
Name Keyword Kind Example Literals Equivale
Allowed
nt
Boolean bool Built-in True or true, false bool
false
Character char Built-in A single ‘a’, ‘x’, ‘9’, ‘\n’ str
character
Integer int Built-in Integers 0, -1, 2145, 0xa3 int
(also within
short/long) some range
Floating- double Built-in Real-valued 1.2, -0.6, .3, .6F, float
point (also float) numbers 1.4e10
within
some range
and to
some
precision
String string Standard Sequence “SaltBae”, str
library of “Hello there\n”
characters
C++

VARIABLES
Declaration
• For variables, need type and name
– int x;
– double y; USE AT DECLARATION
– string someMeaningfulName; TIME ONLY

• “This thing exists here – make memory for it!”

• Uninitialised: unknown/undefined value


Initialisation
• Optional
• Assign value to variable at point of declaration
• “Here’s the initial value for this thing”
– int x = 42;
– double y = 2.45824406892
– string someMeaningfulName = “Pogba’s Haircuts”;
• Uses equal sign; LHS gets value of RHS
Assignment
• Set value of variable after
declaration/initialisation
• Use equal sign; LHS gets the value of RHS

– int x;
– x = 42;
– int y = 23;
– x = y;
Finally
• Must declare a variable before we use it

int x = y + 2; //WTF is y?!


int y = 20; //Too late! We needed it for the previous line

• Do not work with uninitialised variables

int y;
int x = y + 2; //y has an undefined value. What's undefined + 2?!
y = 20; //Too late! We needed it for the previous line
C++

BASIC INPUT/OUTPUT
Input/Output
• Consider code that inputs a user’s first name and then displays the user’s first
name with a message

//Program demonstrates how to input and output data


#include <iostream>
#include <string>

using namespace std;

int main(){
string firstName; //string variable declaration
cin >> firstName;
cout << "Hello, " << firstName << endl; //output message and name
return 0;
}

• Several literals/values can be output by a single statement


• We read into variable firstName of type string
– Reads until whitespace (e.g. space, newline, tab) is seen (i.e. a single word)
String Input
• Consider code that asks the user to input their first name and surname and then
displays the user’s full name with a message

#include <iostream>
#include <string>

using namespace std;

int main(){
string firstName;
string surname;
cout << "Please enter your first and surname" << endl;
cin >> firstName >> surname; //input first name and surname
string fullName = firstName + " " + surname; //concatenate strings
cout << "Hello, " << fullName << endl; //output message and name
return 0;
}
Integer Input
• Consider code that asks the user to input their first name and year of birth and
then displays the user’s first name and age

#include <iostream>
#include <string>

using namespace std;

int main(){
string firstName;
cout << "Please enter your first name" << endl;
cin >> firstName; //input first name
int yearOfBirth;
cout << "Please enter your year of birth" << endl;
cin >> yearOfBirth;
int age = 2018 - yearOfBirth;
cout << "Hello, " << firstName << endl; //output message and name
cout << "Your age is " << age << endl; //output message and age
return 0;
}
Integers and Strings
Integers Strings
• cin >> reads a number • cin >> reads a string
• cout << write • cout << write
• + adds • + concatenates
• - subtracts • - is an error
• … • …

The type of a variable determines which operations are valid and what their meanings are
for that type (“overloading” or “operator overloading”).
Aside: namespace
• A way to differentiate names of
variables/functions
• All functions provided by C++ lives in the standard
namespace (std)
– e.g. sqrt

• You can therefore create own sqrt function


whose name won’t conflict with std::sqrt
• By default, we will specify always using std
– Otherwise would have to write std::cout, std::cin, etc
C++

OPERATORS
Built-in Operators

Add/subtract
{
} Arithmetic

Input/output
{
} x += n is
shorthand
for
x=x+n

} Equalities/in-
equalities
Built-in Operators
bool x = true; //x assigned to true
string s = "Hello"; //s assigned to Hello
s = s + " world"; //s assigned to Hello world (concat)
int x = 5;
x++; //x now equals 6
int y = 7;
bool isEqual = (x == y);
int rem = y % x; //rem is the remainder of y divided by x
int number;
cin >> number; // read an integer into a number
cout << rem; //print out remainder
double z = y; //assign z the current value of y
z *= 3; //equivalent to z = z * 3;
More Built-in Operators
AND/OR Operators
• e.g. 10 ≤ 𝑥 ≤ 20 can be written as
10 <= x && x <=20

• Note that && and || are short-circuit


operators:
– If the answer can be proved after evaluating the
first condition, the second condition is not
evaluated!
Rules of Precedence
Precedence Operator/ Evaluation
Operation
Level Symbol Direction

0 (first) () parentheses Inner ones


evaluated first
Left-to-right
1 (unary) -, ! negation (unary Right-to-left
minus/NOT)
2 *, /, % product, division, modulus Left-to-right

3 +, - addition, subtraction Left-to-right

4 <=, <, >, >= less than or equal, less Left-to-right


than, greater than, greater
than or equal
5 ==, != equivalent to, not Left-to-right
equivalent to
6 && logical AND Left-to-right

7 || logical OR Left-to-right

8 = assignment Right-to-left
C++

IF-STATEMENTS
General Form
• Python
if <exp>:
# do something
else:
# do something else
Must have round brackets

• C++ Curly brackets, not colon


and indentation
if (<exp>){
// do something
}
else{
//do something else
}
The if/elif/else Construct
#include <iostream>
using namespace std;
grade = int(input()) int main(){
int grade;
if grade >= 75:
cin >> grade;
print("A") if (grade >= 75){
elif grade >= 70: cout << "A" << endl;
print("B") }
elif grade >= 60: else if (grade >= 70){
print("C") cout << "B" << endl;
elif grade >= 50: }
print("D") else if (grade >= 60){
cout << "C" << endl;
else:
}
print("F") else if (grade >= 50){
cout << "D" << endl;
}
else{
cout << "F" << endl;
}
return 0;
}
Nested if
num = int(input())
if num % 2 == 0:
if num % 3 == 0:
print("Div by 2 and 3")
else:
print("Div by 2; not by 3")
else:
if num % 3 == 0:
print ("Div by 3; not by 2")
else:
print ("Not div by 2 and 3")
#include <iostream>
using namespace std;
int main(){
int num;
cin >> num;
if (num % 2 == 0){
if (num % 3 == 0){
cout << "Div by 2 and 3" << endl;
}
else{
cout << "Div by 2; not by 3" << endl;
}
}
else{
if (num % 3 == 0){
cout << "Div by 3; not by 2" << endl;
}
else{
cout << "Not div by 2 and 3" << endl;
}
}
return 0;
}
Related: Switch-case
• Switch statement
– Shortcut for doing if statements checking possible
constant values (e.g. days of week, etc)

• Please look up here:


– http://www.cplusplus.com/doc/tutorial/control/
– (last section)
C++

LOOPS
While Loop General Form
• Python
while <exp>:
# statement 1
# statement 2

• C++ Must have round brackets Curly brackets, not colon


and indentation

while (<exp>){
// statement 1
// statement 2
}
While Loops
#include <iostream>
using namespace std;
int main(){
int passes = 0;
passes = 0 int fails = 0;
failures = 0 int n_students = 0;
n_students = 0 int mark;
while n_students < 10: while (n_students < 10){
mark = int(input()) cin >> mark;
if mark >= 50: if (mark >= 50){
passes = passes + 1 passes = passes + 1;
else: }
failures = failures + 1 else{
n_students = n_students + 1 fails = fails + 1;
print("Passes", passes) }
print("Failures", failures) n_students = n_students + 1;
}
cout << "Passes " << passes << endl;
cout << "Fails " << fails << endl;
return 0;
}
For Loop General Form
• Python
for i in range(start, stop, step):
# statement 1
# statement 2

• C++ Initialisation Termination Update

for (int i = start; i < stop; i = i + step){


// statement 1
// statement 2
}
for (<exp_1>; <exp_2>; <exp_3>){
// loop body
}

• <exp_1> initialises control variable


• <exp_2> is termination condition
• <exp_3> changes control variable
– executed after loop body
• All expressions are optional
– if <exp_2> not provided, we always enter the
loop body
• Semicolons are NOT optional
For Loops
#include <iostream>
using namespace std;
int main(){
int passes = 0;
passes = 0 int fails = 0;
failures = 0 int mark;
for n in range(10): for (int n = 0; n < 10; ++n){
mark = int(input()) cin >> mark;
if mark >= 50: if (mark >= 50){
passes = passes + 1 passes = passes + 1;
else: }
failures = failures + 1 else{
print("Passes", passes) fails = fails + 1;
print("Failures", failures) }
}
cout << "Passes " << passes << endl;
cout << "Fails " << fails << endl;
return 0;
}
Break/Continue
• Break and continue statements
– Exactly the same as Python!

for (int i = 3; i < 20; ++i){


for i in range(3, 20): if (i == 7){
if i == 7: continue;
continue }
print(i) cout << i << endl;
}
Do/while loop

For
goto While
loop loop
Do/While Loop
• First execute the loop body, then check the
condition!

do{
while (<exp>){
//statement 1
// statement 1
//statement 2
// statement 2
}
}
while(<exp>);

Semicolon!

You might also like