SlideShare a Scribd company logo
1 of 30
Download to read offline
Introduction to Computer Programming
Basic Elements of C++
C++ Programming: From Problem Analysis to Program Design
1
Chapter Topics
• The Basics of a C++ Program
• Data Types
• Arithmetic Operators and Operator Precedence
• Expressions
• Input
• Increment and Decrement Operators
• Output
• Preprocessor Directives
• Program Style and Form
2
The Basics of a C++ Program
• A C++ program is a collection of one or more
subprograms (functions)
• Function
– Collection of statements
– Statements accomplish a task
• Every C++ program has a function called: main
3
Example Program
#include <iostream>
using namespace std;
int main()
{
cout<<"Welcome to C++ Programming"<<endl;
return 0;
}
Welcome to C++ Programming
Program Output:
4
The Basics of a C++ Program
• Programming language
– a set of rules, symbols, special words
• Rules
– syntax – specifies legal instructions
• Symbols
– special symbols ( + - * ! … )
• Special words
– reserved words
– (int, float, double, char …)
5
Identifiers
• Rules for identifiers
– must begin with letter or the underscore “_”
– followed by any combination of numerals or letters
– recommend meaningful identifiers
• Evaluate the following
ElectricCharge
23Skidoo
_snarFbLat 6
Data Types
• Definition:
– a set of values
– combined with a set of operations
7
Simple: int, float, char, bool, etc…
Structured: A collection of simple data types
Pointers: Points to address
Data Types
• Simple data types include
– Integers
– Floating point
– Enumeration
• Integer data types include
char
short
int
long
bool
Numbers, symbols, letters
Values true and false only
8
Numbers without decimals
Number Data Types
Integer & Decimal
9
Floating‐Point Types (Decimal)
• Stored using scientific notation
– the sign of the number,
– the significant digits of the number
– the sign of the power of 10
– the power of 10
10
Data Types
• Different floating‐
point types
• Note that various types will
– have different ranges of values
– require different amounts of memory
11
Data Types
• The string Type
– a programmer‐defined type
– requires #include <string>
• A string is a sequence of characters
"Hi Mom"
"We're Number 1!"
"75607"
12
Arithmetic Operators and Operator
Precedence
• Common operators for calculations
+ - * / %
• Precedence same as in algebraic usage
– Inside parentheses done first
– Next * / % from left to right
– Then + and - from left to right
13
Expressions
• An expression includes
– constants
– variables
– function calls
– combined with operators
3 / 2 + 5.0 Ans: 6
sin(x) + sqrt(y)
14
Expressions
• Expressions can include
– values all of the same type
3 + 5 * 12 – 7 Ans: 56
– values of different (compatible) types
1.23 * 18 / 9.5 Ans: 2.33053
• An operation is evaluated according to the types of
the operands
– if they are the same, the result is the type of the operands
– if the operands are different (int and float) then the
result is float
15
Type Casting
• Implicit change of type can occur
– when operands are of different type
• It is possible to explicitly specify that an expression
be converted to a different type
static_cast < type > (expression)
static_cast <int> (3.5 * 6.9 / 2.1)
Ans: 11
16
Input
• Storing data in the computer's memory requires two
steps
1. Allocate the memory by declaring a variable
2. Have the program fetch a value from the input device
and place it in the allocated memory location
x
123
cin >> x
17
int x;
123 will be stored in x
Allocating Memory
• Variable
– A memory location whose content may change during
program execution
• Declaration:
– Syntax:
type identifier;
– Example:
double x; (declaration)
int y = 45; (declaration and initialization)
Note optional initialization of
the variable
18
Allocating Memory
• Named Constant
– A memory location whose content cannot be changed
• Declaration
– Syntax:
const type identifier = value;
– Example
const double PI = 3.14159;
Note required initialization
of the named constant
19
Putting Data Into Variables
Data can be put into a variable through either:
1. At initialization time (by programmer) int x=5;
2. Assignment statement (by programmer)
– Syntax:
variable = expression;
– Example
x = 1.234;
volume = sqr (base) * height;
3. Input (read) statement (by user)
– Syntax:
cin >> variable ;
– Example
cin >> height; 20
Increment and Decrement Operators
• Pre‐increment ++x;
equivalent to x = x + 1;
• Pre‐decrement --x;
equivalent to x = x - 1;
– Pre‐(increment/decrement): Changes the value before execution of a statement
– Post‐(increment/decrement): Changes the value after execution of the statement
21
Post‐increment x++;
equivalent to x = x + 1;
Post‐decrement x--;
equivalent to x = x - 1;
Output
• Values sent to an output device
– Usually the screen
– Can also be a file or some device
• Syntax for screen output:
cout << expression << …
• Example
cout << "The total is "<< sum << endl;
Output
command Insertion
operator
Values to be
printed New line
22
Text to be
displayed
Output
• Escape sequences also used to manipulate output
cout << "The total ist "<< sum << endl;
23
Preprocessor Directives
• Commands supplied to the preprocessor
– Runs before the compiler
– Modifies the text of the source code before the compiler
starts
• Syntax
– start with # symbol
– #include <headerFileName>
• Example: #include <iostream>
24
Preprocessor Directives
• Note the preprocessor
step in the sequence
25
Namespace
• The #include <iostream> command is where
cin and cout are declared
• They are declared within a namespace called std
• When we specify
using namespace std;
– Then we need not preface the cin and cout commands
with std::cin and std::cout
26
Program Style and Form
• Every program must contain a function called main
int main ()
{ …
return 0;
}
• The int specifies that it returns an integer value
• Also you can use
void main( )
{ …
}
• The void specifies there will be no return value
27
Program Style and Form
• Variables usually declared
– inside main
– at beginning of program
• Use blanks and space to make the program easy for
humans to read
• Semicolons ; required to end a statement
• Commas used to separate things in a list int x,y,z;
28
Program Style and Form
• Documentation
– Comments specified between
/* this is a comment */
and following // also a comment
– Always put at beginning of program
/* name,
date,
cpo,
purpose of program
*/
29
Program Style and Form
• Names of identifiers should help document program
double electricCharge;
// instead of ec
• Prompt keyboard entry
cout << "Enter the value for x -> ";
cin >> x;
30

