Module2 - Introduction To C++ Prgming
Module2 - Introduction To C++ Prgming
Functions in C++
Tokens
Tokens act as building blocks of a program. Just like a living cell is the smallest possible unit
of life, tokens in C++ are referred to as the smallest individual units in a program.
The following tokens are available in C++ which are similar to that seen in C with the
addition of certain exclusive keywords, strings, and operators:
• Keywords
• Identifiers
• Constants
• Strings
• Operators
These elements help us to construct statements, definitions, declaration and so on. These
tokens are used to construct complete programs.
Keywords
Keywords are pre-defined or reserved words in a programming language, that gives special
meaning to the compiler and keywords are always written or typed in lower cases. Each
keyword is meant to perform a specific function in a program. Since keywords are referred
names for a compiler, they can’t be used as variable names because by doing so, we are
trying to assign a new meaning to the keyword which is not allowed. We cannot redefine
keywords. However, we can specify the text to be substituted for keywords before
compilation by using C/C++ pre-processor directives. These keywords are only to be used
for their intended purpose and not as identifiers.
Identifiers
An identifier is a name assigned to a function, variable, or any other user-defined item.
Identifiers can be from one to several characters long.
Rules for naming identifiers:
• Variable names can start with any letter of the alphabet or an underscore. Next come’s
a letter, a digit, or an underscore.
• Uppercase and lowercase are distinct.
• C++ keywords cannot be used as identifier
• They must consist of only letters, digits, or underscore. No other special character is
allowed.
• It must not contain white space.
Keyword Identifier
Keywords are predefined word that gets Identifiers are the values used to define
reserved for working program that have different programming items such as
special meaning and cannot get used variables, integers, structures, unions and
anywhere else. others and mostly have an alphabetic
character.
They help to identify a specific property They help to locate the name of the entity
that exists within a computer language. that gets defined along with a keyword.
Examples of keywords are: int, char, if, Examples of identifiers are: Test, count1,
while, do, class etc. high_speed, etc.
Constants
Constants refer to fixed values that the program may not alter and they are called literals.
This cannot be modified once they are defined.
Constants can be of any of the basic data types and can be divided into
• Integer Numerals
• Floating-Point Numerals
• Characters
• Strings
• Boolean Values.
Integer Literals
Integer constants are numbers that has no fractional parts or exponent. It refers to the whole
number.
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base
or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and
long, respectively. The suffix can be uppercase or lowercase and can be in any order.
Here are some examples of integer literals −
212 // Legal
215u // Legal
0xFeeL // Legal
078 // Illegal: 8 is not an octal digit
032UU // Illegal: cannot repeat a suffix
Following are other examples of various types of Integer literals −
85 // decimal
0213 // octal
0x4b // hexadecimal
30 // int
30u // unsigned int
30l // long
30ul // unsigned long
Floating-point Literals
A floating-point literal are also called as real constants and it has an integer part, a
decimal point, a fractional part, and an exponent part. Represent floating point literals either
in decimal form or exponential form.
While representing using decimal form, you must include the decimal point, the
exponent, or both and while representing using exponential form, you must include the
integer part, the fractional part, or both. The signed exponent is introduced by e or E.
Here are some examples of floating-point literals −
3.14159 // Legal
314159E-5L // Legal
510E // Illegal: incomplete exponent
210f // Illegal: no decimal or exponent
.e55 // Illegal: missing integer or fraction
Boolean Literals
There are two Boolean literals and they are part of standard C++ keywords −
• A value of true representing true.
• A value of false representing false.
Character Literals
Character literals are enclosed in single quotes. If the literal begins with L (uppercase only), it
is a wide character literal (e.g., L'x') and should be stored in wchar_t type of variable .
Otherwise, it is a narrow character literal (e.g., 'x') and can be stored in a simple variable
of char type.
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a
universal character (e.g., '\u02C0').
There are certain characters in C++ when they are preceded by a backslash they will have
special meaning and they are used to represent like newline (\n) or tab (\t). The list of some
of such escape sequence codes
\\ \ character
\? ? character
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
Strings
Just like characters, strings in C++ are used to store letters and digits. Strings can be
referred to as an array of characters as well as an individual data type.
It is enclosed within double quotes, unlike characters which are stored within single
quotes. The termination of a string in C++ is represented by the null character, that
is, ‘\0’. The size of a string is the number of individual characters it has.
In C++, a string can be declared in the following ways:
char name[30] = “Hello!”; // The compiler reserves 30 bytes of memory for the string.
char name[] = “Hello!”; // The compiler reserves the required amount of memory for the
string.
char name[30] = { ‘H’ , ’e’ , ’l’ , ’l’ , ’o’}; // This is how a string is represented as a set
of characters.
string name = “Hello” // The compiler reserves 32 bytes of memory.
1. ARITHMETIC OPERATORS
All basic arithmetic operators are present in C++.
operator meaning
+ add
- subtract
* multiplication
/ division
% modulo division (remainder)
An arithmetic operation involving only real operands (or integer operands) is called real
arithmetic(or integer arithmetic). If a combination of arithmetic and real is called mixed mode
arithmetic.
2. RELATIONAL OPERATORS
We often compare two quantities and depending on their relation take certain decisions for
that comparison we use relational operators.
Operator meaning
< is less than
> is greater than
<= is less than or equal to
>= is greater than or equal to
== is equal to
!= is not equal to
3. LOGICAL OPERATORS
Logical Data: A piece of data is called logical if it conveys the idea of true or false. In C++
we use int data type to represent logical data. If the data value is zero, it is considered as
false. If it is non -zero (1 or any integer other than 0) it is considered as true. C++ has three
logical operators for combining logical values and creating new logical values:
• Logical NOT (!)
• Logical OR (||)
• Logical AND (&&)
Logical AND:
In logical AND operator, If both the operands are non-zero, then condition becomes true.
Syntax: (condition 1 && condition 2)
Truth table: X Y X&&Y
0 0 0
0 1 0
1 0 0
1 1 1
Logical OR:
In logical OR operator, If any of the two operands is non-zero, then condition becomes true.
Syntax: (condition 1 || condition 2)
X Y X||Y
Truth table: 0 0 0
0 1 1
1 0 1
1 1 1
Logical NOT:
Logical NOT Operator, Use to reverses the logical state of its operand. If a condition is true,
then Logical NOT operator will make false.
Syntax: ! (condition 1 && condition 2)
Truth table: X NOT X
0 1
1 0
4. ASSIGNMENT OPERATOR
Assignment operators are used to assigning a value to a variable and store a value in the
object designated by the left operand. There are two kinds of assignment operations:
•Simple assignment
•Compound assignment
simple assignment, in which the value of the second operand is stored in the object specified
by the first operand, and compound assignment, in which an arithmetic, shift, or bitwise
operation is performed prior to storing the result.
The following are the compound assignment operators in C++
Operators Description
Multiply the value of the first operand by the value of the second
*=
operand; store the result in the object specified by the first operand.
Divide the value of the first operand by the value of the second
/=
operand; store the result in the object specified by the first operand.
Add the value of the second operand to the value of the first operand;
+=
store the result in the object specified by the first operand.
Subtract the value of the second operand from the value of the first
–=
operand; store the result in the object specified by the first operand.
Shift the value of the first operand left the number of bits specified by
<<= the value of the second operand; store the result in the object
specified by the first operand.
Shift the value of the first operand right the number of bits specified
>>= by the value of the second operand; store the result in the object
specified by the first operand.
Obtain the bitwise AND of the first and second operands; store the
&=
result in the object specified by the first operand.
The operator ++ adds one to its operand where as the operator - - subtracts one from its
operand. These operators are unary operators. The increment operator ++ adds 1 to its
operand, and the decrement operator -- subtracts 1 from its operand.
Postfix Operators
Syntax:
int x = 10;
int a;
a = x++;
The value of a will be 10 because the value of x is assigned to a and then x is incremented.
int x = 10;
int a;
a = x--;
The value of a will be 10 because the value of x is assigned to a and then x is decremented.
Prefix Operators
Syntax:
int x = 10;
int a;
a = ++x;
Syntax:
int x = 10;
int a;
a = --x;
The conditional operator (? :) is a ternary operator (it takes three operands). The conditional
operator works as follows:
• The first operand is implicitly converted to bool. It is evaluated and all side effects are
completed before continuing.
• If the first operand evaluates to true (1), the second operand is evaluated.
• If the first operand evaluates to false (0), the third operand is evaluated.
#include <iostream.h>
void main()
{
int a, b,c;
cout<<"Enter a and b values:";
cin>>a>>b;
c=a>b?a:b;
cout<<"largest of a and b is "<<c;
}
Enter a and b values:1 5
largest of a and b is 5
Operator
BitwiseOperation Example Description
Symbol
OR | x|y
Returns the bitwise OR operation
Operator
BitwiseOperation Example Description
Symbol
between x and y.
Bitwise AND operator is denoted by the single ampersand sign (&). Two integer operands
are written on both sides of the (&) operator. If the corresponding bits of both the operands
are 1, then the output of the bitwise AND operation is 1; otherwise, the output would be 0.
For example,
Bitwise OR operator
The bitwise OR operator is represented by a single vertical sign (|). Two integer operands are
written on both sides of the (|) symbol. If the bit value of any of the operand is 1, then the
output would be 1, otherwise 0.
For example,
Bitwise exclusive OR operator is denoted by (^) symbol. Two operands are written on both
sides of the exclusive OR operator. If the corresponding bit of any of the operand is 1 then
the output would be 1, otherwise 0.
For example,
9. UNARY OPERATOR
A unary operator is an operator used to operate on a single operand to return a new value. In
other words, it is an operator that updates the value of an operand or expression's value by
using the appropriate unary operators. In Unary Operator, operators have equal priority from
right to left side associativity.
9. Special operators
• The comma operator
The comma operator gives left to right evaluation of expressions. When the set of
expressions has to be evaluated for a value, only the rightmost expression is considered.
int a = 1, b = 2, c = 3, i; // comma acts as separator, not as an operator
i = (a, b); // stores b into i would first assign the value of a to i, and then assign value of b to
variable i. So, at the end, variable i would contain the value 2.
• The sizeof operator
The sizeof operator can be used to find how many bytes are required for an object to store in
memory.
For example
sizeof (char) returns 1
sizeof (float) returns 4
• Pointer operators
C++ provides two pointer operators, which are
(a) Address of Operator &
(b) Indirection Operator *.
A pointer is a variable that contains the address of another variable or you can say that a
variable that contains the address of another variable is said to "point to" the other variable. A
variable can be any data type including an object, structure or again pointer itself.
The & is a unary operator that returns the memory address of its operand. For example, if var
is an integer variable, then &var is its address. This operator has the same precedence and
right-to-left associativity as the other unary operators.
You should read the & operator as "the address of" which means &var will be read as "the
address of var".
The second operator is indirection Operator *, and it is the complement of &. It is a unary
operator that returns the value of the variable located at the address specified by its operand.
1) To access a global variable when there is a local variable with same name:
#include<iostream>
int x; // Global x
int main()
{
int x = 10; // Local x
cout << "Value of global x is " << ::x;
cout << "\nValue of local x is " << x;
return 0;
}
class Test
{
static int x;
public:
static int y;
int main()
{
Test obj;
int x = 3 ;
obj.func(x);
return 0;
}
class A
{
protected:
int x;
public:
A() { x = 10; }
};
class B
{
protected:
int x;
public:
B() { x = 20; }
};
int main()
{
C c;
c.fun();
return 0;
}
Output
A's x is 10
B's x is 20
2.new operator:
The new operator denotes a request for memory allocation on the Free Store. If sufficient
memory is available, a new operator initializes the memory and returns the address of the
newly allocated and initialized memory to the pointer variable.
Syntax to use new operator
Pointer_variable = new data-type(value);
Here, the pointer variable is the pointer of type data-type. Data type could be any built-in data
type including array or any user-defined data type including structure and class.
Example:
// Pointer initialized with NULL
// Then request memory for the variable
int *p = NULL;
p = new int;
OR
3. delete operator:
Since it is the programmer’s responsibility to deallocate dynamically allocated memory,
programmers are provided delete operator in C++ language.
Syntax:
// Release memory pointed by pointer-variable
delete pointer-variable;
Here, the pointer variable is the pointer that points to the data object created by new.
Examples:
delete p;
delete q;
To free the dynamically allocated array pointed by pointer variable, use the following form
of delete:
// Release block of memory
// pointed by pointer-variable
delete[] pointer-variable;
Example:
// It will free the entire array
// pointed by p.
delete[] p;
4. C++ Manipulator:
In C++ manipulators are used to format the data display. They are endl and setw statements
• endl
The word ‘endl’ in C++, a programming language, stands for end of line. Furthermore, the
use of the endl C++ manipulators takes place to move the cursor to the beginning of the next
line. Moreover, its working is similar to the ‘\n’ escape sequence.
cout<<”object”<<endl<<”Oriented”<<endl<<”Programming”;
• setw
The word ‘setw’ in C++ stands for set width. Furthermore, the use of the setw C++ manipulator
takes place to set the output’s field width on the output device. Moreover, by default, the
displaying or printing of the output takes place right-justified within the specified field of setw
C++ manipulators.
The use of the setw manipulator takes place to set the width of the output in a program.
Furthermore, it takes up an argument ‘n’, the width of the field in which the displaying of the
output is to take place. Moreover, the output in the field, by default, is right-aligned.
The ‘n’ indicates the field width that is the number of columns and it happens to be an integer
value. Also, if the specified field width is less in comparison to the width of the output data’s
width that is to be displayed, then the effect of setw manipulator will not take place. Moreover,
there will be a normal displaying or printing of the output.
The setw C++ manipulator is also a component of “iomanip.h” header file. Furthermore, the
inclusion of this header file must take place in the program to use setw manipulator.
The insertion operator << is the one we usually use for output, as in:
It gets its name from the idea of inserting data into the output stream.
The extraction operator >> is the one we usually use for input, as in:
cin >> X;
It gets its name from the idea of extracting data from the input stream.
C++ Data Types
C++ supports a wide variety of data types and the programmer can select the data type
appropriate to the needs of the application. Data types specify the size and types of values to
be stored. However, storage representation and machine instructions to manipulate each data
type differ from machine to machine, although C++ instructions are identical on all machines.
1. Primitive Data Types: These data types are built-in or predefined data types and can be
used directly by the user to declare variables. example: int, char, float, bool, etc. Primitive
data types available in C++ are,
• Integer: The keyword used for integer data types is int. Integers typically require 4
bytes of memory space and range from -2147483648 to 2147483647.
• Character: Character data type is used for storing characters. The keyword used for
the character data type is char. Characters typically require 1 byte of memory space
and range from -128 to 127 or 0 to 255.
• Boolean: Boolean data type is used for storing Boolean or logical values. A Boolean
variable can store either true or false. The keyword used for the Boolean data type
is bool.
• Floating Point: Floating Point data type is used for storing single-precision floating-
point values or decimal values. The keyword used for the floating-point data type
is float. Float variables typically require 4 bytes of memory space.
• Double Floating Point: Double Floating Point data type is used for storing double-
precision floating-point values or decimal values. The keyword used for the double
floating-point data type is double. Double variables typically require 8 bytes of
memory space.
• void: Void means without any value. void data type represents a valueless entity. A
void data type is used for those function which does not return a value.
2.Derived Data Types
The data-types that are derived from the primitive or built-in datatypes are referred to as
Derived Data Types. These can be of four types namely:
• Function
• Array
• Pointers
• References
Function:
A function is a block of code or program-segment that is defined to perform a specific well-
defined task. A function is generally defined to save the user from writing the same lines of
code again and again for the same input. All the lines of code are put together inside a
single function and this can be called anywhere required. main() is a default function that is
defined in every program of C++.
Syntax:
Function_Type Function_Name(parameters)
Array: An array is a collection of items stored at continuous memory locations. The idea of
array is to represent many instances in one variable.
Syntax:
DataType ArrayName[size_of_array];
Pointers:
Pointers are symbolic representation of addresses. They enable programs to simulate call-
by-reference as well as to create and manipulate dynamic data structures. It’s general
declaration in C/C++ has the format:
Syntax:
datatype *var_name;
Example:
int *ptr;
Reference:
int* ptr;
ptr = &var;
The data types that are defined by the user are called the derived datatype or user-defined
derived datatype.These types include:
• Class
• Structure
• Union
• Enumeration
Class: The building block of C++ that leads to Object-Oriented programming is a Class. It
is a user-defined data type, which holds its own data members and member functions, which
can be accessed and used by creating an instance of that class. A class is like a blueprint for
an object.
Syntax:
Structure :
A structure is a user defined data type in C/C++. A structure creates a data type that can be
used to group items of possibly different types into a single type.
Syntax:
struct address
{
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};
Union: Like Structures, union is a user defined data type. In union, all members share the
same memory location.
Enumeration: Enumeration (or enum) is a user defined data type in C. It is mainly used to
assign names to integral constants, the names make a program easy to read and maintain.
Syntax:
enum State {Working = 1, Failed = 0};