SlideShare une entreprise Scribd logo
1  sur  42
M.Golyani
December 2017
C++ How to program
Mostly based on
Paul Deitel, Harvey Deitel-C++ How to Program-
Pearson (2014)
Outline
 History
 Understanding the compiler basics
 What is an executable?
 C++ program structure
 “Hello, World!”
 Input, Output, Error
 Variables and their types
 Getting input from user
 Performing arithmetic operations
 “if” Conditional statement
History of programming
 1950s: Fortran, IBM corporation
 1950s: Cobol, Grace Hopper (FLOW-MATIC)
 1960s: Pascal, Niklaus Wirth
 1960s: Basic, Dartmouth College
 1970s: Ada, DoD
 1972: C, Dennis Ritchie
 1979: C++, Bjarne Stroustrup
 1991: Java, Sun Microsystems
 2001: C#, Microsoft
 , …
Programs
- A sequence of instructions which perform
a specific task
- The CPU is responsible for executing the commands.
- Each instruction is finally executed by the CPU.
- The final program should be understandable for the CPU
- CPU does not understand the ASCII, human readable texts (known
as source files!!)
- We should translate these sources to machine codes.
- No matter what programming language we use, the CPU instruction
set is fixed.
Programmers
Programmers
Programmers
Programmers
http://Stuffthathappens.com
Eric burke
Compiling the Source
- Compiling a source file to create an executable, is performed in
some steps as bellow:
Preprocessing
Compiling
Assembling
Linking
Compiler does these in
one or more passes
Compiling the Source
- Compiler does some analysis on source file:
Lexical
Syntax
Semantic
Optimizing the Code
Code Generation
Symbol Table
Error Handler
Intermediate Code Generation
Linux C++ compiler
 g++:
 g++ <SOURCE>
 g++ -o <EXECUTABLE> <SOURCE>
 gcc:
 gcc <SOURCE>
 gcc -o <EXECUTABLE> <SOURCE>
 GCC: GNU Compiler Collection
Linux C++ compiler
- The Gnu Compiler Collection (GCC) project started by Richard
Stallman in 1985.
- GCC includes front-ends for lots of languages including:
• C (gcc)
• C++ (g++)
• Java (gcj)
• Ada (GNAT)
• Objective-C (gobjc)
• Objective-C++
• Fortran
Linux Executables
ELF
Relocatable File (.o files)
Shared Object File (.so files)
Executable File
There are 3 main ELF object files:
Linux executable files are in ELF format (Executable and Linkable
Format)
There is no need for specific file extension in Linux, only permission
Core Dumps
C++ libraries
 Each C++ program consists of “classes” and
“functions”
 These are pieces of code that perform special tasks
 Printing a string in the output, opening a file for
writing, accessing specific parts of the memory and
…
 If your program needs to do these tasks, you can
write the code yourself, or you can use the already
provided functions and classes.
 These already prepared functions and classes are
packed into “libraries”
 There are lots of libraries available and you can
C++ libraries
 Shorter development time
 Probably better performance
 Improves program portability
 You don’t need to worry about updating and
maintenance of these libs.
The “C++ standard library” is a rich collection of most
needed functions and classes
C++ header files
 The C++ standard library is automatically attached to
your program.
 The functions and classes in the C++ standard library
are categorized into several sections.
 To use each section, you should “include” the
appropriate header file in your source code.
 To include a header file, you should use “#include”
phrase. #include <iostream>
C++ header files
Header file Usage
iostream
Several standard stream objects
(input, output, …)
memory Memory management utilities
cerrno To view the last error number
cmath Common mathematics functions
chrono C++ time utilities
… …
… …
How can we make our
own header files ???
Sample C++ program structure
#include
<iostream>
int main()
{
….
/*
These lines
are comment
as well
*/
….
return 0;
}
// This is a comment
Header files that we need
Compiler will not compile this
line
This means
that the main()
function is
going to return
an integer
after it finishes
it’s work
Each program
should have a
“main” function
This return value is used by
other programs and shell to
check for errors.
There could be lots of other
functions and codes in our
program, starting from main
function
Hello, World!
You need to know how to create a text file
in Linux CLI
This entity belongs
to “std” namespace
We indicate that this
way
Returning a Zero from main
means that the program
has ended successfully
Lines starting with # are
directives to the “preprocessor”
which is run before the compiler.
This line tells the preprocessor to
include the “iostream” header file
Hello, World!
 Always use and update comments in your code
 C++ statements should end with “;” (almost all of
them)
 “syntax error” indicates you have something wrong in
