About me

Feeds RSS
Feeds RSS

Kamis, 22 November 2012

FUNCTION


Function in C++


Functions are building blocks of the programs. They make the programs more modular and easy to read and manage. All C++ programs must contain the function main( ). The execution of the program starts from the function main( ). A C++ program can contain any number of functions according to the needs. The general form of the function is :
return_type  function_name(parameter list)
{
            body of the function
}
The function of consists of two parts function header and function body. The function header is:
·         return_type   function_name(parameter list)
The return_type specifies the type of the data the function returns. The return_type can be void which means function does not return any data type. The function_name is the name of the function. The name of the function should begin with the alphabet or underscore. The parameter list consists of variables separated with comma along with their data types. The parameter list could be empty which means the function do not contain any parameters. The parameter list should contain both data type and name of the variable. For example,
·         int factorial(int n, float j)
Is the function header of the function factorial. The return type is of integer which means function should return data of type integer. The parameter list contains two variables n and j of type integer and float respectively. The body of the function performs the computations. 


Function Declaration
A function declaration is made by declaring the return type of the function, name of the function and the data types of the parameters of the function.  A function declaration is same as the declaration of the variable. The function declaration is always terminated by the semicolon. A call to the function cannot be made unless it is declared. The general form of the declaration is:
return_type function_name(parameter list);
For example function declaration can be
·         int factorial (int n1,float j1);
The variables name need not be same as the variables of parameter list of the function. Another method can be
·         int factorial (int , float);
The variables in the function declaration can be optional but data types are necessary. 

Function Arguments
The information is transferred to the function by the means of arguments when a call to a function is made.  Arguments contain the actual value which is to be passed to the function when it is called.  The sequence of the arguments in the call of the function should be same as the sequence of the parameters in the parameter list of the declaration of the function. The data types of the arguments should correspond with the data types of the parameters. When a function call is made arguments replace the parameters of the function.

The Return Statement and Return values
A return statement is used to exit from the function where it is. It returns the execution of the program to the point where the function call was made. It returns a value to the calling code. The general form of the return statement is:-
return expression;
The expression evaluates to a value which has type same as the return type specified in the function declaration. For example the statement,
            return (n);
is the return statement of the factorial function. The type of variable n should be integer as specified in the declaration of the factorial function. If a function has return type as void then return statement does not contain any expression. It is written as:
            return; 
The function with return type as void can ignore the return statement. The closing braces at the end indicate the exit of the function. Here is a program which illustrates the working of functions.
#include<iostream>
using namespace std;
int factorial(int n);
int main ()
{
            int n1,fact;
            cout <<"Enter the number whose factorial has to be calculated" <<  endl;
            cin >> n1;
            fact=factorial(n1);
            cout << "The factorial of " << n1 << "  is : " << fact << endl;
            return(0);
}
int factorial(int n)
{
            int i=0,fact=1;
            if(n<=1)
            {
                        return(1);
            }
            else
            {
                        for(i=1;i<=n;i++)
                        {
                                    fact=fact*i;
                        }
                        return(fact);
            }
}

   
                   The result of the program is:


The function factorial calculates the factorial of the number entered by the user. If the number is less than or equal to 1 then function returns 1 else it returns the factorial of the number. The statement :
            int factorial(int n);
is a declaration of the function. The return type is of integer. The parameter list consists of one data type which is integer. The statement :
            cout <<"Enter the number whose factorial has to be calculated" <<  endl;
            cin >> n1;
makes the user enter the number whose factorial is to be calculated. The variable n1 stores the number entered by the user. The user has entered number 5. The statement :          
            fact=factorial(n1);
 makes a call to the function. The variable n1 is now argument to the function factorial. The argument is mapped to the parameters in the parameter list of the function. The function header is :
            int factorial(int n)
The body of the function contains two return statements. If the value entered by the user is less than and equal to 1 then value 1 is returned else computed factorial is returned. The type of the expression returned is integer.

Parameter passing mechanism
There are two parameter passing mechanisms for passing arguments to functions such as pass by value and pass by reference.

Pass by value
In pass be value mechanism copies of the arguments are created and which are stored in the temporary locations of the memory. The parameters are mapped to the copies of the arguments created. The changes made to the parameter do not affect the arguments. Pass by value mechanism provides security to the calling program. Here is a program which illustrates the working of pass by value mechanism.

#include<iostream>
using namespace std;
int add(int n);
int main()
{
            int number,result;
            number=5;
            cout << " The initial value of number : " << number << endl;
            result=add(number);
            cout << " The final value of number : " << number << endl;
            cout << " The result is : " << result << endl;
            return(0);
}
int add(int number)
{
            number=number+100;
            return(number);
}

The result of the program is :



The value of the variable number before calling the function is 5. The function call is made and function adds 100 to the parameter number. When the function is returned the result contains the added value. The final value of the number remains same as 5. This shows that operation on parameter does not produce effect on arguments.

