SlideShare une entreprise Scribd logo
1  sur  27
Télécharger pour lire hors ligne
Introduction to
Programming using C++
Lecture One: Getting Started
Carl Gwilliam
gwilliam@hep.ph.liv.ac.uk
http://hep.ph.liv.ac.uk/~gwilliam/cppcourse
Course Prerequisites
• What you should already know about C++
NOTHING!!
• I have assumed:
– You have never encountered C++ before.
– You have limited to no programming experience in any
language.
By the end of the course
• You should:
– Have a working knowledge of all of the common C++ syntax.
– Know how to avoid common coding pitfalls.
– Be able to use and create your own functions and classes.
– Recognise the advantages of using pointers and references.
– Be able to understand the fundamental ideas of object oriented
(OO) design.
• Be aware!
– This is not the comprehensive course for C++!
– Some advanced topics will not be covered in this course.
– Project specific C++ courses are worth attending if you have
time.
• You are learning a sophisticated language! It will take some time
and a fair amount of hands-on experience to become familiar with
C++.
Course format
• Lecture 1: Getting Started
– Statements, variables, types, operators, I/O, conditional
statements
• Lecture 2: Further Syntax
– For and while loops, increment and logical operators, sorting
algorithms
• Lecture 3: Functions
– Library and user functions, declarations, arguments, overloading
• Lecture 4: Pointers and References
– References, pointers, passing by reference, pointers and arrays,
consts
• Lecture 5: Introducing Classes
– Declarations, member variables and functions, accessors,
overloading
Course Format
• Lecture 6: Classes in Practice
– Constructors and destructors, constant functions, memory
management
• Lecture 7: Designing Classes
– Passing by const reference, copy constructors, overloading
operators
• Lecture 8: Towards OO Design
– Inheritance, virtual functions, multiple inheritance, abstract
classes
• Lecture 9: Templates & the STL
– Function & Class Templates, Specialisation, String, Vector, Map
• Lecture 10: File I/O and Streams
– Reading, writing, formatting, strings as streams
Why do you need to learn how to
write code?
"I am not a computer scientist!“
• Software development skills are usually required in every
element of your project - from extracting data to getting
your results published.
• It will be very useful to learn good programming
techniques now so you can save a lot of time later.
Why Learn C++?
"I already know how to program in FORTRAN/C/ASSEMBLER
so why do I have to bother with C++?“
• In recent times there has been a shift from procedural
languages such as FORTRAN to OO-style languages
such as C++ and Java.
• The language of choice, for now, is C++.
• C++ is ideally suited for projects where the active
developers are not located in the same place.
• Our survey says: almost all of the current HEP Ph.D.
students write and execute C++ code on a daily basis.
C++ is not the answer, it is a reasonable solution..
Hello World!
• Every C++ program must contain one (and only one)
main function.
• When the program is executed "Hello World" is
displayed on the terminal screen.
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
• The first complete C++ program in this course:
Compiling Hello World
• Once the code is written is has
to be compiled:
g++ -Wall -o Hello.exe
HelloWorld.cpp
• If the code compiles successfully
an object file (HelloWorld.o) is
created.
• This object file is then linked with
other object files and libraries
required to create the exe.
• The executable can be run at
the command prompt, just like
any other UNIX command.
A simple example
int a; float b; float c;
float d = 10.2;
float result;
// get two numbers
cout << "Enter two numbers" << endl;
cin >> a; cin >> b;
c = 2.1;
result = b * a + c;
result = (result + 2)/d;
// display the answer
cout << "Result of calculation: " << result << endl;
Statements
• Statements are used to control the sequence of
execution, evaluate an expression (or even do nothing).
• ALL statements are terminated with a semi colon ;
cout << "Enter two numbers" << endl;
result = b * a + c;
result= b* a
+c ;
//is the same as
result = b * a + c;
• One statement can trail over several lines.
• Code is easier to read with a sensible use of whitespace.
Comments
• Comments are useful for you and other developers!
// get two numbers
// display the answer
• A comment begins with // and ends with a line break.
• Comments indicate the purpose of the surrounding code.
• They can be placed anywhere in the program, except
within the body of a statement:
// this is a valid comment
result = b * a; // this is also valid
result = // this is NOT valid (result
+ 2)/d;
/* You may also use this „C‟ style
comment to span multiple lines */
Variables
• Variable ‘a’ has a type integer associated with some
object of type integer.
• Variable ‘d’ has a type float associated with some object
of type float with a value of 10.2
• A variable is a name associated with a location in
computer memory used to store a value.
• In order to use a variable in C++, we must first declare it
by specifying which data type we want it to be.
int a;
float d = 10.2;
Variable Types
• The compiler needs to know how much memory to set
aside for the object associated with the variable.
• Each type requires a specific amount of space in
memory.
• What does it mean to say a variable has a type?
• The C++ built-in types are:
int a; //integer
float b; //real
double c; //real
bool d; //boolean (o or 1)
char e; //character (ASCII value)
The Built-in Types
• That is all? How does C++ deal with complex numbers?
• C++ has the capacity to create user defined types. This
is a fundamental concept of the language.
Type Size (bytes) Range
bool 1 true/false
char 1 256 chars
int 2 or 4 (see below)
short int 2 ± 32,768
long int 4 ± 2.1*109
float 4 ±3.4*1038
double 8 ±1.8*10308
1 byte = 8 bits = 28
possible combos.
Size determined
by the compiler.
Range can be
doubled by using
unsigned int
Initialisation
• When declaring a variable, it’s value is by default
undetermined.
• We can give the variable a value at the same moment it is
declared
• There are two ways to do this in C++.
– The more used c-like method:
– The constructor method:
• It is good practice to always initialise a variable to a value
// type identifier = initial_value
int a = 0;
// type identifier (initial_value)
int a(0);
Assignment
• Do not mistake the above statements for algebra!
• Value of the expression to the right of the assignment
operator (rvalue) is assigned to the variable on the left
(the lvalue). Remember assignment is right-to-left:
c = 2.1; //assignment operator
result = b * a + c;
c = 2.1; //c assigned the value 2.1
2.1 = c; //incorrect!
• A variable can be assigned (or reassigned) to a particular
value with the assignment operator (=).
Arithmetic Operators
• Be careful applying the division operator when
assigning a variable with a different type:
• There are five primary mathematical operators:
int a = 8; int b = 5;
float c = a / b; // c is 1
c = (float)a / (float)b; // c is 1.6
Addition +
Subtraction -
Multiplication *
Division /
Modulus %
the modulus is the
remainder from integer
division (e.g. 33%6 is
equal to 3).
Casting an integer
to a float (‘c’-style)
Multiple Operators and Precedence
• Do not assume that an expression is evaluated from left
to right by the compiler. In C++, an operator has a
precedence value.
result = b * a + c;
result = (result + 2)/d;
• There are no restrictions on the amount of operators in an
expression.
float a = 6 * 4 + 4 * 2; // answer is 32
float b = 6 * (4+4) * 2; // answer is 96
// expression is incomprehensible
float c = b+c * 2/d + 3 + b/c + d - b *c/d;
// still unclear!
float d = b + ((c*2)/(d+3)+(b/(c+d))-(b*c/d));
*
/
%
+
-
PRESEDENCE
Input and Output
• For now, you can use these
statements without fully appreciating
the syntax.
• cin reads information from the keyboard and cout prints
information to the terminal (they’re defined in the header
iosteam).
cin >> a;
cout << "Enter two numbers" << endl;
float a = 13.3;
cout << "This is a string" << endl;
cout << "Value of a: " << a << endl;
cout << "a: " << (int) a << endl;
cout << "a =t" << a << "n";
This is a string
Value of a: 13.3
a: 13
a = 13.3
New line n
Horizontal tab t
Backspace b
Alert a
Backslash
Equality example
float a, b, c = 0;
cout << "Enter two numbers“ << endl;
cin >> a; cin >> b;
c = a - b;
if (a == b) cout << "Two numbers are equaln";
if (!c) {
cout << "Two numbers are equaln"; return 0;
}
if (a > b) {
cout << "The first number is greatern";
} else {
cout << "The second number is greatern";
}
return 0;
Conditional Statements
• Apply the condition in the expression to determine if the
statement will be executed.
• The capability of altering the program flow depending on
a outcome of an expression is a powerful tool in
programming.
• The expression is a conditional statement is always
evaluated as false (0) or true (non-0).
if (expression) statement;
Conditional Statements
• A statement will be included in the program flow if the
condition is true.
• The greater than symbol > and the equivalence symbol
== are relational operators.
if (a > b) statement;
if (a == b) statement;
int x = 4; int y = 3;
if (x = 4) cout << “x equals 4n”;
if (y = 4) cout << “y equals 4n”;
x equals 4
y equals 4
Condition
is always
true
• Remember the difference between the assignment (=)
and equivalence (==) operators!
Relational Operators
• Relational operators are used to evaluate if an
expression is true or false.
• The negation operator ! inverts the logic of the result.
if (!(x > y)) cout << “x less than y”;
x < y Less than
x <= y Less than or equal to
x > y Greater than
x >= y Greater than or equal to
x == y equal
x != y Not equal
Boolean Logic
• Conditional statements use boolean logic to determine
whether the expression is true or false.
• A non-zero value is true, a zero value is false.
if (!c)
int x = 2; int y = 0;
if (x) cout << “x equals 2” << endl;
if (!y) cout << “y equals 0” << endl;
x equals 2
y equals 0
Boolean logic is used frequently in C++ so be prepared!
Compound Statements
• Compound statements (or blocks) act as a single
statement.
• They enable multiple statements to be attached to one
condition.
• Blocks are started and ended with braces { }
• A ; is not placed at the end of a block
{
statement 1;
:
statement n;
}
If-else Statements
• Note, else block is only executed if none of above is true
if (expression) {
block a;
} else {
block b;
}
if (a > b) {
:
} else if (a < b) {
:
} else {
:
}
if (a > b) {
if (a >= c) {
:
} else {
:
}
}
• A true condition in the if expression
will result in block a being executed
otherwise block b will be executed.
• The if statement can be used for
multiple conditions and nested
conditions:

