SUPA Graduate C++ Course: University of Glasgow
SUPA Graduate C++ Course: University of Glasgow
Lecture 1
Sarah Boutle
University of Glasgow
Introduction
• There are 4 lectures
• This is a practical subject, you cannot learn C++ by attending
these 4 lectures
• Starts for complete beginners and gets far in 4 hours
• You need to put some work in yourselves:
• 4 assignments, hand in the assignments to get the credits for
this course
• Try things out yourself, it's the only way to learn to code
• google is your friend
• Labs:
• Monday afternoons, 2-5pm starting 24th November
• Room 220a, Kelvin Building, University of Glasgow
• Can be used to get help for the assignments, but not
compulsory
• Please indicate if you intend to come in person
3
Programming Methodology
Form a plan of the program needed before writing any C++.
– Use a flowchart or pseudo-code http://en.wikipedia.org/wiki/Flow_chart
http://en.wikipedia.org/wiki/Pseudocode
– Think through the implementation
A little planning at the beginning can save a lot of time later on.
– This is especially true of Object Orientated languages
1. Requirements
2. Design
3. Implementation
4. Testing
5. Documentation
5
./HelloWorld
Notes on Compiling
g++ -o Helloworld HelloWorld.cc
g++ -c HelloWorld.cc
int main(){
}
9
#include <iostream>
int main(){
}
13
int i;
Naming tips:
1. Variable names must start with a letter or a _
2. C++ is case sensitive
3. Try to use meaningful variable names
4. Some keywords are reserved: http://en.cppreference.com/w/cpp/keyword
5. Suggest lowerCamelCase
15
int i; //declaration
i=3; //assignment
assignment operator
16
Data types
Data values can be stored in variables of several types
C++ has some predefined types:
Basic integer:
int (also short, unsigned, long int)
Basic floating point types: i.e. for real numbers,
float (32 bits), double (64 bits), ...
Boolean:
bool ( equal to true or false)
Character:
char (single ASCII character only, can be blank), no native string
17
}
18
Constant Variables
Ensure the value of a variable doesn't change
e.g. useful for keeping parameters of a problem in an easy to define
place, where they are easier to modify
Use keyword const in declaration:
Mathematical operators/expressions
1. C++ has obvious notation for
operation symbol mathematical expressions
2. Other basic mathematical functions can
addition +
be found in <cmath> and <math.h>
subtraction - 3. * and / have precedence over + and -, *
and / have same precedence, carry out
multiplication * left to right. If in doubt use parentheses!
Boolean Operators/Expressions
• Logic operators are used for operator meaning
comparing 2 expressions or
variables > greater than
! (not) == equal to
Shorthand assignment
n = n + m n += m
n = n - m n -= m
n = n * m n *= m
n = n / m n /= m
n = n % m n %= m
n = n + 1
n = n - 1
n++
n = n - 1
++n
Example
#include <iostream>
int main() {
int myNum = 3;
int j = myNum++;
return 0;
Conditions
Simple flow control is done with if and else:
if ( boolean test expression ){
Statements executed if test expression true
}
or
if (expression1 ){
Statements executed if expression1 true
}
else if ( expression2 ) {
Statements executed if expression1 false and expression2 true
}
else {
Statements executed if both expression1 and expression2 are false
}
int num = 1;
if(num) {
......
int num = 1;
if(num != 0) {
......
26
Loops
A while loop allows a set of while( boolean expression ){
statements to be repeated // statements to be executed as long as
as long as a particular // boolean expression is true
}
condition is true
do {
A do-while loop is similar // statements to be executed first time
but always executes at lease // through loop and then as long as
once // boolean expression is true
} while ( boolean expression )
Loops
For a while loop to be while (x < xMax){
useful, the boolean x += y;
expression must be updated ...
}
each pass through the loop
int sum = 0;
A for loop note that i will for (int i = 1; i<=n; i++){
only be defined inside the {} sum += i;
}
28
while ( processEvent ) {
Scope
The scope of a variable is that region of the program in which it can be used.
If a block of code is enclosed in braces { }, then this delimits the scope for
variables declared inside the braces.
This includes braces used for loops and if structures:
int x = 5;
for (int i=0; i<n; i++){
int y = i + 3;
x = x + y;
}
cout << "x = " << x << endl; // OK
cout << "y = " << y << endl; // BUG -- y out of scope
cout << "i = " << i << endl; // BUG -- i out of scope
Variables declared outside any function, including main, have ‘global scope’.
They can be used anywhere in the program.
30
Functions
Until now we have seen the main function as well as mathematical functions.
We, the user, can also define functions
return type
function name
type of parameter to be passed to it
int main() {
int myNum = 3;
…
int myNumCubed = cubeNumber(myNum);
cout << “The cube of “ << myNum << “ is “ << myNumCubed <<endl;
return 0;
}
int cubeNumber(int);
To call a function with return type void, we simply write its name with
any arguments followed by a semicolon:
showProduct(3, 7);
33
Functions
• Now we can ‘call’ cubeNumber whenever we need the area of an
ellipse; this is modular programming.
• The user doesn’t need to know about the internal workings of the
function, only that it returns the right result.
• A well written function can be re-used in other parts of the program and
in other programs.
#ifndef CUBE_NUMBER_H
#define CUBE_NUMBER_H
int cubeNumber(int);
#endif
The directives #ifndef (if not defined), etc., serve to ensure that the
prototype is not included multiple times. If ELLIPSE_AREA_H is
already defined, the declaration is skipped.
35
#include <iostream>
#include "cubeNumber.h"
int main() {
int myNum = 3;
…
int myNumCubed = cubeNumber(myNum);
cout << “The cube of “ << myNum << “ is “ << myNumCubed <<endl;
return 0;
}
The directives #ifndef (if not defined), etc., serve to ensure that the
prototype is not included multiple times. If ELLIPSE_AREA_H is
already defined, the declaration is skipped.
36
void tryToChangeArg(int x) {
x = 2*x;
}
It won't work:
int x = 1;
tryToChangeArg(x);
cout << "now x = " << x << endl; // x still = 1
This is because the argument is passed ‘by value’: only a copy of the
value of x is passed to the function.
In general this is a Good Thing: don’t want arguments of functions to
have their values changed unexpectedly.
37
int main(){
int x = 1;
tryToChangeArg(x);
cout << "now x = " << x << endl; // now x = 2
}
Functions: Overloading
We can define versions of a function with different numbers or types
of arguments (signatures). This is called function overloading:
double cubeNumber(double);
double cubeNumber (double x){
return x*x*x;
}
double cubeNumber(float);
double cubeNumber (float x){
double xd = static_cast<double>(x);
return xd*xd*xd;
}
Functions: Overloading
When we call the function, the compiler looks at the signature of the
arguments passed and figures out which version to use:
float x;
double y;
double z = cubeNumber(x); // calls cubeNumber(float) version
double z = cubeNumber(y); // calls cubeNumber(double) version
Streams
Read/Write to File
Simple example that opens and existing file to read data from it:
#include <iostream>
#include <fstream>
#include <cstdlib>
int main(){
// create an ifstream object (name arbitrary)...
ifstream myInput;
// Now open an existing file...
myInput.open("myDataFile.txt");
// check that operation worked...
if ( myInput.fail() ) {
cout << "Sorry, couldn’t open file" << endl;
exit(1); // from cstdlib
}
...
43
double x, y, z;
for(int i=1; i<=numLines; i++){
myInput >> x >> y >> z;
cout << "Read " << x << " " << y << " " << z << endl;
}
This loop requires that we know the number of lines in the file
44
double x, y, z;
int line = 0;
while ( !myInput.eof() ){
myInput >> x >> y >> z;
if ( !myInput.eof() ) {
line++;
cout << x << " " << y << " " << z << endl;
}
}
cout << lines << " lines read from file" << endl;
...
myInput.close(); // close when finished
45
Review
● Introduction
– Foreword
– Programming Methodology
● Basic C/C++ Syntax
– Simple types and operators
– Conditional Statements
– Loops
– Functions
– Header files
– File input
46
Assignment 1
1. Exercise: Read the file input2D_float.txt and for each line print the value from the first column (x
value) and second column (y value). Asumming these are x and y components of a 2-D vector,
compute the absolute value of the vector. Write to a new file called output2D_float.txt for each entry of
the initial file three columns, the first two being the already had x and y, while the third one is the newly
computed absolute value.
Notions you will learn: reading from a file, writing to a file, building a function called absolute value
taking as inputs two values, each of the type float; how to use mathematical functions as square root
and power two.
2. The same as in one, except use the input file input3D_float.txt, which has three values, the
coordinates x, y, z.
Notions you will learn: Though you can build another function with another name,les you can and it is
best practice to do so build another function with the same name (something like absolute_value),
which takes this time three arguments. The fact that you are allowed to have functions with the same
name while the compiler knows they are different because they have different input arguments is called
overloading. Here we are doing function overloading.
47
Assignment 1
3. The same as in 1, except instead of using decimal numbers of type float, use integer numbers of
type unsigned. Use input2D_int.txt and input3D_int.txt.
Notions you will learn: Though you all you need is to copy paste the code from above, and replace float
with int, it is both tedious and a bad software practice. What happens if you found a bug in one
function? Then you would have to modify in the other one, too. But maybe you forget to do so. You can
and it is a good practice to do so, to build a function that can take as arguments either one type of
variable (float), or the other (int). This is called templating. Here we are doing function templating.
4. Now we want to do the same thing for one of the input files, but instead of looping over all the four
lines in the file, we want the user to give it from a command line argument the choice to use only a
certain amount of lines, for example 2. If the user gives a number of lines smaller than 0, then the
program should print an error text and then close. If the user gives a number larger than the number of
lines, it should print a warning and not crash, but simply go through all the lines and end and just
before the end print a warning.
Notions you learn from this: how to pass command line arguments.