33
Page 1 of 33 Prepared By Sumit Kumar Gupta, PGT Computer Science Functions Using functions we can structure our programs in a more modular way, accessing all the potential that structured programming can offer to us in C++. A function is a group of statements that is executed when it is called from some point of the program. The following is its format: type name ( parameter1, parameter2, ...) { statements } where: type is the data type specifier of the data returned by the function. name is the identifier by which it will be possible to call the function. parameters (as many as needed): Each parameter consists of a data type specifier followed by an identifier, like any regular variable declaration (for example: int x) and which acts within the function as a regular local variable. They allow to pass arguments to the function when it is called. The different parameters are separated by commas. statements is the function's body. It is a block of statements surrounded by braces { }. // function example The result is 8 #include <iostream> using namespace std; int addition (int a, int b) { int r; r=a+b; return (r); } int main () { int z; z = addition (5,3); cout << "The result is " << z; return 0; } Write a function to determine whether the year is a leap year or not. #include<stdio.h> main() { int leap_year(year); int year, lp;

Functions

Embed Size (px)

Citation preview

Page 1: Functions

Page 1 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

Functions

Using functions we can structure our programs in a more modular way, accessing all the potential that structured programming can offer to us in C++. A function is a group of statements that is executed when it is called from some point of the program. The following is its format:

type name ( parameter1, parameter2, ...) { statements } where:

type is the data type specifier of the data returned by the function. name is the identifier by which it will be possible to call the function. parameters (as many as needed): Each parameter consists of a data type

specifier followed by an identifier, like any regular variable declaration (for example: int x) and which acts within the function as a regular local variable. They allow to pass arguments to the function when it is called. The different parameters are separated by commas.

statements is the function's body. It is a block of statements surrounded by braces { }.

// function example The result is 8 #include <iostream> using namespace std; int addition (int a, int b) { int r; r=a+b; return (r); } int main () { int z; z = addition (5,3); cout << "The result is " << z; return 0; } Write a function to determine whether the year is a leap year or not. #include<stdio.h> main() { int leap_year(year); int year, lp;

Page 2: Functions

Page 2 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

printf("Enter the year:"); scanf ("%d", &year); lp=leap_year(year); if (lp) { printf("\nThe entered year is a leap year."); } else { printf("\nThe entered year is not a leap year."); } } leap_year(int y) { int lp; if (y%4==0) { lp=1; } else lp=0; return(lp); } Write a general-purpose function to convert any given year into its roman equivalent. The following table shows the roman equivalents of decimal numbers: Decimal:........Roman 1.....................i 5....................v 10..................x 50..................l 100................c 500...............d 1000.............m Example: Roman equivalent of 1988 is mdcccclxxxviii Roman equivalent of 1525 is mdxxv This program is a big lengthy owing to the use of Case Statements. This program can also be rewritten using Arrays, which will reduce the length considerably.

Page 3: Functions

Page 3 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

#include<stdio.h> main() { int year; int convert (int year); { printf("Note:Enter a four year digit year.\n\n"); printf("Enter the year that you wanna convert to Roman: " ); scanf ("%d", &year); if (year> 1999) { printf("Invalid Year.Please enter again.\n\n"); } } convert(year); } convert(int year) { int i; printf("\nYear converted to Roman:"); i=(year/1000); //thousands place if(i==1) { printf("m"); } i=((year/100)%10); //hundreds place switch (i) { case 1: printf("c"); break; case 2: printf("cc"); break; case 3:

Page 4: Functions

Page 4 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

printf("ccc"); break; case 4: printf("cd"); break; case 5: printf("d"); break; case 6: printf("dc"); break; case 7: printf("dcc"); break; case 8: printf("dccc"); break; case 9: printf("dcccc"); //this part you may think is wrong..9 -> cm break; //but i have taken a hint from the example in the question. } i=((year/10)%10); //tens place switch(i) { case 1: printf("x"); break; case 2: printf("xx"); break; case 3: printf("xxx"); break;

Page 5: Functions

Page 5 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

case 4: printf("xl"); break; case 5: printf("l"); break; case 6: printf("lx"); break; case 7: printf("lxx"); break; case 8: printf("lxxx"); break; case 9: printf("lxxxx"); //had it not been for this example, it would have been xc break; } i=year%10; //ones place switch(i) { case 1: printf("i"); break; case 2: printf("ii"); break; case 3: printf("iii"); break; case 4: printf("iv"); break;