Contenu connexe

Tendances

Advanced C Language for Engineering
Advanced C Language for EngineeringAdvanced C Language for Engineering
Advanced C Language for EngineeringVincenzo De Florio
 
Programming in C Basics
Programming in C BasicsProgramming in C Basics
Programming in C BasicsBharat Kalia
 
C notes diploma-ee-3rd-sem
C notes diploma-ee-3rd-semC notes diploma-ee-3rd-sem
C notes diploma-ee-3rd-semKavita Dagar
 
C Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointJavaTpoint.Com
 
Overview of c++ language
Overview of c++ language   Overview of c++ language
Overview of c++ language samt7
 
OpenGurukul : Language : C Programming
OpenGurukul : Language : C ProgrammingOpenGurukul : Language : C Programming
OpenGurukul : Language : C ProgrammingOpen Gurukul
 
A brief introduction to C Language
A brief introduction to C LanguageA brief introduction to C Language
A brief introduction to C LanguageMohamed Elsayed
 
Complete C programming Language Course
Complete C programming Language CourseComplete C programming Language Course
Complete C programming Language CourseVivek chan
 
C programmimng basic.ppt
C programmimng basic.pptC programmimng basic.ppt
C programmimng basic.pptASIT Education
 
Hands-on Introduction to the C Programming Language
Hands-on Introduction to the C Programming LanguageHands-on Introduction to the C Programming Language
Hands-on Introduction to the C Programming LanguageVincenzo De Florio
 

