Introduction To C++ Programming Language

LECTURE

MELJUN CORTES, MBA,MPA

What is C++
C++ is a high-level language and it is evolved from C over a period of several years starting in 1980.  The standard for C++ was jointly developed by the American National Standards Institute (ANSI) and the International Standards Organization (ISO).  a set of rules, symbols, and special words used to construct a computer program.

Structure of a C++ Program

Figure 3.1 Structure of a C++ Program

A Typical C++ Program
// A typical C++ Program

Comment Preprocessor Directive

# include <header files> using namespace std; # define PI 3.142
int Integer;

Global Declaration Local declaration Main function

int main ( ) { double radius, area; radius = 7; area = radius * radius * PI; return 0; }

Statements

Character Set

C++ is composed of character set :

Number : 0 to 9
Alphabetical : a to z and A to Z



Spacing
Special Character :
, . : ; ? ! ( ) {} “ „ + - * / = > < # % & ^ ~ | / _

Token

Token : combination of the characters in C++ Categorised into:
  

Identifiers
Reserved words/keywords Constants


 

Literal String
Punctuators Operators

Identifiers

Allows programmers to name data and other objects in the program-variable, constant, function etc. Can use any capital letter A through Z, lowercase letters a through z, digits 0 through 9 and also underscore ( _ ) Rules for identifier  The first character must be alphabetic character or underscore  It must consists only of alphabetic characters, digits and underscores, cannot contain spaces  It cannot duplicate any reserved word C++ is case-sensitive; this means that CASE, Case, case, and CaSe are four completely different words.

Valid and Invalid Identifiers
Valid names
A  student_name  _aSystemName  pi  al  stdntNm  _anthrSysNm  PI

Invalid names
 $sum

// $ is illegal  2names // can‟t start with 2  stdnt Nmbr // can‟t have space  int // reserved word

Reserved word/Keywords
A word that has special meaning in C++.  Keywords cannot be used to name identifiers.

Constant
Data values that cannot be changed during the execution of a program  Types of constant:

 Literals

constant  Defined constants  Declared constants

Literals Constant

If the data cannot be changed, we can simply code the data value itself in a statement
Eg: discount = 0.10 ;
0.10 is a literal constant

Categorised into:
 Integer