Page 6: Functions

Page 6 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

case 5: printf("v"); break; case 6: printf("vi"); break; case 7: printf("vii"); break; case 8: printf("viii"); break; case 9: printf("ix"); break; } printf ("\n\n"); return 0; } #include <stdio.h> int main(void) { int i = 1, j = 2; void exchange(int, int); printf("main : i = %d j = %d\n", i, j); exchange(i,j); printf("main : i = %d j = %d\n", i, j); return 0; } void exchange(int i, int j) { int t; t = i, i = j, j = t; printf("exchange: i = %d j = %d\n", i, j); }

Page 7: Functions

Page 7 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

#include <stdio.h> int main(void) { int i = 1, j = 2; void exchange(int *, int *); printf("main : i = %d j = %d\n", i, j); exchange(&i,&j); printf("main : i = %d j = %d\n", i, j); return 0; } void exchange(int *ip, int *jp) { int t; t = *ip, *ip = *jp, *jp = t; printf("exchange: i = %d j = %d\n", *ip, *jp); } The following output is produced main : i = 1 j = 2 exchange: i = 2 j = 1 main : i = 2 j = 1

Write a function power(a,b), to calculate the value of a raised to b. #include<stdio.h> main() { int power (a,b); int a, b, result; printf("Enter the value of a and b:"); scanf ("%d %d", &a, &b); result=power(a,b); printf("%d raised to %d is %d", a, b, result); } power (int a, int b) { int calculation=1, calc; for (calc=1; calc <=b; calc++) { calculation=calculation*a; continue; }

Page 8: Functions

Page 8 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

return(calculation); }

A positive integer is entered through the keyboard. Write a function to obtain the prime factors of this number. For example, prime factors of 24 are 2, 2, 2 and 3, whereas prime factors of 35 are 5 and 7. #include<stdio.h> main() { int number; int prime(int number); int primefactor(int number); printf("Enter the number whose prime factors are to be calculated:"); scanf ("%d", &number); primefactor(number); } //The following function detects a Prime number. prime(int num) { int i, ifprime; for (i=2; i<=num-1; i++)

{ if (num%i==0) { ifprime=0; } else ifprime=1; } return (ifprime); }

Page 9: Functions

Page 9 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

//The following function prints the prime factors of a number. primefactor(int num) { int factor,ifprime; for (factor=2; factor<=num;) { prime(factor); //so that the factors are only prime and nothing else. if (ifprime) { if (num%factor==0) //diving by all the prime numbers less than the number itself. { printf("%d ", factor); num=num/factor; continue; } else { factor++;//this cannot be made a part of the for loop } } } return 0; }

Write a function that calculates both Area and Perimeter/ Circumference of the Circle, whose Radius is entered through the keyboard. #include<stdio.h> main() { int radius; float area, perimeter; printf("\nEnter radius of a circle:"); scanf ("%d", &radius); areaperi (radius, &area, &perimeter); printf("Area=%f", area); printf("\nPerimeter=%f", perimeter); } areaperi(int r, float *a, float *p) {

Page 10: Functions

Page 10 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

*a=3.14*r*r; *p=2*3.14*r; }

Write a function which receives a float and an int from main(), finds the product of these two and returns the product which is printed through main(). #include<stdio.h> main() { int i; float j, prod; float product (int x, float y);

printf("Enter the i(int) and j(float):"); scanf ("%d %f", &i, &j); prod = product(i,j); printf("Product:%f", prod); } product (int x, float y) { float product; product = x*y; return (product); }

Write a function that receives 5 integers and returns the sum, average and standard deviation of these numbers. Call this function from main() and print the results in main(). #include<stdio.h> #include<math.h> int calc (float a, float b, float c, float d, float e, float *sum, float *avg,float *sd); int main() { float a, b, c, d, e, sum=0.0, avg=0.0; float sd=0.0; printf("Enter Five Numbers:");

Page 11: Functions

Page 11 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

scanf("%f %f %f %f %f",&a,&b,&c,&d,&e); calc (a, b, c, d, e, &sum, &amp;avg, &sd); printf("\nSum=%f", sum); printf("\nAverage=%f", avg); printf("\nStandard Deviation=%f\n", sd); getchar(); return 0; } calc (float a, float b, float c, float d, float e, float *sum, float *avg, float *sd) { float Calc=0.0; *sum = a+b+c+d+e; *avg = *sum / 5.0; Calc += ( a - *avg) * ( a - *avg); Calc += ( b - *avg) * ( b - *avg); Calc += ( c - *avg) * ( c - *avg); Calc += ( d - *avg) * ( d - *avg); Calc += ( e - *avg) * ( e - *avg); *sd = sqrt((double)Calc/5.0); }

Write a recursive function to obtain the first 25 numbers of a Fibonacci sequence. In a Fibonacci sequence the sum of two successive terms gives the third term. Following are the first few terms of the Fibonacci sequence: 1 1 2 3 5 8 13 21 34 55 89 ... #include<stdio.h> main() { static int prev_number=0, number=1; // static: so value is not lost int fibonacci (int prev_number, int number); printf ("Following are the first 25 Numbers of the Fibonacci Series:\n");

Page 12: Functions

Page 12 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

printf ("1 "); //to avoid complexity fibonacci (prev_number,number); }

fibonacci (int prev_number, int number) { static int i=1; //i is not 0, cuz 1 is already counted in main. int fibo; if (i==25) { printf ("\ndone"); //stop after 25 numbers } else { fibo=prev_number+number; prev_number=number; //important steps number=fibo; printf ("\n%d", fibo); i++; // increment counter fibonacci (prev_number,number); //recursion } }

Write a program to calculate the factorial of a number. Use the concept of recursion instead of using loops. #include<stdio.h> main() { int a, fact; printf("\nEnter any number: "); scanf ("%d", &a); fact=rec (a);

Page 13: Functions

Page 13 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

printf("\nFactorial Value = %d", fact); } rec (int x) { int f; if (x==1) return (1); else f=x*rec(x-1); return (f); }

//1 main() { printf("\nOnly stupids use c?"); display(); } display() { printf("\nFools too use C!"); main(); }

Answer-//1) infinite loop of both the statements

//2 main() { printf("\nC to it that C survives."); main(); }

Answer- //2)The message " C to it that C survives" is iterated infinitesimally!

//3 main() { int i=45, c;

Page 14: Functions

Page 14 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

c=check(i); printf("\n%d", c); } check (int ch) { if (ch>=45) return (100); else return (10*10); }

Answer-//3) 100

main() { int i=45, c; c=check(i*1000); printf("\n%d", c); } check (int ch) { if (ch>=40000) return (ch/10); else return (10); }

Answer--//4) 4500 We can see how the main function begins by declaring the variable z of type int. Right after that, we see a call to a function called addition. Paying attention we will be able to see the similarity between the structure of the call to the function and the declaration of the function itself some code lines above:

The parameters and arguments have a clear correspondence. Within the main function we called to addition passing two values: 5 and 3, that correspond to the int a and int b parameters declared for function addition. The following line of code:

return (r);

Page 15: Functions

Page 15 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

finalizes function addition, and returns the control back to the function that called it in the first place (in this case, main). At this moment the program follows it regular course from the same point at which it was interrupted by the call to addition. But additionally, because the return statement in function addition specified a value: the content of variable r (return (r);), which at that moment had a value of 8. This value becomes the value of evaluating the function call.

So being the value returned by a function the value given to the function call itself when it is evaluated, the variable z will be set to the value returned by addition (5, 3), that is 8. To explain it another way, you can imagine that the call to a function (addition (5,3)) is literally replaced by the value it returns (8). The following line of code in main is:

cout << "The result is " << z;

That, as you may already expect, produces the printing of the result on the screen.

Scope of variables The scope of variables declared within a function or any other inner block is only their own function or their own block and cannot be used outside of them. For example, in the previous example it would have been impossible to use the variables a, b or r directly in function main since they were variables local to function addition. Also, it would have been impossible to use the variable z directly within function addition, since this was a variable local to the function main.

Therefore, the scope of local variables is limited to the same block level in which they are declared. Nevertheless, we also have the possibility to declare

Page 16: Functions

Page 16 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

global variables; These are visible from any point of the code, inside and outside all functions. In order to declare global variables you simply have to declare the variable outside any function or block; that means, directly in the body of the program.

And here is another example about functions:

