0% found this document useful (0 votes)
8 views

Unit 2 - Basics of C++ Programming

The document provides information on various basics of C++ programming. It discusses the main function, comments, input and output operators (cout and cin), cascading I/O operators, the iostream header file, preprocessor directives, namespaces, tokens, keywords, identifiers, variables, constants, data types, operators, type conversion, manipulators, and control structures like conditional and loop statements in C++.

Uploaded by

Anupam Silwal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Unit 2 - Basics of C++ Programming

The document provides information on various basics of C++ programming. It discusses the main function, comments, input and output operators (cout and cin), cascading I/O operators, the iostream header file, preprocessor directives, namespaces, tokens, keywords, identifiers, variables, constants, data types, operators, type conversion, manipulators, and control structures like conditional and loop statements in C++.

Uploaded by

Anupam Silwal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 103

Basics of C++ Programming

main( ) Function

The main function calls member functions of


various classes (using objects) to carry out the
real work
In C++, the return type of the main function is
‘int’

Prepared by Sherin Joshi


Comments

In C++, comments start with a double slash (//)


symbol and end at the end of the line
If we need to comment multiple lines, we can
write as
// this is an
// example
// of multi line comments
The C comment style /*………….*/ may also be
used for multi line comments Prepared by Sherin Joshi
The Output Operator (‘cout’)

The identifier ‘cout’ is a predefined object of


standard stream in C++
The operator ‘<<’ is called ‘insertion’ or ‘put to’
operator
It inserts the content on its right to the object on
its left
cout<<”Hi Everybody”;
cout<<a; //display the content of the variable ‘a’

Prepared by Sherin Joshi


The Input Operator (‘cin’)

A statement cin>>a; is an input statement


This causes the program to wait for the user to
type and give some input
The given input is stored in the variable 'a‘
The identifier ‘cin’ is an object of standard input
stream
The operator ‘>>’ is called ‘extraction’ or ‘get
from’ operator
It extracts or gets value from keyboard and
assigns it to the variable on its right
Prepared by Sherin Joshi
Cascading I/O Operators (Multiple
Input/Output)
The I/O operators can be used repeatedly in a
single i/o statements as follows:

cout<<a<<b<<c;
cin>>x>>y>>z;

Prepared by Sherin Joshi


The iostream Header File

The directive ‘#include <iostream.h>’ causes the


preprocessor to add the contents of 'iostream.h'
file to the program
It contains the declarations of identifiers cout,
cin and the operators << and >>

Prepared by Sherin Joshi


Preprocessor Directives

These are ways to represent the header files or


any library file to bring into memory before their
use
They are preceded by a pound sign ('#')
Eg: #include <iomanip.h>
#define PI 3.14159

Prepared by Sherin Joshi


Namespace

It is a new concept introduced by the ANSI C++


standards committee
It defines a scope for the identifiers that are used
in a program
A C++ program can be divided into different
namespaces
A namespace is a part of the program in which
certain names are recognized; outside of the
namespace they’re unknown
Prepared by Sherin Joshi
Namespace

using namespace std;


The above statement says that all the program
statements that follow are within the std
namespace
Various program components such as cout are
declared within this namespace
Here, std is the namespace where ANSI C++
standard class libraries are defined
And, using and namespace are the new
keywords of C++
Prepared by Sherin Joshi
Tokens

Tokens are the smallest individual units in a


program
Keywords, identifiers, constants, strings and
operators are tokens in C++

Prepared by Sherin Joshi


Keywords

Keywords are explicitly reserved identifiers and


cannot be used as names for the program
variables or other user-defined program
elements
Some keywords are int, auto, switch, case, do,
else, public, default, continue, etc.

Prepared by Sherin Joshi


Identifiers

Identifiers make use of


alphabets [a,b,c,….,z ; A,B,C,…..Z ]
numericals [0,1,2,….9]
underscore [ _ ]
Invalid
Blank spaces and symbols like @, ! , ( , [ , { , ) ,
}, ] are not allowed.
The first character should not be a number
Prepared by Sherin Joshi
Variables

Variable values can change at different


instances within a single run
Declaration: <data_type> <variable_name>;
Eg: int studentID;

Prepared by Sherin Joshi


Constants

They are preceeded by a ‘const’ keyword


The value of these identifiers do not change
throughout the run of the application
Eg : const int estdOfCollege = 1997;

Prepared by Sherin Joshi


Data Types

Prepared by Sherin Joshi


Unsigned Data Types

Prepared by Sherin Joshi


Enumerated Data Types

Enumerated data type is a user defined data


type
Enumerated means that all the values are listed
They are used when we know a finite list of
values that a data type can take on or it is an
alternative way for creating symbolic constants
The ‘enum’ keyword automatically lists a list of
words and assigns them values 0,1,2…

Prepared by Sherin Joshi


Enumerated Data Types

Declaration:
enum shape {circle, square, triangle};
enum Boolean {true, false};
enum switch {on, off};

Prepared by Sherin Joshi


Enumerated Data Types
#include <iostream>
using namespace std;
enum days {sun, mon, tue, wed, thur, fri, sat};
int main()
{
days d1,d2;
d1 = sun;
d2 = thur;
int diff = d2 - d1; // using arithmetic operator
cout<<“Days between = “<<diff;
return 0;
} Prepared by Sherin Joshi
Operators

They are used for manipulating data with other


data to get resultant output.
1. Arithmetic Operators – (+ , - , * , / , % )
2. Assignment Operators – (= , += , - = , *= , /= )
3. Comparison Operators – (< , > , <= , >= , != , = = )
4. Logical Operators – (&& , | | , ! , XOR )
5. Bitwise Operators – (<< , >> )

Prepared by Sherin Joshi


Type Conversion
Implicit Type Conversion

When two operands of different types are


encountered in the same expression, the lower
type variable is converted to the type of the
higher type variable
Prepared by Sherin Joshi
Type Conversion

Explicit Type Conversion: Type Casting


The term type casting refers to data conversion
specified by the programmer, as opposed to
automatic (implicit) data conversions
Eg: int a = 065;
cout << static_cast <char>(a);
Old method:
cout << (char)a; OR cout << char(a);

Prepared by Sherin Joshi


Manipulators

Manipulators are operators used with the


insertion operator (<<) to modify—or
manipulate—the way data is displayed
(1) endl
This causes a linefeed to be inserted into the
stream, so that subsequent text is displayed on
the next line
It has the same effect as sending the ‘\n’
character, but is somewhat clearer
Prepared by Sherin Joshi
Manipulators

Eg:
cout << “First Line”;
cout << endl << “Next Line”;
cout << endl << “Third Line”;
\n – Just adds a new line
endl – In addition to inserting a new line, it also
flushes the stream (buffer)

Prepared by Sherin Joshi


Manipulators

(2) setw
This manipulator changes the field width of
output
The setw manipulator causes the number (or
string) that follows it in the stream to be printed
within a field n characters wide, where n is the
argument to setw(n)
The value is right-justified within the field

Prepared by Sherin Joshi


Prepared by Sherin Joshi
Prepared by Sherin Joshi
Prepared by Sherin Joshi
Prepared by Sherin Joshi
Prepared by Sherin Joshi
Prepared by Sherin Joshi
Control Structures

Control structures in C++ include:


1. Sequence Structure (line by line)
2. Selection Structure (conditional/branching)
3. Loop Structure (iteration)

Prepared by Sherin Joshi


Conditional Statements

Conditional statements are used for the


implementation of branching statements within
the program flow
C++ includes the following branching constructs:
if
if…else
switch case

Prepared by Sherin Joshi


(1) if

Syntax:
if (condition)
{
//statements
}
The statements within the statement block
execute only if the ‘condition’ results to Boolean
true
Prepared by Sherin Joshi
(2) if…else
This construct is suitable if there are mutually
dependent conditions that need to be checked
to decide which statement block to execute
Syntax:
if (condition) else
{ {
//statements1 //statements2
} }

Prepared by Sherin Joshi


if…else (Ladder Structure)

if (condition1) ………
{ else if (condition N)
//statements1 {
} //statementsN
else if(condition 2) }
{ else
//statements2 {
}
//final statement block
………
}
Prepared by Sherin Joshi
(3) Switch Case

