You are on page 1of 41

CO1401

Programming

Week 1
Module Introduction
Module Overview

• A second semester module


– Includes the first two weeks after Easter
• One hour lecture and two hour lab each week
– Drop in support sessions available every week.

• Second lecture with Laurent.

• Introduction to C++
• More advanced programming concepts

2 Programming
Module Overview

• Assessments
• An assignment to do in your own time
• Handed out during week beginning of February
• Hand back middle of March

• Module tutor
– Gareth Bellaby, CM232, gjbellaby@uclan.ac.uk

3 Programming
Module Overview

• Module resources (lectures, lab material) are all held


on eLearn. There will be some updates.
• Programming is a practical subject.
• You can only learn to program by doing!
• It can't be learnt by just attending lectures or reading
notes.
• You need to practice if you want to learn to program!
• Reminder: attendance at all labs / lectures is
compulsory

4 Programming
Speed and Feedback

• You are from a range of backgrounds.


• You are studying different computing degrees.
• I need to monitor the speed of the module.
• Ask questions in the lecture.
• Ask questions in the lab.
• Let me or the lab tutor know if the module is going
too slow or too fast.

5 Programming
Recommended books

• Harvey Deitel, Paul Deitel, C++ How to Program


• Siddhartha Rao, Sams Teach Yourself C++ in One Hour
a Day
• Jesse Liberty, Rogers Cadenhead, Sams Teach Yourself
C++ in 24 Hours.
• Walter Savitch, Absolute C++.
• Walter Savitch, Problem Solving with C.
• Stanley B Lippman, Josee Lajoie, Barbara E Moo, C++
Primer

6 Programming
Recommended websites

• http://www.cplusplus.com/
• https://stackoverflow.com
• Note use of voting system to indicate worthiness of an
answer
• https://www.hackerrank.com/domains/algorithms/war
mup
• Interface is a bit clumsy.
• Compiler is less informative than VS (but can can
code in VS and copy over)
• https://www.lynda.com/
• https://isocpp.org/faq

7 Programming
C++

• Using C++
• C++ is an important programming language.
• Widely used.
• Efficient, flexible and reasonably comprehensible.
• C++ can be faster than C# because it is translated to
machine code.
• C++ allows access to low level operations.

8 Programming
C and C++

• C was invented by Dennis Ritchie in the 1970's.


• In 1983 a committee was established to create a
defining standard: the ANSI/ISO standard.
• C++ is an expanded version of C. Invented by Bjarne
Stroustrup in 1979. C++ is an Object Oriented
Language.

9 Programming
• C# is a part-compiled language
• C++ is a fully compiled language
• Uses a compiler to convert C++ code into machine
language
• Work of translation done at compile time.
• The compiler translates our C++ programs into
executable programs
• The compiled program can be run without reference
to the original source code or compiler. It's a stand-
alone program.

10 Programming
Mechanics of C++

source code

COMPILER

object code

library
LINKER
code

executable code
11 Programming
C++

• Much of C++ is identical to C#

for (int i=0; i<100; i++)

• That example code is valid (and means the same) in:


• C++ and C# (and Java, Javascript, Actionscript, Lua,
etc…)
• Continue to use Visual Studio 2017 to compile C++
• Need to change the default environment to C++.
Details in worksheet

12 Programming
• An example C++ program
#include <iostream>
using namespace std;

// A simple hello world program


int main()
{
// Output to screen
cout << “Hello World!”;
}
13 Programming
Anatomy of C++

• All C++ programs must include the function main().


• Program execution begins with main().
• By convention main() appears at the end of the source
code.
• Note that main() starts with a lower case ‘m’

14 Programming
• Most of the functionality of C++ comes from the use
of libraries.
• For example, to obtain the input and output
commands you need to include the “iostream” library.
#include <iostream>
using namespace std;
• C++ also uses namespaces.
• This is a way of expressing scope.
• I’ll come back to this. For the moment just remember
to include the namespace statement after including the
libraries.
15 Programming
Variables

• C++ uses a number of different data types:


• floating point- a decimal number
float mynumber;
• integer, a whole number
int another_number;
• a single character
char ch;
• Assigning a value to a variable is identical to C#
• Do not have the methods such as TryParse

16 Programming
Conditionals and Loops

• Can use if, if – else, switch


• Can use for, while, do – while
• Arrays look similar, but a slightly different syntax and
meaning. I’ll come back to these in a later lecture.

17 Programming
Topic 2

Input, Output and streams

18 Programming
Cin and Cout

• cin and cout are your input and output statements.


• The direction of the angle brackets is important.
#include <iostream>
using namespace std;

int main()
{
int i;
cout << "enter a number";
cout << endl;
cin >> i;
cout << "The number you entered was " << i;
system( "pause" );
}
19 Programming
Comments

• Pause is non-standard, but allows you to pause the


end of the program easily.
system( "pause" );

