You are on page 1of 90

Programming Fundamentals using C++

UNIT I

1
LIMITATIONS OF C LANGUAGE

⚫ No data security
⚫ No reusability of code
⚫ Does not support exception handling
⚫ No runtime checking mechanism
⚫ No namespace feature

2
PROCEDURAL PROGRAMMING

⚫ The procedural programming is defined as a programming


paradigm that allows the program to be organized as set of
functions.
⚫ In procedural programming, the program code is divided
into group of smaller programs called functions.
⚫ Each function performs a specific task depending upon the
program logic.
⚫ As the name suggests, the procedural programming program
code is organized in the form procedures.
⚫ These procedures are also called as subroutines or functions.

3
PROCEDURAL PROGRAMMING

⚫ The function can access and operate upon its own local data
as well as global data shared by all the functions.
⚫ Any function can be called many times in the program code
as and when required to perform the same task.
⚫ Features:
⚫ Top Down Approach
⚫ Header Files Declaration
⚫ Predefined Functions
⚫ User defined functions
⚫ Global and local variable
⚫ Variable Scope
4
5
OBJECT ORIENTED
PROGRAMMING
⚫ C++ is regarded as a middle-level language, as it comprises
a combination of both high-level and low-level language
features.
⚫ C++ was developed by Bjarne Stroustrup starting in 1979 at
Bell Labs in Murray Hill, New Jersey, as an enhancement
to the C language and originally named C with Classes but
later it was renamed C++ in 1983.
⚫ C++ fully supports object-oriented programming, including the
four pillars of object-oriented development −
⚫ Encapsulation
⚫ Data hiding
⚫ Inheritance
⚫ Polymorphism
6
Procedural vs Object Oriented
Programming
Procedural Object Oriented

->Emphasis is on doing things.(algorithms) ->Emphasis is on data rather than on


->Many data items are placed as global so algorithm.
that they may be accessed by all the ->Data is hidden and cannot be accessed by
functions without any restriction. It has external functions. It provides security.
reduced data security. ->Problem is divided into objects.
->Problem is divided into functions -> Follows bottom-up approach in program
->Employs top-down approach in program design.
design. ->E.g. C++, Java
->E.g. Procedural - FORTRAN, COBOL

7
CHARACTERISTICS OF OBJECT
ORIENTED PROGRAMMING
Class- A class is a collection of objects of similar type.
For example bba, bca, b.com are members of a class
Course. Classes are user defined data types and behave like
built-in data type of a programming language.
Objects

8
CHARACTERISTICS OF OBJECT
ORIENTED PROGRAMMING
Data Abstraction and encapsulation

9
CHARACTERISTICS OF OBJECT
ORIENTED PROGRAMMING
Dynamic Binding

10
CHARACTERISTICS OF OBJECT
ORIENTED PROGRAMMING
Polymorphism: The word polymorphism means having many forms. In simple words, we can
define polymorphism as the ability of a message to be displayed in more than one form. A real-life example

of polymorphism, a person at the same time can have different characteristics. Like a man at the same time

is a father, a husband, an employee. So the same person posses different behavior in different situations.

This is called polymorphism. Polymorphism is considered as one of the important features of Object

Oriented Programming.

11
CHARACTERISTICS OF OBJECT
ORIENTED PROGRAMMING
Inheritance