Tendances (20)

C languaGE UNIT-1
C languaGE UNIT-1C languaGE UNIT-1
C languaGE UNIT-1
 
C programming
C programmingC programming
C programming
 
Advanced C Language for Engineering
Advanced C Language for EngineeringAdvanced C Language for Engineering
Advanced C Language for Engineering
 
C_Programming_Notes_ICE
C_Programming_Notes_ICEC_Programming_Notes_ICE
C_Programming_Notes_ICE
 
Basics of c++
Basics of c++Basics of c++
Basics of c++
 
Introduction to Procedural Programming in C++
Introduction to Procedural Programming in C++Introduction to Procedural Programming in C++
Introduction to Procedural Programming in C++
 
Programming in C Basics
Programming in C BasicsProgramming in C Basics
Programming in C Basics
 
C notes diploma-ee-3rd-sem
C notes diploma-ee-3rd-semC notes diploma-ee-3rd-sem
C notes diploma-ee-3rd-sem
 
C#
C#C#
C#
 
C language
C languageC language
C language
 
C Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpoint
 
Overview of c++ language
Overview of c++ language   Overview of c++ language
Overview of c++ language
 
OpenGurukul : Language : C Programming
OpenGurukul : Language : C ProgrammingOpenGurukul : Language : C Programming
OpenGurukul : Language : C Programming
 
