Computer Programming: Furqan Aziz
Computer Programming: Furqan Aziz
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)
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