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

Functions

Modular programming involves breaking large programs into smaller subprograms called functions. This approach reduces program size and complexity, improves reusability, and reduces errors. C++ provides standard library functions and user-defined functions. Common I/O functions include gets(), puts(), getchar(), putchar(), and stream functions like get() and put(). String functions such as strcpy(), strlen(), strcmp(), and strcmpi() manipulate strings. Mathematical functions include abs() for absolute value.

Uploaded by

Anamika T Anil
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Functions

Modular programming involves breaking large programs into smaller subprograms called functions. This approach reduces program size and complexity, improves reusability, and reduces errors. C++ provides standard library functions and user-defined functions. Common I/O functions include gets(), puts(), getchar(), putchar(), and stream functions like get() and put(). String functions such as strcpy(), strlen(), strcmp(), and strcmpi() manipulate strings. Mathematical functions include abs() for absolute value.

Uploaded by

Anamika T Anil
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

C++ Functions

Modular Programming Console functions for character I/O


The process of breaking large programs opeartions
into smaller sub programs is called C++ provides some functions for
modularization and these subprograms are performing input/ouput operations on
called functions. characters. To use these functions, we must
Merits of Modular Programming include the header file cstdio in the program.
 Reduces the size of the program: The gets( ): This function is used to read a string
modular approach helps to group the through the keyboard and places it in a string
repeating tasks under a name and these variable.
instructions can be called whenever
Eg: char name[20];
necessary. Thus the program size is
cout<< “Enter a name :”;
reduced.
gets(name);
 Less chances of error: In a modularized
puts( ): This function is used to display a
program, we need to concentrate only one
string on the screen. The puts() function
module at a time. If there are some errors,
advances the cursor to the new line.
we can easily identify and rectify them in
Eg: char name[20];
that module. This reduces the occurrence
cout<< “Enter Your name :”;
of syntax and logical errors in the
gets(name);
program.
puts(“Your name is :”);
 Reduces programming complexity: The
puts(name);
above mentioned merits automatically
getchar(): This function is used to input a
reduce programming complexity. If the
character through the keyboard. The
division of modules is simple and smaller,
character can be stored in a variable.
the logic of the program becomes simple.
char ch;
 Improves reusability: A function written
ch = getchar();
once may be reused later in many other
putchar(): This function is used to display the
programs, which reduces the time for
character given as the argument on the
program development.
standard output unit (monitor). The argument
Demerits of Modular Programming
may be a character constant or a variable. If
 Care should be taken while breaking down an integer value is given as the argument, it
the program.
will be considered as an ASCII value and the
 Each sub program must be independent corresponding character will be displayed. Eg:
of others. char ch = 'B'; //assigns 'B' to the variable ch
 Care should be taken to set the hierarchy putchar(ch); //displays 'B' on the screen
of the execution of modules. putchar('c'); //displays 'c' on the screen
Functions in C++ putchar(97); //displays 'a' on the screen
Function is a named unit of statements in
Stream functions for I/O opeartions
a program to perform a specific task. A
C++ provides some stream functions
program in C++ is organized into a collection
to perform input/ouput operations on
of functions. Every C++ program has at least
character/strings. These are generally called
one function called main( ).
stream functions since they allow a stream of
Functions can be classified into two –
bytes (data) to flow between memory and
1) Standard library functions / predefined
objects. To use these functions, we must
functions / built in functions
include the header file iostream in the
2) User defined functions
program.
Standard library functions are built in
A. Input functions
functions which are parts of the compiler
get(): This function is used to input a
package. User defined functions are those
character or string through the keyboard. To
functions which are separately defined by the
accept a string, an array name and size are to
programmer for various purposes.
be given as arguments.
Predefined Functions
The definitions of predefined functions are
stored in header files. Some common types of
predefined functions in C++ are the following.