C Programming
C ProgrammingC Programming
C Programming
 
Ch4 Expressions
Ch4 ExpressionsCh4 Expressions
Ch4 Expressions
 
A brief introduction to C Language
A brief introduction to C LanguageA brief introduction to C Language
A brief introduction to C Language
 
Complete C programming Language Course
Complete C programming Language CourseComplete C programming Language Course
Complete C programming Language Course
 
C programmimng basic.ppt
C programmimng basic.pptC programmimng basic.ppt
C programmimng basic.ppt
 
Hands-on Introduction to the C Programming Language
Hands-on Introduction to the C Programming LanguageHands-on Introduction to the C Programming Language
Hands-on Introduction to the C Programming Language
 
C Programming
C ProgrammingC Programming
C Programming
 

En vedette

Istanbul 2020 presentation (eus 301)
Istanbul 2020 presentation (eus 301)Istanbul 2020 presentation (eus 301)
Istanbul 2020 presentation (eus 301)kateratt
 
Automating development-operations-v1
Automating development-operations-v1Automating development-operations-v1
Automating development-operations-v1Sumanth Vepa
 
2.4 ownership, control a..
2.4 ownership, control a..2.4 ownership, control a..
2.4 ownership, control a..sanjnu
 
Colgate - Dental Hero LST
Colgate - Dental Hero LSTColgate - Dental Hero LST
Colgate - Dental Hero LSTJim Pino
 

En vedette (9)

Ejercicios de Hidrodinámica. Tarea
Ejercicios de Hidrodinámica. TareaEjercicios de Hidrodinámica. Tarea
Ejercicios de Hidrodinámica. Tarea
 
Istanbul 2020 presentation (eus 301)
Istanbul 2020 presentation (eus 301)Istanbul 2020 presentation (eus 301)
Istanbul 2020 presentation (eus 301)
 
Jobs
JobsJobs
Jobs
 
Collage
CollageCollage
Collage
 
Automating development-operations-v1
Automating development-operations-v1Automating development-operations-v1
Automating development-operations-v1
 
2.4 ownership, control a..
2.4 ownership, control a..2.4 ownership, control a..
2.4 ownership, control a..
 
Geology
GeologyGeology
Geology
 
Colgate - Dental Hero LST
Colgate - Dental Hero LSTColgate - Dental Hero LST
Colgate - Dental Hero LST
 
Powerpoint of rocks
Powerpoint of rocksPowerpoint of rocks
Powerpoint of rocks
 

Similaire à Lecture1

Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Rasan Samarasinghe
 
Lecture 2 variables
Lecture 2 variablesLecture 2 variables
Lecture 2 variablesTony Apreku
 
Object oriented programming 7 first steps in oop using c++
Object oriented programming 7 first steps in oop using  c++Object oriented programming 7 first steps in oop using  c++
Object oriented programming 7 first steps in oop using c++Vaibhav Khanna
 
M.Florence Dayana / Basics of C Language
M.Florence Dayana / Basics of C LanguageM.Florence Dayana / Basics of C Language
M.Florence Dayana / Basics of C LanguageDr.Florence Dayana
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAAiman Hud
 
Basics of C.ppt
Basics of C.pptBasics of C.ppt
Basics of C.ppt8759000398
 