Pass by reference
Pass by reference is the second way of passing parameters to the function. The address of the argument is copied into the parameter. The changes made to the parameter affect the arguments.  The address of the argument is passed to the function and function modifies the values of the arguments in the calling function. Here is a program which illustrates the working of pass by reference mechanism.

#include<iostream>
using namespace std;
int add(int &number);
int main ()
{
            int number;
            int result;
            number=5;
            cout << "The value of the variable number before calling the function : " << number << endl;
            result=add(&number);
            cout << "The value of the variable number after the function is returned : " << number << endl;
            cout << "The value of result : " << result << endl;
            return(0);
}
int add(int &p)
{
            *p=*p+100;
            return(*p);
}

The result of the program is :


The address of the variable is passed to the function. The variable p points to the memory address of the variable number. The value is incremented by 100. It changes the actual contents of the variable number. The value of variable number before calling the function is 100 and after the function is returned the value of variable number is changed to 105.


Fungsi dalam C++

Fungsi sedang membangun blok program. Mereka membuat program yang lebih modular dan mudah untuk membaca dan mengatur. Semua C + + program harus mengandung fungsi main (). Pelaksanaan program ini dimulai dari fungsi main (). A C + + program dapat berisi sejumlah fungsi sesuai dengan kebutuhan. Bentuk umum dari fungsi adalah: -
return_type function_name (daftar parameter)
{
tubuh fungsi
}
Fungsi terdiri dari dua bagian kepala fungsi dan fungsi tubuh. Header fungsi: 

return_type function_name (daftar parameter)
Return_type menentukan jenis data fungsi kembali. Return_type dapat kekosongan yang berarti fungsi tidak mengembalikan tipe data. Function_name adalah nama fungsi. Nama fungsi harus diawali dengan huruf atau garis bawah. Daftar parameter terdiri dari variabel dipisahkan dengan koma bersama dengan jenis data mereka. Daftar parameter bisa kosong yang berarti fungsi tidak mengandung parameter. Daftar parameter harus berisi baik tipe data dan nama dari variabel. Misalnya, 

int faktorial (int n, float j)
Adalah header fungsi fungsi faktorial. Jenis kembali adalah integer yang berarti fungsi harus mengembalikan data tipe integer. Daftar parameter berisi dua variabel n dan j bertipe integer dan float masing. Tubuh fungsi melakukan perhitungan. 

Fungsi Deklarasi
Sebuah deklarasi fungsi dibuat dengan menyatakan jenis kembalinya nama, fungsi fungsi dan tipe data dari parameter fungsi. Sebuah deklarasi fungsi yang sama dengan deklarasi variabel. Deklarasi fungsi selalu diakhiri dengan titik koma. Sebuah panggilan ke fungsi tidak dapat dibuat kecuali dinyatakan. Bentuk umum dari deklarasi adalah: 

return_type function_name (daftar parameter);
Misalnya deklarasi fungsi dapat 

·         int faktorial (int n1, float j1); 

Nama variabel tidak perlu sama dengan variabel daftar parameter fungsi. Metode lain bisa 

·         int faktorial (int, float); 

Variabel dalam deklarasi fungsi dapat opsional tapi jenis data yang diperlukan. 

Argumen Fungsi
Informasi ini ditransfer ke fungsi dengan sarana argumen ketika panggilan ke fungsi dibuat. Argumen berisi nilai aktual yang akan dilewatkan ke fungsi ketika dipanggil. Urutan argumen dalam panggilan fungsi harus sama dengan urutan parameter dalam daftar parameter deklarasi fungsi. Tipe data dari argumen harus sesuai dengan tipe data dari parameter. Ketika panggilan fungsi membuat argumen menggantikan parameter dari fungsi. 

Pernyataan Kembali dan nilai-nilai Kembali
Sebuah pernyataan kembali digunakan untuk keluar dari fungsi mana itu. Ia mengembalikan pelaksanaan program ke titik di mana fungsi panggil dibuat. Ini mengembalikan nilai ke kode panggilan. Bentuk umum dari pernyataan kembali adalah: 

kembali berekspresi; 

Ekspresi bernilai nilai yang memiliki tipe yang sama sebagai jenis kembali ditentukan dalam deklarasi fungsi. Misalnya pernyataan, 

kembali (n); 

Adalah pernyataan kembali dari fungsi faktorial. Jenis variabel n harus bilangan bulat sebagaimana tercantum dalam deklarasi fungsi faktorial. Jika fungsi memiliki tipe kembali sebagai batal maka pernyataan kembali tidak mengandung ekspresi apapun. Hal ini ditulis sebagai: 

kembali; 

Fungsi dengan tipe kembali sebagai void dapat mengabaikan pernyataan kembali. Kawat gigi penutupan di akhir menunjukkan keluar dari fungsi. Berikut ini adalah sebuah program yang menggambarkan kerja dari fungsi. 

#include<iostream>
using namespace std;
int factorial(int n);
int main ()
{
            int n1,fact;
            cout <<"Masukkan nomor yang faktorial harus dihitung" <<  endl;
            cin >> n1;
            fact=factorial(n1);
            cout << "The factorial of " << n1 << " adalah : " << fact << endl;
            return(0);
}
int factorial(int n)
{
            int i=0,fact=1;
            if(n<=1)
            {
                        return(1);
            }
            else
            {
                        for(i=1;i<=n;i++)
                        {
                                    fact=fact*i;
                        }
                        return(fact);
            }
}

Hasil dari program ini adalah :


Fungsi faktorial menghitung faktorial dari nomor yang dimasukkan oleh pengguna. Jika jumlahnya kurang dari atau sama dengan 1 maka fungsi mengembalikan 1 lain itu mengembalikan faktorial dari jumlah tersebut. Pernyataan :
int faktorial (n int);
adalah deklarasi fungsi. Jenis kembali adalah integer. Daftar parameter terdiri dari satu tipe data yang integer. Pernyataan
cout << "Masukkan nomor yang faktorial harus dihitung" << endl;
cin >> n1;
membuat pengguna memasukkan nomor yang faktorial yang akan dihitung. The n1 variabel toko nomor yang dimasukkan oleh pengguna. Pengguna telah memasukkan nomor 5. Pernyataan
Bahkan = faktorial (n1);
membuat panggilan ke fungsi. The n1 variabel sekarang argumen untuk fungsi faktorial. Argumen dipetakan ke parameter dalam daftar parameter fungsi. Header fungsi
int faktorial (n int)

Tubuh fungsi berisi dua pernyataan kembali. Jika nilai yang dimasukkan oleh pengguna kurang dari atau sama dengan 1 maka nilai 1 dikembalikan lagi dihitung faktorial dikembalikan. Jenis ekspresi dikembalikan adalah integer. 

Parameter lewat mekanisme
Ada dua mekanisme passing parameter untuk melewati argumen untuk fungsi seperti lulus dengan nilai dan lulus dengan referensi.
Lulus dengan nilai
Dalam lulus menjadi salinan mekanisme nilai argumen yang dibuat dan yang disimpan di lokasi sementara memori. Parameter yang dipetakan ke salinan dari argumen dibuat. Perubahan yang dibuat untuk parameter tidak mempengaruhi argumen. Lewat mekanisme nilai menyediakan keamanan untuk program menelepon. Berikut ini adalah sebuah program yang menggambarkan kerja melewati mekanisme nilai. 

#include<iostream>
using namespace std;
int add(int n);
int main()
{
            int number,result;
            number=5;
            cout << " The initial value of number : " << number << endl;
            result=add(number);
            cout << " The final value of number : " << number << endl;
            cout << " The result is : " << result << endl;
            return(0);
}
int add(int number)
{
            number=number+100;
            return(number);
}

Hasil dari program ini adalah :



Nilai dari variabel nomor sebelum memanggil fungsi ini 5. Fungsi panggil dibuat dan fungsi menambahkan 100 ke nomor parameter. Ketika fungsi dikembalikan hasilnya mengandung nilai tambah. Nilai akhir dari nomor yang sama dengan 5. Hal ini menunjukkan bahwa operasi pada parameter tidak menghasilkan efek pada argumen. 
Lulus dengan referensi
Lulus dengan referensi adalah cara kedua melewati parameter ke fungsi. Alamat argumen tersebut disalin ke dalam parameter. Perubahan yang dibuat untuk parameter mempengaruhi argumen. Alamat dari argumen dilewatkan ke fungsi dan fungsi memodifikasi nilai-nilai argumen dalam pemanggilan fungsi. Berikut ini adalah sebuah program yang menggambarkan kerja melewati mekanisme rujukan. 

#include<iostream>
using namespace std;
int add(int &number);
int main ()
{
            int number;
            int result;
            number=5;
            cout << "The value of the variable number before calling the function : " << number << endl;
            result=add(&number);
            cout << "The value of the variable number after the function is returned : " << number << endl;
            cout << "The value of result : " << result << endl;
            return(0);
}
int add(int &p)
{
            *p=*p+100;
            return(*p);
}

Hasil dari program ini adalah :



Alamat dari variabel dilewatkan ke fungsi. Poin p variabel ke alamat memori dari jumlah variabel. Nilai ini bertambah dengan 100. Ini mengubah isi sebenarnya dari jumlah variabel. Nilai jumlah variabel sebelum memanggil fungsi adalah 100 dan setelah fungsi ini mengembalikan nilai jumlah variabel diubah menjadi 105.


..Selesai..

0 komentar:

Posting Komentar