SlideShare uma empresa Scribd logo
1 de 43
COMPUTATIONAL PHYSICS
LEC#04
REHMAN RASHEED
C/C++
1. Structure of a program
2. Variables, Data Types, and
Constants
3. Operators
4. Basic Input / Output
5. Control structures
6. Functions
7. Arrays
8. Input / Output with files
9. Pointers
Part 1: Structure of a program
// Simple program
#include <iostream>
using namespace std;
int main()
{
int x, y;
x = 2;
y = x + 4;
cout <<" x = "<<x<<" x + 4 = "<<y,< endl;
return 0;
}
Output: x = 2 x + 4 = 6
Common structure of a program
1. Comments
2. Header files
3. Declare variables
4. Declare constants
5. Read initial data
6. Open files
7. CALCULATIONS (include calling other functions)
8. Write results
9. Closing
10. Stop
Part 2: Variables, Data Types, and Constants
Variables, Data Types and Constants
• Identifiers (names of variables)
• Fundamental data types
• Declaration of variables
• Global and local variables
• Initialization of variables
• Constants
Variables and Identifiers
Variable is a location in the computer’s memory
where a value can be stored for use by a program.
A variable name is any valid identifier. An identifier
is a series of characters consisting of letters, digits,
and underscore (_) that does not begin with a digit.
C++ is case sensitive – uppercase and lowercase
letters are different.
Examples: abs, Velocity_i, Force_12
Identifiers: reserved key words
These keywords must not be used as identifiers!
C and C++ keywords
Auto break case char const continue
default do double else enum extern
float for goto if int long register
return short signed sizeof static struct
switch typedef union unsigned void
volatile while
Identifiers: reserved key words II
C++ only keywords
asm bool catch class const_cast delete
dynamic_cast explicit false friend inline
mutable namespace new operator private
protected public reinterpret_cast static_cast
template this throw true try typeid
typename using virtual wchar_t
Variable Data Types
Each variable has a name, a type, a size and a value. Fundamental data types in
C++
Name Description Bytes
char Character or small integer 1
short int Short Integer 2
int Integer 4
long int Long integer 4*
Long long int Long integer 8
bool Boolean 1
float Floating point number 4
double Double precision floating point 8
long double Long double precision 8*
wchar_t Wide character 2
Range of data types in C++
name range bytes
short int signed: -32768 to 32767
unsigned: 0 to 65535 2
int -2,147,483,648 to 2,147,483,647
unsigned: 0 to 4,294,967,295 4
Bool true or false 1
float 3.4e +/- 38 (7 digits) 4
Double 1.7e +/- 308 (15 digits) 8
long double 1.7e +/- 308 (15 digits) 8*
Declaration of variables
//declaration of variables
#include<iostream>
using namespace std;
int main()
{
double a, speed, force_12;
int i, n;
... some operators ...
return 0; }
All variables must be declared with a name and a data
type before they can be used by a program
A global variable is a variable declared in the main body of
the source code, outside all functions. Global variables can be
referred from anywhere in the code, even inside functions
A local variable is one declared within the body of a function
or a block. The scope of local variables is limited to the block
enclosed in braces {} where they are declared.
Initialization of variables
When declaring a regular local variable, its value is by
default undetermined.
Initialization 1:
type identifier = initial_value;
float sum = 0.0;
Initialization 2:
type identifier (initial_value) ;
float sum (0.0);
Constants
Declared constants
const type identifier = initial_value ;
const double pi = 3.1415926;
Constant variable can not be modified thereafter.
Define constants
#define identifier value
#define PI 3.14159265
Example: Add Two integers in C++
#include <iostream>
using namespace std;
int main()
{
int x, y, Sum;
x = 2;
y = 4;
Sum=x+y;
cout <<" Sum = "<<Sum<<endl;
return 0;
}
Output: Sum = 6
https://sourceforge.net/projects/embarcadero-devcpp/
Part 3: Operators
Operators
• Assignment (=)
• Arithmetic operators ( +, -, *, /, % )
• Compound assignation (+=, -=, *=, /=, %=)
• Increment and decrement (++, --)
• Relational and equality operators ( ==, !=, >, =, <= )
Assignment operator (=)
The assignment operator assigns a value to a
variable
#include<iostream>
using namespace std;
int main ()
{ int a, b;
a = 12;
b = a;
cout << " a = " << a << " b = " << b <<endl;
return 0;
}
Arithmetic operators
There are five arithmetic operators
Operator Symbol C++ example
1. addition + f + 7
2. subtraction - p - c
3. multiplication * b * k
4. division / x / y
5. modulus % r % s
The increment/decrement operators
Operator called C++
++ pre increment ++a
++ post increment a++
-- pre decrement --a
-- post decrement a--
Equality and relational operators
Equality operators in decision making
C++ example meaning
== x == y x is equal to y
!= x != y x is not equal to y
Relational operators in decision making
C++ example meaning
> x > y x is greater than y
< x < y x is less than y
>= x >= y x is greater or equal to y
<= x <= y x is less than or equal to y
Logical operators
C++ provides logical operators that are used to form
complex conditions by combining simple conditions.
Operator Symbols C++ example
and && if (i==1 && j>=10)
or || if (speed>=10.0 || t <=2.0)
Part 4: Basic Input / Output
Input / Output
The C++ libraries provide an extensive set of
input/output capabilities.
C++ I/O occurs in stream of bytes.
Iostream Library header files
<iostream> contains cin, cout, cerr, clog.
<iomanip> information for formatting
<fstream> for file processing
Basic Input / Output
cin is an object of the istream class and is
connected to the standard input device (normally
the keyboard)
cout is an object of the ostream class and is
connected to the standard output device (normally
the screen)
// output
#include<iostream>
using namespace std;
int main ()
{ int a;
a=2;
cout << " a = " << a << endl;
//cout << “ a = “ << a << endl;
return 0; }
OUTPUT a=2
// Input and output
#include<iostream>
using namespace std;
int main ()
{ int a, b;
cout << " enter two integers:";
cin >> a >> b;
cout << " a = " << a << " b = " << b << endl;
return 0; }
OUTPUT enter two integers:2 4 a = 2 b = 4
Part 5: Control structures
Three types of selection structures:
• if single-selection structure
• if/else double-selection structure
• switch multiple-selection structure
if - single-selection structure
The if selection structure performs an indicated action
only when the condition is true; otherwise the
condition is skipped
if (grade >=60)
cout << "passed";
if/else - double-selection structure
The if/else selection structure allows the programmer
to specify that a different action is to be performed
when the condition is true than when the condition is
false.
if (grade >=60)
cout << "passed";
else
cout << "failed";
switch - multiple-selection structure
switch (x)
{ case 1:
cout << "x is 1";
break;
case 2:
cout << "x is 2";
break;
default: cout << "value of x unknown"; }
Three types of repetition structures:
1. while
2. do/while
3. for
The while repetition structure
A repetition structure allows the programmer to specify
an action is to be repeated while some condition remains
true
int n = 2;
while (n <= 100)
{n = 2 * n;
cout < n;}
The do/while repetition structure
The loop-continuation condition is not executed
until after the action is performed at least once
do { statement } while (condition);
int i = 0;
do { cout << i;
i = i + 10; }
while (i <=100);
The for repetition structure.
The for repetition structure handles all the details of counter-
controlled repetition.
for (i=0; i <=5; i=i+1)
{ … actions … }
The break and continue statements
The break and continue statements alter the flow of the
control.
The break statement, when executed in a while, for,
do/while, or switch structure, causes immediate exit from
that structure.
The continue statement, when executed in a while, for, or
do/while structure, skips the remaining statements in the
body of the structure, and proceeds with the next iteration.
// using the break statement
#include<iostream>
using namespace std;
int main ()
{ int n;
for (n = 1; n <=10; n = n+1)
{ if (n == 5)
break;
cout << n << " ";
} cout << "nBroke out of loop at n of " << n << endl;
return 0; }
OUTPUT 1 2 3 4 Broke out of loop at n of 5
// using the continue statement
#include<iostream>
using namespace std;
int main()
{ for ( int x=1; x<=10; x++)
{ if (x == 5)
{continue;}
cout << x << " "; }
cout << "nUsed continue to skip printing 5" << endl;
return 0; }
OUTPUT 1 2 3 4 6 7 8 9 10 Used continue to skip printing 5
CP 04.pptx