This construct is used when the specified


conditions are mutually exclusive
It is used in instances when from many available
options, only a single option is to be selected

Prepared by Sherin Joshi


Switch Case (Syntax)

switch (value) ………


{ default:
case label1: //statements
//statements1 //break;
break; }
case label2:
//statements2
break;
………
Prepared by Sherin Joshi
Switch Case

value can be integer or character or return


value of any function call (of type integer or
character)
label can be integer or character
label is matched against value, and if match is
found, the statement block that corresponds to
the match gets executed
break is a keyword which separates each case
break need not be written in the default section
Prepared by Sherin Joshi
Switch Case

statements can be
any valid statement like declaration and
assignment of any variable
any function call
instantiation of class
break exits the switch case block and the
statement immediately after the switch case
block will get executed
default need not be written at last compulsorily
Prepared by Sherin Joshi
Classwork

Write a program to input two integer values. Then,


ask the user to enter a choice:
- ‘a’ or ‘A’ or ‘+’ for addition
- ‘s’ or ‘S’ or ‘-’ for subtraction

Print the result of the chosen operation.

Prepared by Sherin Joshi


Loops

Used when a statement or a block of statements


is to be executed repeatedly until a stopping
criteria is met
Such repeated execution of statements is called
iteration
C++ allows the following basic loops:
for loop
while loop
do…while loop Prepared by Sherin Joshi
(1) for Loop