your coding syntax.
 Whitespaces and blank lines are OK.
 Use “TAB”, blank lines and whitespaces to have a
human readable code!
Input, Output, Error
 The std namespace contains some “standard”
library routines.
 cin:
 Used to get data from standard input
 cout:
 Used to send data to standard output
 cerr:
 Used to send data to standard error
 , …
Usually the STDIN, STDOUT, and STDERR are
connected to the working terminal
Input, Output, Error
Use “std::cerr” to send error messages to STDERR
How can we redirect
program’s output to one
file and errors to
another?
Escape sequence
 The “” character in output string is an “escape
character”
 According to what comes after “”, the output
differs.
 The “” and the following character is named
“escape sequence”
Variables
 We use variables to store data.
 Variables are placed in computer’s memory
(RAM).
 To use a variable, we should first declare it.
Variable
declaration
Add comments here
to remember why
you have declared
this variable
Variable declaration could be anywhere, just
remember to declare before use
Variables
 Each variable has its own type, name, size, and
value.
 Integer, float, double,…
 String, char, …
 , ….
The “int” phrase is a
keyword. We can’t use
keywords as our variable
names!
C++ variable types
Type Meaning Example
int Integer numbers -3, 0, 5
double Real numbers 3.4, 0.04, -2.5
float Real numbers ???
char Any single character ‘A’, ‘+’, ‘*’
bool Boolean type “true” or “false”
… … …
Type Meaning
Signed Negative or positive
Unsigned Only positive
Long At least 32 bits
Short At least 16 bits
Input from user
 Using std::cin, you can get input from command
line.
 Remember the direction of “>>” and “<<“
 Using “std::cout” at each statement is awkward!
How can we provide a
program’s required
inputs to avoid
interaction?
Arithmetic operations
 You can use “using” declaration to avoid
repeating “std::”
Arithmetic operations
 The precedence of arithmetic operations are
important.
 Parentheses are always considered first.
y = a * x * x + b * x + c ;
Arithmetic operations
16 2 4 3 5
Arithmetic operations
 What is the output of this program?
 1  2  9  10  0
Arithmetic operation
If there are lots of names
that we want to use, we
should declare them here
Conditional statement
 “if” statement is used to implement conditional
statements.
if ( CONDITION )
{
.......
.......
.......
}
else
{
.......
.......
.......
}
If “CONDITION” is true,
then this piece of code is
executed
If “CONDITION” is NOT
true, then this piece of code
is executed
Conditional statement
 “CONDITION”s in if statements, can be formed by
using the “relational operators” and “equality
operators”
Conditional statement
 What is wrong in this program?
Notice that we used “using”
directive here instead of
using multiple using
declaration.
This enables the program
to use all the names in any
standard C++ header that
a program might include.
If the statements of the
condition are one line
length, you can omit the {
… } block.
End of Section 1
 In this section, you learned about:
 What is an executable
 How compilers work
 What are libraries and headers
 C++ program structure
 How to send strings to stdout, stderr
 How to get user input from stdin
 Variables and their types
 Arithmetic operations and their precedence
 “if” conditional statement and it’s usage

Contenu connexe

Tendances

Inheritance
InheritanceInheritance
Inheritance
Tech_MX
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt
Tareq Hasan
 

Tendances (20)

Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
 
Programming in C Presentation upto FILE
Programming in C Presentation upto FILEProgramming in C Presentation upto FILE
Programming in C Presentation upto FILE
 
C++ Overview PPT
C++ Overview PPTC++ Overview PPT
C++ Overview PPT
 
Complete C++ programming Language Course
Complete C++ programming Language CourseComplete C++ programming Language Course
Complete C++ programming Language Course
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
Variables in C Programming
Variables in C ProgrammingVariables in C Programming
Variables in C Programming
 
Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming
 
C tokens
C tokensC tokens
C tokens
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
Basics of JAVA programming
Basics of JAVA programmingBasics of JAVA programming
Basics of JAVA programming
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in Python
 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in python
 