Mais conteúdo relacionado

Semelhante a CP 04.pptx

Java Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionJava Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionSvetlin Nakov
 
Practical basics on c++
Practical basics on c++Practical basics on c++
Practical basics on c++Marco Izzotti
 
System programmin practical file
System programmin practical fileSystem programmin practical file
System programmin practical fileAnkit Dixit
 
Getting Started Cpp
Getting Started CppGetting Started Cpp
Getting Started CppLong Cao
 
OOPS using C++
OOPS using C++OOPS using C++
OOPS using C++cpjcollege
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptxNelyJay
 
Introduction to C++ lecture ************
Introduction to C++ lecture ************Introduction to C++ lecture ************
Introduction to C++ lecture ************Emad Helal
 
Programming using c++ tool
Programming using c++ toolProgramming using c++ tool
Programming using c++ toolAbdullah Jan
 
C++ process new
C++ process newC++ process new
C++ process new敬倫 林
 
The best every notes on c language is here check it out
The best every notes on c language is here check it outThe best every notes on c language is here check it out
The best every notes on c language is here check it outrajatryadav22
 
C cpluplus 2
C cpluplus 2C cpluplus 2
C cpluplus 2sanya6900
 
Getting started cpp full
Getting started cpp   fullGetting started cpp   full
Getting started cpp fullVõ Hòa
 