1
char ch, str[10]; (iii) strlen( ) – This function is used to find
ch=cin.get(ch); //accepts a character the length (number of characters) of a
and stores in ch string.
cin.get(ch); //equivalent to the above Syntax: int strlen(string)
statement Here string is the name of the string.
cin.get(str,10); //accepts a string of Eg:- char str[15] = “COMPUTER”;
maximum 10 characters cout<<strlen(str); // Displays 8
getline(): This function is used to input a (iv) strcmp( ) – This function is used to
string through the keyboard. The delimiter will compare two strings. In this comparison,
be Enter key, the number of characters or a the alphabetical order of characters in the
specified character. Eg: string is considered.
char ch=‟s‟, str[10]; Syntax: strcmp(string1, string2)
int len; This function returns 0, when string1 and
cin.getline(str,len); // with 2 arguments string2 are same, it returns a –ve value,
cin.getline(str,len,ch); // with 3 arguments when string1 is alphabetically lower than
While inputting the string, only len–1 string2 and returns a +ve value, when
characters, or characters up to the specified string1 is alphabetically higher than
delimiting character (here „s‟), whichever string2.
occurs first will be stored in the array. Eg:- char s1[20] = “COMPUTER”,
A. Output functions s2[10] = “SCIENCE”;
put(): This function is used to display a Here strcmp(s1,s2) returns a value less
character constant or the content of a than zero.
character variable given as argument. (v) strcmpi( ) – This function is used to
Eg: char ch='c'; compare two strings ignoring cases. That
cout.put(ch); //character 'c' is displayed is this function will treat both the upper
cout.put('B'); //character 'B' is printed case and lower case letters same for
cout.put(65); //character 'A' is printed comparison.
write(): This function is used to display the Syntax: strcmpi(string1, string2)
string contained in the argument. Eg:- char s1[20] = “COMPUTER”,
Eg: char str[10]="hello"; s2[10] = “computer”;
cout.write(str,10); Here strcmpi(s1,s2) returns zero.
The above code segment will display the Mathematical Functions
string hello followed by 5 white spaces, The following are some important
String Functions mathematical functions. To use these
The following are some important string functions, we must include the header file
manipulating functions. To use these cmath (math.h in Turbo C++).
functions, we must include the header file (i) abs( ) – This function is used find the
cstring (string.h in Turbo C++). absolute value of an integer. It takes an
(i) strcpy( ) – This function is used to copy integer argument.
one string into another. Syntax: int abs(int)
Syntax: strcpy(string1, string2); Eg:- int a = - 234, b; b = abs(a); // b =
Here string2 is copied to string1 234
Eg:- char s1[10], s2[10] = “COMPUTER”; Note: If we want to find the absolute
strcpy(s1,s2); // Copies “COMPUTER” to value of a floating point number, we can
the string s1 use fabs( )
(ii) strcat( ) – This function appends a string (ii) sqrt( ) – This function is used to find
to the end of another string. The length of square root of a number. Here the
the resulting string is the sum of lengths argument can be of type int, float or
of both the strings. double and returns the non-negative
Syntax: strcat(string1, string2); square root of that argument.
Here string2 is concatenated to string1 Syntax: double sqrt(double)
Eg:- char s1[20] = “COMPUTER ”, eg : int a = 64; cout<<sqrt(a); //Displays 8
s2[10] =“SCIENCE”; strcat(s1,s2); //s2 is (iii) pow( ) – This function is used to find the
combined to s1 power of a number. It takes two
puts(s1); //Displays COMPUTER SCIENCE arguments x and y of type integer or float
or double and returns x y.