Syntax:
for(initialization; test_condition; increment/decrement)
{
//statements
}
initialization – Section for loop declaration, assigning
and re-assigning variables
test_condition – Any valid expression that results to
Boolean true or false can be used (including
function that returns a Boolean value)
Prepared by Sherin Joshi
for Loop

increment/decrement – Any valid expression


that has a step increment or a step decrement
to change the state of loop variable
Different structures:
for(int i=0; …..; …..)
for(int i=0, j=5, k=3; …..; …..)
for(; …..; …...)

Prepared by Sherin Joshi


for Loop – Outputs?

(1) for(int i=0, j=5; (i<=10 && j>= -2); i++, j- -)


{
cout << i << “\t” << j << endl;
}

(2) for(int i=0; i<=10; j=0)


cout << “Hello”;
i++;
Prepared by Sherin Joshi
for Loop – Outputs?

(3) for(int i=0; i<=10; j=0)


{
cout << “Hello”;
i++;
}

Prepared by Sherin Joshi


(2) while Loop

Syntax:
while(condition)
{
//statements
//change in loop variable
}

Prepared by Sherin Joshi


while Loop

Working Principle: The statements within the


while block gets executed only if the condition is
a Boolean true. Otherwise, the loop terminates.
Both for loop and while loop are pretested, that
is, both of them test the condition before
executing the statement block

Prepared by Sherin Joshi


(3) do…while Loop

Sometimes, there are instances when the


condition should be checked only after
executing the looping statement block
In such cases, do…while loop is preferred
Syntax:
do
{
//statements
//change in loop variable
}while(condition);
Prepared by Sherin Joshi
do…while Loop

In the first iteration, the statements within the


statement block get executed unconditionally,
then the condition is evaluated
If the result is
FALSE – loop terminates
TRUE – loop continues

Prepared by Sherin Joshi


Classwork

Write a program to evaluate the roots of a


quadratic equation ax2+bx+c=0 using if…else and
iteration.

(Recall that there may be two real roots, two


imaginary roots or one repeated real root)

Prepared by Sherin Joshi


‘break’ and ‘continue’
break is a keyword that helps to terminate the
loop whenever it is executed
eg: int i =1;
while(i !=10)
{
i++;
cout << i << endl;
if (i == 5)
break;
} OUTPUT =?
Prepared by Sherin Joshi
‘break’ and ‘continue’

continue is a keyword that skips that particular


iteration of the loop when encountered
eg: int i = 7;
for(i=0; i<=10; i++)
{
if(i % 2 == 0) continue;
cout << i << endl;
} OUTPUT = ?
Prepared by Sherin Joshi
Arrays

Arrays are data structures that can hold similar


data in contiguous memory
Declaration:
data_type arr_name[dim1]; //one dimensional

data_type arr_name[dim1][dim2]…[dimN];
//multi dimensional

Prepared by Sherin Joshi


Arrays

eg: int roll[4] = {401, 402, 405, 406};


In memory, roll[0] = 401, roll[1] = 402, roll[2] = 405,
roll[3] = 406

eg: float area[4] = {7, 15, 6}


area[3] = ?
area[1] = ?

Prepared by Sherin Joshi


Classwork

Write a program that inputs the contents of a 2X3


size array ‘A’. Then, display the contents of A as
well as 5*A.

Prepared by Sherin Joshi


Functions

A function is a block of organized, reusable


