Computer Programming Introduction to the course and C++ Prof. Dr. Mohammad Haseeb Zafar haseeb@uetpeshawar.edu.pk
Course Overview • Aims: – to provide a good introduction to programming in C++ – to give increased familiarity with programming, use of an ‘integrated development environment’ (IDE) and software development in general – to deepen appreciation of object orientation • Personnel – lectures: Prof. Dr. Mohammad Haseeb Zafar – labs: Engr. Maha Gul
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! – You will need at least 2 hours • 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
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#Con – 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
Assessment • Sessionals: 25% – Assignments: 6% – Quizzes: 9% – Project: 10% • done in pairs in last 8 weeks of course • 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.) • Arrays, Strings and Pointers • 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/ Gratuitous picture of Bjarne Stroustrup
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 Kettle water level == 0? Want milk? Put teabag in mug Tea Drink! NoExtract teabag Yes Add milk Yes Heat kettle Yes Fill kettle Yes Put instant coffee in mug Coffee Teabag in mug? No Want tea or coffee? No Water temp < 100? No A conditional branching A loop Test condition for the loop (whether or not to do an iteration) A conditional branching A conditional branching A conditional branching
A procedural program kettle_water_level = 0 water_temperature = 0 If (kettle_water_level == 0) fill (kettle) If (water_temperature < 100) { Put_on_stove(kettle) Stove(on) until (water_temperature == 100) { /* don’t watch kettle */} Stove(off) } Add_teabag (mug) mug_water_level = 0 mug_water_colour = 0 Until (mug_water_level == 90) poor (kettle, mug) Until (mug_water_colour == 70) { } Add_milk (mug) A conditional branching A conditional branching A conditional loop Data storage A function A function is like a group of instructions carried for one or more given inputs • May or may not return some output
What is an object oriented program? Kettle { water_level = 0 water_temperature = 0 Fill () PlaceOnStove() Boil () } Kettle::Boil() { if (water_level < 50) this->Fill() if (water_temperature < 100) this->PlaceOnStove() stove.on() until (water_temperature == 100) {} stove.off() } Mug { MakeTea(source) MakeCoffee(source) } Mug::MakeTea(source) { source.Boil() Add_TeaBag() Poor_water() Add_Milk() } Mug::MakeCoffee(source) { source.Boil() Add_Coffee() Poor_water() } main () { mug.MakeTea() } The program is organised around the data structures: • what are the objects? • what states do they have? • what do they do?
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 #include <iostream.h> #include <stdio.h> using namespace std; int main() { int n; // Prints “Hello!” cout << “Hello!n”; return 0; } • Basic Structure for any program in C++ Headers: Give access to intrinsic functions All programs must have exactly one entry point. In C and C++, this is the ‘main’ function Don’t forget to terminate instructions with ; Lets the compiler know which version of standard functions to use // Comments behind ‘//’ /* Old C style */
Variables and identifiers • ‘Identifier’ – Name of a variable, structure, class, function, … – Can be quite long and is case sensitive • Count is not the same as count!! • Variables – Named memory locations to hold values that can be modified – In C++, each variable has a specific data ‘type’ – ‘Strong’ typing - why? • Operations can be designed for specific types (for speed) • The user is forced to think about what kind of data they are interested in • Inconsistent treatment of variables is minimised
Variable types Size Type Description Range 4 int Integer -big no. to +big no. 1 char Character – ASCII codes 0 – 255 4 float Floating point number – fractions possible ~1.2 e-38 to 3.4 e38 8 double Double precision float 1.2e-308 to 3.4e308 1 bool Boolean TRUE FALSE 7 or 8 significant figures 15 or 16 significant figures
Operations • Two types of basic operation we can perform on numbers. – Logical tests • Equal to (==), Not equal to (!=), Greater than (>), Less than (<), Greater than or equal to (>=), Less than or equal to (<=). • Logical NOT (!), Logical AND (&&), Logical OR (||) • Be careful when testing equality of two floats or doubles – check absolute value of difference is less than a very small number – Arithmetic operations • Assignment, Addition, Subtraction, Multiplication, Division • =, +, -, *, / • Maths functions achieved using library functions available to the language (‘intrinsic’) – Accessed via calls to code made available with compiler – Let compiler know about them by using a #include statement – #include <math.h> Careful not to confuse assignment with test of equality!
Turning source code into an executable • ‘Interpreted’ code depends on some interpretation software that acts as an interface between the humanly readable source code and the operating system, .e.g. BASIC – Java is a bit like that but depends on a ‘virtual machine’ • Most ‘high level’ languages use a ‘compiler’ to turn source code into binary ‘executable’ code that can be run directly on the host computer – The source code can be transported between operating systems but must be recompiled – Binary executables run faster… – … but you do need to use a compiler
Using a compiler source1.cpp source3.cpp source2.cpp header1.hpp header2.hpp header3.hpp object1.obj object2.obj object3.obj prog.exe Pre-processor Compile Link
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

