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

Ch11 User - Defined Functions2016

The document discusses user-defined functions in C++. It provides examples of function prototypes, definitions, declarations, parameters, return types, scope, and default arguments. It also poses questions about functions and asks the reader to write functions matching certain descriptions. Some key points covered are: - The main purpose of a function is to accept arguments and return a value. - Function prototypes declare a function's name, return type, and parameters while definitions provide the implementation. - Actual parameters pass values during a function call while formal parameters receive those values inside the function. - Functions can return a single value or void if no value is returned.

Uploaded by

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

Ch11 User - Defined Functions2016

The document discusses user-defined functions in C++. It provides examples of function prototypes, definitions, declarations, parameters, return types, scope, and default arguments. It also poses questions about functions and asks the reader to write functions matching certain descriptions. Some key points covered are: - The main purpose of a function is to accept arguments and return a value. - Function prototypes declare a function's name, return type, and parameters while definitions provide the implementation. - Actual parameters pass values during a function call while formal parameters receive those values inside the function. - Functions can return a single value or void if no value is returned.

Uploaded by

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

Assignments of chapter 11: User Defined Functions

Type: A Very Short Type Answers


1 A function’s single most important role is to: (a) give a name to a block of code (b) reduce program size (c) Accept
arguments and provide a value (d) help organize a program well.
Ans: All of the options are correct but the most important one is option (c )
2 Define a function. What is the name od one statement description of a function?
Ans: Function: is a named unit of a group of program statements. The one statement description of a function is
called “ function prototype or function declaration”
3 A function prototype is alternatively called. What is the statement specially called that invokes a function?
Ans: Function prototype is also called as function declaration. The statement which calls a function is called as function
call statement.
4 What is a function declaration? How is a function declaration different from a function definition?
Ans: A function declaration is a statement which declares a function’s name, return type , number and type of its
arguments. The following are the difference between function definition and function declaration.
1. Function declaration is a statement while function definition is followed by function body.
2. The name of arguments is not necessary for declaration while it is must in function definition.
3. Function declaration gives the idea of the function (blue print) while function definition defines the exact
functioning of the function.
4. Function declaration can be skipped in the case if the function definition comes before the function call
e.g. int sum(int x, int y)// function definition
int sum(int ,int);// function declaration {
void main() return x+y;
{ }
int a,b,c; cin>>a>>b;
c=sum(a,b);// function call
cout<<”The sum of A and B is =”<<c;
}

5 What are actual and forma parameters of a function?