Semelhante a CP 04.pptx (20)

Java Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionJava Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type Conversion
 
Practical basics on c++
Practical basics on c++Practical basics on c++
Practical basics on c++
 
System programmin practical file
System programmin practical fileSystem programmin practical file
System programmin practical file
 
Getting Started Cpp
Getting Started CppGetting Started Cpp
Getting Started Cpp
 
Lecture2.ppt
Lecture2.pptLecture2.ppt
Lecture2.ppt
 
OOPS using C++
OOPS using C++OOPS using C++
OOPS using C++
 
901131 examples
901131 examples901131 examples
901131 examples
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 
C
CC
C
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptx
 
Introduction to C++ lecture ************
Introduction to C++ lecture ************Introduction to C++ lecture ************
Introduction to C++ lecture ************
 
Programming using c++ tool
Programming using c++ toolProgramming using c++ tool
Programming using c++ tool
 
C++ Functions
C++ FunctionsC++ Functions
C++ Functions
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 
Oops presentation
Oops presentationOops presentation
Oops presentation
 
C++ process new
C++ process newC++ process new
C++ process new
 
The best every notes on c language is here check it out
The best every notes on c language is here check it outThe best every notes on c language is here check it out
The best every notes on c language is here check it out
 
Prog1-L2.pptx
Prog1-L2.pptxProg1-L2.pptx
Prog1-L2.pptx
 
C cpluplus 2
C cpluplus 2C cpluplus 2
C cpluplus 2
 
Getting started cpp full
Getting started cpp   fullGetting started cpp   full
Getting started cpp full
 

Mais de RehmanRasheed3

Principle And Working of A Semiconductor Laser.pptx
Principle And Working of A Semiconductor Laser.pptxPrinciple And Working of A Semiconductor Laser.pptx
Principle And Working of A Semiconductor Laser.pptxRehmanRasheed3
 
Cocchi_talk_EWPAA2019.pptx
Cocchi_talk_EWPAA2019.pptxCocchi_talk_EWPAA2019.pptx
Cocchi_talk_EWPAA2019.pptxRehmanRasheed3
 
Numerical Methods.pptx
Numerical Methods.pptxNumerical Methods.pptx
Numerical Methods.pptxRehmanRasheed3
 
Gauss jordan method.pptx
Gauss jordan method.pptxGauss jordan method.pptx
Gauss jordan method.pptxRehmanRasheed3
 

Mais de RehmanRasheed3 (8)

Principle And Working of A Semiconductor Laser.pptx
Principle And Working of A Semiconductor Laser.pptxPrinciple And Working of A Semiconductor Laser.pptx
Principle And Working of A Semiconductor Laser.pptx
 
Cocchi_talk_EWPAA2019.pptx
Cocchi_talk_EWPAA2019.pptxCocchi_talk_EWPAA2019.pptx
Cocchi_talk_EWPAA2019.pptx
 
chapter17.ppt
chapter17.pptchapter17.ppt
chapter17.ppt
 
cp05.pptx
cp05.pptxcp05.pptx
cp05.pptx
 
Numerical Methods.pptx
Numerical Methods.pptxNumerical Methods.pptx
Numerical Methods.pptx
 