More Related Content

Similar to Basic Elements of C++

C cpluplus 2
C cpluplus 2C cpluplus 2
C cpluplus 2sanya6900
 
Programming using c++ tool
Programming using c++ toolProgramming using c++ tool
Programming using c++ toolAbdullah Jan
 
Basic elements of java
Basic elements of java Basic elements of java
Basic elements of java Ahmad Idrees
 
Object oriented programming 11 preprocessor directives and program structure
Object oriented programming 11 preprocessor directives and program structureObject oriented programming 11 preprocessor directives and program structure
Object oriented programming 11 preprocessor directives and program structureVaibhav Khanna
 
C programming language tutorial
C programming language tutorialC programming language tutorial
C programming language tutorialSURBHI SAROHA
 
Fundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptxFundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptxVigneshkumar Ponnusamy
 
270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.pptUdhayaKumar175069
 
Survey of programming language getting started in C
Survey of programming language getting started in CSurvey of programming language getting started in C
Survey of programming language getting started in Cummeafruz
 
270 1 c_intro_up_to_functions
270 1 c_intro_up_to_functions270 1 c_intro_up_to_functions
270 1 c_intro_up_to_functionsray143eddie
 
270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.pptAlefya1
 
Nitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxNitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxshivam460694
 
424769021-1-First-C-Program-1-ppt (1).ppt
424769021-1-First-C-Program-1-ppt (1).ppt424769021-1-First-C-Program-1-ppt (1).ppt
424769021-1-First-C-Program-1-ppt (1).pptadvRajatSharma
 

Similar to Basic Elements of C++ (20)

Prog1-L1.pdf
Prog1-L1.pdfProg1-L1.pdf
Prog1-L1.pdf
 
C cpluplus 2
C cpluplus 2C cpluplus 2
C cpluplus 2
 
C
CC
C
 
Programming using c++ tool
Programming using c++ toolProgramming using c++ tool
Programming using c++ tool
 
c-programming
c-programmingc-programming
c-programming
 
Basic elements of java
Basic elements of java Basic elements of java
Basic elements of java
 
c++ UNIT II.pptx
c++ UNIT II.pptxc++ UNIT II.pptx
c++ UNIT II.pptx
 
Presentation c++
Presentation c++Presentation c++
Presentation c++
 
Object oriented programming 11 preprocessor directives and program structure
Object oriented programming 11 preprocessor directives and program structureObject oriented programming 11 preprocessor directives and program structure
Object oriented programming 11 preprocessor directives and program structure
 
C programming language tutorial
C programming language tutorialC programming language tutorial
C programming language tutorial
 
Fundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptxFundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptx
 
270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt
 
Survey of programming language getting started in C
Survey of programming language getting started in CSurvey of programming language getting started in C
Survey of programming language getting started in C
 
270 1 c_intro_up_to_functions
270 1 c_intro_up_to_functions270 1 c_intro_up_to_functions
270 1 c_intro_up_to_functions
 
270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt
 
C++ basics
C++ basicsC++ basics
C++ basics
 
C++ basic.ppt
C++ basic.pptC++ basic.ppt
C++ basic.ppt
 
Nitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxNitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptx
 