// function example #include <iostream> using namespace std; int subtraction (int a, int b) { int r; r=a-b; return (r); } int main () { int x=5, y=3, z; z = subtraction (7,2); cout << "The first result is " << z << '\n'; cout << "The second result is " << subtraction (7,2) << '\n'; cout << "The third result is " << subtraction (x,y) << '\n'; z= 4 + subtraction (x,y); cout << "The fourth result is " << z << '\n'; return 0; }

The first result is 5 The second result is 5 The third result is 2 The fourth result is 6

For example, the first case (that you should already know because it is the same pattern that we have used in previous examples):

z = subtraction (7,2); cout << "The first result is " << z;

If we replace the function call by the value it returns (i.e., 5), we would have:

z = 5; cout << "The first result is " << z;

As well as

cout << "The second result is " << subtraction (7,2);

Page 17: Functions

Page 17 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

has the same result as the previous call, but in this case we made the call to subtraction directly as an insertion parameter for cout. Simply consider that the result is the same as if we had written:

cout << "The second result is " << 5;

since 5 is the value returned by subtraction (7,2). In the case of:

cout << "The third result is " << subtraction (x,y);

The only new thing that we introduced is that the parameters of subtraction are variables instead of constants. That is perfectly valid. In this case the values passed to function subtraction are the values of x and y, that are 5 and 3 respectively, giving 2 as result. The fourth case is more of the same. Simply note that instead of:

z = 4 + subtraction (x,y);

we could have written:

z = subtraction (x,y) + 4;

with exactly the same result. I have switched places so you can see that the semicolon sign (;) goes at the end of the whole statement. It does not necessarily have to go right after the function call. The explanation might be once again that you imagine that a function can be replaced by its returned value:

z = 4 + 2; z = 2 + 4;

Functions with no type. The use of void. If you remember the syntax of a function declaration: type name ( argument1, argument2 ...) statement you will see that the declaration begins with a type, that is the type of the function itself (i.e., the type of the datum that will be returned by the function with the return statement). But what if we want to return no value? Imagine that we want to make a function just to show a message on the screen. We do not need it to return any value. In this case we should use the void type specifier for the function. This is a special specifier that indicates absence of type.

// void function example #include <iostream> using namespace std;

I'm a function!

Page 18: Functions

Page 18 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

void printmessage () { cout << "I'm a function!"; } int main () { printmessage (); return 0; }

void can also be used in the function's parameter list to explicitly specify that we want the function to take no actual parameters when it is called. For example, function printmessage could have been declared as:

void printmessage (void) { cout << "I'm a function!"; }

Although it is optional to specify void in the parameter list. In C++, a parameter list can simply be left blank if we want a function with no parameters. What you must always remember is that the format for calling a function includes specifying its name and enclosing its parameters between parentheses. The non-existence of parameters does not exempt us from the obligation to write the parentheses. For that reason the call to printmessage is:

printmessage ();

The parentheses clearly indicate that this is a call to a function and not the name of a variable or some other C++ statement. The following call would have been incorrect:

printmessage;

Arguments passed by value and by reference. Until now, in all the functions we have seen, the arguments passed to the functions have been passed by value. This means that when calling a function with parameters, what we have passed to the function were copies of their values but never the variables themselves. For example, suppose that we called our first function addition using the following code:

int x=5, y=3, z; z = addition ( x , y );

What we did in this case was to call to function addition passing the values of x and y, i.e. 5 and 3 respectively, but not the variables x and y themselves.

Page 19: Functions

Page 19 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

This way, when the function addition is called, the value of its local variables a and b become 5 and 3 respectively, but any modification to either a or b within the function addition will not have any effect in the values of x and y outside it, because variables x and y were not themselves passed to the function, but only copies of their values at the moment the function was called. But there might be some cases where you need to manipulate from inside a function the value of an external variable. For that purpose we can use arguments passed by reference, as in the function duplicate of the following example:

// passing parameters by reference #include <iostream> using namespace std; void duplicate (int& a, int& b, int& c) { a*=2; b*=2; c*=2; } int main () { int x=1, y=3, z=7; duplicate (x, y, z); cout << "x=" << x << ", y=" << y << ", z=" << z; return 0; }

x=2, y=6, z=14

The first thing that should call your attention is that in the declaration of duplicate the type of each parameter was followed by an ampersand sign (&). This ampersand is what specifies that their corresponding arguments are to be passed by reference instead of by value. When a variable is passed by reference we are not passing a copy of its value, but we are somehow passing the variable itself to the function and any modification that we do to the local variables will have an effect in their counterpart variables passed as arguments in the call to the function.