2 BytesC++ course_2014_c1_basicsc++
2 BytesC++ course_2014_c1_basicsc++2 BytesC++ course_2014_c1_basicsc++
2 BytesC++ course_2014_c1_basicsc++kinan keshkeh
 
C prog ppt
C prog pptC prog ppt
C prog pptxinoe
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programmingAlpana Gupta
 
AVR_Course_Day3 c programming
AVR_Course_Day3 c programmingAVR_Course_Day3 c programming
AVR_Course_Day3 c programmingMohamed Ali
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAAiman Hud
 
C++ language basic
C++ language basicC++ language basic
C++ language basicWaqar Younis
 
C programming language tutorial
C programming language tutorialC programming language tutorial
C programming language tutorialSURBHI SAROHA
 
Chapter 1: Introduction
Chapter 1: IntroductionChapter 1: Introduction
Chapter 1: IntroductionEric Chou
 

Similaire à Lecture1 (20)

Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
College1
College1College1
College1
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
 
C language
C languageC language
C language
 
Lecture 2 variables
Lecture 2 variablesLecture 2 variables
Lecture 2 variables
 
Object oriented programming 7 first steps in oop using c++
Object oriented programming 7 first steps in oop using  c++Object oriented programming 7 first steps in oop using  c++
Object oriented programming 7 first steps in oop using c++
 
M.Florence Dayana / Basics of C Language
M.Florence Dayana / Basics of C LanguageM.Florence Dayana / Basics of C Language
M.Florence Dayana / Basics of C Language
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Basics of C.ppt
Basics of C.pptBasics of C.ppt
Basics of C.ppt
 
Programming in C
Programming in CProgramming in C
Programming in C
 
2 BytesC++ course_2014_c1_basicsc++
2 BytesC++ course_2014_c1_basicsc++2 BytesC++ course_2014_c1_basicsc++
2 BytesC++ course_2014_c1_basicsc++
 
C prog ppt
C prog pptC prog ppt
C prog ppt
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
AVR_Course_Day3 c programming
AVR_Course_Day3 c programmingAVR_Course_Day3 c programming
AVR_Course_Day3 c programming
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
C++ language basic
C++ language basicC++ language basic
C++ language basic
 
C programming language tutorial
C programming language tutorialC programming language tutorial
C programming language tutorial
 
C programming
C programmingC programming
C programming
 
Chapter 1: Introduction
Chapter 1: IntroductionChapter 1: Introduction
Chapter 1: Introduction
 
C for Engineers
C for EngineersC for Engineers
C for Engineers
 

Dernier

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.MateoGardella
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 

Dernier (20)

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 

