Unit 2 - Basic Programming in C++
Unit 2 - Basic Programming in C++
Introduction to Algorithms,
An algorithm is a method for solving a computational problem. A formula or set of steps for solving a
problem. To be an algorithm, a set of rules must be unambiguous and have a clear stopping point.
Algorithms can be expressed in any language, from natural languages like English or French to
programming languages like FORTRAN.
We use algorithms every day. For example, a recipe for baking a cake is an algorithm. Most programs,
except for some artificial intelligence applications, consist of algorithms. Inventing elegant algorithms that are
simple and require the fewest steps possible is one of the principal challenges in programming.
For example, we might be able to say that our algorithm indeed correctly solves the problem in question and
runs in time at most f(n) on any input of size n.
Definition. An algorithm is a finite set of instructions for performing a computation or solving a problem.
Types of Algorithms Considered. In this course, we will concentrate on several different types of relatively simple
algorithms, namely:
Selection -- Finding a value in a list, counting numbers;
Sorting -- Arranging numbers in order of increasing or decreasing value; and
Comparison -- Matching a test pattern with patterns in a database.
Input -- Values that are accepted by the algorithm is called input or arguments.
Output -- The result produced by the algorithm is the solution to the problem that the algorithm is designed to
address.
Definiteness -- The steps in each algorithm must be well defined.
Correctness -- The algorithm must perform the task it is designed to perform, for all input combinations.
Finiteness -- Output is produced by the algorithm after a finite number of computational steps.
Effectiveness -- Each step of the algorithm must be performed exactly, infinite time.
Generality -- The procedure inherent in a specific algorithm should be applicable to all algorithms of the
same general form, with minor modifications permitted.
FLOWCHART
1. The flowchart is a type of diagram (graphical or symbolic) that represents an algorithm or process.
2. Each step in the process is represented by a different symbol and contains a short description of the
process step.
3. The flowchart symbols are linked together with arrows showing the process flow direction.
4. A flowchart typically shows the flow of data in a process.
5. Flowcharts are used in analyzing, designing, documenting or managing a process or program in
various fields.
6. Flowcharts are generally drawn in the early stages of formulating computer solutions.
7. Flowcharts often facilitate communication between programmers and business people.
Example: - Draw a flowchart to find the largest among three different numbers entered by the user.
Advantages of Using Flowcharts
1. Communication: a better way of logical communicating.
2. Effective analysis: the problem can be analyzed in more effective way.
3. Proper documentation.
4. Efficient Coding: a guide or blueprint during the systems analysis and program development phase.
Proper Debugging: helps in debugging process.
5. Efficient Program Maintenance: easy with the help of flowchart.
Flowchart Symbols
1. Terminator: ““tart” or “End”
2. Process
3. Decision: Yes/No question or True/False
4. Connector: jump in the process flow
5. Data: data input or output (I/O)
6. Delay
7. Arrow: flow of control in a process.
Introduction to Programming
1. A computer is a programmable machine. This means it can execute a programmed list of instructions and
respond to new instructions that it is given.
2. Computer Programming is the process of developing and implementing various sets of instructions to enable
a computer to do a certain task.
3. Programs are written to solve problems or perform tasks on a computer.
4. Programmers translate the solutions or tasks into a language the computer can understand.
5. As we write programs, we must keep in mind that the computer will only do what we instruct it to do.
6. Because of this, we must be very careful and thorough with our instructions.
7. Pseudocode is a computer programming language that resembles plain English that cannot be compiled
or executed but explains a resolution to a problem.
8. The source code consists of the programming statements that are created by a programmer with a text
editor or a visual programming tool and then saved in a file. For example, a programmer using the C
language types in a desired sequence of C language statements using a text editor and then saves them
as a named file.
9. This file is said to contain the source code.
10. A flowchart is a formalized graphic representation of a logic sequence, work or manufacturing process,
organization chart, or similar formalized structure.
11. The purpose of a flow chart is to provide people with a common language or reference point when
dealing with a project or process.
12. Flowcharts use simple geometric symbols and arrows to define relationships.
13. Computer programming is almost always done by means of Programming Language.
14. There exist more than 2500 programming languages in the world.
15. Some of them are known by only their developers.
Introduction to Programming
An organized list of instructions that, when executed, causes the computer to behave in a predetermined
manner. Without programs, computers are useless.
A program is like a recipe. It contains a list of ingredients (called variables) and a list of directions (called
statements) that tell the computer what to do with the variables. The variables can represent numeric data,
text, or graphical images.
There are many programming languages -- C, C++, Pascal, BASIC, FORTRAN, COBOL, and LISP are just a few.
These are all high-level languages. One can also write programs in low-level languages called assembly
languages, although this is more difficult. Low-level languages are closer to the language used by a
computer, while high-level languages are closer to human languages.
Eventually, every program must be translated into a machine language that the computer can understand. This
translation is performed by compilers, interpreters, and assemblers.
When you buy software, you normally buy an executable version of a program. This means that the program
is already in machine language -- it has already been compiled and assembled and is ready to execute.
Programming languages fall into two fundamental categories low and high-level languages. Low-level
languages are machine-dependent; that is, they are designed to be run on a particular computer. In
contrast, high-level languages (for example, COBOL and BASIC) are machine-independent and can be run on
a variety of computers.
The hierarchy of programming languages in the Figure summarizes the relationships between the various types of
programming languages. Through the first four decades of computing, programming languages evolved in
generations. The first two generations were low-level and the next two high-level generations of programming
languages.
The higher-level languages do not provide us greater programming capabilities, but they do provide a more
sophisticated programmer/computer interaction. In short, the higher the level of the language, the easier it is to
understand and use. For example, in a fourth-generation language, you need only instruct the computer
system what to do, not necessarily how to do it.
1. Readability: A good high-level language will allow programs to be written in some ways that resemble a
quite-English description of the underlying algorithms. If care is taken, the coding may be done in a way
that is essentially self-documenting.
2. Portability: High-level languages, being essentially machine independent, should be able to develop
portable software.
3. Generality: Most high-level languages allow the writing of a wide variety of programs, thus relieving the
programmer of the need to become an expert in many diverse languages.
4. Brevity: Language should have the ability to implement the algorithm with less amount of code.
Programs expressed in high-level languages are often considerably shorter than their low-level
equivalents.
5. Error checking: Being human, a programmer is likely to make many mistakes in the development of a
computer program. Many high-level languages enforce a great deal of error checking both at compile-time and at
run-time.
6. Cost: The ultimate cost of a programming language is a function of many of its characteristics.
7. Familiar notation: A language should have a familiar notation, so it can be understood by most of the
programmers.
8. Quick translation: It should admit quick translation.
9. Efficiency: It should permit the generation of efficient object code.
10. Modularity: It is desirable that programs can be developed in the language as a collection of separately
compiled modules, with appropriate mechanisms for ensuring self-consistency between these modules.
11. Widely available: Language should be widely available and it should be possible to provide translators for
all the major machines and for all the major operating systems.
Generation of Languages
1GL or first-generation language was (and still is) machine language or the level of instructions and data that
the processor is given to work on (which in conventional computers is a string of 0s and 1s).
2GL or second-generation language is assembler (sometimes called "assembly") language. A typical 2GL
instruction looks like this:
ADD 12,8
An assembler converts the assembler language statements into machine language.
3GL or third-generation language is a "high-level" programming language, such as PL/I, C, or Java. Java
language statements look like this:
4GL or fourth-generation language is designed to be closer to natural language than a 3GL language.
Languages for accessing databases are often described as 4GLs. A 4GL language statement might look like this:
EXTRACT ALL CUSTOMERS WHERE "PREVIOUS PURCHASES" TOTAL MORE THAN $1000
5GL or fifth-generation language is programming that uses a visual or graphical development interface to create
source language that is usually compiled with a 3GL or 4GL language compiler. Microsoft, Borland, IBM, and
other companies make 5GL visual programming products for developing applications in Java, for example. Visual
programming allows you to easily envision object-oriented programming class hierarchies and drags icons to
assemble program components.
Programming paradigms
Programming paradigms are a way to classify programming languages based on their features. Languages can be
classified into multiple paradigms.
Some paradigms are concerned mainly with implications for the execution model of the language, such as
allowing side effects, or whether the sequence of operations is defined by the execution model. Other
paradigms are concerned mainly with the way that code is organized, such as grouping a code into units
along with the state that is modified by the code. Yet others are concerned mainly with the style of syntax
and grammar.
A program in a procedural language is a list of instruction where each statement tells the computer to do
something. It focuses on procedure (function) & algorithm is needed to perform the derived computation.
When the program becomes larger, it is divided into function & each function has clearly defined purpose. Dividing
the program into functions & module is one of the cornerstones of structured programming.
E.g.:- c, basic, FORTRAN.
It's emphasis on doing things. Data is given a second-class status even though data is the reason for the
existence of the program.
Since every function has complete access to the global variables, the new programmer can corrupt the data
accidentally by creating function. Similarly, if new data is to be added, all the function needed to be
modified to access the data.
It is often difficult to design because the components function and data structure do not model the real world.
For example, in designing graphical user interface, we think what functions, what data structures are needed
rather than which menu, menu item and soon.
It is difficult to create new data types. The ability to create the new data type of its own is called
extensibility. Structured programming languages are not extensible.
Difference between Procedure Oriented Programming (POP) & Object-Oriented Programming (OOP)
The core of the pure object-oriented programming is to create an object, in code, that has certain properties
and methods. While designing C++ modules, we try to see the whole world in the form of objects. For
example, a car is an object which has certain properties such as color, the number of doors, and the like. It
also has certain methods such as accelerate, brake, and so on.
There are a few principle concepts that form the foundation of object-oriented programming:
Object
This is the basic unit of object-oriented programming. That is both data and functions that operate on data
are bundled as a unit called as an object.
Class
When you define a class, you define a blueprint for an object. This doesn't define any data, but it does
define what the class name means, that is, what an object of the class will consist of and what operations
can be performed on such an object.
Abstraction
Data abstraction refers to, providing only essential information to the outside world and hiding their
background details, i.e., to represent the needed information in program without presenting the details.
For example, a database system hides certain details of how data is stored and created and maintained. Similar
way, C++ classes provide different methods to the outside world without giving internal detail about those
methods and data.
Encapsulation
Encapsulation is placing the data and the functions that work on that data in the same place. While working
with procedural languages, it is not always clear which functions work on which variables but object-
oriented programming provides you a framework to place the data and the relevant functions together in the
same object.
Inheritance
One of the most useful aspects of object-oriented programming is code reusability. As the name suggests
Inheritance is the process of forming a new class from an existing class that is from the existing class called
as a base class, a new class is formed called as the derived class.
This is a very important concept of object-oriented programming since this feature helps to reduce the code
size.
Polymorphism
The ability to use an operator or function in different ways in other words giving different meaning or
functions to the operators or functions is called polymorphism. Poly refers to many. That is a single
function or an operator functioning in many ways different upon the usage is called polymorphism.
Overloading
The concept of overloading is also a branch of polymorphism. When the exiting operator or function is made
to operate on new data type, it is said to be overloaded.
Advantage of OOP
•“implicity: software objects model real-world objects, so the complexity is reduced and the program
structure is very clear;
•Modularity: each object forms a separate entity whose internal workings are decoupled from other parts
of the system;
•Modifiability: it is easy to make minor changes in the data representation or the procedures in an OO
program. Changes inside a class do not affect any other part of a program since the only public interface
that the external world must a class is using methods;
•Extensibility: adding new features or responding to changing operating environments can be solved by
introducing a few new objects and modifying some existing ones;
•Maintainability: objects can be maintained separately, making locating and fixing problems easier;
•‘e-usability: objects can be reused in different programs.
Introduction to C++
History
The C++ programming languages is an extension of C that was developed by Bjarne Stroustrup in the early
1980s at Bell Laboratories. C++ provides many features that "spruce up" the C language, but more
importantly, it provides capabilities for object-oriented programming. A computer cannot understand our
language that we use in our day to day conversations, and likewise, we cannot understand the binary
language that the computer uses to do its tasks. It is, therefore, necessary for us to write instructions in some
specially defined language like C++ which is like natural language and after conversing with the help of
compiler the computer can understand it.
C++ COMPILER
A C++ compiler is itself a computer program which’s the only job is to convert the C++ program from our
form to a form the computer can read and execute. The original C++ program is called the “source code”, and the
resulting compiled code produced by the compiler is usually called an “object file”.
Before compilation, the preprocessor performs preliminary operations on C++ source files. A preprocessed form
of the source code is sent to the compiler.
After compilation stage object files are combined with predefined libraries by a linker, sometimes called a
binder, to produce the final complete file that can be executed by the computer. A library is a collection of
pre-compiled “object code” that provides operations that are done repeatedly by many computer programs.
Myprog.cpp
Myprog.obj
Myprog.exe
The character set is a set of valid characters that a language can recognize.
Letters A-Z, a-z
Digits 0-9
Special Characters Space + - * / ^ \ () [] {} = != <> ‘ “ $ , ; : % ! & ?
_ # <= >= @
Formatting backspace, horizontal tab, vertical tab, form feed, and carriage return
characters
TOKENS
A token is a group of characters that logically belong together. The programmer can write a program by
using tokens. C++ uses the following types of tokens.
Keywords, Identifiers, Literals, Punctuators, Operators.
1. Keywords
These are some reserved words in C++ which have predefined meaning to compiler called keywords. Some
commonly used Keyword are given below:
2. Identifiers
Symbolic names can be used in C++ for various data items used by a programmer in his program. A
symbolic name is generally known as an identifier. The identifier is a sequence of characters taken from C+
+ character set. The rule for the formation of an identifier are:
C++ is case sensitive that is upper case and lower-case letters are considered different from each
other.
3. Literals
Literals (often referred to as constants) are data items that never change their value during the execution of
the program. The following types of literals are available in C++.
Integer-Constants
Character-constants
Floating-constants
Strings-constants
Integer Constants: Integer constants are the whole number without any fractional part. C++ allows three
types of integer constants.
Decimal integer constants: It consists of a sequence of digits and should not begin with 0 (zero). For
example, 124, - 179, +108.
Octal integer constants: It consists of a sequence of digits starting with 0 (zero). For example. 014, 012.
Hexadecimal integer constant: It consists of a sequence of digits preceded by ox or OX.
Character constants
A character constant in C++ must contain one or more characters and must be enclosed in single quotation
marks. For example, 'A', '9', etc. C++ allows nongraphic characters which cannot be typed directly from the
keyboard, e.g., backspace, tab, carriage return etc. These characters can be represented by using an escape
sequence. An escape sequence represents a single character. The following table gives a listing of common
escape sequences.
Floating constants
They are also called real constants. They are numbers having fractional parts. They may be written in
fractional form or exponent form. A real constant in fractional form consists of signed or unsigned digits
including a decimal point between digits. For example 3.0, -17.0, -0.627 etc.
String Literals
A sequence of characters enclosed in double quotes is called a string literal. String literal is by default
(automatically) added a special character ‘\0' which denotes the end of the string. Therefore the size of
the string is increased by one character. For example "COMPUTER" will re-represented as "COMPUTER\0"
in the memory and its size is 9 characters.
4. Punctuators: The following characters are used as punctuators in C++.
Brackets [ ] Opening and closing brackets indicate single and multidimensional array subscript.
Parentheses ( ) Opening and closing brackets indicate functions calls, function parameters for
grouping expressions etc.
Braces { } Opening and closing braces indicate the start and end of a compound statement.
Comma, It is used as a separator in a function argument list.
Semicolon ; It is used as a statement terminator.
Colon : It indicates a labeled statement or conditional operator symbol.
Asterisk * It is used in pointer declaration or as a multiplication operator.
Equal sign = It is used as an assignment operator.
Pound sign # It is used as pre-processor directive.
5. Operators: Operators are special symbols used for specific purposes. C++ provides six types of
operators. Arithmetical operators, Relational operators, Logical operators, Unary operators, Assignment
operators, Conditional operators, Comma operator
DATA HANDLING BASIC DATA TYPES
C++ supports many data types. The built-in or basic data types supported by C++ are an integer, floating
point, and character. These are summarized in table along with description and memory requirement
VARIABLES
It is a location in the computer memory which can store data and is given a symbolic name for easy
reference. The variables can be used to hold different values at different times during the execution of a
program.
Declaration of a variable
Before a variable is used in a program, we must declare it. This activity enables the compiler to make
available the appropriate type of location in the memory.
float Total;
You can declare more than one variable of the same type in a single statement
int x,y;
Initialization of variable
When we declare a variable it's default value is undetermined. We can declare a variable with some initial
value.
int a = 20;
The following table shows the variable type, how much memory it takes to store the value in memory,
and what is a maximum and minimum value which can be stored in such type of variables.
Typical
Typical Range Bit Width Type
-128 to 127 or 0 to 255 1byte char
0 to 255 1byte unsigned char
-128 to 127 1byte signed char
-2147483648 to 2147483647 4bytes int
0 to 4294967295 4bytes unsigned int
-2147483648 to 2147483647 4bytes signed int
-32768 to 32767 2bytes short int
0 to 65,535 2bytes unsigned short int
-32768 to 32767 2bytes signed short int
-2,147,483,648 to 2,147,483,647 8bytes long int
-9,223,372,036,854,775,808 to 8bytes signed long int
9,223,372,036,854,775,807
0 to 18,446,744,073,709,551,615 8bytes unsigned long int
+/- 3.4e +/- 38 (~7 digits) 4bytes float
+/- 1.7e +/- 308 (~15 digits) 8bytes double
+/- 1.7e +/- 308 (~15 digits) 8bytes long double
1 wide character 2 or 4 bytes wchar_t
The sizes of variables might be different from those shown in the above table, depending on the
compiler and the computer you are using.
Following is the example, which will produce the correct size of various data types on your computer.
#include<iostream>
usingnamespacestd;
int main(){
cout<<"Size of char : "<<sizeof(char)<<endl;
cout<<"Size of int : "<<sizeof(int)<<endl;
cout<<"Size of short int : "<<sizeof(shortint)<<endl;
cout<<"Size of long int : "<<sizeof(longint)<<endl;
cout<<"Size of float : "<<sizeof(float)<<endl;
cout<<"Size of double : "<<sizeof(double)<<endl;
cout<<"Size of wchar_t : "<<sizeof(wchar_t)<<endl;
return0;
}
This example uses endl, which inserts a new-line character after every line and << operator is being used
to pass multiple values out to the screen. We are also using sizeof() operator to get sizeof various
data types.
When the above code is compiled and executed, it produces the following result which can vary from
machine to machine −
Size of char: 1 Size of int: 4
Size of short int: 2 Size of long
int: 8 Size of float: 4 Size of
double: 8 Size of wchar_t: 4
Typedef Declarations:
You can create a new name for an existing type using typedef. Following is the simple syntax to define
a new type using typedef:
typedef type new name;
For example, the following tells the compiler that feet are another name
for int: typedef int feet;
Now, the following declaration is perfectly legal and creates an integer variable called distance:
feet distance;
Enumerated Types:
An enumerated type declares an optional type name and a set of zero or more identifiers that can be
used as values of the type. Each enumerator is a constant whose type is the enumeration.
To create an enumeration requires the use of the keyword enum. The general form of an enumeration
type is:
enumenum-name { list of names } var-list;
Here, the enum-name is the enumeration's type name. The list of names is comma separated.
For example, the following code defines an enumeration of colors called colors and the variable c of
type color. Finally, c is assigned the value "blue".
enum color { red, green, blue } c; c = blue;
By default, the value of the first name is 0, the second name has the value 1, the third has the value 2,
and so on. But you can give a name a specific value by adding an initializer. For example, in the
following enumeration, green will have the value 5.
E num color { red, green=5, blue };
The above result is because the bit pattern that represents 50,000 as a short unsigned integer is
interpreted as -15,536 by a short.
Meaning Qualifier
Objects of type const cannot be changed by your program during const
execution
The modifier volatile tells the compiler that a variable's value may volatile
be changed in ways not explicitly specified by the program.
A pointer qualified by restricting is initially the only means by which restrict
the object it points to can be accessed. Only C99 adds a new type qu
alifier called restrict.
Flow of control
Statements
Statements are the instructions given to the computer to perform any kind of action. Action may be in
the form of data movement, decision making etc. Statements form the smallest executable unit within
a C++ program. Statements are always terminated by a semicolon.
Compound Statement
A compound statement is a grouping of statements in which each individual statement ends with a
semi- colon. The group of statements is called block. Compound statements are enclosed between the
pair of braces ({}.). The opening brace ({) signifies the beginning and closing brace (}) signifies the end of
the block. Null Statement
Writing only a semicolon indicates a null statement. Thus ';' is a null or empty statement. This is quite
useful when the syntax of the language needs to specify a statement but the logic of the program does
not need any statement. This statement is generally used in for and while looping statements.
Conditional Statements
Sometimes the program needs to be executed depending upon a condition. C++ provides the following
statements for implementing the selection control structure.
•if statement
•if else statement
•nested if statement
•switch statement
if statement
The syntax of the if
statement if (condition)
{
statement(s);
}
From the flowchart, it is clear that if the if the condition is true, the statement is executed; otherwise it is
skipped. The statement may either be a single or compound statement.
if else statement
syntax of the if - else
statement if (condition)
statem
ent1;
else
statem
ent2;
From the above flowchart, the given condition is evaluated first. If the condition is true, statement1 is
executed. If the condition is false, statement2 is executed. It should be kept in mind that statement and
statement2 can be a single or compound statement.
if example
if (x == 100)
cout << "x is 100";
if else example
if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";
Nested if statement
The if block may be nested in another if or else block. This is called nesting of if or else block.
The syntax of the nested if
statement if(condition 1)
{
if(condition 2)
{
statement(s);
}
}
if(condition 1)
statement 1;
else if (condition 2)
statement2;
else
stateme
nt3;
if-else-if example
if(percentage>=60)
cout<<"Ist division";
else if(percentage>=50)
cout<<"IInd division";
else if(percentage>=40)
cout<<"IIIrd division";
else
cout<<"Fail" ;
Switch statement
The if and if-else statements permit two-way branching whereas switch statement permits multiple
branching. The syntax of the switch statement is:
switch (var / expression)
{
case constant1:
statement 1;
break;
case constant2:
statement2;
break;
.
.
default:
statement3;
break;
}
The execution of switch statement begins with the evaluation of an expression. If the value of
expression matches with the constant then the statements following this statement execute
sequentially till it executes break. The break statement transfers control to the end of the switch
statement. If the value of expression does not match with any constant, the statement with default is
executed.
Some important points about switch statement
• The expression of a switch statement must be of type integer or character type.
• The default case need not be used at last case. It can be placed at any place.
• The case values need not be in specific order.
Flow of control Looping statement
It is also called a repetitive control structure. Sometimes we require a set of statements to be executed
many times by changing the value of one or more variables each time to obtain a different result. This
type of program execution is called looping. C++ provides the following construct
• while loop
• do-while loop
• for loop
While loop
Syntax of while loop
while(condition)
{
statement(s);
}
The flow diagram indicates that a condition is first evaluated. If the condition is true, the loop body is
executed and the condition is re-evaluated. Hence, the loop body is executed repeatedly if the
condition remains true. As soon as the condition becomes false, it comes out of the loop and goes to
the state next to the ‘while’ loop.
do-while loop
Syntax of do-while
loop do
{statements;
} while (condition);
Note: That the loop body is always executed at least once. One important difference between the
while loop and the do-while loop the relative ordering of the conditional test and loop body execution.
In the while loop, the loop repetition test is performed before each execution the loop body; the loop
body is not executed at all if the initial test fails. In the do-while loop, the loop termination test is
Performed after each execution of the loop body. Hence, the loop body is always executed least once.
for loop
It is a count controlled loop in the sense that the program knows in advance how many times the loop is
to be executed.
The flow diagram indicates that in for loop three operations take place:
• Initialization of loop control variable
• Testing of loop control variable
• Update the loop control variable either by incrementing or decrementing.
Operation (i) is used to initialize the value. On the other hand, operation (ii) is used to test whether the
condition is true or false. If the condition is true, the program executes the body of the loop and then
the value of loop control variable is updated. Again, it checks the condition and so on. If the condition
is false, it gets out of the loop
Jump Statements
The jump statements unconditionally transfer program control within a function.
• goto statement
• break statement
• continue statement
The break statement, when executed in a switch structure, provides an immediate exit from the switch
structure. Similarly, you can use the break statement in any of the loops. When the break statement
executes in a loop, it immediately exits from the loop.
ARRAY
An array is a collection of data elements of same data type. It is described by a single name and each
element of an array is referenced by using array name and its subscript no.
Declaration of Array
Type
arrayname[numberofelements];
For example, int Age[5] ;
float cost[30];
Functions in C++
A function is a group of statements that together perform a specific task. Every C++ program has at
least one function, which is main ().
The function is used for dividing a large code into a module, due to this we can easily debug and
maintain the code. For example, if we write calculator programs at that time we can write every logic
in a separate function (For addition sum (), for subtraction sub()). Any function can be called many
times.
Advantage of Function
Code Re-usability
Develop an application in module format.
Easily to debug the program.
Code optimization: No need to write a lot of code.
Type of Function
There are two types of function in C++ Language. They are;
Library function or pre-define function.
User defined function.
Library function
Library functions are those which are predefined in C++ compiler. The implementation part of pre-defined
functions is available in library files that are .lib/.obj files. .lib or .obj files are contained pre-compiled
code. printf(), scanf(), clrscr(), pow() etc. are pre-defined functions.
User-defined function
These functions are created by a programmer according to their requirement, for example, suppose
you want to create a function for add two number then you create a function with name sum() this
type of function is called a user-defined function.
Defining a function.
Defining of the function is nothing but give the body of the function that means write logic inside the
function body.
Syntax
return_type function_name(parameter)
{
function body;
}
Return type: A function may return a value. The return type is the data type of the value the function
returns. Return type parameters and returns statement are optional.
Function name: Function name is the name of the function it is decided by programmer or you.
Parameters: This is a value which is passed to function at the time of calling of function A parameter is
a placeholder. It is optional.
Function body: Function body is the collection of statements.
Function Declarations
A function declaration is a process of tells the compiler about a function name. The actual body of the
function can be defined separately.
Syntax
return_type function_name(parameter);
Note: At the time of function declaration function must be terminated with ';'.
Calling a function.
When we call any function, control goes to function body and execute entire code. For a call, any
function just writes the name of the function and if any parameter is required then pass a parameter.
Syntax function_name();
or variable=function_name(argument);
Note: At the time of function calling function must be terminated with ';'.
If a function takes any arguments, it must declare variables that accept the values as arguments. These
variables are called the formal parameters of the function. There are two ways to pass value or data
to function in C++ language which is given below;
call by value
call by reference
Call by value
In call by value, original value cannot be changed or modified. In call by value, when you passed a
value to the function it is locally stored by the function parameter in stack memory location. If you
change the value of function parameter, it is changed for the current function only but it does not
change the value of a variable inside the caller function such as main().
Program Call by value in C++
#include<iostream.h>
#include<conio.h>
void main()
{
int a=100, b=200;
clrscr();
swap(a, b); // passing value to function
cout<<"Value of a"<<a;
cout<<"Value of b"<<b;
getch();
}
Output
Value of a: 200
Value of b: 100
Call by reference
In call by reference, the original value is changed or modified because we pass a reference
(address). Here, the address of the value is passed to the function, so actual and formal arguments share
the same address space. Hence, any value changed inside the function is reflected inside as well as
outside the function.
Example Call by Reference in C++
#include<iostream.h>
#include<conio.h>
void swap(int *a, int *b)
{
int temp; temp=*a;
*a=*b;
*b=temp;
}
void main()
{
int a=100, b=200;
clrscr();
swap(&a, &b); // passing value to function
cout<<"Value of a"<<a;
cout<<"Value of b"<<b;
getch();
}
Output
Value of a: 200 Value of b: 100
type *var-name;
Here, the type is the pointer's base type; it must be a valid C++ type and var-name is the name of the
pointer variable. The asterisk you used to declare a pointer is the same asterisk that you use for
multiplication. However, in this statement, the asterisk is being used to designate a variable as a
pointer.
The actual data type of the value of all pointers, whether integer, float, character or otherwise, is the
same, a long hexadecimal number that represents a memory address. The only difference between
pointers of different data types is the data type of the variable or constant that the pointer points to.
#include <iostream>
using namespace
std; int main ()
{
int var = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &var; // store address of var in pointer variable
<< "Value of var variable: ";
cout
cout << var << endl; // print the address stored in ip pointer variable
cout << "Address stored in ip variable: ";
cout << ip << endl; // access the value at the address available in pointer
cout << "Value of *ip variable: ";
cout << *ip << endl;
return 0;
}