2
Syntax: double pow(double, double) the character specified as its argument is
Eg:- int a = 2, b = 3; cout<<pow(a,b); an uppercase character, otherwise
//Displays 8 returns zero (0).
Character Functions Syntax: int isupper(char)
The following are some important Eg:- char ch;
character functions. To use these functions, if(isupper(ch))
we must include the header file cctype cout<<” Upper case letter”;
(ctype.h in Turbo C++). int a=isupper(„f‟); // a=0
(i) isalnum( ) – This function is used to int b=isupper(„F‟); // b=1
check whether a character is alpha (vi) tolower( ) – This function is used to
numeric or not. It returns a non zero convert an upper case character to its
value (1) if the character specified as its equivalent lower case character.
argument is alpha numeric, otherwise Syntax: char tolower(char)
returns zero (0). Eg:- putchar(tolower(„A‟)); // Displays a
Syntax: int isalnum(char) char ch=‟E‟;
Eg:- char ch; char c=tolower(ch); //c=‟e‟
if(isalnum(ch)) (vii) toupper( ) – This function is used to
cout<<” Alpha Numeric”; convert an lower case character to its
int a=isalnum(„#‟); // a=0 equivalent upper case character.
int b=isalnum(„2‟); // b=1 Syntax: char toupper(char)
(ii) isalpha( ) – This function is used to Eg:- putchar(toupper(„a‟)); // Displays A
check whether a character is an alphabet char ch=‟e‟;
or not. It returns a non zero value (1) if char c=tolower(ch); //c=‟E‟
the character specified as its argument is User Defined Functions
an alphabet, otherwise returns zero (0). The creation and usage of user defined
Syntax: int isalpha(char) functions involve three steps:
Eg:- char ch; 1) Definition of a function.
if(isalpha(ch)) 2) Declaration of a function.
cout<<” Alphabet”; 3) Invoking a function (Function call).
int a=isalpha(„2‟); // a=0 Definition of a function.
int b=isalpha(„e‟); // b=1 The function definition consists of the
(iii) isdigit( ) – This function is used to check function header and its body. A function
whether a character is a digit or not. It header specifies the type of the data returned
returns a non zero value (1) if the by the function, name of the function and the
character specified as its argument is an list of parameters (arguments) used by the
digit, otherwise returns zero (0). function. The body of a function is a set of
Syntax: int isdigit(char) statements enclosed within braces. The
Eg:- char ch; general form of a function definition is,
if(isdigit(ch)) return_type function_name(argument_list)
cout<<” Digit”; {
int a=isdigit(„2‟); // a=1 statements in the body;
int b=isdigit(„e‟); // b=0 }
(iv) islower( ) – This function is used to Here return_type specifies the data type of the
check whether a character is lower case value returned from the function. All functions
or not. It returns a non zero value (1) if should return a value. If the return_type is not
the character specified as its argument is specified explicitly it will be „int‟ (by default).
a lowercase character, otherwise returns A function_name is used to identify the
zero (0). function. It should be a valid identifier. The
Syntax: int islower(char) argument_list or parameter_list is a comma
Eg:- char ch; separated list of variables, referred to as the
if(islower(ch)) arguments of the function. This list is optional.
cout<<” Lower case letter”; The parameters are used to supply data to the
int a=islower(„f‟); // a=1 function from the caller. The data type of each
int b=islower(„F‟); // b=0 parameter in the list should be explicitly
(v) isupper( ) – This function is used to stated.
check whether a character is upper case
or not. It returns a non zero value (1) if

3
Eg: 1) void display( ) Passing arguments to a function
{ Arguments or parameters are the means
cout<<”Welcome to C++”; to pass values from the calling function to the
} called function. A function call should normally
2) void area(int a,float b) contain the same number and type of
{ arguments in the same order as they are in
cout<<”Area = ”<<a*b; the prototype or function header.
} Note: The number and type of arguments of a
function is called that function‟s signature
3) float area(int a,float b) (function‟s argument list).
{ Actual Parameters and Formal Parameters
float ar; The parameters that are used in the
ar=a*b; function call statement are called actual
return ar; // return(ar); (original) arguments/parameters. The
} parameters that appear in the function
‘return’ statement definition are called formal
A return statement has the following jobs: parameters/arguments. The arguments used
(i) returns the program execution control in the function prototype are called dummy
back to the caller function and arguments.
(ii) passes a value back to the caller function. Eg:- # include<iostream>
A function can return only a single value at using namespace std;
a time. If no value is to be returned the return int add(int, int); //Fn. Declaration/Prototype
type in the function header should be int main( )
specified as „void‟. A function can also have {
more than one return statement. int a,b;
Declaration of a function (Prototype) cout<< “Enter two numbers :”;
The function declaration (function cin>>a>>b;
prototype) informs the compiler the name of cout<< “Sum =”<<add(a,b); //Fn. Call
the function, its return type and the number return 0;
and the type of the arguments passed to the }
function. A function has to be declared in the int add(int x, int y)//Fn. definition
program before using it. If the function is {
defined before it is used in the program, there return(x+y);
is no need of declaration. The general form of }
a function declaration is, In the above program, a and b are actual
return_type function_name(parameter_list); parameters and x and y are formal
Note: In the function prototype, the argument parameters.
names need not be specified. ● Write a program to find the area of a
Eg: 1) void display(); circle using a function.
2) void area(int, float); #include<iostream>
3) float area(int, float); using namespace std;
Invoking a function int main( )
A function is called by providing its name {
followed by the values of parameters float r;
enclosed within parenthesis ( and ). When a float cir_area(float); // fn declaration
function is called the control of execution cout<<“Enter the radius of the circle :”;
branches to the function body, the values of cin>>r;
parameters are passed and the body of the cout<<“Area =”<<cir_area(r); // fn call
function is executed. After the execution of the return 0;
function body, a value may be returned and }
the control returns back to the caller function. float cir_area(float a) //fn definition
The general form of a function call is, {
function_name(parameter_list); return(3.14*a*a);
Eg: 1) display(); }
2) area(2,5.6);
3) cout<<”Area = “<<area(3,4.5);