code that is used to perform a single, related
action
Function Declaration:
ret_type fun_name (list_of_args);
Functions may also not return any value in which
case their return type is ‘void’
The argument list may contain one or more
arguments or it may also be empty
Prepared by Sherin Joshi
Functions

Function Call: fun_name(list_of_args);


Function Definition:
ret_type fun_name (list_of_args)
{
//statements
return data; //not required if ret_type is ‘void’
}

Prepared by Sherin Joshi


Default Arguments

A function can be called without specifying all


its arguments
The function declaration must provide default
values for those arguments that are not
specified
Missing arguments must be the trailing
arguments i.e., for eg, you can leave out the last
three arguments but you cannot leave out the
next-to-last and then put in the last
Prepared by Sherin Joshi
//Demonstration of default arguments
#include <iostream>
using namespace std;
//declaration with default arguments
void repchar(char = ‘!’, int = 45);

int main( )
{
repchar( ); //prints 45 exclamation marks
repchar(‘=’); //prints 45 equal signs
repchar(‘+’, 30); //prints 30 plus signs
return 0;
} Prepared by Sherin Joshi
void repchar(char ch, int n)
{
for(int j=0; j<n; j++)
cout<<ch;
cout << endl;
}

We can also use variable names in declaration of


functions with default arguments:

void repchar(char reptChar = ‘*’, int numberReps =


45);
Prepared by Sherin Joshi
Pass by Reference

When function arguments are passed by value,


the called function creates a new variable of
the same type as the argument and copies the
argument’s value into it
The function cannot access the original variable
in the calling program, only the copy it created
This is useful when the function does not need to
modify the original value

Prepared by Sherin Joshi


Pass by Reference

When passing arguments by reference, instead


of a value being passed to the function, a
reference to the original variable (memory
address) in the calling program is passed
In this mechanism, the function can access the
actual variables in the calling program
It also provides a mechanism for passing more
than one value from function back to the calling
program
Prepared by Sherin Joshi
//Swapping values through call by reference
#include <iostream>
using namespace std;
void swap (int &, int &);
int main( )
{
int n1, n2;
cout << “Enter n1: ”;
cin >> n1;
cout << endl << “Enter n2: ”;
cin >> n2;
cout << endl << “Original Values: ”; Prepared by Sherin Joshi
cout << “n1 = ” << n1 << “n2 = ” << n2;
swap (n1, n2);
cout << endl << “After Swap: ”;
cout << “n1 = ” << n1 << “n2 = ” << n2;
return 0;
}
void swap (int &n1, int &n2) {
int temp;
temp = n1;
n1 = n2;
n2 = temp;
}
Prepared by Sherin Joshi
Returning by Reference
We can also return a value by reference in
addition to passing values
One reason to do this is to avoid copying a large
object
Another reason is to allow us to use a function
call on the left side of the equal sign
An ordinary function that returns a value is
treated as if it were a value
On the other hand, a function that returns a
reference is treated as if it were a variable
Prepared by Sherin Joshi
//Returning reference values
#include <iostream>
using namespace std;

int x; //global variable


int& setx( );

int main( ) int& setx( )


{ {
setx( ) = 99; return x;
cout << “x = ” << x }
cout << endl;
return 0;
} Prepared by Sherin Joshi
Returning by Reference

(1) We can’t return a constant from a function


that returns by reference. In setx( ), we can’t say

int& setx( )
{
return 3; //not possible
}

Prepared by Sherin Joshi


Returning by Reference

(2) We can’t return a reference to a local variable

int& setx( )
{
int x = 3;
return x; //error
}

Prepared by Sherin Joshi


inline Function
In many places we create the functions for small
work/functionality which contain simple and less
number of executable instruction
When a normal function call instruction is
encountered, the program stores the memory
address of the instructions immediately following
the function call statement, loads the function
being called into the memory, copies argument
values, jumps to the memory location of the called
function, executes the function codes, stores the
return value of the function, and then jumps back
to the address of the instruction that was saved just
before executing the called function
Prepared by Sherin Joshi
inline Function
This results in too much runtime overhead
The C++ inline function provides an alternative
With 'inline' keyword, the compiler replaces the
function call statement with the function code
itself then compiles the entire code
Thus, with inline functions, the compiler does not
have to jump to another location to execute the
function, and then jump back as the code of
the called function is already available to the
calling program
This results in fast execution of code Prepared by Sherin Joshi
inline Function

It’s just a suggestion, not compulsion