Numerals ( eg: 178, -9, 0113, 0x4b)  Floating-Point Numerals (eg: 3.14159,6.02e23,1.6e-19
,3.0
 Characters

( eg: „A‟, „p‟)  Strings ( eg; “Hello World”)  Boolean (eg: true , false).

Defined Constant (#define)

Use the #define preprocessor directive Format: #define identifier value  Eg : #define EPF_RATE 0.11
Placed at the beginning of the program
#include <header files> using namespace std; #define EPF_RATE 3.142

int main() { ……; nett = salary – ( salary * EPF_RATE); ………; }

Declared Constants
Use a type const qualifier to indicate that data cannot be changed and to fix the contents of the memory location  Eg: const float pi = 3.1416;
 

Declared inside a function
#include <header files> using namespace std; #define EPF_RATE 3.142

int main() { const double socso_rate = 0.05; nett = salary – ( salary * EPF_RATE * socso_rate); ………; }

Data Types in C++

Type defines a set of value and operations that can be applied on those values Set of values for each type is known as the domain for the type

Functions also have types which is determined by the data it returns

Data Types

Standard

They serves as the basic building blocks for derived types (complex structures that are built using the standard types

Serves as the basic building blocks for derived types

Data Types

Derived

Data Type : Void


 

Typed as void Has no values and operations Both set of values are empty Usually used in functions
 Eg:

void printSum()

Data Type : Char

 

Used to hold characters or very small integer values Usually 1 byte of memory CODE:
char letter; letter = 'C';

Data Type : Integer


Coded as int A number without a fraction part C++ supports three different sizes of integer
 short

int int

 int
 long

Can be signed and unsigned

Data Type : Integer
Type Byte Size Minimum Value -32,768 0 -2,147,483,648 0 -2,147,483,648 Maximum Value

short int unsigned short int int unsigned int long int

2 2 4 4 4

32,767 65,535 2,147,483,647 4,294,967,295 2,147,483,647

unsigned long int

4

0

4,294,967,295

Data Type : Float

 

A number with fractional part such as 43.32, - 2.33 C++ supports three types of float  float  double  long float Stored in a form similar to scientific notation Can be represented in  Fixed point (decimal) notation: 31.4159 0.0000625  E notation: 3.14159E1 6.25e-5

Data Type Float

Are double by default Can be forced to be float (3.14159f) or long double (0.0000625L)

All floating-point numbers are signed
Type float double long double Byte Size 4 8 8 Precision 7 15 15 Range 10-37 ..1038 10-307 ..10308 10-307 ..10308

Data Type : Boolean

Represents values that are true or false


bool variables are stored as small integers
false is represented by 0, true by 1:
bool allDone = true;
bool finished = false;
allDone finished

0

Variables

 

A storage location in memory whose contents can change while program is running Has an identifier and a type of data it can hold Variable declaration syntax :
type identifier [= initial_value] eg : int itemsOrdered;

To hold the number of items ordered.

A variable name should represent the purpose of the variable.

Variables

Variables Initialization

To initialize a variable means to assign it a value when it is declared: int length = 12;

Can initialize some or all variables:
int length = 12, width = 5, area;

Variables Assignment

An assignment statement uses the = operator to store a value in a variable. item = 12; This statement assigns the value 12 to the item variable. The variable receiving the value must appear on the left side of the = operator. This will NOT work: // ERROR! 12 = item;

Variables Scope

The scope of a variable: the part of the program in which the variable can be accessed A variable cannot be used before it is defined

Variables Scope
#include <iostream> using namespace std; #define EPF_RATE 0.11 double nett = 0; bool isEmployee; int main() { double salary; isEmployee = true nett = salary – ( salary * EPF_RATE); ………; } void printSalary() { int Integer = 150;

Global Variables

Local Variable

Local Variable

cout << “Total Salary = “ << nett + Integer }

Variables Scope

Global scope
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, whenever it is after its declaration.

Local Scope
a

local variable is one declared within the body of a function or a block.  is limited to the block enclosed in braces ({})

Operators

C ++ uses a set of built in operators ( Eg : +, -, / etc). Four classes of operators :
 Arithmetic

 Relational
 Logical  Assignment

Arithmetic Operators

Assume int a=4, b= 5, d;
C++ Operation Addition Substraction Arithmetic Operator + C++ Expression d=a+b d=b-2 Value of d after assignment 9 3

Multiplication
Division Modulus

*
/ %

d=a*b
d = a/2 d = b%3

20
2 2

Assignment Operators

Assume x=4, y=5, z=8;
Assignment Operator += -= *= /= %= Sample Expression x += 5 y -= x x *= z z /=2 y %=x Similar Expression x=x+5 y=y-x x = x*z z = z/2 y = y%x Value of variable after assignment x=9 y=1 x=32 z=4 y=1

Relational & Equality Operators

Assume y = 6, x =5
Relational Operators > < >= Sample Expression y>x y<2 x >= 3 Value T F T

<=
Equality Operators == !=

y <= x
Sample Expression x == 5 y !=6

F
Value T F

Logical Operators
Logical Operators && || ! Called AND OR NOT Sample Operation expression1 && expression 2 expression1 | | expression2 !expression

Example :Assume int x = 50
expression !expression Sample Expression

F
T

T
F

!(x == 60)
!(x != 60)

Logical Operators

Assume x=4, y=5, z=8
expression1 expression2 expression1 && expression2 Sample Expression

F
F T T

F
T F T

F
F F T

( y > 10) && ( z <=x )
( z <= y) && ( x == 4) ( y != z) && ( z < x ) ( z >= y ) && ( x != 3 )

Increment and Decrement Operators
Operator Called Sample Expression ++a Similar Expression a = a +1 a += 1 ++ postincrement a++ a = a +1 a += 1 -predecrement --a a = a -1 a -= 1 -postdecrement a-a = a -1 a -= 1 Explanation ++ preincrement Increment a by 1, then use the new value of a in expression in which a reside Use the current value of a in the expression which a reside, then increment a by 1 Decrement a by 1, then use the new value of a in expression in which a reside Use the current value of a in the expression which a reside, then decrement a by 1

Operator Precedence
Operators () ++ - - + - ! Associative Left to right Right to left

* / %
+ < <= > >= = = != && || *= += - = /= %=

Left to right
Left to right Left to right Left to right Left to right Left to right Right to left

Operator Precedence
Example 1:

Example 2:
int a=15, b=6, c=5, d=4; d *= ++b – a/3 + c
1. d *= ++b – a/3+ c
2. d*=7- a/3+c 3. d*=7- 5+c 4. d*=2 + c 5. d*= 7 6. d = d*7 7. d = 28

int a=10, b=20, c=15, d=8;
a*b/(-c*31%13)*d
1.

a*b/(-15*31%13)*d

2.
3. 4. 5. 6.

a*b/(-465%13)*d
a*b/(-10)*d 200/(-10)*d

-20*d
-160

Example of a program
// Operating with variables #include <iostream> using namespace std;
int main() { //variables declaration int no1; int no2; int value_div; int value_mod; cout << “Enter two integral numbers:”; cin >> no1 >> no2; value_div= no1 / no2; cout << no1 << “ / ” << no2 << “ is ” << value_div;

Output :
Enter two integral numbers : 10 6 10 / 6 is 1 with a remainder of 4

value_mod = no1 % no2; cout << “ with a remainder of ” << value_mod << endl; return 0;
}

/*Evaluate two complex expression*/ #include <iostream> using namespace std; void main ( ) { int a =3, b=4, c = 5, x, y; cout << “Initial values of the variables:\n”; cout << “a = “ << a<< “ b = “ << b <<“ c = “ << c<< endl; cout << endl; Output : Initial values of the variables : a=3 b=4 c= 5

x = a * 4 + b / 2 – c * b;
cout << “Value of a * 4 + b/2-c * b is : “ << x << endl; y = - - a * (3 + b) / 2 – c++ * b; Value of a * 4 + b/2-c * b is : -6 Value of - - a * (3 + b) / 2 – c++ * b is: -13 Values of the variables are now :

cout << “Value of - - a * (3 + b) / 2 – c++ * b is: “
<< y << endl; cout << “a = “ << a << “ b = “ << b << “ c = “ << c << endl; }

a=2

b=4 c= 6

Formatting Output

Output is made more readable using manipulator

Must include <iomanip> header file.
Manipulators endl dec oct hex fixed showpoint setw(…) setprecision setfill(…) Use New line Formats output as decimal Formats output as octal Formats output as hexadecimal Set floating-point decimals Shows decimal in floating-point values Sets width of output fields Specifies number of decimals for floating point Specifies fill character

Formatting Output

Set Width (setw)
 Set

the minimum width for an output  Two alignment : right justified and left justified

Set Fill Character (setfill)
 If

the output width is greater than the data values placed in it, a fill character can be used to fill the empty spaces whenever required

Formatting Output

Three integer manipulators:
 Decimal
 The

(dec)

default  Value in decimal form
 Octal

(oct)
are displayed in octal numbering system

 Values

 Hexadecimal
 Values

(hex)

are in hexadecimal format

Formatting Output

Three Floating-point manipulators: Fixed (fixed)
 Displays

floating-point numbers (eg: 1.234568e+6) in the fixed-point format (1234567.875) to control the number of the decimal places to be displayed show value with the decimal point

Set precision (setprecision)
 Used

Showpoint (showpoint)
 To

//demonstrate the output manipulator #include <iostream> #include <iomanip> using namespace std; int main( ) {

char aChar;
int integer; float dlrAmnt;

Output :
cout << “Please enter an integer ,\n”; << “ a dollar amount and a character.\n”; cin >> integer>>dlrAmnt >> aChar; cout <<“\nThank you.You entered:\n”; Please enter an integer, a dollar amount and a character. 12 123.45 G

Thank you. You entered: 12 $****123.45 G

cout << setw( 6 ) << integer << “ “
<< setfill(„*‟) << setprecision (2) << fixed << „$‟ << setw(10) << dlrAmnt << setfill(„ „) << setw( 3 ) <<aChar << endl; 46 }

THANK YOU!

Sign up to vote on this title
UsefulNot useful

Master Your Semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master Your Semester with a Special Offer from Scribd & The New York Times

Cancel anytime.