Chapter - 3
Chapter - 3
INTRODUCTION TO C++
INTRODUCTION TO C++
• C++ is a middle-level programming language developed by
Bjarne Stroustrup starting in 1980 at Bell Labs.
• It was designed to support the features of C such as efficiency
and low-level support for system level coding.
• Some additional features such as classes with Inheritance,
Virtual functions, Operator overloading.
• C++ is superset of C with full support for object oriented
programming.
• C++ programs are fast and efficient which makes this language
as popular programming language.
C++ Get Started
• To start using C++, you need two things:
• A text editor, like Notepad, to write C++ code
• A compiler, like GCC, to translate the C++ code into a language that
the computer will understand.
• There are many text editors and compilers to choose from.
• Turbo C++ and Borland C++ provide an integrated program
development environment (IDE) under MS-DOS.
• They provide a built-in editor and a menu bar, which includes options
such as file, edit, compile and run.
• We can create and save the source files under the file option and
edit them under the edit option.
• C++ programs are saved using file extension .cpp
Write a simple C++ program
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
cout<<“Hello World ”;
getch();
}
b) Character Constant:
It is declare with const keyword and has fixed character value.
Example : const char a = ‘\t’;
When C++ compiler encounters character constant, that translates it into
corresponding ASCII value and stores that number.
TYPES OF CONSTANTS
• Character escape sequence
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).
Backslash Character Meaning
\a (alert) Produces an available or visible signal.
\b (backslash) Moved the cursor bar one space.
\f (Form feed) Moves ….. To the next page.
\n (new line) Prints a new line.
\r (Carriage return) Prints a Carriage return.
\t (horizontal tab) Prints a horizontal tab space.
\v (vertical tab) Prints a vertical tab space.
TYPES OF CONSTANTS
c) Floating point constant:
Floating point constants are also called as real constant.
It has an integer part, a decimal point, a fractional part, and an
exponent part.
Example : const float pi = 3.14;
d) String Constant:
String constants are enclosed in double quotes. It has sequence
of 2 or more characters. This can be also defined as an array of
character constants.
Example : const char arr[4] = “abcd”;
TYPES OF CONSTANTS
e) Hexadecimal and octal constants:
We use decimal constants having base 10. Numbers can be also
specified using base 8 and 16.
Numbers represented using base 8 Octal number systems (uses 0 – 7
digits) while having base 16 Hexadecimal number system (uses 0 – 9
and letters A to F).
The octal number begins with letter 0 and hexadecimal number begins
with 0x.
Example : 0xAB is Hexadecimal number.
0123 is Octal number.
TYPES OF CONSTANTS
2. Defined Constants:
• There are two simple ways in C++ to define constants −
• Using #define preprocessor.
• Using const keyword.
#define Directive( PREPROCESSOR directive)
It causes macro or symbolic name to be defined as a macro i.e. it sets
up an equivalence between identifier and text phares.
Syntax: #define macro_name replacement_list
#define identifires text_pharse
Example: #define PI 3.14159
TYPES OF CONSTANTS
3. Symbolic Constants:-- Enumerations
Along with pre-defined datatypes C++ allows you to define your own
datatypes. The one way of this to use enumeration.
Enumeration of symbolic constant is introduced by an enum declaration,
which is useful for declaring a set of closely related constants.
Syntax : enum TypeName {enumeration –list};
Example: enum { north, south, east, west}
OPERATORS IN C++
• An operator is a symbol that tells the compiler to perform
specific mathematical or logical manipulations.
• C++ is rich in built-in operators. They are classified as unary
operators, working on single operand and binary operators,
working on 2 operands.
• Although C++ allows us to multiple meanings to the operators,
yet their association and precedence remain same. Eg. (*)
multiplication operator is having high precedence than (+) add
operator.
OPERATORS IN C++
1. Arithmetic Operators
• Arithmetic operators are used to perform common mathematical
operations.
• An arithmetic expression is made up of constants, variables, a combination
if both or a function call, connected by arithmetic operators. Following are
the subtypes.
a. Unary Arithmetic Operators
Needs only one operand.
Example : +a, -b uses unary operators namely + (positive) and – (negative).
b. Ternary Arithmetic operators
Needs 3 operands. This is one of the special features of C++ language.
OPERATORS IN C++
c. Binary Arithmetic Operators
Needs 2 operands
OPERATORS IN C++
2) Increment and decrement operators
• In this , the first operand is the test condition while 2nd and 3rd represents
final value.
OPERATORS IN C++
6. Assignment operator (=)
• Assignment operators are used to assign values to
variables.
• = operator causes the value of the right hand operand to be assigned
to the left hand operand.
• The left hand operand, is also called as Ivalue, must always refers to a
memory location.
• Example : int x = 10;
int x = y = z = 5;
7. Shorthand (Compound) operators:
C++ supports additional assignment operators combining assignment
with each of the arithmetic operations.
Operator Symbol Description Form Operation
a << b
<< Bitwise Shift Left Operator
a >> b
>> Bitwise Shift Right Operator
OPERATORS IN C++
a. one’s complement
In this number is complemented means all the 1’s are replaced by 0’s and vice
versa.
Eg. 1010 1’s complement is 0101
e. Bitwise OR operators
Binary OR (|) Operator copies a bit if it exists in either operand.
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100 11000011
B = 0000 1101 11110010
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
OPERATORS IN C++
9. Operators dealing with streams:
C++ is able to input and output the built-in data types using the stream
extraction operator >> and the stream insertion operator <<.
Dealing with input output is called as iostream.
a. Insertion operator (<<)
It is a put to operator. The operators dealing with output stream is called insertion
operator.
Eg. cout<<a;
a. Extraction operator (>>)
It is a get from operator. It extracts the value from standard input device and assign
variable at its right. It is related to input stream.
Eg. cin>>a;
OPERATORS IN C++
10. Comma operator
The purpose of comma operator is to string together several expressions. The value of a
comma-separated list of expressions is the value of the right-most expression. Essentially,
the comma's effect is to cause a sequence of operations to be performed.
• The values of the other expressions will be discarded. This means that the expression on
the right side will become the value of the entire comma-separated expression. For
example −
var = (count = 19, incr = 10, count+1);
• Here first assigns count the value 19, assigns incr the value 10, then adds 1 to count, and
finally, assigns var the value of the rightmost expression, count+1, which is 20. The
parentheses are necessary because the comma operator has a lower precedence than
the assignment operator.
OPERATORS IN C++
11. The sizeof operator
• The sizeof is a keyword, but it is a compile-time operator that
determines the size, in bytes, of a variable or data type.
• The sizeof operator can be used to get the size of classes,
structures, unions and any other user defined data type.
• The syntax of using sizeof is as follows −
sizeof(data_type)
• Where data type is the desired data type including classes,
structures, unions and any other user defined data type.
• The outcome is totally depended on machine.
OPERATORS IN C++
12. Scope resolution operator
• The scope resolution operator is used for several reasons. For
example: If the global variable name is same as local variable
name, the scope resolution operator will be used to call the
global variable. It is also used to define a function outside the
class and used to access the static variables of class.
OPERATORS IN C++
13. Type cast operator
• A cast is a special operator that forces one data type to be
converted into another. As an operator, a cast is unary and has
the same precedence as any other unary operator.
• Syntax : type_name(expression)
eg. Avg= sum/float(i);
• A value in any built-in types can convert to any of other types.
• Example: (int)3.14 //converts 3.14 to an int to give 3.
(double)2 //converts 2 to double to give 2.0
OPERATORS IN C++
14. Stream manipulation operator
• Manipulators are helping functions that can modify the input/output stream. It
does not mean that we change the value of a variable, it only modifies the I/O
stream using insertion (<<) and extraction (>>) operators. The most important
manipulators defined by the IOStream library
• Statement 1 is executed (one time) before the execution of the code block.
• Statement 2 defines the condition for executing the code block.
• Statement 3 is executed (every time) after the code block has been executed.
ITERATIVE CONTROL STRUCTURES (LOOPS)
2. Nested for loop
• A loop can be nested inside of another loop.
Syntax
ITERATIVE CONTROL STRUCTURES (LOOPS)
3. While statement
The while loop loops through a block of code as long as a specified
condition is true.
Syntax
while (condition)
{
// code block to be executed
}
ITERATIVE CONTROL STRUCTURES (LOOPS)
4. do…. While statement
The do/while loop is a variant of the while loop. This loop will execute
the code block once, before checking if the condition is true, then it will
repeat the loop as long as the condition is true.
Syntax
do {
// code block to be executed
}
while (condition);
USE OF break and continue
• You have already seen the break statement used in switch case.
• It was used to "jump out" of a switch statement. The break
statement can also be used to jump out of a loop.
• The continue statement breaks one iteration (in the loop), if a
specified condition occurs, and continues with the next iteration in
the loop.
• Exit Success is indicated by exit(0) statement which means successful
termination of the program, i.e. program has been executed without
any error or interrupt.
Functions in C++
• A function is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a function.
• Functions are used to perform certain actions, and they are important
for reusing code: Define the code once, and use it many times.
• This divides the complexity of one program into sub programs, which
are easy to wite and debug.
• Standard C++ library is a collection of pre-defined functions called as
library or built in functions, which are access through header file.
• While users can also define his/her own functions called as user
defined functions.
Functions in C++
• C++ inline function is powerful concept that is commonly used with classes. If a function is
inline, the compiler places a copy of the code of that function at each point where the
function is called at compile time.
• Like a #define macro, inline functions improve the performance by avoiding the overhead of
the call thus inline functions are new design approach to speed up the program execution.
• They save memory space, as the calls to the same code needed not to be duplicate in
memory. when you declare an inline function, it looks just like a normal function:
• But when you define an inline function, you prepared the functions definition with the
keyword inline, and you put the definition into the header file:
inline void function(int a, int b)
{
// function code.......
}
• But note that overuse of inline function should be avoided since it can cause the size of code
getting larger and that might cause the operating system to trash, i.e. use of inline function
can cause the negative side effect also, like it can limit the portability of your code across the
platform
Recursion
• When function is called within the same function, it is known as recursion in C++.
The function which calls the same function, is known as recursive function.
• A function that calls itself, and doesn't perform any task after function call, is
known as tail recursion. In tail recursion, we generally call the same function with
return statement.
• Actually, you do not place the null character at the end of a string constant. The C++
compiler automatically places the '\0' at the end of the string when it initializes the array.
Array of characters(string)
• A string literal is a sequence of characters enclosed within the double
quotes. A storage class of a string literal is static.
• The compiler initialise the memory occupied by a string literal with the
specified character sequence.
• A null Terminator ( denotes the end of the string) is also included. The
size of the string literal is the number of characters enclosed within the
double quotes plus one for the null Terminator.
• It is easy to calculate the dimension of an array using the sizeof operator.
for example: given an array arr
• So the dimension of arr is: sizeof(arr)/sizeof(datatype)
string processing functions
• There were number of string processing functions provided as a
part of standard library declare in the header file ' string.h’
• C++ supports a wide range of functions that manipulate null-
terminated strings. These are:
1. strcpy(str1, str2): Copies string str2 into string str1.
2. strcat(str1, str2): Concatenates string str2 onto the end of string
str1.
3. strlen(str1): Returns the length of string str1.
4. strcmp(str1, str2): Returns 0 if str1 and str2 are the same; less than
0 if str1<str2; greater than 0 if str1>str2.
Passing array to the function
• A pointer is a variable whose value is the address of another variable. Like any variable or
constant, you must declare a pointer before you can work with it. A pointer variable is defined
to ‘point to’ data of specific type. The general form of a pointer variable declaration is −
type *var;
• Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name
of the pointer variable.
eg. int *a; //pointer to an int
char *b; //pointer to char
• The value of a pointer variable is the address to which it points(i.e. address of the memory
location where the variable is stored)
eg. Int variable1;
a=&variable1;
POINTRS IN C++
• The symbol & is the address operator; it takes a variable as a argument
and return the memory address of that variable.
• The effect of the above assignment is that the address of the variable1 is
assigned to ptr1. therefore, we say that ptr1 points to value of variable1.
ptr1 variable1
• Given that ptr1 points to variable 1.
• *ptr1 dereferences ptr1 to get to what it points to, is therefore
equivalent to variable1.
• The symbol * is the dereference operator; it takes a pointer as
argument and returns the content of the location to which it points.
POINTRS IN C++
• In general, the type of pointer must the type of the data it is set to point to.
• Regardless of its type, pointer may be assigned the value 0( called as the null
pointer).
reference variable in C++
• Reference variable in C++ allows two variable names to address the same memory
location.
• Reference does not create a copy of a variable, but merely a symbolic alias for it.
• A reference must always be initialised when it is defined: it should be an alias for
something. It will be illegal to define a reference and initialize it later
double &var1; // illegal: reference without an initializer
var1=num2;
• You can also initialise a reference to a constant. in this case a copy of a constant is
made ( after any necessary type conversion) and the reference is set to refer to the
copy.
int &n=1; // n refers to a copy of 1
• The most common use of reference is for function parameters. reference
parameters facility at the pass- by- reference style of arguments, as opposed to
the pass -by -Value style
Arrays and pointers
• Arrays and pointers are very closely related C++ compiler interprets
the name of the array as an address of the 1st element.
• You can reverse the whole array with the help of pointers.
• Once pointer is initialized to the starting address of the array, it works
like an index of the array.
Dynamic allocation
• C++ provides the way to allocate memory dynamically at run time by
2 memory management operators namely, new and delete.
• The new operator returns a pointer to allocated memory.
• Syntax: ptr_var= new datatype(initializer);
• You can initialize the allocated memory to some known value by using
an initializer.
• The delete operator frees memory.
• Warning : In C++ it is possible to access and modify the unallocated
memory locations, but it should be avoided.
Functions, returning the reference
• A function may return a reference.
• A function’s return type may be a reference provided that the value
returned is a lvalue, which is not local to the function, which gives us
a facility for treating functions as lvalue on left side of the assignment
of operator.
Thank you