5-1-reimann-sums.ppt
5-1-reimann-sums.ppt5-1-reimann-sums.ppt
5-1-reimann-sums.ppt
 
Prerna actual.pptx
Prerna actual.pptxPrerna actual.pptx
Prerna actual.pptx
 
Gauss jordan method.pptx
Gauss jordan method.pptxGauss jordan method.pptx
Gauss jordan method.pptx
 

Último

Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
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
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
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
 
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
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
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
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 

Último (20)

Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
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
 
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"
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
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
 
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
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
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
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 

CP 04.pptx

  • 2. C/C++ 1. Structure of a program 2. Variables, Data Types, and Constants 3. Operators 4. Basic Input / Output 5. Control structures 6. Functions 7. Arrays 8. Input / Output with files 9. Pointers
  • 3. Part 1: Structure of a program
  • 4. // Simple program #include <iostream> using namespace std; int main() { int x, y; x = 2; y = x + 4; cout <<" x = "<<x<<" x + 4 = "<<y,< endl; return 0; } Output: x = 2 x + 4 = 6
  • 5. Common structure of a program 1. Comments 2. Header files 3. Declare variables 4. Declare constants 5. Read initial data 6. Open files 7. CALCULATIONS (include calling other functions) 8. Write results 9. Closing 10. Stop
  • 6. Part 2: Variables, Data Types, and Constants
  • 7. Variables, Data Types and Constants • Identifiers (names of variables) • Fundamental data types • Declaration of variables • Global and local variables • Initialization of variables • Constants
  • 8. Variables and Identifiers Variable is a location in the computer’s memory where a value can be stored for use by a program. A variable name is any valid identifier. An identifier is a series of characters consisting of letters, digits, and underscore (_) that does not begin with a digit. C++ is case sensitive – uppercase and lowercase letters are different. Examples: abs, Velocity_i, Force_12
  • 9. Identifiers: reserved key words These keywords must not be used as identifiers! C and C++ keywords Auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while
  • 10. Identifiers: reserved key words II C++ only keywords asm bool catch class const_cast delete dynamic_cast explicit false friend inline mutable namespace new operator private protected public reinterpret_cast static_cast template this throw true try typeid typename using virtual wchar_t
  • 11. Variable Data Types Each variable has a name, a type, a size and a value. Fundamental data types in C++ Name Description Bytes char Character or small integer 1 short int Short Integer 2 int Integer 4 long int Long integer 4* Long long int Long integer 8 bool Boolean 1 float Floating point number 4 double Double precision floating point 8 long double Long double precision 8* wchar_t Wide character 2
  • 12. Range of data types in C++ name range bytes short int signed: -32768 to 32767 unsigned: 0 to 65535 2 int -2,147,483,648 to 2,147,483,647 unsigned: 0 to 4,294,967,295 4 Bool true or false 1 float 3.4e +/- 38 (7 digits) 4 Double 1.7e +/- 308 (15 digits) 8 long double 1.7e +/- 308 (15 digits) 8*
  • 13. Declaration of variables //declaration of variables #include<iostream> using namespace std; int main() { double a, speed, force_12; int i, n; ... some operators ... return 0; } All variables must be declared with a name and a data type before they can be used by a program
  • 14. A global variable is a variable declared in the main body of the source code, outside all functions. Global variables can be referred from anywhere in the code, even inside functions A local variable is one declared within the body of a function or a block. The scope of local variables is limited to the block enclosed in braces {} where they are declared.
  • 15. Initialization of variables When declaring a regular local variable, its value is by default undetermined. Initialization 1: type identifier = initial_value; float sum = 0.0; Initialization 2: type identifier (initial_value) ; float sum (0.0);
  • 16. Constants Declared constants const type identifier = initial_value ; const double pi = 3.1415926; Constant variable can not be modified thereafter. Define constants #define identifier value #define PI 3.14159265
  • 17. Example: Add Two integers in C++ #include <iostream> using namespace std; int main() { int x, y, Sum; x = 2; y = 4; Sum=x+y; cout <<" Sum = "<<Sum<<endl; return 0; } Output: Sum = 6
  • 20. Operators • Assignment (=) • Arithmetic operators ( +, -, *, /, % ) • Compound assignation (+=, -=, *=, /=, %=) • Increment and decrement (++, --) • Relational and equality operators ( ==, !=, >, =, <= )
  • 21. Assignment operator (=) The assignment operator assigns a value to a variable #include<iostream> using namespace std; int main () { int a, b; a = 12; b = a; cout << " a = " << a << " b = " << b <<endl; return 0; }
  • 22. Arithmetic operators There are five arithmetic operators Operator Symbol C++ example 1. addition + f + 7 2. subtraction - p - c 3. multiplication * b * k 4. division / x / y 5. modulus % r % s
  • 23. The increment/decrement operators Operator called C++ ++ pre increment ++a ++ post increment a++ -- pre decrement --a -- post decrement a--
  • 24. Equality and relational operators Equality operators in decision making C++ example meaning == x == y x is equal to y != x != y x is not equal to y Relational operators in decision making C++ example meaning > x > y x is greater than y < x < y x is less than y >= x >= y x is greater or equal to y <= x <= y x is less than or equal to y
  • 25. Logical operators C++ provides logical operators that are used to form complex conditions by combining simple conditions. Operator Symbols C++ example and && if (i==1 && j>=10) or || if (speed>=10.0 || t <=2.0)
  • 26. Part 4: Basic Input / Output
  • 27. Input / Output The C++ libraries provide an extensive set of input/output capabilities. C++ I/O occurs in stream of bytes. Iostream Library header files <iostream> contains cin, cout, cerr, clog. <iomanip> information for formatting <fstream> for file processing
  • 28. Basic Input / Output cin is an object of the istream class and is connected to the standard input device (normally the keyboard) cout is an object of the ostream class and is connected to the standard output device (normally the screen)
  • 29. // output #include<iostream> using namespace std; int main () { int a; a=2; cout << " a = " << a << endl; //cout << “ a = “ << a << endl; return 0; } OUTPUT a=2
  • 30. // Input and output #include<iostream> using namespace std; int main () { int a, b; cout << " enter two integers:"; cin >> a >> b; cout << " a = " << a << " b = " << b << endl; return 0; } OUTPUT enter two integers:2 4 a = 2 b = 4
  • 31. Part 5: Control structures
  • 32. Three types of selection structures: • if single-selection structure • if/else double-selection structure • switch multiple-selection structure
  • 33. if - single-selection structure The if selection structure performs an indicated action only when the condition is true; otherwise the condition is skipped if (grade >=60) cout << "passed";
  • 34. if/else - double-selection structure The if/else selection structure allows the programmer to specify that a different action is to be performed when the condition is true than when the condition is false. if (grade >=60) cout << "passed"; else cout << "failed";
  • 35. switch - multiple-selection structure switch (x) { case 1: cout << "x is 1"; break; case 2: cout << "x is 2"; break; default: cout << "value of x unknown"; }
  • 36. Three types of repetition structures: 1. while 2. do/while 3. for
  • 37. The while repetition structure A repetition structure allows the programmer to specify an action is to be repeated while some condition remains true int n = 2; while (n <= 100) {n = 2 * n; cout < n;}
  • 38. The do/while repetition structure The loop-continuation condition is not executed until after the action is performed at least once do { statement } while (condition); int i = 0; do { cout << i; i = i + 10; } while (i <=100);
  • 39. The for repetition structure. The for repetition structure handles all the details of counter- controlled repetition. for (i=0; i <=5; i=i+1) { … actions … }
  • 40. The break and continue statements The break and continue statements alter the flow of the control. The break statement, when executed in a while, for, do/while, or switch structure, causes immediate exit from that structure. The continue statement, when executed in a while, for, or do/while structure, skips the remaining statements in the body of the structure, and proceeds with the next iteration.
  • 41. // using the break statement #include<iostream> using namespace std; int main () { int n; for (n = 1; n <=10; n = n+1) { if (n == 5) break; cout << n << " "; } cout << "nBroke out of loop at n of " << n << endl; return 0; } OUTPUT 1 2 3 4 Broke out of loop at n of 5
  • 42. // using the continue statement #include<iostream> using namespace std; int main() { for ( int x=1; x<=10; x++) { if (x == 5) {continue;} cout << x << " "; } cout << "nUsed continue to skip printing 5" << endl; return 0; } OUTPUT 1 2 3 4 6 7 8 9 10 Used continue to skip printing 5