To explain it in another way, we associate a, b and c with the arguments passed on the function call (x, y and z) and any change that we do on a within the function will affect the value of x outside it. Any change that we do on b will affect y, and the

Page 20: Functions

Page 20 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

same with c and z. That is why our program's output, that shows the values stored in x, y and z after the call to duplicate, shows the values of all the three variables of main doubled. If when declaring the following function:

void duplicate (int& a, int& b, int& c)

we had declared it this way:

void duplicate (int a, int b, int c)

i.e., without the ampersand signs (&), we would have not passed the variables by reference, but a copy of their values instead, and therefore, the output on screen of our program would have been the values of x, y and z without having been modified. Passing by reference is also an effective way to allow a function to return more than one value. For example, here is a function that returns the previous and next numbers of the first parameter passed.

// more than one returning value #include <iostream> using namespace std; void prevnext (int x, int& prev, int& next) { prev = x-1; next = x+1; } int main () { int x=100, y, z; prevnext (x, y, z); cout << "Previous=" << y << ", Next=" << z; return 0; }

Previous=99, Next=101

Default values in parameters. When declaring a function we can specify a default value for each parameter. This value will be used if the corresponding argument is left blank when calling to the function. To do that, we simply have to use the assignment operator and a value for the arguments in the function declaration. If a value for that parameter is not passed when the function is called, the default value is used, but if a value is specified this default value is ignored and the passed value is used instead. For example:

// default values in functions 6

Page 21: Functions

Page 21 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

#include <iostream> using namespace std; int divide (int a, int b=2) { int r; r=a/b; return (r); } int main () { cout << divide (12); cout << endl; cout << divide (20,4); return 0; }

5

As we can see in the body of the program there are two calls to function divide. In the first one:

divide (12)

we have only specified one argument, but the function divide allows up to two. So the function divide has assumed that the second parameter is 2 since that is what we have specified to happen if this parameter was not passed (notice the function declaration, which finishes with int b=2, not just int b). Therefore the result of this function call is 6 (12/2). In the second call:

divide (20,4)

there are two parameters, so the default value for b (int b=2) is ignored and b takes the value passed as argument, that is 4, making the result returned equal to 5 (20/4). Overloaded functions. In C++ two different functions can have the same name if their parameter types or number are different. That means that you can give the same name to more than one function if they have either a different number of parameters or different types in their parameters. For example:

// overloaded function #include <iostream> using namespace std; int operate (int a, int b) { return (a*b); }

10 2.5

Page 22: Functions

Page 22 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

float operate (float a, float b) { return (a/b); } int main () { int x=5,y=2; float n=5.0,m=2.0; cout << operate (x,y); cout << "\n"; cout << operate (n,m); cout << "\n"; return 0; }

In this case we have defined two functions with the same name, operate, but one of them accepts two parameters of type int and the other one accepts them of type float. The compiler knows which one to call in each case by examining the types passed as arguments when the function is called. If it is called with two ints as its arguments it calls to the function that has two int parameters in its prototype and if it is called with two floats it will call to the one which has two float parameters in its prototype. In the first call to operate the two arguments passed are of type int, therefore, the function with the first prototype is called; This function returns the result of multiplying both parameters. While the second call passes two arguments of type float, so the function with the second prototype is called. This one has a different behavior: it divides one parameter by the other. So the behavior of a call to operate depends on the type of the arguments passed because the function has been overloaded. Notice that a function cannot be overloaded only by its return type. At least one of its parameters must have a different type.

Arguments passed by value and by reference. Until now, in all the functions we have seen, the arguments passed to the functions have been passed by value. This means that when calling a function with parameters, what we have passed to the function were copies of their values but never the variables themselves. For example, suppose that we called our first function addition using the following code:

int x=5, y=3, z; z = addition ( x , y );

What we did in this case was to call to function addition passing the values of x and y, i.e. 5 and 3 respectively, but not the variables x and y themselves.

Page 23: Functions

Page 23 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

This way, when the function addition is called, the value of its local variables a and b become 5 and 3 respectively, but any modification to either a or b within the function addition will not have any effect in the values of x and y outside it, because variables x and y were not themselves passed to the function, but only copies of their values at the moment the function was called. But there might be some cases where you need to manipulate from inside a function the value of an external variable. For that purpose we can use arguments passed by reference, as in the function duplicate of the following example:

// passing parameters by reference #include <iostream> using namespace std; void duplicate (int& a, int& b, int& c) { a*=2; b*=2; c*=2; } int main () { int x=1, y=3, z=7; duplicate (x, y, z); cout << "x=" << x << ", y=" << y << ", z=" << z; return 0; }

x=2, y=6, z=14

The first thing that should call your attention is that in the declaration of duplicate the type of each parameter was followed by an ampersand sign (&). This ampersand is what specifies that their corresponding arguments are to be passed by

reference instead of by value. When a variable is passed by reference we are not passing a copy of its value, but we are somehow passing the variable itself to the function and any modification that we do to the local variables will have an effect in their counterpart variables passed as arguments in the call to the function.

To explain it in another way, we associate a, b and c with the arguments passed on the function call (x, y and z) and any change that we do on a within the function will affect the value of x outside it. Any change that we do on b will affect y, and the same with c and z.

Page 24: Functions

Page 24 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

That is why our program's output, that shows the values stored in x, y and z after the call to duplicate, shows the values of all the three variables of main doubled. If when declaring the following function:

void duplicate (int& a, int& b, int& c)

we had declared it this way:

void duplicate (int a, int b, int c)

i.e., without the ampersand signs (&), we would have not passed the variables by reference, but a copy of their values instead, and therefore, the output on screen of our program would have been the values of x, y and z without having been modified. Passing by reference is also an effective way to allow a function to return more than one value. For example, here is a function that returns the previous and next numbers of the first parameter passed.

// more than one returning value #include <iostream> using namespace std; void prevnext (int x, int& prev, int& next) { prev = x-1; next = x+1; } int main () { int x=100, y, z; prevnext (x, y, z); cout << "Previous=" << y << ", Next=" << z; return 0; }

Previous=99, Next=101

Default values in parameters. When declaring a function we can specify a default value for each parameter. This value will be used if the corresponding argument is left blank when calling to the function. To do that, we simply have to use the assignment operator and a value for the arguments in the function declaration. If a value for that parameter is not passed when the function is called, the default value is used, but if a value is specified this default value is ignored and the passed value is used instead. For example:

// default values in functions #include <iostream> using namespace std; int divide (int a, int b=2)

6 5

Page 25: Functions

Page 25 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

{ int r; r=a/b; return (r); } int main () { cout << divide (12); cout << endl; cout << divide (20,4); return 0; }

As we can see in the body of the program there are two calls to function divide. In the first one:

divide (12)

we have only specified one argument, but the function divide allows up to two. So the function divide has assumed that the second parameter is 2 since that is what we have specified to happen if this parameter was not passed (notice the function declaration, which finishes with int b=2, not just int b). Therefore the result of this function call is 6 (12/2). In the second call:

divide (20,4)

there are two parameters, so the default value for b (int b=2) is ignored and b takes the value passed as argument, that is 4, making the result returned equal to 5 (20/4). Overloaded functions. In C++ two different functions can have the same name if their parameter types or number are different. That means that you can give the same name to more than one function if they have either a different number of parameters or different types in their parameters. For example:

// overloaded function #include <iostream> using namespace std; int operate (int a, int b) { return (a*b); } float operate (float a, float b) { return (a/b); }

10 2.5

Page 26: Functions

Page 26 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

int main () { int x=5,y=2; float n=5.0,m=2.0; cout << operate (x,y); cout << "\n"; cout << operate (n,m); cout << "\n"; return 0; }

Recursive Functions:- Recursive is the property that functions have to be called themselves For Example;- n!=n(n-1)*(n-2)*(n-3)……..*1 Functions Questions- Find the output of the following program class Sample { public: int *ptr; Sample(int i) { ptr = new int(i); } ~Sample() { delete ptr; } void PrintVal() { cout << "The value is " << *ptr; } }; void SomeFunc(Sample x) { cout << "Say i am in someFunc " << endl; } int main() { Sample s1= 10; SomeFunc(s1); s1.PrintVal(); } Answer: Say i am in someFunc What do you mean by inline function?

Page 27: Functions

Page 27 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

The idea behind inline functions is to insert the code of a called function at the point where the function is called. If done carefully, this can improve the applications Performance in exchange for increased compile time and possibly (but not always) an increase in the size of the generated binary executables. What do you mean by binding of data and functions? Encapsulation. What is abstraction? Abstraction is of the process of hiding unwanted details from the user. What is encapsulation? Packaging an object’s variables within its methods is called encapsulation.