Features of java
Features of javaFeatures of java
Features of java
 
History of c++
History of c++ History of c++
History of c++
 
Conceptual dependency
Conceptual dependencyConceptual dependency
Conceptual dependency
 
Type Conversion, Precedence and Associativity
Type Conversion, Precedence and AssociativityType Conversion, Precedence and Associativity
Type Conversion, Precedence and Associativity
 
Inheritance
InheritanceInheritance
Inheritance
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt
 

Similaire à C++ How to program

C5 c++ development environment
C5 c++ development environmentC5 c++ development environment
C5 c++ development environment
snchnchl
 
C LANGUAGE UNIT-1 PREPARED BY MVB REDDY
C LANGUAGE UNIT-1 PREPARED BY MVB REDDYC LANGUAGE UNIT-1 PREPARED BY MVB REDDY
C LANGUAGE UNIT-1 PREPARED BY MVB REDDY
Rajeshkumar Reddy
 

Similaire à C++ How to program (20)

C++ programming language basic to advance level
C++ programming language basic to advance levelC++ programming language basic to advance level
C++ programming language basic to advance level
 
Tutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng verTutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng ver
 
C++ AND CATEGORIES OF SOFTWARE
C++ AND CATEGORIES OF SOFTWAREC++ AND CATEGORIES OF SOFTWARE
C++ AND CATEGORIES OF SOFTWARE
 
Prog1-L1.pdf
Prog1-L1.pdfProg1-L1.pdf
Prog1-L1.pdf
 
OOPS using C++
OOPS using C++OOPS using C++
OOPS using C++
 
Bcsl 031 solve assignment
Bcsl 031 solve assignmentBcsl 031 solve assignment
Bcsl 031 solve assignment
 
C tutorials
C tutorialsC tutorials
C tutorials
 
Basic c
Basic cBasic c
Basic c
 
Introduction to cpp language and all the required information relating to it
Introduction to cpp language and all the required information relating to itIntroduction to cpp language and all the required information relating to it
Introduction to cpp language and all the required information relating to it
 
Session 1 - c++ intro
Session   1 - c++ introSession   1 - c++ intro
Session 1 - c++ intro
 
C Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.comC Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.com
 
The basics of c programming
The basics of c programmingThe basics of c programming
The basics of c programming
 
Fp201 unit2 1
Fp201 unit2 1Fp201 unit2 1
Fp201 unit2 1
 
C5 c++ development environment
C5 c++ development environmentC5 c++ development environment
C5 c++ development environment
 
Chap 2 c++
Chap 2 c++Chap 2 c++
Chap 2 c++
 
Let's us c language (sabeel Bugti)
Let's us c language (sabeel Bugti)Let's us c language (sabeel Bugti)
Let's us c language (sabeel Bugti)
 
C LANGUAGE UNIT-1 PREPARED BY MVB REDDY
C LANGUAGE UNIT-1 PREPARED BY MVB REDDYC LANGUAGE UNIT-1 PREPARED BY MVB REDDY
C LANGUAGE UNIT-1 PREPARED BY MVB REDDY
 
C Programming UNIT 1.pptx
C Programming  UNIT 1.pptxC Programming  UNIT 1.pptx
C Programming UNIT 1.pptx
 
Lab 1.pptx
Lab 1.pptxLab 1.pptx
Lab 1.pptx
 
Presentation 2.ppt
Presentation 2.pptPresentation 2.ppt
Presentation 2.ppt
 

Plus de Mohammad Golyani

Plus de Mohammad Golyani (9)

A holistic Control Flow Integrity
A holistic Control Flow IntegrityA holistic Control Flow Integrity
A holistic Control Flow Integrity
 
GCC, Glibc protections
GCC, Glibc protectionsGCC, Glibc protections
GCC, Glibc protections
 
GCC, Glibc protections
GCC, Glibc protectionsGCC, Glibc protections
GCC, Glibc protections
 
Exec-shield
Exec-shieldExec-shield
Exec-shield
 
ASLR
ASLRASLR
ASLR
 
Advanced c programming in Linux
Advanced c programming in Linux Advanced c programming in Linux
Advanced c programming in Linux
 
How to get LBR contents on Intel x86
How to get LBR contents on Intel x86How to get LBR contents on Intel x86
How to get LBR contents on Intel x86
 
Data encryption standard
Data encryption standardData encryption standard
Data encryption standard
 
Linux Protections Against Exploits
Linux Protections Against ExploitsLinux Protections Against Exploits
Linux Protections Against Exploits
 

Dernier

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
anilsa9823
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Dernier (20)

Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 

C++ How to program

  • 1. M.Golyani December 2017 C++ How to program Mostly based on Paul Deitel, Harvey Deitel-C++ How to Program- Pearson (2014)
  • 2. Outline  History  Understanding the compiler basics  What is an executable?  C++ program structure  “Hello, World!”  Input, Output, Error  Variables and their types  Getting input from user  Performing arithmetic operations  “if” Conditional statement
  • 3. History of programming  1950s: Fortran, IBM corporation  1950s: Cobol, Grace Hopper (FLOW-MATIC)  1960s: Pascal, Niklaus Wirth  1960s: Basic, Dartmouth College  1970s: Ada, DoD  1972: C, Dennis Ritchie  1979: C++, Bjarne Stroustrup  1991: Java, Sun Microsystems  2001: C#, Microsoft  , …
  • 4.
  • 5.
  • 6. Programs - A sequence of instructions which perform a specific task - The CPU is responsible for executing the commands. - Each instruction is finally executed by the CPU. - The final program should be understandable for the CPU - CPU does not understand the ASCII, human readable texts (known as source files!!) - We should translate these sources to machine codes. - No matter what programming language we use, the CPU instruction set is fixed.
  • 11. Compiling the Source - Compiling a source file to create an executable, is performed in some steps as bellow: Preprocessing Compiling Assembling Linking Compiler does these in one or more passes
  • 12. Compiling the Source - Compiler does some analysis on source file: Lexical Syntax Semantic Optimizing the Code Code Generation Symbol Table Error Handler Intermediate Code Generation
  • 13. Linux C++ compiler  g++:  g++ <SOURCE>  g++ -o <EXECUTABLE> <SOURCE>  gcc:  gcc <SOURCE>  gcc -o <EXECUTABLE> <SOURCE>  GCC: GNU Compiler Collection
  • 14. Linux C++ compiler - The Gnu Compiler Collection (GCC) project started by Richard Stallman in 1985. - GCC includes front-ends for lots of languages including: • C (gcc) • C++ (g++) • Java (gcj) • Ada (GNAT) • Objective-C (gobjc) • Objective-C++ • Fortran
  • 15.
  • 16. Linux Executables ELF Relocatable File (.o files) Shared Object File (.so files) Executable File There are 3 main ELF object files: Linux executable files are in ELF format (Executable and Linkable Format) There is no need for specific file extension in Linux, only permission Core Dumps
  • 17. C++ libraries  Each C++ program consists of “classes” and “functions”  These are pieces of code that perform special tasks  Printing a string in the output, opening a file for writing, accessing specific parts of the memory and …  If your program needs to do these tasks, you can write the code yourself, or you can use the already provided functions and classes.  These already prepared functions and classes are packed into “libraries”  There are lots of libraries available and you can
  • 18. C++ libraries  Shorter development time  Probably better performance  Improves program portability  You don’t need to worry about updating and maintenance of these libs. The “C++ standard library” is a rich collection of most needed functions and classes
  • 19. C++ header files  The C++ standard library is automatically attached to your program.  The functions and classes in the C++ standard library are categorized into several sections.  To use each section, you should “include” the appropriate header file in your source code.  To include a header file, you should use “#include” phrase. #include <iostream>
  • 20. C++ header files Header file Usage iostream Several standard stream objects (input, output, …) memory Memory management utilities cerrno To view the last error number cmath Common mathematics functions chrono C++ time utilities … … … …
  • 21. How can we make our own header files ???
  • 22. Sample C++ program structure #include <iostream> int main() { …. /* These lines are comment as well */ …. return 0; } // This is a comment Header files that we need Compiler will not compile this line This means that the main() function is going to return an integer after it finishes it’s work Each program should have a “main” function This return value is used by other programs and shell to check for errors. There could be lots of other functions and codes in our program, starting from main function
  • 23. Hello, World! You need to know how to create a text file in Linux CLI This entity belongs to “std” namespace We indicate that this way Returning a Zero from main means that the program has ended successfully Lines starting with # are directives to the “preprocessor” which is run before the compiler. This line tells the preprocessor to include the “iostream” header file
  • 24. Hello, World!  Always use and update comments in your code  C++ statements should end with “;” (almost all of them)  “syntax error” indicates you have something wrong in your coding syntax.  Whitespaces and blank lines are OK.  Use “TAB”, blank lines and whitespaces to have a human readable code!
  • 25. Input, Output, Error  The std namespace contains some “standard” library routines.  cin:  Used to get data from standard input  cout:  Used to send data to standard output  cerr:  Used to send data to standard error  , … Usually the STDIN, STDOUT, and STDERR are connected to the working terminal
  • 26. Input, Output, Error Use “std::cerr” to send error messages to STDERR
  • 27. How can we redirect program’s output to one file and errors to another?
  • 28. Escape sequence  The “” character in output string is an “escape character”  According to what comes after “”, the output differs.  The “” and the following character is named “escape sequence”
  • 29. Variables  We use variables to store data.  Variables are placed in computer’s memory (RAM).  To use a variable, we should first declare it. Variable declaration Add comments here to remember why you have declared this variable Variable declaration could be anywhere, just remember to declare before use
  • 30. Variables  Each variable has its own type, name, size, and value.  Integer, float, double,…  String, char, …  , …. The “int” phrase is a keyword. We can’t use keywords as our variable names!
  • 31. C++ variable types Type Meaning Example int Integer numbers -3, 0, 5 double Real numbers 3.4, 0.04, -2.5 float Real numbers ??? char Any single character ‘A’, ‘+’, ‘*’ bool Boolean type “true” or “false” … … … Type Meaning Signed Negative or positive Unsigned Only positive Long At least 32 bits Short At least 16 bits
  • 32. Input from user  Using std::cin, you can get input from command line.  Remember the direction of “>>” and “<<“  Using “std::cout” at each statement is awkward!
  • 33. How can we provide a program’s required inputs to avoid interaction?
  • 34. Arithmetic operations  You can use “using” declaration to avoid repeating “std::”
  • 35. Arithmetic operations  The precedence of arithmetic operations are important.  Parentheses are always considered first.
  • 36. y = a * x * x + b * x + c ; Arithmetic operations 16 2 4 3 5
  • 37. Arithmetic operations  What is the output of this program?  1  2  9  10  0
  • 38. Arithmetic operation If there are lots of names that we want to use, we should declare them here
  • 39. Conditional statement  “if” statement is used to implement conditional statements. if ( CONDITION ) { ....... ....... ....... } else { ....... ....... ....... } If “CONDITION” is true, then this piece of code is executed If “CONDITION” is NOT true, then this piece of code is executed
  • 40. Conditional statement  “CONDITION”s in if statements, can be formed by using the “relational operators” and “equality operators”
  • 41. Conditional statement  What is wrong in this program? Notice that we used “using” directive here instead of using multiple using declaration. This enables the program to use all the names in any standard C++ header that a program might include. If the statements of the condition are one line length, you can omit the { … } block.
  • 42. End of Section 1  In this section, you learned about:  What is an executable  How compilers work  What are libraries and headers  C++ program structure  How to send strings to stdout, stderr  How to get user input from stdin  Variables and their types  Arithmetic operations and their precedence  “if” conditional statement and it’s usage

Notes de l'éditeur

  1. If CPU executes the code, so why can’t we run MS Windows exe on Linux box?
  2. In first program, show that spaces don’t matter, but coding style matters.
  3. http://en.cppreference.com/w/cpp/header
  4. And libraries…
  5. Test the return value…
  6. << operator overloading Return non-zero, work with \n, \t, \a , …
  7. D&D, pp42 Man printf
  8. HW: What is the difference between double and float?, what is the maximum size of these types? Appendix C deitel&deitel
  9. Ex: What will happen if you replace all “int” s to “double” s??
  10. Deitel & Deitel C++ How to program, p51 Parentheses is not an arithmetic operator
  11. Ex: write a program that gets user’s age and prints the year of birth
  12. Ex: write a program to get user’s age, compute the date of birth and check if he is old. D&D C++ How to Program, p53
  13. D&D C++ How to Program, p53