Ans:
Actual parameters Formal parameters(Arguments)
1. These are the variables used to pass values 1. The variables that receives the incoming values in a
to a function. function.
2. Actual arg. are used in function call 2. Formal arg. are used in function header .
statement. 3. The are also called parameters.
3. The are called arguments.
6. Where is a function’s return type specified? What is the return type of a function that does not return a value?
How many values can be returned from a function?
Ans:
1. The return type of a function is specified at the beginning of function prototype or function header.
e.g int sum(int , int );
2. void is the return type of the function which does not return any value.
3. Only one value can be returned from a function.
7. What are global and local prototypes?
Global prototypes Local prototypes
1. Global prototypes are declared out side all the 1.
Local prototypes are declared locally, i.e. inside a
blocks. block.
2. The function declared globally are accessible 2. Local function are accessible with in the scope.
any where in the program. Example: Outside they are not accessible. Example:
#include<iostream.h> #include<iostream.h>
int sum(int arr[50]; // global prototype void main()
void main() {
{ int sum(int arr[50];// local prototype
}
}

1
8. When can a function prototype be omitted?
Ans: A function prototype can be omitted if the function definition comes before the function call statement. Or function is
defined before the use of the function.
9. Construct function prototypes for descriptions given below:
(i) Rarb() takes no arguments and has no return type: void Rarb(void);
(ii) mains() takes a float argument and return an int int mains( float);
(iii) san() takes two double arguments and return a double double san(double, double);
(iv) sum() takes an integer array and an an int value and long sum(int [], int);
returns a long result.
(v) check() takes a string argument and returns an int. int check(char []); or int check(char *);
10. What is the condition of using a function in an expression? When a function returns a value, the entire function call
can be assigned to a variable. True or false?
Ans: A function can be used in an expression if it returns a value.
Yes, when a function returns a value, the entire function call can be Eg. int check(char str[]); // function prototype.
int len=check(str); // function call statement assigned to a variable.

11. Identify the errors in the function prototypes given below:

Statement Error Corrected statement


float average(a,b); Data type missing float average(float, float);
float mult(int x,y); Data type of y missing float mult(int x , int y);
void calc(int a[],s=10); Data type of s missing void calc(int a[],int s=10);
void arithop(int a[],int b,int s=10,int j);
All the arguments to the rhs of void arithop(int a[],int b,int s=10,int j=10);
S must be default also.
float doer(int,int, float =3.14) No error. The name of var. is not compulsory.
12. When is a default argument value used inside a function?
Ans: The default argument is used in a function if some value(s) is/are not provided in the function call statement.
E.g. float simpint(float p=1000, float r=10, int time=3);// default arguments.
Si=simpint(5000,5); // the value for the time is considered as default value
13. What is the use of constant arguments?
The constant arguments can’t be modified by the function.
1. We can declare const argument by using a keyword const in function definition as well as function definition.
2. int sum( const int a[] , int n); //function prototype with constant argument
14. Write a function that takes a double array name and an array size as arguments and swaps the first and last value in
that array.
void swapfisrtnlast(double Arr[],int n)
{ double t=Arr[0]; // first value
Arr[0]=Arr[n-1];
Arr[n-1];t;
}
15. Write a function that takes three arguments : the name of a float array, the array size, and a float value, have the
function set each element of the array to float value?
void setvalue(float Arr[], float val, int n)
{ for(int i=0 ; i<n ; i++)
{
Arr[i]=val;
}
}
16. Write a function that takes an integer argument and doubles it. The function does not return a value.
void twotimes(int &a)
{ a=2*a; }
17. Write a function that takes two char arguments and returns zero if both the arguments are equal. The function
returns -1 if the first argument is smaller than the second and 1 if the second argument is smaller than the first.
Ans: int compare( char ch1, char ch2)
{ if(ch1==ch2) return 0;
else if(ch1<ch2) return -1;
else return 1;
}
2
18. Write a function to take an int argument and return 0 if the given number is prime otherwise return -1.
int checkprime( int n)
{ for(int i=2; i<=n/2; i++)
{
if(n%1==0 return -1)
}
return -1;
}
19. Write a function to receive an int array, its size and a character ‘+’ or ‘-‘. By default, the character should be ‘+’. For
the character ‘+’, the function returns the sum of positive numbers stored in the array and for the character ‘-‘, the
function returns the sum of negative numbers stored in the array.
Int sum(int Arr[], int n, char ch)
{ int sum1=0,sum2=0;
for(int i=0 ; i<n ; i++)
{
if(Arr[i]>=0) sum+=Arr[i]; // positive number
else sum2+=Arr[i]; // else negative number
}
if(ch===’+’) return sum1;
else if(ch==’-‘) return sum2;
}
20. Write a function that tales a character argument and prints it number of times equal to number of times that
function has been called to the point.
void printchar(char ch)
{ static int n=0;
for(int i=1; i<=n; i++)
cout<<ch;
n++;
}
21. Write a function that takes two int arguments and returns reference of the odd number out of the two. If both the
arguments are odd, then the reference of the smaller one is returned.
int & compare(int N1, int N2)
{ if(N1%2==0 && N2%2==0) // both the numbers are odd
{ if(N1>N2) return N1;
else return N2;
}
else if( N1%2==1 && N2%2==0) return N1; // first is odd
else if( N1%2==0 && N2%2==1) return N2;// second is odd
}
22. What all kinds of scope is supported in C++?
Ans: Scope: Scope of a code is the area where a piece of code is accessible.
There are four kind of scopes in C++. Local, function, file , and class.
23. Discuss the similarities and differences between global and local variable in terms of their lifetime and scope.
Ans:
Local Prototype/Local Variable Global Prototype/Global Variable

1. The scope of a local var. is the function/block The scope of a global variable
which declares it. is the entire program.
2. The life time is the function/block run. It remains in the memory till the program run.

3. Example:
#include<iostream.h>
int x; // variable x is global variable
void check()// global prototype
void main()
{ int x , y; // variable x ,y are local to main()
Void check() // local prototype
cout<<x<<y<< ::x ; // to access global variable x, we use ::
}
void check()
3
{ int z ; // variable z is local to check()
cout<<x<<z;// variable x is global so directly accessible here
}
24. Write a function having prototype : int replace(char* string, char ch1, char ch2); have the function replace every
occurrence of ch1 in the string with ch2, and have the function return number of replacements it makes.
int replace( char string, char ch1, char ch2)
{ int count=0;
for( int i=0; string[i]!=’\0’ ; i++)
{
if( string[i]==ch1)
{
string[i]=ch2;
count++;
}
}
return count;
}
25. Complete the following function power() by filling up the correct symbols/expressions/variable at place indicated
by -------. The function power() is declared as follows.
long power(int x, int n); The power( ) works as given below:
power( 0,n)=0 for each n
power(x,n)=xn if x!=0 and n>0
power (x,0)=1 for each x
The function definition is as follows:
long power( int x, int n)
long res=1;
if(x == 0 )
res=0;
else if( n > 0)
res=1;
else if (n ! = 0)
for(int i=0; i<n ; i++)
res*=x;
else
{ for( int j=0; j>=-n; i--)
res*=x;
res=1/res;
}
return res;
}
26. Write a C++ function to sum n natural numbers starting from a given number.
Ans: void sumnatural( int start, int n)
{ for(int i=1 , sum=0 ; i<=n ; i++)
{
sum+=start;
start++;
}
return sum;
}
27. Write a C++ function to find least common divisor of two integers.
Void LCM(int n1, int n2)
{ int small;
if(n1>n2) small=n2
else small=n1;
for(int i=small; i<=n1*n2; i++)
{ if(n1%i==0 && n2%i==0)
{ break; }
return i;
}

4
28. Write a C++ function that compares two strings and returns 0 if the two strings are equal and -1 if the strings are
unequal.
void compstrings( char str1, char str2)
{ if(strcmp( str1,str2)==0 )
return 0;
else return -1;
}
Type C: Long Answer questions:

1. Write a complete C++ program that reads a float array having 15 elements. The program uses a function reverse()
to reverse this array. Make suitable assumptions wherever required.
#include<iostream.h> void reverse(int arr[],int n)
#include<conio.h> {
void reverse(int arr[],int n); int i,j,temp;
void main() for(i=0,j=n-1;i<n/2;i++,j--)
{ {
int i,arr[40],n; temp=arr[i];
clrscr(); arr[i]=arr[j];
cout<<"How many numbers you want array with arr[j]=temp;
?:"; }
cin>>n;
for(i=0;i<n;i++)
{
cout<<"Enter Arr["<<" ]:"; cin>>arr[i];
}
cout<<"\nThe array before reverse is :\n";
for(i=0;i<n;i++)
cout<<arr[i]<<", ";
reverse(arr,n);
cout<<"\nThe array after reverse is :\n";
for(i=0;i<n;i++)
cout<<arr[i]<<", ";
getch();
}
2. Write a complete C++ program that invokes a function satis() to find whether four integers a, b, c, d sent to satis( )
satisfy the equation a3+b3+c3=d3 or not. The function satis() returns 0 if the above equation is satisfied with the
given four numbers otherwise it returns -1.
#include<iostream.h> int satis(int a,int b, int c, int d)
#include<conio.h> {
int satis(int a,int b, int c, int d); if( (pow(a,2)+pow(b,2)+pow(c,2)) ==
void mian() pow(d,2))
{ int A,B,C,D, ans; return 0;
clrscr(); else return -1
cout<<”Enter the 4 numbers :”; }
cin>>A>>B>>C>>D;
ans=satis(A,B,C,D);
if(ans== 0) cout<<”The equation is
satisfied”;
else cout<<”The equation is not
satisfied”;
getch();
}
3. Write a complete C++ program that uses a function called carea() to calculate area of a circle. The function carea()
receives the radius of type float type and returns area of double type. The function main() gets a radius value from
user, calls carea(), and displays the result. The function carea() is local to main().

5
#include<iostream.h> double carea(float r)
#include<conio.h> {
const float pi=3.14159; return (pi*r*r);
void main() }
{
double carea(float r);/// local to main()
float rad; double area;
clrscr();
cout<<"Enter the radius :"; cin>>rad;
area=carea(rad);
cout<<"The area of the circle is :"<<area;
getch();
}

4. Write a C++ program that uses a function smallo() that is passed two int argument by value to receive reference of
the smaller value. Then using this reference the smaller value is set to 0. Write a main() function also to exercise
this function.
#include<iostream.h> int & smallo(int &a, int &b )
#incldue<conoi.h> { if( a>b) return b;
int & smallo(int &,int &); else return a;
void main()
}
{
int x,y;
cout<<”enter the value of x and y:”;
cin>>x>>y;
smallo(x,y)=0;
cout<<the value of x=”<<x<<” and value
of y=”<<y;
}
5. Write a C++ program that uses following functions:
(i) sqlarge() that is passed two int arguments by reference and then sets the larger of the two numbers
to its square
(ii) sum() that is passed an int argument by value and that returns the sum of the individual digits of
the passed number.
(iii) main() that exercises above two functions by getting two integers from the user and by printing the sum of
the individual digits of the square of the larger number.

#include<iostream.h> void sqlarge(int &a, int &b)


#incldue<conoi.h> {
void sqlarge(int &,int &); if(a>b)
Int sumdigit(int ); a=2*a;
void main() else
{ b=2*a;
int x,y; }
cout<<”enter two numbers ”; cin>>x>>y;
sqlarge(x,y); int sumdigits(int n)
cout<<the value of first number {
x=”<<x<<” and value of second number int sum=0;
y=”<<y; while(n!=0)
int num, sum; {
cout<<”Enter a number(max 4 digits :”; sum+=n%10;
cin>>num; n=n/10;
sum=sumdigits(); }
cout<<”The sum of digits id=”<<sum; return sum;
} }
6. Write a C++ program to us the following function:
1. display() to display a matrix of size 2x2.
2. times2() to double each number of the matrix of size 2x2.
3. main() to read a matrix of size m x n and then to display original matrix and then to display the new matrix
formed by doubling its elements.
6
#include<iostream.h> void display(int a[][], int m, int n)
#include<conio.h> {
void display(int [][10]); for(int i=0;i<m;i++)
void times2(int [][10]); {
long power(int m,int n=2); for (int j=0;j<n;j++)
void main() {
{int a[10][10],m,n; cout<<a[i][j]<<” “;
cout<<”enter the no of rows and columns:”; }
cin>>m>n; cout<<endl;
cout<<”enter the elements :”; }
for(int i=0;i<m;i++) }
{ for(int j=0;j<n;j++) void times2(int a[][], int m, int n)
{ {
cin>>a[i][j]; for(int i=0;i<m;i++)
} {
cout<<”\nthe matrix is :\n”; for (int j=0;j<n;j++)
display(a,m,n); {
times2(a,m,n); a[i][j]*=2;
cout<<”\nthe matrix after double the elements }
is:\n”; cout<<endl;
display(a,m,n); }
getch(); }
}

7. Write a program that uses a function power( ) to raise a number m to power n. The function takes integer values for
m and n and returns the result correctly. Use a default value of 2 for n and make the function calculate squares
when this argument is omitted. Write a main( ) to get the value of m and n from the user and display the result.
#include<iostream.h> long power(int m,int n)
#include<conio.h> {
long power(int m,int n=2); long p=1;
void main() for(int i=1;i<=n;i++)
{ {
int m,n;char ch; p*=m;
long ans; }
clrscr(); return p;
cout<<"Enter the number :";cin>>m; }
cout<<"Do you want to enter the power (y/n) :";
cin>>ch;
if(ch=='y'||ch=='Y')
{
cout<<"Enter the power :";cin>>n;
}

if(ch=='y'||ch=='Y')
ans=power(m,n);
else
ans=power(m);
cout<<"The result is :"<<ans;
getch();
}
Theoretical questions for the chapter of Function
Note: The following questions are important for Class XI and XII(Board Exam)
Q.1 What is a function declaration? How a function declaration is different from function definition?

Ans: Function Declaration Function Definition

5. Function declaration is a statement. 1. Function definition is followed by function body.


6. The name of arguments is not necessary for 2. Name of variables is a must in function definition.
declaration.
7. Function declaration gives the idea of the function 3. Function definition defines the exact functioning of the
(blue print). function.
8. Function declaration can be skipped in the case if the 4. Without function definition the function can’t work
function definition comes before the function call