12
DIFFERENCES BETWEEN C AND
C++
C++, as the name suggests is a superset of C. As a matter of
fact, C++ can run most of C code while C cannot run C++
code. Here are the 10 major differences between C++ & C...
⚫ 1. C follows the procedural programming paradigm while
C++ is a multi-paradigm language(procedural as well as
object oriented). In case of C, importance is given to the
steps or procedure of the program while C++ focuses on the
data rather than the process. Also, it is easier to
implement/edit the code in case of C++ for the same reason.
⚫ 2. In case of C, the data is not secured while the data is
secured(hidden) in C++. This difference is due to specific
OOPfeatures like Data Hiding which are not present in C.
DIFFERENCES BETWEEN C AND
C++
⚫ 3. C is a low-level language while C++ is a middle-
level language. C is regarded as a low-level
language(difficult interpretation & less user friendly)
while C++ has features of both low-level(concentration
on whats going on in the machine hardware) & high-
level languages(concentration on the program itself) &
hence is regarded as a middle-level language.
⚫ 4. C uses the top-down approach while C++ uses the
bottom-up approach. In case of C, the program is
formulated step by step, each step is processed into
detail while in C++, the base elements are first
formulated which then are linked together to give rise to
larger systems.
14
DIFFERENCES BETWEEN C AND
C++
⚫ 5. C is function-driven while C++ is object-driven.
Functions are the building blocks of a C program while
objects are building blocks of a C++ program.
⚫ 6. C++ supports function overloading while C does
not. Overloading means two functions having the same
name in the same program. This can be done only in
C++ with the help of Polymorphism.
⚫ 7. We can use functions inside structures in C++ but not in
C. In case of C++, functions can be used inside a
structurewhile structures cannot contain functions in C.
DIFFERENCES BETWEEN C AND
C++
⚫ 8. The NAMESPACE feature in C++ is absent in case
of C. C++ uses NAMESPACE which avoid name
collisions. For instance, two students enrolled in the
same university cannot have the same roll number
while two students in different universities might have
the same roll number. The universities are two
different namespace & hence contain the same roll
number(identifier) but the same university(one
namespace) cannot have two students with the same
roll number(identifier).
16
DIFFERENCES BETWEEN C AND
C++
⚫ 9. The standard input & output functions differ in the
two languages. C uses scanf & printf while C++ uses
cin>> & cout<< as their respective input & output
functions
⚫ 10. C++ allows the use of reference variables while C
does not. Reference variables allow two variable names
to point to the same memory location. We cannot use
these variables in C programming.
17
BEGINNING WITH C++
⚫ It was developed by Bjarne Stroustrup at AT&T Bell
Laboratories
in Murray Hill, New Jersey, USA, in the early 1980’s.
⚫ Stroustrup, an admirer of simula67 and a strong supporter
of C, wanted to combine the best of both the languages and
create a more powerful language that could support object-
oriented programming features and still retain the power
and elegance of C. The result was C++.
⚫ C++ is a superset of C.
BEGINNING WITH C++
⚫ A C++ program to calculate average of two numbers.
⚫ #include<iostream.h>
⚫ #include<conio.h>
⚫ void main()
⚫ {
⚫ float num1, num2, sum, avg; //variable declaration
⚫ cout<<”Enter two numbers”;
⚫ cin>>num1;
⚫ cin>>num2;
⚫ sum = num1 + num2;
⚫ avg = sum/2;
⚫ cout<<”Sum =” << sum <<”\n”;
⚫ cout<<”Average =” << avg <<”\n”;
⚫ getch();
⚫ }

19
20
21
22
place
STRUCTURE OF C++ i
PROGRAM n
a
⚫A typical C++ program would
t
contain four sections. These
h
sections may be placed in separate
i
code files and then compiled
r
independently.
d
It is common practice to organize f
a program into three separate files. i
The class declarations are placed l
in a header file and the definitions e
of member functions go into w
another file. Finally the main h
program that uses the class is i
ch includes the previous two files
as Pwrepealreld a
Bys: M
asn. Cyhaorutl hNiegarm files
required.
TOKENS

24
KEYWORDS

25
IDENTIFIERS AND CONSTANTS
Identifiers
Identifiers refers to the name of variables, functions, arrays, classes, etc. created by the user. Identifiers are the fundamental
requirement of any language.

Identifier naming conventions

 Only alphabetic characters, digits and underscores are permitted.


 First letter must be an alphabet or underscore (_).
 Identifiers are case sensitive.
 Reserved keywords can not be used as an identifier's name.

Constants
Constants refers to fixed values that do not change during the execution of a program.

Declaration of a constant :

const [data_type] [constant_name]=[value];


Consider the example

#include <iostream.h>
int main()
{
const int max_length=100; // integer constant
const char choice='Y'; // character constant
const char title[]="www.includehelp.com"; // string constant
const float temp=12.34; // float constant

cout<<"max_length :"<<max_length<<endl;
cout<<"choice :"<<choice<<endl;
cout<<"title :"<<title<<endl;
cout<<"temp :"<<temp<<endl;
return 0;
}

Output
max_length :100
choice :Y
title :www.includehelp.com
temp :12.34
DATATYPES IN C++

27
DATATYPES IN C++
⚫ Built-In Data Types- The basic (fundamental) data types
provided by c++ are integral, floating point and void data
type. Among these data types, the integral and floating-point
data types can be preceded by several type modifiers.
⚫ Integral Data Type: The integral data type is used to store
integers and includes char (character) and int (integer) data
types.
⚫ Char: Characters refer to the alphabet, numbers and other
characters (such as {, @, #, etc.) defined in the ASCII
character set. In C++, the char data type is also treated as an
integer data type as the characters are internally stored as
integers that range in value from -128 to 127.
⚫ Int: Numbers without the fractional part represent integer
data. In C++, the int data type is used to store integers such
as 4, 42,
28
52P3re3pa,re-d3By2: M, s-. C7h4ar5ul
.Nigam
DATATYPES IN C++
⚫ Floating-point Data Type: A floating-point data type is
used to store real numbers such as 3 .28, 64. 755765, 8.01, -
24.53. Thisdata type includes float and double' data types.
⚫ Void: The void data type is used for specifying an empty
parameter list to a function and return type for a function.
When void is used to specify an empty parameter list, it
indicates that a function does not take any arguments and
when it is used as a return type for a function, it indicates
that a function does not return any value. For void, no
memory is allocated and hence, It cannot store anything.
⚫ Bool Data type: The bool data type can hold only Boolean
values, that is; either true or false, where true represents 1
and false represents O. It requires only one bit of storage,
however, it is
stored as an integer in the memory. Thus, it is also
considered as anintegral data type.
DATATYPES IN C++
⚫ Derived Data Types- Data types that are derived from the built-
in data types are known as derived data types. The various
derived data types provided by C++ are arrays, junctions,
references and pointers.
⚫ Array An array is a set of elements of the same data type that are
referred to by the same name. All the elements in an array are
stored at contiguous (one after another) memory locations and
each element isaccessed by a unique index or subscript value.
⚫ Function A function is a self-contained program segment that
carries
out a specific well-defined task.
⚫ Reference A reference is an alternative name for a
variable.That is, a reference is an alias for a variable in a
program. A variable and its reference can be used
interchangeably in a program as both refer to the same memory
location.
⚫ Pointer A pointer is a variable that can store the memory
address of another variable. Pointers allow to use the memory
dynamically.That is, with the help of pointers, memory can be
allocated or de-allocated to thePrvepaarreidaBby:lMess. Cahtarruul Nnig-atmime, thus,
making a program more efficient.
DATATYPES IN C++
⚫ User-Defined Data Types- Various user-defined data types
provided by C++ are structures,unions,enumerations and
classes.
⚫ Structure, Union and Class: Structure and union are the
significant features of C language. Structure and union
provide a way to group similar or dissimilar data types
referred to by a single name. However, C++ has extended
the concept of structure and union by incorporating some
new features in these data types to support object -oriented
programming.
⚫ C++ offers a new user-defined data type known as class,
which forms the basis of object-oriented programming. A
class acts as a template which defines the data and functions
that are included in an object of a class. Classes are declared
using the keyword class. OnPrcepearead Bcyl:aMss.sChharausl Nbigeamen declared, its
object can be easily create7/d1./2021
32
typedef KEYWORD
⚫ C++ provides a typedef feature that allows to define new
data type names for existing data types that may be built-in,
derived or user- defined data types. Once the new name has
been defined, variables can be declared using this new name.
For example, consider thisdeclaration.
typedef int integer;
⚫ In this declaration, a new name integer is given to the data
type into This new name now can be used to declare integer
variables as shown here.
integer i, j,
k;
SYMBOLIC CONSTANTS

34
REFERNCE VARIABLES

35
OPERATORS IN C++
⚫ C++ has a rich set of operators. All C operators are valid
in C++ also. C++ introduces some new operators such as:
⚫ Input Operator
⚫ Output Operator
⚫ Scope Resolution Operator
⚫ Memory Management Operators
⚫ Manipulators
⚫ Comma Operator
⚫ Type Cast Operator

36
OPERATORS IN C++
⚫ Scope Resolution Operator- In C++ program we can use the same variable names but in
separate blocks. The declaration of same variable names refers to different memory
locations. When we declare a variable it is available only to a specific block of the
program. The remaining block cannot access the variable.
⚫ The scope resolution operator :: allows a programmer to access a global variable name
even if it is hidden by a local re-declaration of that name.The syntax of scope resolution
operator is:
⚫ :: variable_name
⚫ Example:
⚫ #include <iostream.h>
⚫ #include <conio.h>
⚫ int a= 10;
⚫ void main()
⚫ {
⚫ clrscr();
⚫ int a=20;
⚫ cout<<”::a=”<<::a;
⚫ cout<<”a=”<<a;
⚫ getch();
⚫ }

37
OPERATORS IN C++
⚫ Memory Management Operator
⚫ There are two types of memory management operators in C++:
⚫ new
⚫ delete
⚫ new operator- The new operator in C++ is used for dynamic storage
allocation. This operator can be used to create object of any type. The
general syntax of new operator in C++ is as follows:
⚫ pointer variable = new datatype;
⚫ For example:
⚫ int *a=new int;
⚫ In the above example, the new operator allocates sufficient memory to
hold the object of datatype int and returns a pointer to its starting point.
The pointer variable a holds the address of memory space allocated.
⚫ The assignment can be made in either of the two ways:
⚫ int *a = new int;*a = 20; or
⚫ int *a = new int(20);
38
OPERATORS IN C++
⚫ delete operator: The delete operator in C++ is used for
releasingmemory space when the object is no longer needed.
Once a new operator is used, it is efficient to use the
corresponding delete operator for release of memory.
⚫ The general syntax of delete operator in C++ is as follows:
⚫ delete pointer variable;

39
OPERATORS IN C++
⚫ Example:
⚫ #include <iostream>
⚫ #include<conio.h>
⚫ void main()
⚫{
⚫ int *a= new int;
⚫ *a=100;
⚫ cout << " The Output is:a= " << *a;
⚫ delete a;
⚫ getch();
⚫}
40
MANIPULATORS

endl manipulator

setw manipulator

41
MANIPULATORS

42
COMMA OPERATOR
⚫ In C every statement is terminated by a semi-colon (;). It is also applicable in c++ and in
addition, c++ allows us to terminate a statement using comma operator after satisfying
the following rules:-
⚫ The variable declaration statements should be terminated by semi-colon.
⚫ The statements followed by declaration statements like clrscr(), cin, cout can be
terminated by comma operator.
⚫ C++ permits declaration of variables at any place in the program but such declaration is
not allowed in between the statements terminated by comma operator.The initialization
of previously declared variables can be done.
⚫ The last statement of the program must be terminated by a semi-colon.
⚫ Example:
⚫ void main()
⚫ {
⚫ int x;
⚫ clrscr(),
⚫ x=10,
⚫ cout<<”x=”<<x,
⚫ cout<<endl;
⚫ getch();
⚫ }
43
CONTROL STRUCTURES

44
45
46
47
FUNCTIONS IN C++
⚫ Functions are used to provide modularity to a program. Creating
an application using function makes it easier to understand, edit,
check errors etc.
⚫ Syntax of Function
⚫ return-type function-name (parameters)
⚫{
⚫ // function-body
⚫}
⚫ return-type: suggests what the function will return. It can be int,
char, some pointer or even a class object. There can be functions
which does not return anything, they are mentioned with void.
⚫ Function Name: is the name of the function, using the function
name it is
called.
⚫ Parameters: are variables to hold values of arguments passed
while
function is called.A function may or may not contain parameter list.
48⚫
FunPcretpiaorend Bby:oMds.yC:hairsul hNeigampart where the code statements are
written.
FUNCTIONS IN C++
⚫ void sum(int x, int y)
⚫{
⚫ int z;
⚫ z = x + y;
⚫ cout << z;
⚫}
⚫ int main()
⚫{
⚫ int a = 10;
⚫ int b = 20;
⚫ sum (a, b);
⚫}
⚫ Here, a and b are sent as arguments, and x and y are parameters
which
will hold values of a and b to perform required operation inside
function.
49
FUNCTIONS IN C++
⚫ Declaring, Defining and Calling Function
⚫ Function declaration, is done to tell the compiler about the existence of the function.
Function's return type, its name & parameter list is mentioned. Function body is written
in its definition.
⚫ #include < iostream>
⚫ #include<conio.h>
⚫ int sum (int x, int y); //declaring function
⚫ void main()
⚫ {
⚫ int a = 10;
⚫ int b = 20;
⚫ int c = sum (a, b); //calling function
⚫ cout << c;
⚫ getch();
⚫ }
⚫ int sum (int x, int y) //defining function
⚫ {
⚫ return (x + y);
⚫ }
50
FUNCTIONS IN C++
⚫ There are many advantages in using functions in a program they
are:
⚫ It makes possible top down modular programming. In this style of
programming, the high level logic of the overall problem is solved
first while the details of each lower level functions is addressed
later.
⚫ The length of the source program can be reduced by using functions
at
appropriate places.
⚫ It becomes uncomplicated to locate and separate a faulty function
for
further study.
⚫ A function may be used later by many other programs this means
that a c programmer can use function written by others, instead of
starting overfrom scratch.
⚫ A function can be used to keep away from rewriting the same
block of codes which we are going use two or more locations in a
program. This is especially useful if the code involved is long or
complicated
51
FUNCTIONS IN C++
⚫ A function may belong to any one of the following categories:
⚫ Functions with no arguments and no return values.
⚫ Functions with arguments and no return values.
⚫ Functions with arguments and return values.
⚫ Functions that return multiple values.
⚫ Functions with no arguments and return values.

52
FUNCTIONS IN C++
⚫ Calling a Function
⚫ Functions are called by their names. If the function is without
argument, it can be called directly using its name. But for
functions with arguments, we have two ways to call them,
⚫ Call by Value
⚫ Call by Reference
⚫ Call by Value
⚫ In this calling technique we pass the values of arguments
which are stored or copied into the formal parameters of
functions. Hence, the original values are unchanged only the
parameters inside function changes.

53
⚫ Output
54
FUNCTIONS IN : 20
C++
⚫ int calc(int x);
⚫ int main()
⚫{
⚫ int x = 10;
⚫ x = calc(x);
⚫ printf("%d", x);
⚫}
⚫ int calc(int x)
⚫{
⚫ x = x + 10 ;
⚫ return x;
⚫}
FUNCTIONS IN C++
⚫ Call by Reference
⚫ In this we pass the address of the variable as arguments. In this case the
formal parameter can be taken as a reference or a pointer, in both the case
they will change the values of the original variable.
⚫ void calc(int *p);
⚫ int main()
⚫{
⚫ int x = 10;
⚫ calc(&x); // passing address of x as argument
⚫ printf("%d", x);
⚫}

⚫ void calc(int *p)
⚫{
⚫ *p = *p + 10;
⚫}
55
RECURSIVE FUNCTIONS
⚫ A recursive function is one which calls itself.
⚫ Example of findinga factorial in c++
⚫ #include <iostream.h>
⚫ int factorial(int);
⚫ void main(void)
⚫ {
⚫ int number;
⚫ cout << "Please enter a positive integer: ";
⚫ cin >> number;
⚫ if (number < 0)
⚫ cout << "That is not a positive integer.\n";
⚫ else
⚫ cout << number << " factorial is: " << factorial(number) << endl;
⚫ }
⚫ int factorial(int number)
⚫ { int temp;
⚫ if(number <= 1) return 1;
⚫ temp = number * factorial(number -
⚫ 1); return temp;
56⚫
}
INLINE FUNCTION
⚫ C++ has a different solution to this problem. To eliminate the cost
of calls to the small functions, C++ proposes a new feature called
as inline function.
⚫ An inline function is a function that is expanded in a line when it
is invoked. That is the compiler replaces the function call with the
corresponding function code.
⚫ An inline function can be defined as follows:-

57
INLINE FUNCTIONS
⚫ Following are the situations where inline function may not
work:-
⚫ The function should not be recursive.
⚫ Function should not contain static variables.
⚫ For functions containing control structure statements such as
switch, if etc.
⚫ The function main() cannot work as inline.
⚫ The inline functions are similar to macros of C. The main
limitation with macros is that they are not functions and
errors are not checked at the time of compilation. The
function offers better type testing and do not contain side
effects as present in macros.
58
s=16
59
INLINE
FUNCTIONS
⚫ Example: Calculate square using inline and macros.
⚫ #include<iostream.h>
⚫ #include<conio.h>
⚫ #define SQUARE(v) v * v
⚫ inline float square (float j)
⚫ {
⚫ return (j * j);
⚫ }
⚫ void main()
⚫ {
⚫ clrscr();
⚫ int p = 3, q = 3, r,s;
⚫ r = SQUARE (++p);
⚫ s= square (++q);
⚫ cout<<”r=”<<r<<”\n”<<”s=”<<s;
⚫ getch();
⚫ }
⚫ Output
⚫ r=25
INLINE FUNCTIONS
⚫ Macros vs Inline functions
⚫ Macros are not type safe, and can be expanded regardless of
whether they are syntactically correct - the compile phase will
report errorsresulting from macro expansion problems.
⚫ Macros are more flexible, in that they can expand other
macros -whereas inline functions don't necessarily do this.
⚫ Macros can result in side effects because of their expansion,
since the input expressions are copied wherever they appear
in the pattern.
⚫ Inline function are not always guaranteed to be inlined -
some compilers only do this in release builds, or when they
are specifically configured to do so. Also, in some cases
inlining may not be possible.
60
FUNCTION WITH DEFAULT
ARGUMENTS
⚫ A default argument is an argument to a function that a
programmer is not required to specify. C++ allows the
programmer to specify default arguments that always have a value,
even if one is not specified when calling the function. For
example, in the following function declaration:
⚫ int my_func(int a, int b, int c=12);
⚫ This function takes three arguments, of which the last one has a
default of twelve. The programmer may call this function in two
ways:
⚫ result = my_func(1, 2, 3);
⚫ result = my_func(1, 2);
⚫ In the first case the value for the argument called c is specified as
normal. In the second case, the argument is omitted, and the
default value of 12 will be used instead.
⚫ There is no means to know if the argument has been specified by
the caller or if the default value was used.
61
FUNCTION WITH DEFAULT
ARGUMENTS
⚫ Example of default arguments in C++
⚫ #include<iostream.h>
⚫ void showVolume(int len, int width, int height=12)
⚫{
⚫ cout<<”Volume =”<<len*width*height;
⚫}
⚫ void main()
⚫{
⚫ showVolume(2,3,4); //takes the height as 4
⚫ showVolume(2,3); // takes the height as default 12
⚫}
⚫ Output:
⚫ Volume=24
⚫ Volume=72
FUNCTION OVERLOADING

63
FUNCTION OVERLOADING

64
FUNCTION OVERLOADING
⚫ #include<iostream.h>
⚫ #include<conio.h>
⚫ int sqr (int);
⚫ float sqr (float);
⚫ void main()
⚫ {
⚫ clrscr();
⚫ int a=15;
⚫ float b=2.5;
⚫ cout<<”Square=”<<sqr(a)<<”\n”;
⚫ cout<<”Square=”<<sqr(b)<<”\n”;
⚫ getch();
⚫ }
⚫ int sqr(int s)
⚫ {
⚫ return (s * s);
⚫ }
⚫ float sqr(float j)
⚫ {
⚫ return (j * j);
⚫ }

65

You might also like