Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Functions

592 views

Published on

Published in: Education
  • Be the first to comment

Functions

  1. 1. Page 1 of 33 FunctionsUsing functions we can structure our programs in a more modular way, accessing allthe 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 somepoint 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 functions 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; Prepared By Sumit Kumar Gupta, PGT Computer Science
  2. 2. Page 2 of 33printf("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;}elselp=0;return(lp);}Write a general-purpose function to convert any given year into its romanequivalent.The following table shows the roman equivalents of decimal numbers:Decimal:........Roman1.....................i5....................v10..................x50..................l100................c500...............d1000.............mExample:Roman equivalent of 1988 is mdcccclxxxviiiRoman equivalent of 1525 is mdxxvThis program is a big lengthy owing to the use of Case Statements. This program canalso be rewritten using Arrays, which will reduce the length considerably. Prepared By Sumit Kumar Gupta, PGT Computer Science
  3. 3. Page 3 of 33#include<stdio.h>main(){int year;int convert (int year);{printf("Note:Enter a four year digit year.nn");printf("Enter the year that you wanna convert to Roman: " );scanf ("%d", &year);if (year> 1999){printf("Invalid Year.Please enter again.nn");}}convert(year);}convert(int year){int i;printf("nYear converted to Roman:");i=(year/1000); //thousands placeif(i==1){printf("m");}i=((year/100)%10); //hundreds placeswitch (i){case 1:printf("c");break;case 2:printf("cc");break;case 3: Prepared By Sumit Kumar Gupta, PGT Computer Science
  4. 4. Page 4 of 33printf("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 -> cmbreak; //but i have taken a hint from the example in the question.}i=((year/10)%10); //tens placeswitch(i){case 1:printf("x");break;case 2:printf("xx");break;case 3:printf("xxx");break; Prepared By Sumit Kumar Gupta, PGT Computer Science
  5. 5. Page 5 of 33case 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 xcbreak;}i=year%10; //ones placeswitch(i){case 1:printf("i");break;case 2:printf("ii");break;case 3:printf("iii");break;case 4:printf("iv");break; Prepared By Sumit Kumar Gupta, PGT Computer Science
  6. 6. Page 6 of 33case 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 ("nn");return 0;}#include <stdio.h>int main(void) { int i = 1, j = 2; void exchange(int, int); printf("main : i = %d j = %dn", i, j); exchange(i,j); printf("main : i = %d j = %dn", i, j); return 0; }void exchange(int i, int j) { int t; t = i, i = j, j = t; printf("exchange: i = %d j = %dn", i, j); } Prepared By Sumit Kumar Gupta, PGT Computer Science
  7. 7. Page 7 of 33#include <stdio.h>int main(void) { int i = 1, j = 2; void exchange(int *, int *); printf("main : i = %d j = %dn", i, j); exchange(&i,&j); printf("main : i = %d j = %dn", i, j); return 0; }void exchange(int *ip, int *jp) { int t; t = *ip, *ip = *jp, *jp = t; printf("exchange: i = %d j = %dn", *ip, *jp); }The following output is producedmain : i = 1 j = 2exchange: i = 2 j = 1main : i = 2 j = 1Write 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;} Prepared By Sumit Kumar Gupta, PGT Computer Science
  8. 8. Page 8 of 33return(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 of35 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;}elseifprime=1;}return (ifprime);} Prepared By Sumit Kumar Gupta, PGT Computer Science
  9. 9. Page 9 of 33//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 ofthe Circle, whose Radius isentered 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){ Prepared By Sumit Kumar Gupta, PGT Computer Science
  10. 10. Page 10 of 33*a=3.14*r*r;*p=2*3.14*r;}Write a function which receives a float and an int from main(), finds theproductof 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 andstandarddeviation of these numbers. Call this function from main() and print theresults 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:"); Prepared By Sumit Kumar Gupta, PGT Computer Science
  11. 11. Page 11 of 33scanf("%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=%fn", 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 Fibonaccisequence. In a Fibonacci sequence the sum of two successive terms givesthethird 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 lostint fibonacci (int prev_number, int number);printf ("Following are the first 25 Numbers of the Fibonacci Series:n"); Prepared By Sumit Kumar Gupta, PGT Computer Science
  12. 12. Page 12 of 33printf ("1 "); //to avoid complexityfibonacci (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 stepsnumber=fibo;printf ("n%d", fibo);i++; // increment counterfibonacci (prev_number,number); //recursion}}Write a program to calculate the factorial of a number. Use the concept ofrecursioninstead of using loops.#include<stdio.h>main(){int a, fact;printf("nEnter any number: ");scanf ("%d", &a);fact=rec (a); Prepared By Sumit Kumar Gupta, PGT Computer Science
  13. 13. Page 13 of 33printf("nFactorial Value = %d", fact);}rec (int x){int f;if (x==1)return (1);elsef=x*rec(x-1);return (f);}//1main(){printf("nOnly stupids use c?");display();}display(){printf("nFools too use C!");main();}Answer-//1) infinite loop of both the statements//2main(){printf("nC to it that C survives.");main();}Answer- //2)The message " C to it that C survives" is iterated infinitesimally!//3main(){int i=45, c; Prepared By Sumit Kumar Gupta, PGT Computer Science
  14. 14. Page 14 of 33c=check(i);printf("n%d", c);}check (int ch){if (ch>=45)return (100);elsereturn (10*10);}Answer-//3) 100main(){int i=45, c;c=check(i*1000);printf("n%d", c);}check (int ch){if (ch>=40000)return (ch/10);elsereturn (10);}Answer--//4) 4500We 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 willbe able to see the similarity between the structure of the call to the function and thedeclaration of the function itself some code lines above:The parameters and arguments have a clear correspondence. Within the mainfunction we called to addition passing two values: 5 and 3, that correspond to the inta and int b parameters declared for function addition.The following line of code: return (r); Prepared By Sumit Kumar Gupta, PGT Computer Science
  15. 15. Page 15 of 33finalizes function addition, and returns the control back to the function that called itin the first place (in this case, main). At this moment the program follows it regularcourse from the same point at which it was interrupted by the call to addition. Butadditionally, because the return statement in function addition specified a value: thecontent of variable r (return (r);), which at that moment had a value of 8. This valuebecomes the value of evaluating the function call.So being the value returned by a function the value given to the function call itselfwhen 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 Prepared By Sumit Kumar Gupta, PGT Computer Science
  16. 16. Page 16 of 33 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> The first result is 5using namespace std; The second result is 5 The third result is 2int subtraction (int a, int b) The fourth result is 6{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;}For example, the first case (that you should already know because it is the samepattern 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); Prepared By Sumit Kumar Gupta, PGT Computer Science
  17. 17. Page 17 of 33has the same result as the previous call, but in this case we made the call tosubtraction directly as an insertion parameter for cout. Simply consider that theresult 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 arevariables instead of constants. That is perfectly valid. In this case the values passedto 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 thesemicolon sign (;) goes at the end of the whole statement. It does not necessarilyhave to go right after the function call. The explanation might be once again that youimagine 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 ...) statementyou will see that the declaration begins with a type, that is the type of the functionitself (i.e., the type of the datum that will be returned by the function with the returnstatement). 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. Wedo not need it to return any value. In this case we should use the void type specifierfor the function. This is a special specifier that indicates absence of type.// void function example Im a function!#include <iostream>using namespace std; Prepared By Sumit Kumar Gupta, PGT Computer Science
  18. 18. Page 18 of 33void printmessage (){cout << "Im a function!";}int main (){printmessage ();return 0;}void can also be used in the functions parameter list to explicitly specify that wewant the function to take no actual parameters when it is called. For example,function printmessage could have been declared as: void printmessage (void) { cout << "Im a function!"; }Although it is optional to specify void in the parameter list. In C++, a parameter listcan 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 includesspecifying its name and enclosing its parameters between parentheses. The non-existence of parameters does not exempt us from the obligation to write theparentheses. 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 avariable 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 functionshave been passed by value. This means that when calling a function withparameters, what we have passed to the function were copies of their values butnever the variables themselves. For example, suppose that we called our firstfunction 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 andy, i.e. 5 and 3 respectively, but not the variables x and y themselves. Prepared By Sumit Kumar Gupta, PGT Computer Science
  19. 19. Page 19 of 33This way, when the function addition is called, the value of its local variables a and bbecome 5 and 3 respectively, but any modification to either a or b within the functionaddition will not have any effect in the values of x and y outside it, because variablesx and y were not themselves passed to the function, but only copies of their valuesat the moment the function was called.But there might be some cases where you need to manipulate from inside a functionthe value of an external variable. For that purpose we can use arguments passed byreference, as in the function duplicate of the following example:// passing parameters by reference x=2, y=6, z=14#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;}The first thing that should call your attention is that in the declaration of duplicatethe type of each parameter was followed by an ampersand sign (&). This ampersandis what specifies that their corresponding arguments are to be passed by referenceinstead of by value.When a variable is passed by reference we are not passing a copy of its value, butwe are somehow passing the variable itself to the function and any modification thatwe do to the local variables will have an effect in their counterpart variables passedas arguments in the call to the function.To explain it in another way, we associate a, b and c with the arguments passed onthe function call (x, y and z) and any change that we do on a within the function willaffect the value of x outside it. Any change that we do on b will affect y, and the Prepared By Sumit Kumar Gupta, PGT Computer Science
  20. 20. Page 20 of 33same with c and z.That is why our programs output, that shows the values stored in x, y and z afterthe 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 byreference, but a copy of their values instead, and therefore, the output on screen ofour 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 thanone value. For example, here is a function that returns the previous and nextnumbers of the first parameter passed.// more than one returning value Previous=99, Next=101#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;}Default values in parameters.When declaring a function we can specify a default value for each parameter. Thisvalue will be used if the corresponding argument is left blank when calling to thefunction. To do that, we simply have to use the assignment operator and a value forthe arguments in the function declaration. If a value for that parameter is not passedwhen the function is called, the default value is used, but if a value is specified thisdefault value is ignored and the passed value is used instead. For example:// default values in functions 6 Prepared By Sumit Kumar Gupta, PGT Computer Science
  21. 21. Page 21 of 33#include <iostream> 5using 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;}As we can see in the body of the program there are two calls to function divide. Inthe first one: divide (12)we have only specified one argument, but the function divide allows up to two. Sothe function divide has assumed that the second parameter is 2 since that is what wehave specified to happen if this parameter was not passed (notice the functiondeclaration, which finishes with int b=2, not just int b). Therefore the result of thisfunction 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 takesthe 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 ornumber are different. That means that you can give the same name to more thanone function if they have either a different number of parameters or different typesin their parameters. For example:// overloaded function 10#include <iostream> 2.5using namespace std;int operate (int a, int b){return (a*b);} Prepared By Sumit Kumar Gupta, PGT Computer Science
  22. 22. Page 22 of 33float 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 ofthem accepts two parameters of type int and the other one accepts them of typefloat. The compiler knows which one to call in each case by examining the typespassed as arguments when the function is called. If it is called with two ints as itsarguments it calls to the function that has two int parameters in its prototype and ifit is called with two floats it will call to the one which has two float parameters in itsprototype.In the first call to operate the two arguments passed are of type int, therefore, thefunction with the first prototype is called; This function returns the result ofmultiplying both parameters. While the second call passes two arguments of typefloat, so the function with the second prototype is called. This one has a differentbehavior: it divides one parameter by the other. So the behavior of a call to operatedepends on the type of the arguments passed because the function has beenoverloaded.Notice that a function cannot be overloaded only by its return type. At least one ofits 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 functionshave been passed by value. This means that when calling a function withparameters, what we have passed to the function were copies of their values butnever the variables themselves. For example, suppose that we called our firstfunction 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 andy, i.e. 5 and 3 respectively, but not the variables x and y themselves. Prepared By Sumit Kumar Gupta, PGT Computer Science
  23. 23. Page 23 of 33This way, when the function addition is called, the value of its local variables a and bbecome 5 and 3 respectively, but any modification to either a or b within the functionaddition will not have any effect in the values of x and y outside it, because variablesx and y were not themselves passed to the function, but only copies of their valuesat the moment the function was called.But there might be some cases where you need to manipulate from inside a functionthe value of an external variable. For that purpose we can use arguments passed byreference, as in the function duplicate of the following example:// passing parameters by reference x=2, y=6, z=14#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;}The first thing that should call your attention is that in the declaration of duplicatethe type of each parameter was followed by an ampersand sign (&). This ampersandis what specifies that their corresponding arguments are to be passed byreference instead of by value.When a variable is passed by reference we are not passing a copy of its value, butwe are somehow passing the variable itself to the function and any modification thatwe do to the local variables will have an effect in their counterpart variables passedas arguments in the call to the function.To explain it in another way, we associate a, b and c with the arguments passed onthe function call (x, y and z) and any change that we do on a within the function willaffect the value of x outside it. Any change that we do on b will affect y, and thesame with c and z. Prepared By Sumit Kumar Gupta, PGT Computer Science
  24. 24. Page 24 of 33That is why our programs output, that shows the values stored in x, y and z afterthe 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 byreference, but a copy of their values instead, and therefore, the output on screen ofour 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 thanone value. For example, here is a function that returns the previous and nextnumbers of the first parameter passed.// more than one returning value Previous=99, Next=101#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;}Default values in parameters.When declaring a function we can specify a default value for each parameter. Thisvalue will be used if the corresponding argument is left blank when calling to thefunction. To do that, we simply have to use the assignment operator and a value forthe arguments in the function declaration. If a value for that parameter is not passedwhen the function is called, the default value is used, but if a value is specified thisdefault value is ignored and the passed value is used instead. For example:// default values in functions 6#include <iostream> 5using namespace std;int divide (int a, int b=2) Prepared By Sumit Kumar Gupta, PGT Computer Science
  25. 25. Page 25 of 33{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. Inthe first one: divide (12)we have only specified one argument, but the function divide allows up to two. Sothe function divide has assumed that the second parameter is 2 since that is what wehave specified to happen if this parameter was not passed (notice the functiondeclaration, which finishes with int b=2, not just int b). Therefore the result of thisfunction 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 takesthe 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 ornumber are different. That means that you can give the same name to more thanone function if they have either a different number of parameters or different typesin their parameters. For example:// overloaded function 10#include <iostream> 2.5using namespace std;int operate (int a, int b){return (a*b);}float operate (float a, float b){return (a/b);} Prepared By Sumit Kumar Gupta, PGT Computer Science
  26. 26. Page 26 of 33int 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 themselvesFor Example;- n!=n(n-1)*(n-2)*(n-3)……..*1Functions Questions-Find the output of the following programclass 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 someFuncWhat do you mean by inline function? Prepared By Sumit Kumar Gupta, PGT Computer Science
  27. 27. Page 27 of 33The idea behind inline functions is to insert the code of a called function at the pointwhere the function is called. If done carefully, this can improve the applicationsPerformance 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 ofthe 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 bythe base class. The compiler makes sure the replacement is always called wheneverthe object in question is actually of the derived class, even if the object is accessedby a base pointer rather than a derived pointer. This allows algorithms in the baseclass to be replaced in the derived class, even if users dont know about the derivedclass.What does extern mean in a function declaration?Using extern in a function declaration we can make a function such that it can usedoutside the file in which it is defined.An extern variable, function definition, or declaration also makes the describedvariable or function usable by the succeeding part of the current source file. Thisdeclaration does not replace the definition. The declaration is used to describe thevariable that is externally defined.If a declaration for an identifier already exists at file scope, any extern declaration ofthe same identifier found within a block refers to that same object. If no otherdeclaration 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 tofunctions returning pointers to characters?Answer1If 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 integralAnswer2 Prepared By Sumit Kumar Gupta, PGT Computer Science
  28. 28. Page 28 of 33char* (* (*a[N])())()Here a is that array. And according to question no function will not take anyparameter 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’tyet seen it in the file currently being compiled. This variable or function may bedefined 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 functionvoid 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);} Prepared By Sumit Kumar Gupta, PGT Computer Science
  29. 29. Page 29 of 33 Object Oriented ProgrammingData Abstraction:-is the act of representing the essential features without includingthe background details and explanations.Data Hiding:-is a related concept to data abstraction. Unessential features orbackground details are hidden from the world.Data Encapsulation:-is the wrapping up of data and associated functions in onesingle 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, fromexisting classes or base classes. The derived class inherits all the capabilities of thebase class, but can add embellishments and refinements of its own.Base Class:-is the class, which gets inherited from other classes. It is also calledSuper class.Derived class is the class which inherits from other classes. It is also calledSubclass.What is polymorphism? Explain with an example?"Poly" means "many" and "morph" means "form". Polymorphism is the ability of anobject (or reference) to assume (be replaced by) or become many different forms ofObject.Example: function overloading, function overriding, virtual functions. Anotherexample 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 packagedtogether 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 bedefined, as long as these functions have different sets of parameters (at least as faras their types are concerned). This capability is called function overloading. When anoverloaded function is called, the C++ compiler selects the proper function byexamining the number, types and order of the arguments in the call.Function overloading is commonly used to create several functions of the same namethat perform similar tasks but on different data types.Operator overloading allows existing C++ operators to be redefined so that theywork on objects of user-defined classes. Overloaded operators are syntactic sugar forEquivalent function calls. They form a pleasant facade that doesnt add anythingfundamental to the language (but they can improve understandability and reduceMaintenance costs). Very Short Answer Questions:-1-2 MarksFill in the blanks;(i)………….. is a named collection of attributes and behaviour related to modeling agiven entity for some particular purpose? Prepared By Sumit Kumar Gupta, PGT Computer Science
  30. 30. Page 30 of 33(ii) …………..is a programming approach where data and behaviour are encapsulatedto 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) Virtualfunctions, overloading.What is abstract class?Ans:- Abstract class is a class that defines an interface, but does not necessaryprovide implementation for all its member functions. No objects of an abstract classexit 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 themissing functionality . A concrete class can be instantiated i.e. its objects can becreated.What is the importance of the function overloading?Ans:- Function overloading not only implements polymorphism but also reducesnumber 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 orientedlanguage?Ans: - A Function overloading must be a part of an object oriented language as it isthe feature that implements polymorphism in an object oriented language. That isthe ability of an object to behave differently circumstances can effectively beimplemented 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() Prepared By Sumit Kumar Gupta, PGT Computer Science
  31. 31. Page 31 of 33{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,3Give the output of the following program:-void main(){ char*name=”ProOcessoR” for(int x=0,x<strlen(name);x++ { if(islower(name[x])) Prepared By Sumit Kumar Gupta, PGT Computer Science
  32. 32. Page 32 of 33 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 OEesOrWhat is function overloading? Use the concept of the function overloadingto 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 Menun”;cout<<”n Rectanglen”;cout<<”n Trianglen”;cout<<”n Circlen”;cout<<”n Exitn”;cout<<”n Enter your choice(1-4):-”;cin>>choice; cout<<endl;switch(choice) Prepared By Sumit Kumar Gupta, PGT Computer Science
  33. 33. Page 33 of 33{case 1: cout<<”Enter Length & Breadthn”; cin>>S1>>S2; ar=area(S1,S2); cout<<”The Area is<<ar<<endl”; break;case 2: cout<<”Enter 3 sidesn”; cin>>S1>>S2>>S3; ar=area(S1,S2,S3); cout<<”The Area is<<ar<<endl”; break;case 2: cout<<”Enter Radiusn”; 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;} Prepared By Sumit Kumar Gupta, PGT Computer Science

×