Lect 10 (Lab & Theory)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

Functions

Dr. Fakhre Alam Khan


MED UET Peshawar
Functions
Functions and Structures
 The structures can also be used with functions.
 A function can accept structures as parameters.
 A function can also return a structure variable.
 The process of passing structures to a function is similar to passing a simple variable.
 The structure used as parameter must be defined before using it as parameter.

Passing Structure by Value:


 A structure can be passed to a function by value.
 The method of passing a structure by value is same as passing a simple variable by value.
Write a program that declares a structure to store marks and grade. It defines structure variable and inputs
values. It passes the variable to a function that shows its contents.

#include <iostream.h>
#include <conio.h>
struct Test void show(Test p)
{ {
int marks; cout<<"Marks: "<<p.marks<<endl;
char grade; cout<<"Grade: "<<p.grade<<endl;
}; }
void show(Test p);
void main()
{
clrscr();
Test t;
cout<<"Enter marks: ";
cin>>t.marks;
cout<<"Enter grade: ";
cin>>t.grade;
show(t);
getch();
}
Functions
Passing Structure by Reference:
 A structure variable can also be passed to a function by reference.
 The method of passing a structure by reference is same as passing a simple variable by
reference.
Write a program that declares a structure to store price and author name of a book. It defines a structure variable
and inputs values. It passes the variable to a function by reference that doubles the value of price. The main()
function finally displays the values.
#include <iostream.h>
#include <conio.h>
void dbl(Book &x)
struct Book
{
{
x.price = x.price*2;
char author[50];
}
float price;
};
void dbl(Book &x);
void main ()
{
clrscr();
Book b;
cout<<"Enter author name and price: ";
cin>>b.author>>b.price;
dbl(b);
cout<<"Author Name: "<<b.author<<endl;
cout<<"Price: "<<b.price<<endl;
getch();
}
Functions
Returning Structure from Function:
 A function can also return a structure variable.
 The method of returning a structure variable from a function is same as returning a simple
variable.
 The return type of the function must be the type of structure to be returned.
Write a program that declares a structure to store author name, pages and price of a book. It declares two
structure variables and inputs values. It passes these variables to a function. The function returns the variable with
more price. The program finally displays the values of the returned structure variable..
#include <iostream.h>
#include <conio.h>
struct Book Book check(Book x, Book y)
{ {
int pages; if(x.price > y.price)
float price; return x;
}; else return y;
Book check(Book x, Book y); }
void main()
{
Book a, b , r;
cout<<"Enter pages and price: ";
cin>>a.pages>>a.price;
cout<<"Enter pages and price: ";
cin>>b.pages>>b.price;
r = check(a, b);
cout<<"The more costly book is:\n";
cout<<"Pages: "<<r.pages<<endl;
cout<<"Price: "<<r.price<<endl;
getch();
}
Functions
Default Parameters:
 The parameters initialized during function declaration are called default parameters.
 The default parameters allow user to call a function without giving required parameters.
 The initialized values of default parameters are used if the user does not specify any
value for the parameters in function call.
 Default values can be constants, global variables or function calls.
Example:
#include<iostream.h>
#include <conio.h>
void Test(int n=100);
void main()
{
Test();
Test(2);
Test(75);
getch();
}
void Test(int n)
{
cout<<"n = "<<n<<endl;
}
Functions
Inline Functions:
 The function declared with keyword inline is known as inline function.
 The inline function is declared before main function.
 Only very small functions are declared as inline functions.
 When a program is compiled, the compiler generates special code at each function call to
move the control to the called function.
 It also generates special code at the end of function definition to move the control back to
the calling function.
 The shifting of control from calling function to called function and back to calling
function takes time during program execution.
 This time can be eliminated by using inline functions.
Example:
#include<iostream.h>
#include <conio.h>
Inline int cube(int n);
{
return n*n*n:
}
void main()
{
clrscr();
cout<<cube(3)<<endl;
cout<<cube(5)<<endl;
cout<<cube(9)<<endl;
getch();
}
Functions
Function Overloading:
 The process of declaring multiple functions with same name but different parameters is
called function overloading.
 The functions with same name must differ in one of the following ways:
1) Number of parameters
2) Type of parameter
3) Sequence of parameters

 Function overloading allows the programmer to assign same name to all functions with
similar tasks.
 It helps the user in using different functions easily.
 The user does not need to remember many names for similar types of tasks.
 For example, the programmer can declare the following functions to calculate average:
Example
float Average(int, int);
float Average(float, float);
float Average(int, float);
Write three versions of function line. The first version takes no parameter and displays a line of 10 asterisks(*). The
second version takes an integer parameter and displays a line of n asterisks. The third version takes an integer and a
character as parameters and displays a line of given character of n length.

#include<iostream.h> void line(int n)


#include <conio.h> {
void line(); int i;
void line(int n); for(i=1 ; i<=n; i++)
void line(int n, char c); cout<<"*";
void main() cout<<endl;
{ }
clrscr(); void line(int n, char c)
line(); {
line(3); int i;
line(5, '@'); for(i=1; i<=n; i++)
getch(); cout<<c;
} cout<<endl;
void line() }
{
int i;
for(i=1 ; i<=10; i++)
cout<<"*";
cout<<endl;
}
Functions
Recursion:
 A programming technique in which a function calls itself is known as recursion.
 A function that calls itself is called recursive function.
 The recursion is a powerful technique.
 A recursive function must have at-least one termination condition that can be satisfied.
Otherwise, the function will call itself indefinitely.
 The following Factorial function has the termination condition n == 0 that causes the
recursive calls to move back. Factorial(4) = 4 *Factorial(3) 24
Example:
int Factorial (unsigned int n) Factorial(3) = 3 *Factorial(2) 6
{
if(n == 0) Factorial(2) = 2 *Factorial(1) 2
return 1;
else Factorial(1) = 1 *Factorial(0) 1
return n * Factorial(n-1);
} Factorial(0) = 1 1
Write a program that inputs a number from user and calculates its factorial recursively.

#include<iostream.h>
#include <conio.h>
long int fact(int n)
{
if(n == 0)
return 1;
else
return n * fact(n-1);
}
void main()
{
clrscr();
int num;
cout<<"Enter an Integer: ";
cin>>num ;
cout<<"Factorial of "<<num<<" is "<<fact(num);
getch();
}
Built-in Functions
Built-in Functions
 A type of function that is available as a part of language is known as built-in function or
library function.
 These functions are ready-made programs. These functions are stored in different header
files.
 Different built-in functions are defined in different header files.
 Built-in functions can be accessed in programs by including the header files in which
these functions are defined.

The 'conio.h' Header File


 The word 'conio' stands for console input/output.
 The header file 'conio.h' contains the built-in function that are used for input and output.
 Some important function defined in this header file are as:
1. clrscr()
 The word 'clrscr' stands for clear screen. The function is used to clear the contents of the
screen. When this function is executed, the screen is cleared and the cursor moves to the
start of first line on the screen.
Built-in Functions
2. clreol()
 The word 'clreol' stands for clear end of line. The function is used to clear current line
from current cursor position to the end of line. The remaining text on screen is not
cleared.
3. getch()
 The word 'getch' stands for get character. The function is used to input single character
from the keyboard. The character typed by the user does not appear on the screen. It can
be stored in a variable by using assignment statement. The user does not need to press
Enter key to complete the input. The function is frequently used to pause program
execution. #include <iostream.h>
Syntax: variable = getch(); The use of variable is optional. #include <conio.h>
void main()
{
char ch;
cout<<"Enter any character: " ;
ch = getch();
cout<<"You entered "<<ch;
getch(); }
Built-in Functions
4. getche()
 The word 'getche' stands for get character echo. The function is used to input a single
character from the key board. The character typed by the user also appears on the screen.
It can be stored in a variable by using assignment statement. The user does not need to
press Enter key to complete the input.
Syntax: variable = getche(); The use of variable is optional.

5. kbhit()
 The word 'kbhit‘ stands for keyboard hit. The function is used to check if the user hit
The keyboard or not. It returns a non-zero value if the user hits any key on the keyboard
and returns zero otherwise. The value of the key can also be stored in a variable by using
assignment statement. #include <iostream.h>
#include <conio.h>
Syntax: variable = kbhit(); void main()
The use of variable is optional. {
while(!kbhit())
cout<<"Pakistan Zindabad\t" ;
}
Built-in Functions
6. gotoxy()
 The gotoxy() function is used to move the cursor to a specific location on the screen. It
moves the cursor with respect to x-axis and y-axis. It is very useful when the output is to
be displayed at a specific location on the screen.
Syntax: gotoxy(x, y);
The variable x indicated x-axis. Its value can be from 0 to 79. the variable y indicates the y-
axis. Its value can be from 0 to 24.
#include <iostream.h>
#include <conio.h>
void main()
{
clrscr();
gotoxy(0,0);
cout<<"Pakistan Zindabad";
gotoxy(1,50);
cout<<"Pakistan Zindabad";
getch();
}
Built-in Functions
7. textcolor()
 The function is used to change the output display text color. The user can enter either
color name or color code as shown in table. Colors Value
Syntax: textcolor(name or code);
1. BLACK 0
2. BLUE 1
8. textbackground() 3. GREEN 2
 The function is used to change the output display text background color. 4. CYAN 3
5. RED 4
 The user can enter either color name or color code as shown in table. 6. MAGENTA 5
Syntax: textbackground(name or code); 7. BROWN 6
8. LIGHTGRAY 7
9. DARKGRAY 8
 Default background color is set to 0 and text color is set to 15. 10. LIGHTBLUE 9
11. LIGHTGREEN 10
Important: 12. LIGHTCYAN 11
13. LIGHTRED 12
 Use cprintf("Pakistan"); rather than cout<<"Pakistan"; 14. LIGHTMAGENTA 13
(cprintf in c-language is same as cout in c++ language) 15. YELLOW 14
16. WHITE 15
Built-in Functions
Output display text and background color:

system()
 The function system() is used to change the output display text and background color.
 It is defined in 'stdlib.h' header file.
 The word 'stdlib' stands for standard library.
Syntax: system("color code");

 The color code can be any combination of 0-9 and A-F.


 First character code represent background color.
 Second character code represent text color.
 Maximum of 15x15=225 possible color combination.

Example: system("color 4F");


Built-in Functions
The 'stdio.h' Header File
 The word 'stdio' stands for standard input/output.
 The 'stdio.h' header files contains different function that are used in the tasks of input and
output.
 Some important function defined in this header file are as:

1. getchar()
 The word 'getchar' stands for get character. The function works similar to getch() and
getche() functions of 'conio.h' header file. It is used to input single character from
keyboard. The character can be stored in a variable by using assignment statement. The
user needs to press Enter key to complete input. The character typed by the user also
appears on screen.

Syntax: variable = getchar(); The use of variable is optional.


2. putchar()
Built-in Functions
 The word ‘putchar' stands for put character. The function is used to display single
character on the screen.

Syntax: putchar(ch);
The parameter ch is the variable or constant whose value is to be displayed on screen.
#include <iostream.h>
#include <conio.h>
#include <stdio.h>
void main()
{
char ch;
cout<<"Enter a character:";
cin>>ch;
putchar(ch);
getch();
}
Built-in Functions
3. gets()
 The word 'gets' stands for get string. The function is used to input a string value from
keyboard. The value entered by, the user can be stored in an array of characters. The string
may consist of any characters and space. The user also needs to press Enter key after typing
the string to complete the input. A NULL character is added at the end of string
automatically when the user presses Enter key.
Syntax: gets(variable);
The parameter variable is the variable the is used to store the string value.

4. puts()
 The word 'puts' stands for put string. The function is used to display a string value on the
screen. It can display both string variable as well as string constant. The string constant is
enclosed in double quotation marks.
Syntax: puts(variable); Note:
The parameter variable is the variable the is used to store the string value. puts() and gets() are
used in combination.
Built-in Functions
Example

#include <iostream.h>
#include <conio.h>
#include <stdio.h>
void main()
{
clrscr();
char f[] = "This is an example output string\n";
puts(f);
gets(f);
}
Built-in Functions
The 'math.h' Header File
 The header file 'math.h' contains the built-in function that are used to perform arithmetic
calculations.
 Some important function defined in this header file are as:

1. abs()
 The abs() function is used to find the absolute value of an integer.
Syntax: abs(x); x indicates the integer whose absolute value is to be found.

2. fabs()
 The abs() function is used to find the absolute value of a floating number.
Syntax: fabs(x); x indicates the floating number whose absolute value is to be found.

3. ceil()
 The ceil() function rounds a float or double number to the next integer and returns it..
Syntax: ceil(x); x indicates the float or double number that is to be rounded.
Built-in Functions
4. floor()
 The floor() function rounds a float or double number to an integer and returns it. The
rounded value is not greater than the original value.
Syntax: floor(x); x indicates the float or double value, that is to be rounded.

5. cos()
 The cos() function is used to find the trigonometric cosine of the specified angle. The
angle is given in radians as floating number.
Syntax: cos(x); x indicates the angle in radians.

6. sin()
 The sin() function is used to find the trigonometric sine of the specified angle. The angle
is given in radians as floating number.
Syntax: sin(x); x indicates the angle in radians.
Built-in Functions
7. tan()
 The tan() function is used to find the trigonometric tangent of the specified angle. The
angle is given in radians as floating number.
Syntax: tan(x); x indicates the angle in radians.

8. log()
 The log() function is used to find the natural logarithm of a given floating point value.
Syntax: log(x); x indicates the value whose natural log is to be found.

9. log10()
The log10() function is used to find the base 10 logarithm of a given floating point value.
Syntax: log10(x); x indicates the value whose base 10 log is to be found.
Write a program that inputs a floating point number: and displays: cosine, sine,
tangent, natural-log and base-10 log of the given number.
#include <iostream.h>
#include <conio.h>
#include <math.h>
void main()
{
clrscr();
float n;
cout<<"Enter a floating point value: '';
cin>>n;
cout<<"Trigonometric cosine of "<<n<<" is = ''<<cos(n)<<endl;
cout<<"Trigonometric sine of "<<n<<" is = "<<sin(n)<<endl;
cout<<"Trigonometric tangent of "<<n<<" is = "<<tan(n)<<endl;
cout<<"Natural log of "<<n<<" is = "<<log(n)<<endl;
cout<<"Base 10 Log of "<<n<<" is = "<<log10(n)<<endl;
getch();
}
Built-in Functions
10. fmod()
 The fmod() function is used to find remainder by dividing two floating point values.
Syntax: fmod(x,y); floating point value “x” is nominator and “y” is denominator.

11. pow()
 The pow() function is used to find the result of one integer raised to the power of second
integer (nm).
Syntax: pow(x,y); “x” indicates the base and “y” indicates the exponent.

12. sqrt()
 The sqrt() function is used to calculate the square root of a floating point number.
Syntax: sqrt(x); x indicates the value whose square root is to be calculated.
Assignment # 4
Write down pseudo code (algorithm) and make flow chart of the
given problems.

Write down code of all programs as well…

Next week: Quiz 4 (be ready…)


Problem 1:
Write a program that uses a function EQ() to find whether four integers a,b,c,d passed to the function satisfy the equation
a3+b3+c3 = d3 or not. The function returns 0 if the above equation is satisfied and returns -1 otherwise.

Problem 2:
Write a program that prompts the user for Cartesian coordinates of two points xl, yl and x2, y2 and displays the distance
between them. Write a function Distance() with four input parameters to compute the distance. The function uses the
following formula to compute distance and return result to calling function.
(𝑥𝑥2 − 𝑥𝑥1 )2 +(𝑦𝑦2 − 𝑦𝑦1 )2
Problem 3:
Write a function that accepts a salary and returns the tax according to following rules:
No tax for first Rs.1000
5% for second Rs.1000
4% for third Rs.1000
3% for remain untaxed salary
For example, if the salary is Rs.4000, then the tax is Rs.120

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy