Computer Programming: Introduction To The Course and C++
Computer Programming: Introduction To The Course and C++
Computer Programming: Introduction To The Course and C++
• Personnel
– lectures: Prof. Dr. Mohammad Haseeb Zafar
– labs: Engr. Muhammad Farooq
Course format
• A weekly lecture introducing programming concepts and
examples
• From week 2, a weekly lab to practise the new ideas
– Practice of the ideas will be essential to learning enough
to pass the course
– You should complete the exercise in the lab
• People who fail to complete the labs tend to fail the course
• Don’t fall behind!
• Do not assume the lab is effectively free time
• You will not be able to simply copy and paste from the
lectures!
– You need to use the idea from the lecture
– Copying and pasting is the enemy of understanding…
Recommended resources
• Books
– “C++ How to Program” by Deitel & Deitel
– “C++ programming in easy steps” by Mike McGrath
– “Thinking in C++” by Bruce Eckel available at
http://mindview.net/Books/TICPP/ThinkingInCPP2e.html#
Contents
– For the advanced programmer: “The C++ Programming
Language” by Bjarne Stroustrup, published by Addison
Wesley
• Web resources
– http://www.cplusplus.com/
– Stroustrup’s website:
http://www.research.att.com/~bs/C++.html
Course Material & Assessment
Course Material:
• Link to access course material: https://www.dropbox.com/
• Email: [email protected]; password: plusplus
Assessment:
• Sessionals: 25%
• Mid Term Exam: 25%
• Final Term Exam: 50%
Course content
• Introduction to the course, C++ and the IDE
• Data types and operators
• Functions
• Conditions (if…)
• Iteration (for loops, etc.)
• Strings
• Arrays
• Pointers
• Structures
• Classes and objects
Why learn to program?
• You are likely to have to write some code some time
– to do accurate calculations quickly and repeatably
– to modify existing programs to reflect changed needs
– for processing of large amounts of data
• format changes, extraction of key information, …
– for actions on a programmable device
– to do your FYP
– to learn about algorithms and how to solve problems
Why learn C++?
• It is sort of an extension of C
– Lots of old code is in C – don’t want to throw it away!
• Lots of professional software is written in C++
– games
– engineering and statistical software
– database managers
– operating systems
– word processors
– spreadsheets
– embedded systems
• It affords use of object orientation
Object orientation and C++
• C++ is an extension of C invented in the 1980s by Bjarne
Stroustrup of AT&T Bell Labs (no relation)
– It was originally ‘C with classes’, i.e. an attempt to enable
decent object orientation in C
– C was used as the ‘base language’ as (according to
Stroustrup)
• it is versatile, terse and relatively low level
• is adequate for most tasks
• is widely available and use
– C is retained as a subset of C++ to avoid the need for
millions of lines of code to be re-written
• Stroustrup and his friends took the opportunity to add a few
useful extra features (see later)
The inventor of C++
Not a typical
computer
nerd?
http://www.research.att.com/~bs/
Why use C++ rather than Java?
• C++ can re-use old C code
• Use of executables created using C++ do not depend on
‘virtual machines’ to run
• C++ is stable
– There is an international standard for C++
– Java is changing all the time so code might not work
everywhere
• Because C and C++ get quite close to the operating system,
code tends to be efficient and to run fast
• Lots of professional software is written using C++
– games, embedded systems, etc.
What is software?
• Generally means anything relating to a computer that is not
hardware
– Term first used by John Tukey – a Princeton statistician –
in 1958
– Separation – as articulated by Turing – of a single
physical machine from the different programmable tasks
that it can perform
• If the single machine to do what you want doesn’t exist, use a
computer and program it
– To be able to write software is useful even when using
software!
• A program doesn’t do quite what you need: create your own
• A program that you need to use laboriously and repeatedly: write
your own to perform the repeated operations
Algorithms and problem solving
• In essence, computer programs are solutions to problems
– What is the critical clearing time for a three-phase short-
circuit fault?
– What is average delay of a message on a given comms
network?
– What is the way of simulating a game of tennis?
• Problem solving is a key activity
– the process of taking a statement of a problem and
developing a computer program that solves it
• A solution consists of
1. an algorithm
2. a way to store data
What is a program?
• A program might be thought of simply as a solution to a
computation problem
– The solution will involve a sequence of instructions
• Some of these may be conditional on values of data
• In the early days of programming, software engineers
focused on the algorithm and implemented it in a procedural
way
– An example: instructions to make a cup of tea
– The means of storing data was often an afterthought
An algorithm to make a hot drink
Start
Heat kettle
Water Test condition for the loop
Yes temp < 100? (whether or not to do an
A loop iteration)
No
A conditional branching Coffee
Tea Want tea
or coffee?
Put teabag in mug Put instant coffee in mug
Yes
Want milk?
Add milk No
A conditional branching
Yes
Teabag in mug?
Extract teabag No
A conditional branching
Drink!
A procedural program
Data storage
kettle_water_level = 0
A conditional branching
water_temperature = 0
If (kettle_water_level == 0) fill (kettle)
If (water_temperature < 100) {
Put_on_stove(kettle)
A conditional branching
Stove(on) A function
until (water_temperature == 100) { /* don’t watch kettle */}
Stove(off)
} A conditional loop
Add_teabag (mug) A function is like a group of instructions
mug_water_level = 0 carried for one or more given inputs
mug_water_colour = 0 • May or may not return some output
Until (mug_water_level == 90) poor (kettle, mug)
Until (mug_water_colour == 70) { }
Add_milk (mug)
What is an object oriented program?
Kettle Mug
{ {
water_level = 0 MakeTea(source)
water_temperature = 0 MakeCoffee(source)
}
Fill ()
Mug::MakeTea(source)
PlaceOnStove() The program is organised
around the data structures: {
Boil () source.Boil()
• what are the objects?
} Add_TeaBag()
• what states do they have?
Kettle::Boil() • what do they do? Poor_water()
{ Add_Milk()
if (water_level < 50) this->Fill() }
if (water_temperature < 100) Mug::MakeCoffee(source)
this->PlaceOnStove() {
stove.on() source.Boil()
Add_Coffee()
until (water_temperature == 100)
{} Poor_water()
}
stove.off()
main ()
}
{ mug.MakeTea() }
Features of a program - 1
• Variables (‘data’)
– storage or representation of the present state of the
program
– these may or may not be ‘typed’
• e.g. integer, floating point, string, …
• Operators
– the program can change the values of variables
– there are standard operations on variables
• e.g. increase or decrease the values, add two together, take one
from another, mulitply two together, …
• Functions
– standard or defined sets of operations on variables
Features of a program - 2
• Branches
– Testing of conditions (based on values of variables) and calling of
different functions depending on the test result
• Output to the user
– Something to tell the user the result(s) of the program
• Message to the screen (‘console’) or a file
• Input from the user
– If execution depends on values given by the user ‘at run time’, i.e. not
‘hard coded’ into the program, there should be input
• From the keyboard (‘console’), mouse or a file
• An entry point
– Where program execution starts
• One or more exit points
– Where program execution finishes
– Might depend on the flow of the program
Anatomy of a C++ program
• As in any high level language, we find
– A mechanism for storing data in the computer’s memory
• Known as variables
– Processes that can be used to perform calculations on
this data
• Operations and Functions
– Control Structures
• Allow control of how the operations are performed
– Optional execution (conditions and branches)
– Repeated execution (‘loops’)
– Mechanisms for inputting and outputting data
What C++ looks like
Headers: Give access to
intrinsic functions #include <iostream.h>
#include <stdio.h>
Lets the compiler know which using namespace std;
version of standard functions to use
int main()
All programs must have {
exactly one entry point. int n;
In C and C++, this is the // Prints “Hello!”
‘main’ function cout << “Hello!\n”;
// Comments behind ‘//’ return 0;
/* Old C style */ }
Don’t forget to terminate instructions with ;
source1.cpp object1.obj
Compile
source3.cpp object3.obj
Link
header1.hpp
header2.hpp
header3.hpp
Using a C++ compiler
• C and C++ source code is
– ‘compiled’ into ‘objects’
– ‘objects’ are ‘linked’ into a binary ‘executable’ particular to the host
operating system
– You run the ‘executable’
• Naming convention
– stem.extension
• Source code: *.cpp
• Object code: *.obj or *.o
• Executable: can be with or without .exe extension
• * is a ‘wildcard’ character
• Use of compilers allows the code to be optimised for execution speed
– Very important for large, complex programs!
– (For simple stuff, some sort of ‘interpreted’ language such as Java,
VBA, awk or Perl is often fine even though these run slower)
More on compilers
• Compilers are themselves programs
• There are many different C and C++ compilers
– Different compilers sometimes assume source code with
slightly different syntax or with different intrinsic functions
• Source code may not be fully ‘portable’ to different
compilers/platforms
• If in doubt, write in ‘ANSI standard’ C or C++
• Switch on compiler option for ANSI standard source code
– Different compilers are better or worse at
• optimising code
• indicating problems with source code
– Some compilers are more ‘buggy’ than others!
Messages from compilers
• Compilers will flag up:
– ‘Errors’ – code that the complier cannot interpret or that
is inconsistent with code already processed
– ‘Warnings’ – code that, according to rules coded in the
compiler, might give errors upon execution
• You will not get object files or executables without fixing the
errors
• You should also resolve the warnings
Development environments
• An ‘integrated development environment’ (IDE) comprises
– a compiler
– a ‘debugger’
– some nice visual aids for writing and managing code
• otherwise, you would need just a text editor for creating the source code
• On this course we will use ‘Visual C++’ (see later)
– It is built around Microsoft’s C++ compiler
– Visual C++ Express is a free version that you can download at home
• Debuggers allow you to
– stop program execution at different points and look at the values of
variables
– you can check the program flow is as you expect
– need to compile the code specifically for debugging
– when satisfied it works, compile again for fast execution