4
● Write a program to find the largest of two ● Write a program to reverse a number
numbers using a function ‘large2( )’. using a function.
#include<iostream> #include<iostream>
using namespace std; using namespace std;
int large2(int, int); int rev_no(int);
int main( )
int main( ) {
{ int no;
int a,b; cout<<“Enter a number :”;
cout<<“Enter two numbers :”; cin>>no ;
cin>>a>>b; cout<<“Reverse is : ”<<rev_no(no);
cout<<“Largest of ”<<a<<“&”<<b<<“=”;
cout<<large2(a,b); return 0;
return 0; }
} int rev_no(int n)
int large2(int x, int y) { int rev=0,d;
{ if(x>y) while(n!=0)
return x; { d=n%10;
else rev=(rev*10)+d;
return y; n=n/10;
} }
● Write a program to find the largest of return(rev);
three numbers using a function. }
#include<iostream> ● Write a program to check whether a
using namespace std; given number is odd or even using a
int large3(int, int, int); function.
int main( ) #include<iostream>
{ using namespace std;
int a,b,c; void check(int);
cout<<“Enter three numbers :”; int main( )
cin>>a>>b>>c; {
cout<<“Largest= ”<<large3(a,b,c); int n;
return 0; cout<<“Enter a number :”;
} cin>>n ;
int large3(int x, int y, int z) check(n);
{ int l; return 0;
l = (x>y) ? ((x>z) ? x : z) : ((y>z) ? y : z); }
return (l); void check(int a)
} { if(a%2==0)
● Write a program to find the factorial of a cout<<“The Number is Even”;
number using a function. else
#include<iostream> cout<<“The Number is Odd”;
using namespace std; }
int fact(int); ● Write a program to find the sum of digits
int main( ) of a number using a function.
{ #include<iostream>
int n; using namespace std;
cout<<“Enter a number :”; int main( )
cin>>n ; {
cout<<“Factorial of ”<<n<<“=”<<fact(n); int n;
return 0; int sumdigits(int);
} cout<<“Enter a number :”;
int fact(int x) cin>>n;
{ int f=1; cout<<“Sum of digits is : ”<<sumdigits(n);
for(int i=1; i<=x; i++) return 0;
f = f * i; }
return (f); }
5
int sumdigits(int x) within the function does not reflect back to the
{ int i, sum=0,d; actual parameters. Eg:
while(x!=0) #include<iostream>
{ d=x%10; using namespace std;
sum=sum+d; void change(int);
x=x/10; int main()
} { int a=10;
return(sum); cout<< “Value of a =”<<a<< “\n”;
} change(a);
● Write a program to find the value of nCr cout<< “Value of a =”<<a;
#include<iostream> return 0;
using namespace std; } Output
long fact(int); void change(int x) Value of a =10
int main( ) { Value of a =10
{ x++;
int n,r; long ncr }
cout<<“Enter the values of n and r :”; 2. Call by reference (Pass by reference)
cin>>n>>r; Method
ncr=fact(n)/(fact(r) * fact(n-r)); In call by reference method a reference to
cout<<n<<”C”<<r<<” = “<<ncr; the actual parameter is passed to the function.
return 0; Reference is an „alias‟ name (alternative
} name) for a previously defined name. The
long fact(int x) reference variable shares the memory
{ int i, sum=0,d; location of the actual parameter. Therefore
for(long f=1;x>0;x--) any change made in the formal parameters
f=f * x; within the function is reflected back to the
return f; actual parameters.Eg:
} #include<iostream>
Functions with default arguments using namespace std;
Default values can be assigned to void change(int &);
parameters if the calling statement does not int main()
provide a value for that parameter. If an {
argument has a default value, then all the int a=10;
arguments to its right should also have default cout<< “Value of a =”<<a<< “\n”;
values. change(a);
Eg:- long timesec(int H, int M=0, int S=0) cout<< “Value of a =”<<a;
{ return 0;
long sec=H*3600 + M*60 + S; }
return sec; void change(int &x) Output
} { Value of a =10
int main( ) x++; Value of a =11
{ }
cout<< timesec(2,10,40); Call by Value Method Call by Reference Method
Ordinary variables are Reference variables are
cout<< timesec(1,30); used as formal parameters used as formal parameters
cout<< timesec(3); Actual parameters may be Actual parameters will be
return 0; constants, variables or variables only
} expressions
Methods for calling a function The changes made in the The changes made in the
formal parameters do not formal parameters do
A function can be invoked (called) in two reflect in the actual reflect in the actual
ways. parameters parameters
(i) Call by value method Exclusive memory Memory of actual
(ii) Call by reference method allocation is required for parameters is shared by
1. Call by value (Pass by value) Method the formal parameters formal parameters
In call by method, a copy of actual
parameter is passed to the function. Therefore
any change made in the formal parameters

6
Write a program to interchange (swap) Eg:- int rev_no(int n)
values of two variables (use both call by { int r=0, d;
value method and call by reference ….
method). return(r);
}
// By call by value method Here r and d are local variables of „rev_no‟
function.
#include<iostream> Global Variables
using namespace std; Variables declared outside the bodies of
void swap(int, int); all functions are called global variables.
int main( ) Global variables have global scope. i.e., these
{ int a,b; variables can be accessed from anywhere in
cout<<“Enter two numbers :”; the program.
cin>>a>>b; Eg:- int n;
cout<<“Value of a=”<<a<<“and b=”<<b; void main( )
swap(a,b); { …..
cout<<“Value of a=”<<a<<“and b=”<<b; }
Note : A local variable with the same name of
return 0; global variable hides the global variable.
} Eg:- float n=1.25; //global variable
void swap(int x, int y) void main( )
{ int t; { float n=2.0; //local variable
t=x; cout<<n;
x=y; }
y=t; Local Functions
cout<<“Value of a=”<<x<<“and b=”<<y; Functions declared within the body of
} another function will have local scope. i.e.,
local functions cannot be accessed or called
// By call by reference method from outside the function body.
Eg:- void main( )
#include<iostream> { int rev_no(int); //local function
using namespace std; ………..
void swap(int &, int &); }
int main( ) Global Functions
{ int a,b; Functions declared outside the bodies of
cout<<“Enter two numbers :”; all functions are called global functions. These
cin>>a>>b; functions have global scope. i.e., they can be
cout<<“Value of a=”<<a<<“and b=”<<b; accessed and called from anywhere in the
swap(a,b); program.
cout<<“Value of a=”<<a<<“and b=”<<b; Eg:- int area(int, int);//global function
return 0; void main( )
} { int l, b;
void swap(int &x, int &y) cout<<“Enter l and b :” ; cin>>l>>b;
{ int t; cout<<“Area =”<<area(l,b);
t=x; getch( );
x=y; }
Scope &
y=t; life
Local Global
cout<<“Value of a=”<<x<<“and b=”<<y;  Declared within a  Declared
} function or a outside all
Scope and Life of Variables and block of the
statements. functions.
Functions  Available only  Available to
Local Variables within that all the
Variables
Variables declared within a function body function or block. functions of
are local variables to that function. Local  Memory is the program.
variables have local scope. These variables allocated when  Memory is
the function or allocated just
can be accessed only within that function. block is active before the
and freed when execution of

7
the execution of the program 12. Look at the following functions:
the function or and freed int sum(int a,int b=0,int c=0)
block is when the
completed. program {
stops return (a + b + c);
execution. }
 Declared within a  Declared or a. What is the speciality of the function
function or a defined regarding the parameter list?
block of outside all
statements and other b. Give the outputs of the following function
defined after the functions. calls by explaining its working and give
Functions
calling function.  Accessible reason, if the function call is wrong.
 Accessible only by all the i) cout << sum (1, 2, 3); ii) cout << sum(5, 2);
within that functions in iii) cout << sum(); iv) cout << sum(0);
function or the the program.
block. 13. The prototype of a function is:
Sample Questions int fun(int, int);
1. What is a meant by a function in C++? The following function calls are invalid. Give
2. The built-in function to find the length of a reason for each.
string is _________. a) fun("hello",4); b) cout<<fun();
3. Write down the role of header files in C++ c) val = fun(2.5, 3.3);
programs. d) cin>>fun(a, b); e. z=fun(3);
4. When will you use void data type for 14. Consider the following program and
function definition? predict the output, if the radius is 5. Also write
5. Distinguish between actual parameters and the reason for the output.
formal parameters. #include<iostream>
6. Construct the function prototypes for the using namespace std;
following functions float area(float &);
a. Total() takes two double arguments and int main()
returns a double {
b. Math() takes no arguments and has no float r, ans;
return value cout<<"Enter radius :";
7. Discuss the scope of global and local cin>>r;
variables with examples. ans = area(r);
8. Distinguish between Call-by-value method cout<<area;
and Call-by-reference method used for cout<<r;
function calls. return 0;
9. In C++, function can be invoked without }
specifying all its arguments. How? float area(float &p)
10. How a local function differs from a global {
function? float q;
11. Identify the built-in functions needed for q = 3.14 * p * p;
the following cases p++;
a. To convert the letter 'c' to 'C' return q;
b. To check whether a given character is }
alphabet or not. 15. Modify the program given in question 14
c. To combine strings "compu" and "ter" to by applying call by value method to call the
make "computer" function and write the possible difference in
d. To find the square root of 25 the output.
e. To return the number 10 from -10

You might also like