Compiler may or may not inline the functions we
marked as inline
It may also decide to inline functions not marked
as inline at compilation or linking time
Syntax: inline ret_type fun_name (list_of_args);
Example: inline double avg(int n1, int n2, int n3);

Prepared by Sherin Joshi


Classwork

Write a program that reads ‘n’ integers in an array.


Then, create a function that searches for an
integer ‘x’ in the array. The function should:
- display “Search Unsuccessful” if x is not found in
the array
- display the number of occurrences if x is found in
the array

Prepared by Sherin Joshi


Storage Classes

The storage class of a variable specifies the


lifetime and visibility (scope) of a variable within
the program
There are four types of storage classes
NOTE: Scope of a variable can be local, file(i.e.
global) or class

Prepared by Sherin Joshi


(1) Automatic
Default storage class of any type of variable.
Scope/Visibility: Restricted to the function in
which it is declared.
Lifetime: Limited till the time its container
function is executed. That is, it is created as soon
as its declaration statement is encountered and
is destroyed as soon as the program control
leaves its container function block.
Initial Value: Garbage
Keyword: auto

Prepared by Sherin Joshi


(2) External
Keyword: extern
Variables of extern storage class have a global
scope. We use extern variables when we want a
variable to be visible outside the file in which it is
declared. So, an extern variable can be shared
across multiple files. An extern variable remains
alive as long as program execution continues.
An extern global variable is visible across all the
files of a program.
Initial Value: 0

Prepared by Sherin Joshi


(3) Static
A static variable has the scope/visibility of a
local variable but the lifetime of an external
variable.
Once declared inside of a function block, it
does not get destroyed after the function is
executed, but retains its value so that it can be
used by future function calls.
Initial value: 0
Keyword: static

Prepared by Sherin Joshi


(4) Register
Similar in behavior to an automatic variable, only
differs in the manner in which it is stored in
memory.
Unlike automatic variables that are stored in the
primary memory, the register variables are stored
in CPU registers.
The objective of storing a variable in registers is to
increase its access speed, which eventually
makes the program run faster.
Initial Value: Garbage
Keyword: register
Note: If there are no registers vacant to
accommodate the variable, then it is stored just
like any other automatic variable. Prepared by Sherin Joshi
Function Overloading

Sometimes we maybe have multiple functions


that perform similar tasks
It is better to give the same name to those
functions
This feature is called function overloading
Overloaded functions should have varying
signatures
This means the functions could have different
number of arguments or different types of
arguments Prepared by Sherin Joshi
Function Overloading

If any overloaded function is called in such a


way that no corresponding match is predefined,
then implicit conversion of the arguments/ return
type is made and then the matched definition
executes
Overloaded functions make system design
easier since inner details are not considered

Prepared by Sherin Joshi


Function Overloading

Example declarations:

int sum (int, int);


double sum (double, double);
int sum (int, int, int);

Prepared by Sherin Joshi


// example demonstrating function overloading
#include <iostream>
using namespace std;
void repchar( ); //declarations
void repchar(char);
void repchar(char, int);
int main( ) {
repchar( );
repchar(‘=’);
repchar(‘+’, 30);
return 0;
} Prepared by Sherin Joshi
// repchar( ) definition 1, displays 45 asterisks
void repchar( ) {
for(int j=0; j<45; j++) // always loops 45 times
cout << ‘*’; // always prints asterisk
cout << endl;
}
// repchar( ) definition 2
//displays 45 copies of specified character
void repchar(char ch) {
for(int j=0; j<45; j++) // always loops 45 times
cout << ch; // prints specified character
cout << endl;
} Prepared by Sherin Joshi
// repchar( ) definition 3
// displays specified number of copies of specified
// character
void repchar(char ch, int n)
{
for(int j=0; j<n; j++) // loops n times
cout << ch; // prints specified character
cout << endl;
}

Prepared by Sherin Joshi


Prepared by Sherin Joshi
Pointers

Pointer is a derived data type that refers to


another data variable by storing the variable’s
memory address rather than data
It is used for indirect access of any variable in
the memory
Syntax: data_type *pointer_name;
Here, ‘data_type’ represents that the pointer
variable can be assigned to access any variable
of that type
Prepared by Sherin Joshi
Pointers

Eg: int x = 25; (value of x)

25
0073H

int *ptr = &x; (address of x)

Prepared by Sherin Joshi


// Accessing and storing a pointer
#include <iostream>
using namespace std;
int main( ) {
int y = -35, x = 25;
int *ptr; //declaring a pointer to integer
cout << “x = ” << x;
cout << endl << &x; //address of x
ptr = &x; //assign ptr -> x, initialization
cout << endl << ptr; //address of x
cout << endl << *ptr; //25
ptr = &y;
cout << endl << *ptr; //-35
return 0; } Prepared by Sherin Joshi
Pointer Arithmetic (Operators on
pointers)
Like other usual primitive data types, pointer
arithmetic is also possible
Pointer arithmetic must follow some rules:
A pointer can be incremented(++) or
decremented(- -)
Any integer can be added or subtracted from
a pointer
One pointer can be subtracted from another

Prepared by Sherin Joshi


Pointer Arithmetic

Arithmetic operations other than addition and


subtraction are not allowed (multiplication,
division, bitwise operations are not allowed)
Arithmetic operations should not work on two
different data types

Prepared by Sherin Joshi


Pointer Arithmetic

++*ptr; //increment the content pointed by ptr


++ptr; //increment the address by the size of
//data type

int c = 35, **ptr1, *ptr2;


ptr2 = &c;
ptr1 = &ptr2;
cout << *ptr1; //address of c
cout << **ptr1; //35
Prepared by Sherin Joshi
Function Pointer (Pointer to Function)

Functions can also be accessed with the help of


a pointer to function
C++ allows pointer to function for easy and
efficient handling of functions
General Syntax:
return_type (*ptrFunName)(listOfArgs);
Function pointer does not have a definition
body

Prepared by Sherin Joshi


Function Pointer

Usually, in large programs or memory hungry


applications like computer graphics, simulation,
gaming, etc, we can save memory by defining
and implementing function pointers (or pointers
to functions) for easy and efficient handling of
memory

Prepared by Sherin Joshi


//Pointer to function cout << “Sum = ”;
#include <iostream> cout << fsum;
using namespace std; return 0;
float sum(float, float); }
float (*ptr)(float, float);
int main( ) float sum(float a, float b)
{ {
ptr = &sum; return (a+b);
float x = 3.5, y = 7.6, fsum; }
fsum = (*ptr)(x, y);
//fsum = sum(x, y)
Prepared by Sherin Joshi
Pointer to Arrays

int value[10];
int *ptr;

Then the following is a valid assignment:


ptr = &value[0]; OR ptr = value;
This allocates the pointer (ptr) to the address of
the first element

Prepared by Sherin Joshi


Pointer to Arrays

Then, ptr++ == &value[1]


Pointer arithmetic can help access any
element of the array

ptr+6 == &value[6]
*ptr == value[0]
*(ptr + 3) == value[3]
*(ptr + 7) == value[7]
Prepared by Sherin Joshi
//Reading values of an array using pointer
#include <iostream>
using namespace std;
int main( )
{
int myArr[5] = {5,6,7,8,9};
int *ptr;
ptr = &myArr[0]; //or, ptr = myArr;
for(int i = 0; i<5; i++)
cout << *((ptr)+i) << endl;
return 0;
} Prepared by Sherin Joshi
Pointer to Arrays

For multidimensional arrays;


int value [4][3];
int *ptr;
ptr = &value[0][0]; OR ptr = value;

Then,ptr++ == &value[0][1];
ptr+6 == &value[2][0];

Prepared by Sherin Joshi


Passing function pointer as an
argument
Syntax:

ret_type func_name
(ret_type(*func_ptr)(list_of_args),other_arg_types);

Prepared by Sherin Joshi


// n * sum(a, b)
#include <iostream>
using namespace std;
int sum(int, int); //function declaration
int (*ptrsum)(int, int); //function pointer
void calculate(int (*ptrsum)(int, int), int, int, int);

int main( ) {
int a = 10, b = 20, n = 3;
ptrsum = &sum;
calculate(ptrsum, a, b, n);
return 0;
} Prepared by Sherin Joshi
int sum(int x, int y)
{
return (x+y);
}

void calculate(int (*ptrsum)(int, int), int a, int b, int n)


{
int total;
total = (*ptrsum)(a, b) * n;
cout << “Result = ” << total;
}

Prepared by Sherin Joshi


Classwork

Write a program to find out the greatest and the


smallest among N numbers using pointers.

Prepared by Sherin Joshi

You might also like