01 introduction to cpp

  • 1.
    Computer Programming Introduction tothe course and C++ Prof. Dr. Mohammad Haseeb Zafar haseeb@uetpeshawar.edu.pk
  • 2.
    Course Overview • Aims: –to provide a good introduction to programming in C++ – to give increased familiarity with programming, use of an ‘integrated development environment’ (IDE) and software development in general – to deepen appreciation of object orientation • Personnel – lectures: Prof. Dr. Mohammad Haseeb Zafar – labs: Engr. Maha Gul
  • 3.
    Course format • Aweekly 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! – You will need at least 2 hours • 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
  • 4.
    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#Con – 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
  • 5.
    Assessment • Sessionals: 25% –Assignments: 6% – Quizzes: 9% – Project: 10% • done in pairs in last 8 weeks of course • Mid Term Exam: 25% • Final Term Exam: 50%
  • 6.
    Course content • Introductionto the course, C++ and the IDE • Data types and operators • Functions • Conditions (if…) • Iteration (for loops, etc.) • Arrays, Strings and Pointers • Classes and objects
  • 7.
    Why learn toprogram? • 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
  • 8.
    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
  • 9.
    Object orientation andC++ • 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)
  • 10.
    The inventor ofC++ Not a typical computer nerd? http://www.research.att.com/~bs/ Gratuitous picture of Bjarne Stroustrup
  • 11.
    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.
  • 12.
    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
  • 13.
    Algorithms and problemsolving • 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
  • 14.
    What is aprogram? • 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
  • 15.
    An algorithm tomake a hot drink Start Kettle water level == 0? Want milk? Put teabag in mug Tea Drink! NoExtract teabag Yes Add milk Yes Heat kettle Yes Fill kettle Yes Put instant coffee in mug Coffee Teabag in mug? No Want tea or coffee? No Water temp < 100? No A conditional branching A loop Test condition for the loop (whether or not to do an iteration) A conditional branching A conditional branching A conditional branching
  • 16.
    A procedural program kettle_water_level= 0 water_temperature = 0 If (kettle_water_level == 0) fill (kettle) If (water_temperature < 100) { Put_on_stove(kettle) Stove(on) until (water_temperature == 100) { /* don’t watch kettle */} Stove(off) } Add_teabag (mug) mug_water_level = 0 mug_water_colour = 0 Until (mug_water_level == 90) poor (kettle, mug) Until (mug_water_colour == 70) { } Add_milk (mug) A conditional branching A conditional branching A conditional loop Data storage A function A function is like a group of instructions carried for one or more given inputs • May or may not return some output
  • 17.
    What is anobject oriented program? Kettle { water_level = 0 water_temperature = 0 Fill () PlaceOnStove() Boil () } Kettle::Boil() { if (water_level < 50) this->Fill() if (water_temperature < 100) this->PlaceOnStove() stove.on() until (water_temperature == 100) {} stove.off() } Mug { MakeTea(source) MakeCoffee(source) } Mug::MakeTea(source) { source.Boil() Add_TeaBag() Poor_water() Add_Milk() } Mug::MakeCoffee(source) { source.Boil() Add_Coffee() Poor_water() } main () { mug.MakeTea() } The program is organised around the data structures: • what are the objects? • what states do they have? • what do they do?
  • 18.
    Features of aprogram - 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
  • 19.
    Features of aprogram - 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
  • 20.
    Anatomy of aC++ 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
  • 21.
    What C++ lookslike #include <iostream.h> #include <stdio.h> using namespace std; int main() { int n; // Prints “Hello!” cout << “Hello!n”; return 0; } • Basic Structure for any program in C++ Headers: Give access to intrinsic functions All programs must have exactly one entry point. In C and C++, this is the ‘main’ function Don’t forget to terminate instructions with ; Lets the compiler know which version of standard functions to use // Comments behind ‘//’ /* Old C style */
  • 22.
    Variables and identifiers •‘Identifier’ – Name of a variable, structure, class, function, … – Can be quite long and is case sensitive • Count is not the same as count!! • Variables – Named memory locations to hold values that can be modified – In C++, each variable has a specific data ‘type’ – ‘Strong’ typing - why? • Operations can be designed for specific types (for speed) • The user is forced to think about what kind of data they are interested in • Inconsistent treatment of variables is minimised
  • 23.
    Variable types Size TypeDescription Range 4 int Integer -big no. to +big no. 1 char Character – ASCII codes 0 – 255 4 float Floating point number – fractions possible ~1.2 e-38 to 3.4 e38 8 double Double precision float 1.2e-308 to 3.4e308 1 bool Boolean TRUE FALSE 7 or 8 significant figures 15 or 16 significant figures
  • 24.
    Operations • Two typesof basic operation we can perform on numbers. – Logical tests • Equal to (==), Not equal to (!=), Greater than (>), Less than (<), Greater than or equal to (>=), Less than or equal to (<=). • Logical NOT (!), Logical AND (&&), Logical OR (||) • Be careful when testing equality of two floats or doubles – check absolute value of difference is less than a very small number – Arithmetic operations • Assignment, Addition, Subtraction, Multiplication, Division • =, +, -, *, / • Maths functions achieved using library functions available to the language (‘intrinsic’) – Accessed via calls to code made available with compiler – Let compiler know about them by using a #include statement – #include <math.h> Careful not to confuse assignment with test of equality!
  • 25.
    Turning source codeinto an executable • ‘Interpreted’ code depends on some interpretation software that acts as an interface between the humanly readable source code and the operating system, .e.g. BASIC – Java is a bit like that but depends on a ‘virtual machine’ • Most ‘high level’ languages use a ‘compiler’ to turn source code into binary ‘executable’ code that can be run directly on the host computer – The source code can be transported between operating systems but must be recompiled – Binary executables run faster… – … but you do need to use a compiler
  • 26.
  • 27.
    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)
  • 28.
    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!
  • 29.
    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
  • 30.
    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