• C++ uses libraries of pre-written functions and classses.


• In the above example “iostream” is a library.
• The function cout can be found inside iostream.

#include <iostream>
using namespace std;

20 Programming
cin & cout

• cin is for input

int size;
cin >> size;
// into the variable

• cout is for output

int size;
cout << size;
// out of the variable

21 Programming
Input

• Input is directed into a variable.


• cin automatically tries to convert keyboard input into
the data type of the variable.
• For example

int size;
cin >> size;

• cin will assume here that the data coming from the
keyboard is an integer.

22 Programming
Streams

• C++ uses the metaphor of streams.

cin cout

• Other streams exist, e.g. files i/o is treated as


streams.

23 Programming
The input stream

• cin reads until it #include <iostream>


#include <string>
reaches a carriage using namespace std;

return or a space. int main()


{
string str;
cin >> str;
cout << str;
system( "pause" );
}

• If you entered the phrase "once upon a time" at


the keyboard then it would only read in the word
"once“. You need another read in order to get the
rest of the phrase.
24 Programming
Validating input

•No access to the parsing and checking routines of C#.


However, can validate data type.
•The check on the input stream will work with any data type.

int i;
float f;
char ch;
cin >> i >> f >> ch;
if(cin.fail())
{
cout << "an error has occurred";
}

25 Programming
Flags

• Can be useful to set up your flag and then use it to


monitor all of the different aspects of the input.

bool error = false;


cin >> a >> b >> ch;
error = cin.fail();

if(ch != 'y')
{
error = true;
}

26 Programming
Validating input

• If a read failure occurs then the input stream is set to


0, i.e. false.
• Each successive read will fail unless you clear the fail
flag.
• (You will be able to use this same method with files!)
• If an error occurs need to clear the fail flag using
clear().
if(cin.fail())
{
cout << "Error\n";
cin.clear();
}

27 Programming
get: reading a single character

• It can be useful to for input to be read


character by character. In this case use get:

char ch;
ch = cin.get();

28 Programming
Topic 2

Functions

29 Programming
Functions

• You have used methods in C#.


• C++ also has methods. They are part of the object
oriented aspect of C++.
• They are declared inside a class in the same way as in
C#.

• However, C++ also has functions.


• Functions are like stand-alone methods. They are
declared outside main() and outside any classes (if
there are any).

30 Programming
Functions

• Do not use the #include <iostream>


using namespace std;
keyword static.
• Use parameters (as // function outputs double the size
// of the integer sent to it
C#) void doubleSize( int i )
• Can return a value {
cout << i * 2;
or need the cout << endl;
keyword void if }
they do not return
int main()
a value (as C#) {
doubleSize( 2 );
system( "pause" );
}
31 Programming
Functions

• Functions are building blocks.


• They break programs down into smaller units.
• When a function is invoked then execution passes
over to the function.
• When the function finishes then execution passes
back to the line of code that invoked the function.
• A function can be considered to be a mini-program in
its own right.

32 Programming
Examples

• skipthree(). Write threes lines to screen.

void skipthree( )
{
cout << endl << endl << endl;
}

int main( )
{
skipthree();
system( "pause" );
}

33 Programming
Functions

• main() is itself a function.

• main() is the first function executed by the program. All


other functions follow on from main().

• Often written so that main() appears first in the code.


I’ll come back to this later on.

• The compiler needs to know about a function before it


can use it. What if a function is written after it is called?

34 Programming
Parameters

• Functions with no parameters are of limited use.


Usually they will not return a value but carry out some
operation.
• For example, it would be better if skipthree could skip
a variable number of lines.

35 Programming
Parameters

• Functions can be void skip( int amount )


customised using {
parameters. for( int i = 0; i < amount
{
• The function cout << endl;
skipthree() is now }
changed to the }
function skip() that
has a parameter int main( )
{
amount indicating skip( 4 );
how many lines system( "pause" );
have to be skipped. }

36 Programming
Reasons to use functions.

• Decomposition: sub-problems

• Modularisation

• Repetition

• Code re-use

37 Programming
Decomposition: Sub-problems

• Problems naturally break down into sub-problems.

• Top-down design.

• A large problem is broken down into sub-problems.

• Each sub-problem could be a mini-program in its own


right.

38 Programming
Modularisation

• Real world software is written by teams.

• Functions allow modularization.

• This supports team work because a module can be written


by one team.

• Error checking.

• Functions can accept parameters to customise each usage.

39 Programming
Repetition

• Functions allow code to be written once but used


many times in the same program.

• Functions help the programmer to avoid repetition.

• Functions can accept parameters to customise each


usage.

40 Programming
• A solution may be useful in more than one program.

• Frequently occurring units can be turned into


functions and re-used in different programs.

• For example, max() is a solution to a common


problem.

• Functions can also be used to build up libraries.

41 Programming

You might also like