7
e.g. int sum(int x, int y)// function definition
int sum(int ,int);// function declaration
void main() {
{
int a,b,c; cin>>a>>b; return x+y;
c=sum(a,b);// function call
cout<<”The sum of A and B is =”<<c; }
}

Q.2 How is a global prototype/global variable different from a local prototype/local variable?
Ans: The Differences are:
Local Prototype/Local Variable Global Prototype/Global Variable

1. The scope of a local var. is the function/block The scope of a global variable is
which declares it. the entire program.
2. The life time is the function/block run. It remains in the memory till the program run.

3. Example:
#include<iostream.h>
int x; // variable x is global variable
void check()// global prototype
void main()
{ int x , y; // variable x ,y are local to main()
Void check() // local prototype
cout<<x<<y<< ::x ; // to access global variable x, we use ::
}
void check()
{ int z ; // variable z is local to check()
cout<<x<<z;// variable x is global so directly accessible here
}
Q.3 What do you mean by default arguments? When is a default argument value used inside a function?

Default arguments

1. Default arguments is the value(s) which compiler inserts automatically in case a matching argument(s) .
2. Default arguments is not passed in the function call statement.
3. The default values are specified in the function declaration.
4. All the arguments to the right side of the default argument must be default.
5. E.g. float interest(float p=1000, float t=5; float r=10); //function prototype with all the arguments
with default values.
Q.4 What do you mean by constant arguments.
3. The constant arguments can’t be modified by the function.
4. We can declare const argument by using a keyword const in function definition as well as function definition.
5. int sum( const int a[] , int n);
//function prototype with constant argument

Q.5 Differentiate between actual and formal parameters.


1. Formal arguments are arguments which are used in Function definition(function header).
2. Actual arguments are arguments which are used in function call statement.

8
3. The name of variables in Actual and formal Arguments may or may not be the same.
Example:
void interchange(int &,int& );
void main( )
{
int a=5,b=10 ;
cout<< ″ a= ″ <<a << ″ b= ″ <<b ;
change(a,b) ; // actual arguments are used in function call
cout<< ″ a= ″ <<a << ″ b= ″ <<b ;
}
void interchange(int x ,int y) // formal arguments are used in fun. Definition
{ int t=x;
x=y;
y=t;;
}
Q.6 How is call by value method of function invoking is different from call by reference method? Give appropriate example. Or
Differentiate between call by value & call by reference with a suitable example.
Ans. The Difference between Call by value and Call by reference are:
S.# Call by value Call by reference

1. The formal arguments are copy of actual arguments. The formal arguments are reference of actual
arguments.
2. It is a safe method of function call as changes in This is not safe as the changes are reflected on original
arguments are not reflected back. values.
3. void change(int ); void change(int &);
void main( ) void main( )
{ {
int a=5 ; int a=5 ;
cout<< ″ a= ″ <<a ; cout<< ″ a= ″ <<a ;
change(a) ; change(a) ;
cout<< ″\n a= ″<<a ; cout<< ″\n a= ″<<a ;
} }
void change(int b) void change(int &b)
{ b=10 ; } { b=10 ; }
Output will be : Output will be :
a=5; a=5;
a=5; a=10;
Q.7 What is the role of keyword void in declaring functions?
Ans: The key word void has the following uses
1. It specifies the return type of the function. E.g. void sum( );
2. It is also used to specify empty argument list. If the function does not accept any argument list
e.g.void sum(void);

Q.8 Compare default arguments and constant arguments.

Default arguments Constant arguments

1. Default arguments is the value(s) which compiler Constant arguments are arguments which can be modified
inserts automatically in case a matching argument(s) is by the function.
not passed in the function call statement..
2. The default values are specified in the function We can define constant arguments by adding a keyword
declaration. const in the function parameter list in the declaration as well
as function definition.
3. All the arguments to the right side of the default We can define constant arguments in any order i.e. no
argument must be default. restriction over the order of parameter list.

4. float interest(float p=1000, float t=5; float int sum( const int a[] , int n);
r=10); //function prototype with all the arguments
with default values. //function prototype with constant argument

You might also like