Lecture1

  • 1. Introduction to Programming using C++ Lecture One: Getting Started Carl Gwilliam gwilliam@hep.ph.liv.ac.uk http://hep.ph.liv.ac.uk/~gwilliam/cppcourse
  • 2. Course Prerequisites • What you should already know about C++ NOTHING!! • I have assumed: – You have never encountered C++ before. – You have limited to no programming experience in any language.
  • 3. By the end of the course • You should: – Have a working knowledge of all of the common C++ syntax. – Know how to avoid common coding pitfalls. – Be able to use and create your own functions and classes. – Recognise the advantages of using pointers and references. – Be able to understand the fundamental ideas of object oriented (OO) design. • Be aware! – This is not the comprehensive course for C++! – Some advanced topics will not be covered in this course. – Project specific C++ courses are worth attending if you have time. • You are learning a sophisticated language! It will take some time and a fair amount of hands-on experience to become familiar with C++.
  • 4. Course format • Lecture 1: Getting Started – Statements, variables, types, operators, I/O, conditional statements • Lecture 2: Further Syntax – For and while loops, increment and logical operators, sorting algorithms • Lecture 3: Functions – Library and user functions, declarations, arguments, overloading • Lecture 4: Pointers and References – References, pointers, passing by reference, pointers and arrays, consts • Lecture 5: Introducing Classes – Declarations, member variables and functions, accessors, overloading
  • 5. Course Format • Lecture 6: Classes in Practice – Constructors and destructors, constant functions, memory management • Lecture 7: Designing Classes – Passing by const reference, copy constructors, overloading operators • Lecture 8: Towards OO Design – Inheritance, virtual functions, multiple inheritance, abstract classes • Lecture 9: Templates & the STL – Function & Class Templates, Specialisation, String, Vector, Map • Lecture 10: File I/O and Streams – Reading, writing, formatting, strings as streams
  • 6. Why do you need to learn how to write code? "I am not a computer scientist!“ • Software development skills are usually required in every element of your project - from extracting data to getting your results published. • It will be very useful to learn good programming techniques now so you can save a lot of time later.
  • 7. Why Learn C++? "I already know how to program in FORTRAN/C/ASSEMBLER so why do I have to bother with C++?“ • In recent times there has been a shift from procedural languages such as FORTRAN to OO-style languages such as C++ and Java. • The language of choice, for now, is C++. • C++ is ideally suited for projects where the active developers are not located in the same place. • Our survey says: almost all of the current HEP Ph.D. students write and execute C++ code on a daily basis. C++ is not the answer, it is a reasonable solution..
  • 8. Hello World! • Every C++ program must contain one (and only one) main function. • When the program is executed "Hello World" is displayed on the terminal screen. #include <iostream> using namespace std; int main() { cout << "Hello World!"; return 0; } • The first complete C++ program in this course:
  • 9. Compiling Hello World • Once the code is written is has to be compiled: g++ -Wall -o Hello.exe HelloWorld.cpp • If the code compiles successfully an object file (HelloWorld.o) is created. • This object file is then linked with other object files and libraries required to create the exe. • The executable can be run at the command prompt, just like any other UNIX command.
  • 10. A simple example int a; float b; float c; float d = 10.2; float result; // get two numbers cout << "Enter two numbers" << endl; cin >> a; cin >> b; c = 2.1; result = b * a + c; result = (result + 2)/d; // display the answer cout << "Result of calculation: " << result << endl;
  • 11. Statements • Statements are used to control the sequence of execution, evaluate an expression (or even do nothing). • ALL statements are terminated with a semi colon ; cout << "Enter two numbers" << endl; result = b * a + c; result= b* a +c ; //is the same as result = b * a + c; • One statement can trail over several lines. • Code is easier to read with a sensible use of whitespace.
  • 12. Comments • Comments are useful for you and other developers! // get two numbers // display the answer • A comment begins with // and ends with a line break. • Comments indicate the purpose of the surrounding code. • They can be placed anywhere in the program, except within the body of a statement: // this is a valid comment result = b * a; // this is also valid result = // this is NOT valid (result + 2)/d; /* You may also use this „C‟ style comment to span multiple lines */
  • 13. Variables • Variable ‘a’ has a type integer associated with some object of type integer. • Variable ‘d’ has a type float associated with some object of type float with a value of 10.2 • A variable is a name associated with a location in computer memory used to store a value. • In order to use a variable in C++, we must first declare it by specifying which data type we want it to be. int a; float d = 10.2;
  • 14. Variable Types • The compiler needs to know how much memory to set aside for the object associated with the variable. • Each type requires a specific amount of space in memory. • What does it mean to say a variable has a type? • The C++ built-in types are: int a; //integer float b; //real double c; //real bool d; //boolean (o or 1) char e; //character (ASCII value)
  • 15. The Built-in Types • That is all? How does C++ deal with complex numbers? • C++ has the capacity to create user defined types. This is a fundamental concept of the language. Type Size (bytes) Range bool 1 true/false char 1 256 chars int 2 or 4 (see below) short int 2 ± 32,768 long int 4 ± 2.1*109 float 4 ±3.4*1038 double 8 ±1.8*10308 1 byte = 8 bits = 28 possible combos. Size determined by the compiler. Range can be doubled by using unsigned int
  • 16. Initialisation • When declaring a variable, it’s value is by default undetermined. • We can give the variable a value at the same moment it is declared • There are two ways to do this in C++. – The more used c-like method: – The constructor method: • It is good practice to always initialise a variable to a value // type identifier = initial_value int a = 0; // type identifier (initial_value) int a(0);
  • 17. Assignment • Do not mistake the above statements for algebra! • Value of the expression to the right of the assignment operator (rvalue) is assigned to the variable on the left (the lvalue). Remember assignment is right-to-left: c = 2.1; //assignment operator result = b * a + c; c = 2.1; //c assigned the value 2.1 2.1 = c; //incorrect! • A variable can be assigned (or reassigned) to a particular value with the assignment operator (=).
  • 18. Arithmetic Operators • Be careful applying the division operator when assigning a variable with a different type: • There are five primary mathematical operators: int a = 8; int b = 5; float c = a / b; // c is 1 c = (float)a / (float)b; // c is 1.6 Addition + Subtraction - Multiplication * Division / Modulus % the modulus is the remainder from integer division (e.g. 33%6 is equal to 3). Casting an integer to a float (‘c’-style)
  • 19. Multiple Operators and Precedence • Do not assume that an expression is evaluated from left to right by the compiler. In C++, an operator has a precedence value. result = b * a + c; result = (result + 2)/d; • There are no restrictions on the amount of operators in an expression. float a = 6 * 4 + 4 * 2; // answer is 32 float b = 6 * (4+4) * 2; // answer is 96 // expression is incomprehensible float c = b+c * 2/d + 3 + b/c + d - b *c/d; // still unclear! float d = b + ((c*2)/(d+3)+(b/(c+d))-(b*c/d)); * / % + - PRESEDENCE
  • 20. Input and Output • For now, you can use these statements without fully appreciating the syntax. • cin reads information from the keyboard and cout prints information to the terminal (they’re defined in the header iosteam). cin >> a; cout << "Enter two numbers" << endl; float a = 13.3; cout << "This is a string" << endl; cout << "Value of a: " << a << endl; cout << "a: " << (int) a << endl; cout << "a =t" << a << "n"; This is a string Value of a: 13.3 a: 13 a = 13.3 New line n Horizontal tab t Backspace b Alert a Backslash
  • 21. Equality example float a, b, c = 0; cout << "Enter two numbers“ << endl; cin >> a; cin >> b; c = a - b; if (a == b) cout << "Two numbers are equaln"; if (!c) { cout << "Two numbers are equaln"; return 0; } if (a > b) { cout << "The first number is greatern"; } else { cout << "The second number is greatern"; } return 0;
  • 22. Conditional Statements • Apply the condition in the expression to determine if the statement will be executed. • The capability of altering the program flow depending on a outcome of an expression is a powerful tool in programming. • The expression is a conditional statement is always evaluated as false (0) or true (non-0). if (expression) statement;
  • 23. Conditional Statements • A statement will be included in the program flow if the condition is true. • The greater than symbol > and the equivalence symbol == are relational operators. if (a > b) statement; if (a == b) statement; int x = 4; int y = 3; if (x = 4) cout << “x equals 4n”; if (y = 4) cout << “y equals 4n”; x equals 4 y equals 4 Condition is always true • Remember the difference between the assignment (=) and equivalence (==) operators!
  • 24. Relational Operators • Relational operators are used to evaluate if an expression is true or false. • The negation operator ! inverts the logic of the result. if (!(x > y)) cout << “x less than y”; x < y Less than x <= y Less than or equal to x > y Greater than x >= y Greater than or equal to x == y equal x != y Not equal
  • 25. Boolean Logic • Conditional statements use boolean logic to determine whether the expression is true or false. • A non-zero value is true, a zero value is false. if (!c) int x = 2; int y = 0; if (x) cout << “x equals 2” << endl; if (!y) cout << “y equals 0” << endl; x equals 2 y equals 0 Boolean logic is used frequently in C++ so be prepared!
  • 26. Compound Statements • Compound statements (or blocks) act as a single statement. • They enable multiple statements to be attached to one condition. • Blocks are started and ended with braces { } • A ; is not placed at the end of a block { statement 1; : statement n; }
  • 27. If-else Statements • Note, else block is only executed if none of above is true if (expression) { block a; } else { block b; } if (a > b) { : } else if (a < b) { : } else { : } if (a > b) { if (a >= c) { : } else { : } } • A true condition in the if expression will result in block a being executed otherwise block b will be executed. • The if statement can be used for multiple conditions and nested conditions: