Computer Programming: Furqan Aziz

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 30

Computer Programming

Lecture 6
Furqan Aziz
Announcements……….
 Assignment Due today
 Submit the soft copy
 Quiz in Next class
 Thursday 12th Feb, 2009
Functions
 Modularize a Program: Dividing your program into
manageable chunks
 Easier to write and understand programs.
 Easier to change, test, and debug.
 code reusability: avoid unnecessary repetition of code .

 Functions in C++
A function is a basic building block in all C++ programs.
 There is at least one function, main(), in every C++ program
– its where program execution starts.
 Functions in C++ are either
 Built-in (e.g., Math functions, String functions)
 OR User-defined.
The Structure of a function
 Declaring a function (The function prototypes)
 Defining a function (The function body)
 Calling a function (Using a function)

Compare it with a variable. ????


Compare a C++function with mathematical
function. ????
Declaring a function
 A prototype describes a function for the compiler to be
able to compiles call to it. It does not define a function.
It has three parts – the return type, the function name
and the list of parameters.
 The function prototype
 return_type func_name(list of parameters); // general format
 double pow(double x, int n);
 int square (int x);
 void line (int n);
 void line (void); or void line(); // both are equivalent
Defining a function
 The definition of a function contains the code, it has to execute.
 The function definition starts with a function header followed by
function body.
double power (double x, int n)
{
double ans = 1;
for (int i=0; i<n; i++)
ans * = x;
return ans;
}

Note: function header and prototype must match.


If a function is defined before the main() then there is no need to
declare it.
Calling a function
 To use a function you must call it somewhere.
 You can pass values to a function. These values are
called arguments.
 Examples
 double x = 10;
int p = 3;
double res;
res = power(x, p);
res = power(x, 3);
res = power(10, p);
res = power (10, 3);
There are three places where variables are declared
 Inside functions (Local Variables). They are created
when the function is called and destroyed when the
function is exited.
 In the definition of function (Formal Parameters).
Just like local variables, they are created when the
function is called and destroyed when the function is
exited. They have a special task of receiving the values
of arguments.
 Outside of all functions (Global Variables). They hold
their value throughout the lifetime of the program and
destroyed when the program completes its execution.
Passing Arguments to a Function
 Pass-by-Value
 Pass-by-Reference
 Pass-by-Pointers
#include<iostream>
using namespace std;
Function Prototype
double power (double, int);
int main()
{
double num = 10.0;
int pow = 3; Function Call
double res = power(num, pow); Call-by-Value
cout<<res<<endl;
cout<<power(2.0, 10); Function Call
return 0; Call-by-Value
}
double power (double x, int n)
{
double ans = 1;
for (int i=0; i<n; i++) Function Body
ans * = x;
return ans;
}
#include<iostream>
…………………….
…………………….
double power (double, int);
…………………….
…………………….
int main()
{
…………………….
…………………….
double res = power(num, pow);
……………………. num pow
…………………….
return 0;
}
double power (double x, int n) x n
{
…………………….
…………………….
}
Examples
 Printing Lines
void Line( int x, char ch)
{
for ( int i = 0; i < x; i++)
cout << ch;
cout <<endl;
}
 What will be the output :
Line (10, *);
Line (20, ‘%’);
Line (5, ‘+’);
Swapping: What's wrong here?
 consider the function
void swap(int x, int y)
{
int temp = x;
x = y;
y = temp;
}
 What will be the output if the following statements are
executed?
int a = 10, b = 20;
swap(a, b);
cout << a << endl << b;
 WHY?
Reference
 Reference is simply an alias for another variable.
 What will be the output in each case:
int x = 10; int x = 10;
int y = x; int &y = x;
cout << x << endl; cout << x << endl;
cout << y << endl; cout << y << endl;
y = 20; y = 20;
cout << x << endl; cout << x << endl;
cout << y << endl; cout << y << endl;

 To declare a variable of reference type, you just add &


after the type name.
Pass-by-Reference
 Variable can be passed by Reference.
 What will be the output in each case.
void somefunc( int x) void somefunc( int& x)
{ {
x = 20; x = 20;
} }
……………… ………………
int y = 10; int y = 10;
somefunc(y); somefunc(y);
cout << y; cout << y;

 Use & sign if you want to pass value by reference.


Swapping
 consider the function
void swap(int& x, int& y)
{
int temp = x;
x = y;
y = temp;
}
 What will be the output if the following statements are
executed?
int a = 10, b = 20;
swap(a, b);
cout << a << endl << b;
 WHY?
Passing Arrays to Functions
 Example
 Finding Sum
 Finding Average

Be Careful! Arrays are not passed by value.


Default Arguments
 Parameters can be assigned default values.
 If you don’t pass arguments default values will be
assigned to parameters.
 If you pass an arguments, the value you passed will be
assigned
Example – Default Arguments
 Consider the following function definition
void Line(int x = 50, char ch = ‘ * ‘)
{
int i = 0;
for ( i = 0; i<x; i++)
cout<<ch;
cout << endl;
}
 What will be the output if the following statements are executed.
 Line ( );
 Line ( 100 );
 Line (80, ‘$’);
 Line(‘<’); // What’s Wrong Here.
Multiple Default Arguments
Default values can be specified to all or some of the
parameters. But
parameters for which you specify default values must be
placed at the end of the parameter list. So
void Line (int x = 10, char ch); is invalid. But
void Line (char ch, int x = 10); is valid.
Built-in Functions
Some common Library Functions
NAME DESCRIPTION TYPE OF TYPE OF EXAMPLE VALUE LIBRAR
ARGUMENT VAULE Y
RETURNED HEADER
sqrt Square root double double sqrt(4.0) 2.0 cmath
pow Powers double double power(2.0,3.0 8.0 cmath
)
abs Absolute value for int int int abs(7) 7 cstdlib
abs(-7) 7
labs Absolute value for long long labs(-70000) 70000 cstdlib
long
fabs Absolute value for double double fabs(-7.5) 7.5 cmath
long
ceil Ceiling (round up) double double ceil(3.2) 4.0 cmath
ceil(3.9) 4.0
floor Floor (round down) double double float(3.2) 3.0 cmath
float(3.9) 3.0
exit End program int void exit(1); None cstdlib
rand Random number None int rand() varies cstdlib
srand Set seed for rand unsigned int void srand(42) None cstdlib
Random Numbers
 Return ‘randomly chosen’ number
 Used for simulations, games
rand()
 Takes no arguments
 Returns value between 0 & RAND_MAX
 Scaling
 Squeezesrandom number into smaller range
rand() % 6
 Returns random value between 0 & 5
 Shifting
rand() % 6 + 1
 Shifts range between 1 & 6 (e.g.: die roll)
Example
int main()
{
for(int i=0; i<20; i++)
cout<<rand()%10<<"\t";
getch();
return 0;
}

Sample output
Using srand()
int main()
{
for(int i=0; i<20; i++)
cout<<rand()%10<<"\t";
getch();
return 0;
}

Sample output
Pseudorandom numbers
 What is Pseudorandom number
 Call
to rand() always produce same ‘sequence’ of random
numbers
 Use ‘seed’ to alter sequence
srand(seed_value);
 void function
 Receives one argument, the ‘seed’
 Can use any seed value, including system time:
srand(time(0));
 time() returns system time as numeric value
 Library <time> contains time() functions
Using srand()
int main()
{
for(int i=0; i<20; i++)
cout<<rand()%10<<"\t";
getch();
return 0;
}

Sample output
Function Overloading
 What is Function Overloading
 Examples
 The combination of name of a function, together with its
parameter type define a unique characteristic, called function
Signature.
 Functions are differentiated by function signature and not by
function name. So two functions are different if
 their name is different
 their name is same but the number of parameters in each function is
different.
 their name is same and the nubmer of parameters is also same, but at
least one pair of corresponding parameters have different type.
 Remember return type is not included in function signature.
 Reference type and function oveloading.
C++ Templates
 A function template is a blueprint for a function.
 Example
template <class T>
T larger ( T a, T b)
{
return a>b ? a: b;
}
Recursion
 A function in C++ can call itself.
 When a function contains a call to itself, it is reffered
to as a recursive function.
 A recursive function must contain a base condition ?
 Examples
 Sum of numbers
 Factorial of a number
 Power of a number
 Fibonacci Numbers
Announcements

You might also like