424769021-1-First-C-Program-1-ppt (1).ppt
424769021-1-First-C-Program-1-ppt (1).ppt424769021-1-First-C-Program-1-ppt (1).ppt
424769021-1-First-C-Program-1-ppt (1).ppt
 
Presentation 2.ppt
Presentation 2.pptPresentation 2.ppt
Presentation 2.ppt
 

More from Jason J Pulikkottil

Overview of computers and programming
Overview of computers and programmingOverview of computers and programming
Overview of computers and programmingJason J Pulikkottil
 
Repetition, Basic loop structures, Loop programming techniques
Repetition, Basic loop structures, Loop programming techniquesRepetition, Basic loop structures, Loop programming techniques
Repetition, Basic loop structures, Loop programming techniquesJason J Pulikkottil
 
Computer Architecture Performance and Energy
Computer Architecture Performance and EnergyComputer Architecture Performance and Energy
Computer Architecture Performance and EnergyJason J Pulikkottil
 
ARM 7 and 9 Core Architecture Illustration
ARM 7 and 9 Core Architecture IllustrationARM 7 and 9 Core Architecture Illustration
ARM 7 and 9 Core Architecture IllustrationJason J Pulikkottil
 
Microprocessors and Microcontrollers 8086 Pin Connections
Microprocessors and Microcontrollers 8086 Pin ConnectionsMicroprocessors and Microcontrollers 8086 Pin Connections
Microprocessors and Microcontrollers 8086 Pin ConnectionsJason J Pulikkottil
 
Basic Electronics Theory and Components
Basic Electronics Theory and ComponentsBasic Electronics Theory and Components
Basic Electronics Theory and ComponentsJason J Pulikkottil
 
Deep Learning for Health Informatics
Deep Learning for Health InformaticsDeep Learning for Health Informatics
Deep Learning for Health InformaticsJason J Pulikkottil
 

More from Jason J Pulikkottil (12)

Overview of computers and programming
Overview of computers and programmingOverview of computers and programming
Overview of computers and programming
 
Repetition, Basic loop structures, Loop programming techniques
Repetition, Basic loop structures, Loop programming techniquesRepetition, Basic loop structures, Loop programming techniques
Repetition, Basic loop structures, Loop programming techniques
 
Selection
SelectionSelection
Selection
 
Input and Output
Input and OutputInput and Output
Input and Output
 
Computer Architecture Performance and Energy
Computer Architecture Performance and EnergyComputer Architecture Performance and Energy
Computer Architecture Performance and Energy
 
ARM 7 and 9 Core Architecture Illustration
ARM 7 and 9 Core Architecture IllustrationARM 7 and 9 Core Architecture Illustration
ARM 7 and 9 Core Architecture Illustration
 
Microprocessors and Microcontrollers 8086 Pin Connections
Microprocessors and Microcontrollers 8086 Pin ConnectionsMicroprocessors and Microcontrollers 8086 Pin Connections
Microprocessors and Microcontrollers 8086 Pin Connections
 
Basic Electronics Theory and Components
Basic Electronics Theory and ComponentsBasic Electronics Theory and Components
Basic Electronics Theory and Components
 
Electronic Circuits
Electronic CircuitsElectronic Circuits
Electronic Circuits
 
Power Amplifier
Power AmplifierPower Amplifier
Power Amplifier
 
E12 Resistor Series
E12 Resistor SeriesE12 Resistor Series
E12 Resistor Series
 
Deep Learning for Health Informatics
Deep Learning for Health InformaticsDeep Learning for Health Informatics
Deep Learning for Health Informatics
 

Recently uploaded

APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...Call Girls in Nagpur High Profile
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 

Recently uploaded (20)

APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 

Basic Elements of C++

  • 1. Introduction to Computer Programming Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design 1
  • 2. Chapter Topics • The Basics of a C++ Program • Data Types • Arithmetic Operators and Operator Precedence • Expressions • Input • Increment and Decrement Operators • Output • Preprocessor Directives • Program Style and Form 2
  • 3. The Basics of a C++ Program • A C++ program is a collection of one or more subprograms (functions) • Function – Collection of statements – Statements accomplish a task • Every C++ program has a function called: main 3
  • 4. Example Program #include <iostream> using namespace std; int main() { cout<<"Welcome to C++ Programming"<<endl; return 0; } Welcome to C++ Programming Program Output: 4
  • 5. The Basics of a C++ Program • Programming language – a set of rules, symbols, special words • Rules – syntax – specifies legal instructions • Symbols – special symbols ( + - * ! … ) • Special words – reserved words – (int, float, double, char …) 5
  • 6. Identifiers • Rules for identifiers – must begin with letter or the underscore “_” – followed by any combination of numerals or letters – recommend meaningful identifiers • Evaluate the following ElectricCharge 23Skidoo _snarFbLat 6
  • 7. Data Types • Definition: – a set of values – combined with a set of operations 7 Simple: int, float, char, bool, etc… Structured: A collection of simple data types Pointers: Points to address
  • 8. Data Types • Simple data types include – Integers – Floating point – Enumeration • Integer data types include char short int long bool Numbers, symbols, letters Values true and false only 8 Numbers without decimals
  • 10. Floating‐Point Types (Decimal) • Stored using scientific notation – the sign of the number, – the significant digits of the number – the sign of the power of 10 – the power of 10 10
  • 11. Data Types • Different floating‐ point types • Note that various types will – have different ranges of values – require different amounts of memory 11
  • 12. Data Types • The string Type – a programmer‐defined type – requires #include <string> • A string is a sequence of characters "Hi Mom" "We're Number 1!" "75607" 12
  • 13. Arithmetic Operators and Operator Precedence • Common operators for calculations + - * / % • Precedence same as in algebraic usage – Inside parentheses done first – Next * / % from left to right – Then + and - from left to right 13
  • 14. Expressions • An expression includes – constants – variables – function calls – combined with operators 3 / 2 + 5.0 Ans: 6 sin(x) + sqrt(y) 14
  • 15. Expressions • Expressions can include – values all of the same type 3 + 5 * 12 – 7 Ans: 56 – values of different (compatible) types 1.23 * 18 / 9.5 Ans: 2.33053 • An operation is evaluated according to the types of the operands – if they are the same, the result is the type of the operands – if the operands are different (int and float) then the result is float 15
  • 16. Type Casting • Implicit change of type can occur – when operands are of different type • It is possible to explicitly specify that an expression be converted to a different type static_cast < type > (expression) static_cast <int> (3.5 * 6.9 / 2.1) Ans: 11 16
  • 17. Input • Storing data in the computer's memory requires two steps 1. Allocate the memory by declaring a variable 2. Have the program fetch a value from the input device and place it in the allocated memory location x 123 cin >> x 17 int x; 123 will be stored in x
  • 18. Allocating Memory • Variable – A memory location whose content may change during program execution • Declaration: – Syntax: type identifier; – Example: double x; (declaration) int y = 45; (declaration and initialization) Note optional initialization of the variable 18
  • 19. Allocating Memory • Named Constant – A memory location whose content cannot be changed • Declaration – Syntax: const type identifier = value; – Example const double PI = 3.14159; Note required initialization of the named constant 19
  • 20. Putting Data Into Variables Data can be put into a variable through either: 1. At initialization time (by programmer) int x=5; 2. Assignment statement (by programmer) – Syntax: variable = expression; – Example x = 1.234; volume = sqr (base) * height; 3. Input (read) statement (by user) – Syntax: cin >> variable ; – Example cin >> height; 20
  • 21. Increment and Decrement Operators • Pre‐increment ++x; equivalent to x = x + 1; • Pre‐decrement --x; equivalent to x = x - 1; – Pre‐(increment/decrement): Changes the value before execution of a statement – Post‐(increment/decrement): Changes the value after execution of the statement 21 Post‐increment x++; equivalent to x = x + 1; Post‐decrement x--; equivalent to x = x - 1;
  • 22. Output • Values sent to an output device – Usually the screen – Can also be a file or some device • Syntax for screen output: cout << expression << … • Example cout << "The total is "<< sum << endl; Output command Insertion operator Values to be printed New line 22 Text to be displayed
  • 23. Output • Escape sequences also used to manipulate output cout << "The total ist "<< sum << endl; 23
  • 24. Preprocessor Directives • Commands supplied to the preprocessor – Runs before the compiler – Modifies the text of the source code before the compiler starts • Syntax – start with # symbol – #include <headerFileName> • Example: #include <iostream> 24
  • 25. Preprocessor Directives • Note the preprocessor step in the sequence 25
  • 26. Namespace • The #include <iostream> command is where cin and cout are declared • They are declared within a namespace called std • When we specify using namespace std; – Then we need not preface the cin and cout commands with std::cin and std::cout 26
  • 27. Program Style and Form • Every program must contain a function called main int main () { … return 0; } • The int specifies that it returns an integer value • Also you can use void main( ) { … } • The void specifies there will be no return value 27
  • 28. Program Style and Form • Variables usually declared – inside main – at beginning of program • Use blanks and space to make the program easy for humans to read • Semicolons ; required to end a statement • Commas used to separate things in a list int x,y,z; 28
  • 29. Program Style and Form • Documentation – Comments specified between /* this is a comment */ and following // also a comment – Always put at beginning of program /* name, date, cpo, purpose of program */ 29
  • 30. Program Style and Form • Names of identifiers should help document program double electricCharge; // instead of ec • Prompt keyboard entry cout << "Enter the value for x -> "; cin >> x; 30