Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Abu Java’s Note of Week 8

The document explains the concept of functions in C++, including their definition, declaration, and the distinction between built-in and user-defined functions. It also covers the importance of variable scope, differentiating between local and global variables, and provides examples of function usage and output. Additionally, it discusses the inclusion of libraries and the syntax for function return statements.

Uploaded by

alepikinsamson
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Abu Java’s Note of Week 8

The document explains the concept of functions in C++, including their definition, declaration, and the distinction between built-in and user-defined functions. It also covers the importance of variable scope, differentiating between local and global variables, and provides examples of function usage and output. Additionally, it discusses the inclusion of libraries and the syntax for function return statements.

Uploaded by

alepikinsamson
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

LIBRARY AND FUNCTION

FUNCTIONS
A complex problem may be decomposed into a small or easily manageable parts or modules
called Functions. Functions are very useful to read, write, debug and modify complex programs.
They can also be incorporated easily in the main program. In C++, the main itself is a function
means the main function is invoking the other functions to perform various tasks. There are two
types of function. These are inbuilt function and user-define function. These are further
explained further in "LIBRARIES" in this handout. (next topic).

DEFINING A FUNCTION
A function definition has a name, parenthesis ( ) pair containing zero or more parameters and a
body. For each parameter, there should be a corresponding declaration that occurs before the
body. Any parameters' not declare is taken to be int by default. It is good programming practice
to declare all parameters.
The general format of the function definition is given below:
Functiontype functionname (datatype argument1, datatype argument2, .. )
{
Body of function
---------------------
---------------------
Return 0;
}
DECLARATION FUNCTION
(a) Function Declaration. Refers to the type of value it would return to the calling portion of
the program. Any of the basic data types such as int, float, char e.t.c may appear in the function
declarations. In many compilers, when a function is not suppose to return any value, it may be
declared as type void, which informs the compiler not to save any temporary space for a value
to be sent back to the calling program.
For example:
void function_ name ( )
int function_name ( )
float function_name ( )
char function_name ( )

(b) Function name. The function name can be any name conforming to the syntax rules of the
variables. Normally, a function name is made relevant to the function operation.
For example;
Square();
display_value ( );

(c) Formal arguments. Any variable declared in the body of a function is said to be local to that
function. Other variables which are not declared either as arguments or in the function body are
considered global to the function and must be defined externally.
For example:
1. void square ( int a, int b)
// a, b are the formal arguments
{
………………;
………………;
}
2. int counter ( float xl, float x2, int y1, int y2)
{ // xI, x2, y1, and y2 are the formal arguments
……………;
……………;
Return (int value);
}
Function body: After declaring the type of a function, function name, and formal arguments,
statement or a block of statements is enclosed between the beginning and the end statements. In
C++, each function is declared almost like main ( ) function. .
For example;
Void find_sum (int a, int b, int c, float r, float y)
{
Int i, j, n;
………….;}
Example:
A program to demonstrate a function declaration, function calling and function definition in
C++.
#include <iostream>
using namcspace std;
void main ( )
{
void display ( ); // function declaration
display ( ); // function calling
}
void display (void) // function
definition {
cout << "this is a test program \n
";
cout <<” in C++ \n";
}
The main ( ) function invokes the display ( ) function. In C++, each function is almost like
separate program.

 return statement
The keyword return is used to terminate function und returns a value to its caller. The return
statement may also be used to exit a function without returning a value. The return statement
may or may not include an expression.
The general syntax of the return statement
is; Return (expression);

USER-DEFINED FUNCTIONS
At times, the great varieties of function provided by the C++ compiler might not be sufficient
enough for a programmer to use. In this case, user define functions is introduced. This allows,
the programmer to define their own functions.

Here is a simple example of user-defined


function:

lnt cube (int x)


{
// returns cube of x
return x * x * x;
}

The function return the cube of the integer passed to it. Thus, the call cube (2) would return 8

A user-defined function has two parts: its head and its body. The syntax for the head of a
function is
Return-type name (parameter-list)
This specifics for the compiler the function return type, its name, and it~ parameter list. In the
example above, the function's return type is int, its name is cube, and its parameter list is int x.
So, its head is int cube (int x)

The body of the function is the block of code that follows its head. It contains the code that
performs the function's action, including the return statement that specifics the value that the
function sends back to the place where it was called. The body of the cube function is:
{
// returns cube of x
Return x * x *x;
}

This is about as simple body as function could have. Usually, the body is much larger. But the
function's head typically fits on a single line.
Note that main() itself is a function. Its head is int main() and its body is the program itself. Its
return type is int, its name is main. and its parameter list is empty.

A function's return statement serves two purposes: it terminates the execution of the function,
and it returns a value to the calling program. Its syntax is return expression where expression is
any expression whose value could be assigned to a variable whose type is the same as the
function's return type.

Example 9:
A program to find the sum of the given numbers using function declaration with the return
statement.
#include <iostream>
using namespace std;

//function declaration
int addition(int a, int b);

int main()
{
int num1; //to store first number
int num2; //to store second number
int add; //to store addition

//read numbers
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;

//call function
add = addition(num1, num2);

//print addition
cout << "Addition is: " << add << endl;

return 0;
}