What is friend function? As the name suggests, the function acts as a friend to a class. As a friend of a class, it can access its private and protected members. A friend function is not a member of the class. But it must be listed in the class definition.

What are virtual functions? A virtual function allows derived classes to replace the implementation provided by the base class. The compiler makes sure the replacement is always called whenever the object in question is actually of the derived class, even if the object is accessed by a base pointer rather than a derived pointer. This allows algorithms in the base class to be replaced in the derived class, even if users don't know about the derived class.

What does extern mean in a function declaration? Using extern in a function declaration we can make a function such that it can used outside the file in which it is defined. An extern variable, function definition, or declaration also makes the described variable or function usable by the succeeding part of the current source file. This declaration does not replace the definition. The declaration is used to describe the variable that is externally defined. If a declaration for an identifier already exists at file scope, any extern declaration of the same identifier found within a block refers to that same object. If no other declaration for the identifier exists at file scope, the identifier has external linkage.

How do I declare an array of N pointers to functions returning pointers to functions returning pointers to characters? Answer1 If you want the code to be even slightly readable, you will use typedefs. typedef char* (*functiontype_one)(void); typedef functiontype_one (*functiontype_two)(void); functiontype_two myarray[N]; //assuming N is a const integral

Answer2

Page 28: Functions

Page 28 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

char* (* (*a[N])())() Here a is that array. And according to question no function will not take any parameter value.

What does extern mean in a function declaration? It tells the compiler that a variable or a function exists, even if the compiler hasn’t yet seen it in the file currently being compiled. This variable or function may be defined in another file or further down in the current file.

How do I initialize a pointer to a function? This is the way to initialize a pointer to a function void fun(int a) { } void main() { void (*fp)(int); fp=fun; fp(1); }

Write a fucntion that will reverse a string. char *strrev(char *s) { int i = 0, len = strlen(s); char *str; if ((str = (char *)malloc(len+1)) == NULL) /*cannot allocate memory */ err_num = 2; return (str); } while(len) str[i++]=s[–len]; str[i] = NULL; return (str); }

Page 29: Functions

Page 29 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

Object Oriented Programming

Data Abstraction:-is the act of representing the essential features without including the background details and explanations. Data Hiding:-is a related concept to data abstraction. Unessential features or background details are hidden from the world. Data Encapsulation:-is the wrapping up of data and associated functions in one single until,while implementing abstraction at the same time. Objects:-represents an identifiable entity with some characteristics and behaviour. What do you mean by inheritance? Inheritance is the process of creating new classes, called derived classes, from existing classes or base classes. The derived class inherits all the capabilities of the base class, but can add embellishments and refinements of its own. Base Class:-is the class, which gets inherited from other classes. It is also called Super class. Derived class is the class which inherits from other classes. It is also called Subclass. What is polymorphism? Explain with an example? "Poly" means "many" and "morph" means "form". Polymorphism is the ability of an object (or reference) to assume (be replaced by) or become many different forms of Object. Example: function overloading, function overriding, virtual functions. Another example can be a plus ‘+’ sign, used for adding two integers or for using it to concatenate two strings. OPP is approach for writing software in which data and behaviour are packaged together as classes whose instances are objects. A class is a named software representation for an abstraction. What is function overloading and operator overloading? Function overloading: C++ enables several functions of the same name to be defined, as long as these functions have different sets of parameters (at least as far as their types are concerned). This capability is called function overloading. When an overloaded function is called, the C++ compiler selects the proper function by examining the number, types and order of the arguments in the call. Function overloading is commonly used to create several functions of the same name that perform similar tasks but on different data types. Operator overloading allows existing C++ operators to be redefined so that they work on objects of user-defined classes. Overloaded operators are syntactic sugar for Equivalent function calls. They form a pleasant facade that doesn't add anything fundamental to the language (but they can improve understandability and reduce Maintenance costs).

Very Short Answer Questions:-1-2 Marks

Fill in the blanks; (i)………….. is a named collection of attributes and behaviour related to modeling a given entity for some particular purpose?

Page 30: Functions

Page 30 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

(ii) …………..is a programming approach where data and behaviour are encapsulated to gether as………… (iii) An instance of a class is called …………… (iv) A class enforces data hiding through …………and……………members. (v) Polymorphism is implemented in c++ through ……..and…………… Answer:- 1) OPP, Classes 2) Abstraction 3) Object 4) Private, Protected 5) Virtual functions, overloading. What is abstract class? Ans:- Abstract class is a class that defines an interface, but does not necessary provide implementation for all its member functions. No objects of an abstract class exit i.e, it cannot be instantited. What is concrete class? Ans:- A Concrete class is a derived class of an abstract class that implements all the missing functionality . A concrete class can be instantiated i.e. its objects can be created. What is the importance of the function overloading? Ans:- Function overloading not only implements polymorphism but also reduces number of comparisons in a program and thereby makes the program run faster. How objects implemented in c++? Ans:- The object is implemented in software terms as follows:-

(1) Characteristics / attributes are implemented through member variables or data items of the object.

(2) Behaviour is implemented through member functions called method. (3) It is given a unique name to give it identify.

Why do you think function overloading must be a part of an object oriented language? Ans: - A Function overloading must be a part of an object oriented language as it is the feature that implements polymorphism in an object oriented language. That is the ability of an object to behave differently circumstances can effectively be implemented in programming through function overloading. Find the syntax error, if any in the following program. Include<iostream.h> Void main() Int R; w=90;

While w>60 {

R=W-50; Switch(W) {

20: cout<<”Lower range”<<endl; 30: cout<<”Middle range”<<endl; 40: cout<<”Higher range”<<endl;

} } } Find the syntax error, if any in the following program. #include<iostream.h> void main()

Page 31: Functions

Page 31 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

{ int X,Y, cin>>X; for(Y=0;Y<10;Y++) { (X==Y) cout<<Y+X; else cout>>4; } } Find the syntax error, if any in the following program. Include<iostream.h> Void main() { int P[ ]= {90,60,30,10}; Q;Number=4; Q=9; For[int i=Number-1;>=0;i--] Switch(i) { case0: case 3: cout>>P[i]*Q<<endl; break; case 1: case 2: cout<<p[i]+q; } } Give the output of the following program:- #include<iostream.h> int global=10; void sunil(int &x, int y) { x=x-y;y=x*10; cout<<x<<”,”<<y<<’\n’; } void main() { int global=7; sunil(::global,global); cout<<global<<”,”<<::global<<’\n’;

sunil(global,::global); cout<<global<<”,”<<::global<<’\n\; } Ans:- 3,30 7,3 4,40 4,3 Give the output of the following program:- void main() { char*name=”ProOcessoR” for(int x=0,x<strlen(name);x++ { if(islower(name[x]))

Page 32: Functions

Page 32 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

name(x)=toupper(name[x]); else if(isupper(name[x])) if(x%2==0)tolower name[x]=(name[x]); else name(x)=name[x-1]; } puts(name); } Ans:- pRo OEesOr What is function overloading? Use the concept of the function overloading to compute area of rectangle (given length of two sides), area of a triangle (given length of the three sides using Hero’s formula) and area of circle (given length of a radius). #include<iostream.h> #include<conio.h> #include<math.h> float area(float a, float b) { return a*b; float area(float a, float b, float c) { float s, ar; s=(a+b+c)/2; ar=sqrt(s*(s-a)*(s-b)*(s-c)); return ar; } float area(float a) { return 3.1423*a*a;} int main() { clrscr(); int choice, S1,S2,S3; float ar; do { cout<<”\n Area Main Menu\n”; cout<<”\n Rectangle\n”; cout<<”\n Triangle\n”; cout<<”\n Circle\n”; cout<<”\n Exit\n”; cout<<”\n Enter your choice(1-4):-”; cin>>choice; cout<<endl; switch(choice)

Page 33: Functions

Page 33 of 33

Prepared By Sumit Kumar Gupta, PGT Computer Science

{ case 1: cout<<”Enter Length & Breadth\n”; cin>>S1>>S2; ar=area(S1,S2); cout<<”The Area is<<ar<<endl”;

break; case 2: cout<<”Enter 3 sides\n”; cin>>S1>>S2>>S3; ar=area(S1,S2,S3); cout<<”The Area is<<ar<<endl”;

break; case 2: cout<<”Enter Radius\n”; cin>>S1; ar=area(S1); cout<<”The Area is<<ar<<endl”;

break; case 4: break; default: cout<<”Wrong choice!\n”; }; } while(choice>)&&choice<4); return 0; }