FPCPP C2
FPCPP C2
FUNDAMENTALS OF
2
PROGRAMMING IN C++
FUNCTIONS
Functions 2
A good plan for designing algorithm is
to break down the task into smaller subtasks,
Then decompose each of these subtasks into smaller sub-subtasks, and so forth.
Eventually, the subtasks become so small that they become trivial to implement.
This method is called top-down design( mostly divide and conquer.)
The same is applied to a program by
breaking the program's task into subtasks
and solve these subtasks by sub-algorithms as functions.
• In C++, programs are organized into functions.
• A program must have at least one function, called main function.
… 3
• A function is a block of codes(actually related)grouped together to perform a specific task
in a program.
• Grouping related codes to perform a specific task will have the following advantages:
• enhance readability,
• ease of maintenance,
• allows reusability, – define once and use whenever necessary.
• allows to unit test the code,
• one way of putting the principle of abstraction into effect
• and etc.
Categories… 4
• Functions, based on how they occurred into the program, can be categorized as:
1. Built-in (predefined) functions
• are functions that comes with the compiler as a package in some library.
2. User defined functions
• are functions that explicitly defined by the programmers for their own purpose.
If that’s how the functions appeared in a program, then the remaining question is:
How could one use a built-in functions? and
How could one define a function?
Using built-in functions 5
• In order to use a built-in function:
1. Include the library file, where the function is pre-defined.
2. Invoke( or call) the function from the main and
3. Pass arguments accordingly.
Example: #include <cmath>
#include <iostream>
using namespace std;
int main(){
int a;
cout<<“Enter your number:”;
cin>>a;
cout<<“square root =“<<sqrt(a)<<endl;
return 0;
}
…for type casting 6
• Type casting is a technique used to convert the type of a certain data to other types.
• Type casting can be done:
1. Implicitly by the compiler
• The compiler automatically convert a type of a data into another type.
• Implicit casting is done from lowest order to the highest order types only.
• Done when assigning values only.