//function definition
int addition(int a, int b)
{
return (a + b);
}

LIBRARIES
What libraries do you need to “#include"? Someone will have to tell you which libraries are
needed for a particular assignment. The libraries are not perfectly standardized. You do find
difference between environments (e.g. the header file for the maths library on Unix contains
Definitions of the values of useful constants like PI = 3.14 59....., the corresponding header file
with Symantec C++ doesn't have these constants).

Built-in functions
Built-in functions are part of your compiler package--they are supplied by the manufacturer for
your Function Prototypes. Many of the built-in function you use will have their function
prototypes already written in the files you include in your program by using #include. For
functions you write yourself, you must include the prototype.

The function prototype is a statement, which means it ends with a semicolon. It consists of the
function's return type, name, and parameter list.
The parameter list is a list of all the parameters and their types, separated by commas.

Some C++ libraries functions (In-built functions) are: ~ .'


 iostream: standard C++ input output library
 stdio: alternate input output library (standard for C programs)
 cmath functions: things like sine, cosine, tan, log, expone~tial etc.
 string functipns: for manipulating sequences of characters ("strings") - copying them,
searching for occurrences of particular letters, etc.
 ctype functions: for testing whether a character is a letter or a digit, is upper case or
lower case, etc. limits constants defining things like largest integer that can be used on a
particular machine.
 Stdlib: assorted "goodies" like u function for generating random numbers.

Example 10: Sample program on cout is used in C++ Output Using cout
1: // using cout
2: #include<iostream>
3: using namespace std;
4: int main()
5: {
6: cout<< :Hello there.\n”;
7: cout << “Here is 5: “<< 5 << “\n;
8: cout << “The manipulator endl writes a new line to the screen. “<<endl;
9: cout << “Here is a very big number:\t” << 70000 << endl;
10: cout << “Here is the sum of 8 and 5:\t” << 8+5 << endl;
11: cout << “Here’s a fraction:\t\t” << (float) 5/8 << endl;
12: cout << “And a very very big number:\t” << (double) 7000 * 7000 <<endl;
13: cout << “Don’t forget to replace Opeyemi Ibrahim with your name…\n”;
14: cout << “Opeyemi Ibrahim is a C++ programmer!\n;
15: return 0;
16: }

Hello there.
Here is 5:5
The manipulator endl writes a new line to the screen
Here is a very big number: 70000
Here is the sum of 8 and 5: 13
Here’s a fraction: 0.625
And a very big number: 4.9e+07

On line 2, the statement #include <iostream> causes the iostream file to be added to your source
code. This is required if you use cout and its related functions.
On line 6 is the simplest use of cout, printing a string or series of character. The symbol \n is a
special formatting character. It tells cout to print a newline character to the screen. Three values
are passed to cout on line 7, and each value is separated by the insertion operator. The first value
is the string “Here is 5: “. Note the space after the colon. The space is part of the string. Next, the
value 5 is passed to the insertion operator and the newline character (always in double quotes or
single quotes). This causes the line.
Here is 5:5 to be printed to the screen. Because there is no newline character after the first string,
the next value is printed immediately afterwards. This is called concatenating the two values.
On line 8, an informative message is printed, and then the manipulator endl is used. The purpose
of endl is to write a new line to the screen. On line 9, a new formatting character, \t, is
introduced. This insert a tab character and is used on line 8-12 to line up the output. Line 9
shows that not only integers, but long integers as well can be printed. Line 10 demonstrates that
cout will do simple addition. The value of 8+5 is passed to cout, but 13 is printed.
On line 11, the value 5/8 is inserted into cout. The term (float) tells cout that you want this value
evaluated as a decimal equivalent, and so a fraction is printed. On line 12 the value 7000 * 7000
is given to cout, and the term (double) is used to tell cout that you want this to be printed using
scientific notation.
On line 14, you substituted your name, and the output confirmed that you are indeed a C++
programmer. It must be true, because the computer said so.

LOGICAL AND GLOBAL VARIABLES

Scope of variables refers to the accessibility of a particular variable within the program

For example, assuming you have two different functions. First, you declare a variable in
function 1 int K. Then, you move on to the following function, i.e., function 2. it not possible to
access the variable int K made in function 1 from function 2. This refers to the Scope of a
Variable in.

The variables in general may be classified as local or global variables.


Local variables: these are variables defined inside a function block or a compound statement. For
example:
Void funct ( int i, int j )
{

Int k, m; // local variables


……………….;
……………….;
/ / body of the function
}

The integer k and m are defined within a function block of the funct ( ). All the variables to be
used within the function block must either defined at the beginning of the block itself or before
using It In a statement.

Global variable: Global variables are variables defined outside the main function block. These
variables are referred by the same data type and by the same name through out the program in
both calling portion of a program and function block. i
For example:
Int x, y = 4; // global declaration
void main( )
{
Void function1 ( )
x = 10;
…………..;
…………..;
Function1 ();
}
Function1 ()
{
int sum;
sum = x
+y;
………......;
}

You might also like