Pages

Tampilkan postingan dengan label C plusplus. Tampilkan semua postingan
Tampilkan postingan dengan label C plusplus. Tampilkan semua postingan

Minggu, 16 Desember 2012

Fungsi C++


kali ini saya memosting sebuah program C++ mengenai fungsi pada C++




























source code :

#include <iostream.h>
#include <math.h>

void Panjang(int x_1, int x_2, int y_1, int y_2)
{
float hasil;
if(x_2==x_1)
{
hasil = abs (y_2 - y_1);
}
else if (y_2==y_1)
{
hasil= abs (x_2-x_1);
}
else
{
hasil=sqrt((x_2-x_1)*(x_2-x_1) + (y_2-y_1)*(y_2-y_1));
}
cout<<"hasil = "<<hasil;
}


int main()
{
int a, b, c, d;

cout<<"Masukkan Nilai X1 : ";
cin>>a;
cout<<"Masukkan Nilai X2 : ";
cin>>b;
cout<<"Masukkan Nilai Y1 : ";
cin>>c;
cout<<"Masukkan Nilai Y2 : ";
cin>>d;

Panjang(a,b,c,d);

cout<<"Selamat dan Sukses"<<endl;
cout<<"Agung Fajar Riyadi"<<endl;
cout<<"TI111034"<<endl;


return 0;

}

#screencapture :


Minggu, 09 Desember 2012

Function : Menentukan Waktu Tempuh

ini merupakan suatu program visual studio c++ yg bisa menampilkan waktu tempuh kendaraan. kali ini saya menggunakan rumus Fisika GLB (Gerak Lurus Beraturan) dan GLBB (Gerak Lurus Berubah Beraturan). Langsung saja bini listing Programnya :





Menggunakan Rumus GLB (Gerak Lurus Beraturan)
S = v.t

// agung.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream.h>


int waktu(int s,int v)
{
int hasil;
hasil = s / v;
return hasil;
}

int main()
{
int s,v,hasil;
cout <<"MENENTUKAN WAKTU TEMPUH KENDARAAN"<<endl;
cout <<"Masukkan jarak : ";
cin >> s;
cout <<"Masukkan kecepatan : ";
cin >> v;
hasil=waktu(s,v);
cout <<"Hasil = "<<hasil<<endl;
cout <<"Agung Fajar Riyadi"<<endl;
return 0;
}

Screencapture :

 Menggunakan Rumus GLBB (Gerak Lurus Berubah Beraturan)
V = Vo.at

// fajar.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream.h>

float waktu (float vo,float vt,float a)
{
float hasil;
hasil = vt / (vo + a);
return hasil;
}

int main()
{
float vo,vt,a,hasil;
cout <<"MENENTUKAN WAKTU TEMPUH KENDARAAN"<<endl;
cout <<"Masukkan kecepatan awal : ";
cin >> vo;
cout <<"Masukkan kecepatan akhir : ";
cin >> vt;
cout <<"Masukkan percepatan : ";
cin >> a;
hasil=waktu(vo,vt,a);
cout <<"Hasil = "<<hasil<<endl;
cout <<"Agung Fajar Riyadi"<<endl;
return 0;
}

screencapture :
selamat mencoba teman-teman :)

Kamis, 29 November 2012

Contoh Program Calculator Menggunakan Fungsi c++

 Listing program Calculator (By : Agung Fajar Riyadi)









// tugas fungsi.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream.h>


int main(int argc, char* argv[])
{
int x, y,awal;
char pil;
char jwb;

cout <<"1.Perkalian" << endl;
cout <<"2.Penjumlahan" << endl;
cout <<"3.Pembagian" << endl;
cout <<"4.Pengurangan" << endl;
cout <<"Pilihan Anda" << endl;
cin>>pil;
cout <<endl;

switch (pil)
{
case '1' : cout <<"Anda memilih menu Perkalian"<<endl;
cout << "masukan nilai ke 1"<<endl;
cin >> x;
cout << "Masukan nilai ke 2"<<endl;
cin >>y;
cout << "Hasi Perkalian = ";
cout << x * y <<endl;
break;
case '2' : cout <<"Anda memilih menu Penjumlahan"<<endl;
cout << "masukan nilai ke 1"<<endl;
cin >> x;
cout << "Masukan nilai ke 2"<<endl;
cin >>y;
cout << "Hasil Penjumblahan = ";
cout << x + y <<endl;
break;
case '3' : cout <<"Anda memilih menu Pembagian"<<endl;
cout << "masukan nilai ke 1"<<endl;
cin >> x;
cout << "Masukan nilai ke 2"<<endl;
cin >>y;
cout << "Hasil Pembagian = ";
cout << x / y <<endl;
break;
case '4' : cout <<"Anda memilih menu Pengurangan"<<endl;
cout << "masukan nilai ke 1"<<endl;
cin >> x;
cout << "Masukan nilai ke 2"<<endl;
cin >>y;
cout << "Hasil Pengurangan = ";
cout << x - y <<endl;
break;
}

{
cout << "Apakah penghitungan mau dilanjutkan(Y/T) \n";
cin >> jwb;
if (jwb=='y') {

return 0;
}
}


}


Screenshot Program :
*Awal

 *Pembagian
 *Pengurangan
 *Penjumlahan
 *Perkalian


*SEKIAN DAN TERIMAKASIH*


Kamis, 22 November 2012

Materi Function C++ (Indonesian Version)


Fungsi
Argumen melewati nilai dan dengan referensi.

Sampai saat ini, di semua fungsi yang telah kita lihat, argumen dilewatkan ke fungsi telah melewati nilai. Ini berarti bahwa ketika memanggil fungsi dengan parameter, apa yang telah kita dilewatkan ke fungsi adalah salinan dari nilai-nilai mereka tapi tidak pernah variabel itu sendiri. Sebagai contoh, misalkan kita disebut fungsi pertama kami selain menggunakan kode berikut:

 int x=5, y=3, z;
 z = addition ( x , y );

Apa yang kita lakukan dalam hal ini adalah untuk memanggil berfungsi selain mengirimkan nilai x dan y, yaitu 5 dan 3 masing-masing, tetapi tidak variabel x dan y sendiri.




Dengan cara ini, ketika penambahan fungsi disebut, nilai dari variabel lokal dan b menjadi 5 dan 3 masing-masing, tetapi setiap modifikasi baik atau b dalam penambahan fungsi tidak akan memiliki efek apapun dalam nilai-nilai x dan y luar itu, karena variabel x dan y sendiri tidak dilewatkan ke fungsi, tetapi hanya salinan dari nilai-nilai mereka pada saat fungsi dipanggil.

Tapi mungkin ada beberapa kasus di mana Anda perlu untuk memanipulasi dari dalam fungsi nilai dari variabel eksternal. Untuk itu kita dapat menggunakan argumen dikirimkan dengan referensi, seperti dalam fungsi duplikat dari contoh berikut:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// passing parameters by reference
#include <iostream>
using namespace std;

void duplicate (int& a, int& b, int& c)
{
  a*=2;
  b*=2;
  c*=2;
}

int main ()
{
  int x=1, y=3, z=7;
  duplicate (x, y, z);
  cout << "x=" << x << ", y=" << y << ", z=" << z;
  return 0;
}
x=2, y=6, z=14



Hal pertama yang harus menarik perhatian Anda adalah bahwa dalam deklarasi menduplikasi jenis parameter masing-masing diikuti dengan tanda ampersand (&). Ampersand ini adalah apa yang menetapkan bahwa argumen yang berhubungan harus dilalui oleh referensi bukan oleh nilai.

Ketika sebuah variabel dilewatkan dengan referensi kita tidak melewati salinan nilainya, tapi kami entah bagaimana melewati variabel itu sendiri dengan fungsi dan modifikasi apapun yang kita lakukan untuk variabel lokal akan berpengaruh dalam variabel rekan mereka lulus sebagai argumen panggilan ke fungsi.




Untuk menjelaskan hal itu dengan cara lain, kita kaitkan a, b dan c dengan argumen berlalu pada panggilan fungsi (x, y, dan z) dan setiap perubahan yang kami lakukan pada dalam fungsi akan mempengaruhi nilai x di luar itu. Setiap perubahan yang kami lakukan pada b akan mempengaruhi y, dan sama dengan c dan z.

Itulah sebabnya output program kita, yang menunjukkan nilai-nilai yang tersimpan dalam x, y, dan z setelah panggilan untuk menduplikasi, menunjukkan nilai-nilai dari semua tiga variabel utama dua kali lipat.

Jika ketika mendeklarasikan fungsi berikut:

 
void duplicate (int& a, int& b, int& c)


kami telah menyatakan dengan cara ini:

 
void duplicate (int a, int b, int c)


yaitu, tanpa tanda-tanda ampersand (&), kita akan tidak lulus variabel dengan referensi, namun salinan dari nilai-nilai mereka bukan, dan karena itu, output pada layar program kami akan menjadi nilai x, y, dan z tanpa yang telah dimodifikasi.

Lewat referensi juga merupakan cara yang efektif untuk memungkinkan fungsi untuk mengembalikan lebih dari satu nilai. Sebagai contoh, di sini adalah fungsi yang mengembalikan angka sebelumnya dan berikutnya dari parameter pertama berlalu.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// more than one returning value
#include <iostream>
using namespace std;

void prevnext (int x, int& prev, int& next)
{
  prev = x-1;
  next = x+1;
}

int main ()
{
  int x=100, y, z;
  prevnext (x, y, z);
  cout << "Previous=" << y << ", Next=" << z;
  return 0;
}
Previous=99, Next=101  


Standar nilai dalam parameter.
Ketika mendeklarasikan fungsi kita dapat menentukan nilai default untuk masing-masing parameter terakhir. Nilai ini akan digunakan jika argumen yang sesuai dibiarkan kosong saat memanggil ke fungsi. Untuk melakukan itu, kita hanya harus menggunakan operator penugasan dan nilai argumen dalam deklarasi fungsi. Jika nilai parameter yang tidak lulus saat fungsi ini dipanggil, nilai default digunakan, tetapi jika nilai tersebut ditentukan nilai default ini diabaikan dan nilai berlalu digunakan sebagai gantinya. Sebagai contoh:


// default values in functions
#include <iostream>
using namespace std;

int divide (int a, int b=2)
{
  int r;
  r=a/b;
  return (r);
}

int main ()
{
  cout << divide (12);
  cout << endl;
  cout << divide (20,4);
  return 0;
}


Seperti yang bisa kita lihat dalam tubuh program ada dua panggilan berfungsi membagi. Dalam yang pertama:

 
divide (12)


kita hanya ditentukan satu argumen, tapi membagi fungsi memungkinkan hingga dua. Jadi membagi fungsi telah diasumsikan bahwa parameter kedua adalah 2 karena itu adalah apa yang kita telah ditentukan untuk terjadi jika parameter ini tidak lulus (perhatikan deklarasi fungsi, yang berakhir dengan int = 2 b b, tidak hanya int). Oleh karena itu hasil dari pemanggilan fungsi ini adalah 6 (12/2).

Pada panggilan kedua:

 
divide (20,4)


ada dua parameter, sehingga nilai default untuk b (int b = 2) diabaikan dan b mengambil nilai yang dikirimkan sebagai argumen, yaitu 4, membuat hasilnya dikembalikan sebesar 5 (20/4).

Kelebihan beban fungsi.
Dalam C + + dua fungsi yang berbeda dapat memiliki nama yang sama jika parameter mereka jenis atau nomor berbeda. Itu berarti bahwa Anda dapat memberikan nama yang sama untuk lebih dari satu fungsi jika mereka memiliki sebuah nomor yang berbeda dari parameter atau jenis yang berbeda dalam parameter mereka. Sebagai contoh:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// overloaded function
#include <iostream>
using namespace std;

int operate (int a, int b)
{
  return (a*b);
}

float operate (float a, float b)
{
  return (a/b);
}

int main ()
{
  int x=5,y=2;
  float n=5.0,m=2.0;
  cout << operate (x,y);
  cout << "\n";
  cout << operate (n,m);
  cout << "\n";
  return 0;
}
10
2.5


Dalam kasus ini kita telah mendefinisikan dua fungsi dengan nama yang sama, beroperasi, tapi salah satu dari mereka menerima dua parameter bertipe int dan yang lainnya menerima mereka tipe float. Compiler tahu mana yang untuk memanggil setiap kasus dengan memeriksa jenis lulus sebagai argumen saat fungsi ini dipanggil. Jika disebut dengan dua ints sebagai argumen itu panggilan ke fungsi yang memiliki dua parameter int dalam prototipe dan jika hal itu disebut dengan dua mengapung ia akan menelepon ke salah satu yang memiliki dua parameter mengapung di prototipe.

Pada panggilan pertama untuk mengoperasikan dua argumen berlalu adalah dari tipe int, oleh karena itu, fungsi dengan prototipe pertama disebut, fungsi ini mengembalikan hasil perkalian dua parameter. Sedangkan panggilan kedua melewati dua argumen tipe float, sehingga fungsi dengan prototipe kedua disebut. Yang satu ini memiliki perilaku yang berbeda: ia membagi satu parameter oleh yang lain. Jadi perilaku panggilan untuk beroperasi tergantung pada jenis argumen berlalu karena fungsi telah kelebihan beban.

Perhatikan bahwa fungsi tidak dapat kelebihan beban hanya dengan jenis kembalinya. Setidaknya salah satu parameter yang harus memiliki tipe yang berbeda.

fungsi inline.
Specifier inline menunjukkan bahwa substitusi compiler inline lebih disukai untuk mekanisme pemanggilan fungsi biasa untuk fungsi tertentu. Hal ini tidak mengubah perilaku fungsi itu sendiri, tetapi digunakan untuk menunjukkan kepada compiler bahwa kode yang dihasilkan oleh fungsi tubuh dimasukkan pada setiap titik fungsi ini dipanggil, bukannya dimasukkan hanya sekali dan melakukan panggilan biasa untuk itu , yang umumnya melibatkan beberapa overhead tambahan dalam waktu berjalan.

Format untuk deklarasi adalah:

jenis inline Nama (argumen ...) {petunjuk ... }

dan panggilan seperti panggilan ke fungsi lainnya. Anda tidak perlu memasukkan kata kunci inline saat memanggil fungsi, hanya dalam deklarasi.

Sebagian besar kompiler sudah mengoptimalkan kode untuk menghasilkan fungsi inline ketika itu lebih nyaman. Ini specifier hanya menunjukkan bahwa compiler inline lebih disukai untuk fungsi ini.

Recursivity.
Recursivity adalah properti yang berfungsi harus dipanggil sendiri. Hal ini berguna untuk banyak tugas, seperti pemilahan atau menghitung faktorial dari angka. Misalnya, untuk mendapatkan faktorial dari sejumlah (n!) rumus matematika akan menjadi:

 n!  = N * (n-1) * (n-2) * (n-3) ...  * 1


lebih konkret, 5! (Faktorial 5) akan menjadi:

 5!  = 5 * 4 * 3 * 2 * 1 = 120


dan fungsi rekursif untuk menghitung ini dalam C + + dapat:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// factorial calculator
#include <iostream>
using namespace std;

long factorial (long a)
{
  if (a > 1)
   return (a * factorial (a-1));
  else
   return (1);
}

int main ()
{
  long number;
  cout << "Please type a number: ";
  cin >> number;
  cout << number << "! = " << factorial (number);
  return 0;
}
Please type a number: 9
9! = 362880  



Perhatikan bagaimana dalam fungsi faktorial kami termasuk panggilan untuk dirinya sendiri, tetapi hanya jika argumen berlalu lebih besar dari 1, karena jika fungsi akan melakukan loop rekursif tak terbatas di mana setelah tiba ke 0 akan terus mengalikan oleh semua angka negatif ( mungkin memprovokasi kesalahan stack overflow pada runtime).

Fungsi ini memiliki keterbatasan karena jenis data yang kita digunakan dalam desain (panjang) untuk kesederhanaan lebih. Hasil yang diberikan tidak akan berlaku untuk nilai-nilai yang jauh lebih besar dari 10! atau 15!, tergantung pada sistem Anda compile.

Mendeklarasikan fungsi.
Sampai saat ini, kita telah mendefinisikan semua fungsi sebelum penampilan pertama dari panggilan kepada mereka dalam kode sumber. Panggilan ini umumnya dalam fungsi utama yang kami selalu meninggalkan pada akhir kode sumber. Jika Anda mencoba untuk mengulangi beberapa contoh fungsi yang dijelaskan sejauh ini, tapi menempatkan fungsi utama sebelum salah satu fungsi lain yang disebut dari dalamnya, Anda kemungkinan besar akan mendapatkan kompilasi kesalahan. Alasannya adalah bahwa untuk dapat memanggil fungsi itu harus telah dinyatakan di beberapa titik sebelumnya dari kode, seperti yang telah kita lakukan di semua contoh kami.

Tapi ada cara alternatif untuk menghindari menulis kode seluruh fungsi sebelum dapat digunakan dalam utama atau dalam beberapa fungsi lainnya. Hal ini dapat dicapai dengan menyatakan hanya prototipe fungsi sebelum digunakan, bukan seluruh definisi. Deklarasi ini lebih pendek dari seluruh definisi, namun cukup signifikan untuk compiler untuk menentukan jenis kembali dan jenis parameter.

Bentuknya adalah:

ketik nama (argument_type1, argument_type2, ...);

Hal ini identik dengan definisi fungsi, kecuali bahwa ia tidak termasuk tubuh fungsi itu sendiri (yaitu, pernyataan fungsi bahwa dalam definisi normal diapit oleh kurung {}) dan bukannya kita mengakhiri deklarasi prototipe dengan titik koma wajib (;).

Pencacahan Parameter tidak perlu menyertakan pengenal, tetapi hanya penspesifikasi jenis. Dimasukkannya nama untuk setiap parameter seperti dalam definisi fungsi adalah opsional dalam deklarasi prototipe. Sebagai contoh, kita dapat mendeklarasikan fungsi yang disebut protofunction dengan dua parameter int dengan salah satu deklarasi berikut:


1
2
int protofunction (int first, int second);
int protofunction (int, int);


Pokoknya, termasuk nama untuk masing-masing variabel membuat prototipe lebih mudah dibaca.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// declaring functions prototypes
#include <iostream>
using namespace std;

void odd (int a);
void even (int a);

int main ()
{
  int i;
  do {
    cout << "Type a number (0 to exit): ";
    cin >> i;
    odd (i);
  } while (i!=0);
  return 0;
}

void odd (int a)
{
  if ((a%2)!=0) cout << "Number is odd.\n";
  else even (a);
}

void even (int a)
{
  if ((a%2)==0) cout << "Number is even.\n";
  else odd (a);
}
Type a number (0 to exit): 9
Number is odd.
Type a number (0 to exit): 6
Number is even.
Type a number (0 to exit): 1030
Number is even.
Type a number (0 to exit): 0
Number is even.



Contoh ini memang bukan contoh efisiensi. Saya yakin bahwa pada titik ini Anda sudah bisa membuat program dengan hasil yang sama, tetapi menggunakan hanya setengah dari baris kode yang telah digunakan dalam contoh ini. Pokoknya contoh ini menggambarkan bagaimana prototyping bekerja. Selain itu, dalam contoh beton prototipe dari setidaknya satu dari dua fungsi yang diperlukan dalam rangka untuk mengkompilasi kode tanpa kesalahan.

Hal pertama yang kita lihat adalah deklarasi fungsi ganjil dan genap:


1
2
void odd (int a);
void even (int a); 


Hal ini memungkinkan fungsi-fungsi yang akan digunakan sebelum mereka didefinisikan, misalnya, di utama, yang sekarang terletak di mana beberapa orang merasa menjadi tempat yang lebih logis untuk memulai sebuah program: awal dari kode sumber.

Pokoknya, alasan mengapa program ini membutuhkan setidaknya salah satu fungsi yang harus dideklarasikan sebelum didefinisikan karena dalam aneh ada panggilan untuk bahkan dan bahkan ada panggilan untuk aneh. Jika tidak ada dua fungsi sebelumnya telah menyatakan, kesalahan kompilasi akan terjadi, karena baik aneh tidak akan terlihat dari bahkan (karena masih belum dinyatakan), atau bahkan tidak akan terlihat dari aneh (untuk alasan yang sama) .

Memiliki prototipe dari semua fungsi bersama-sama di tempat yang sama dalam kode sumber ditemukan praktis oleh beberapa programmer, dan ini dapat dengan mudah dicapai dengan menyatakan semua prototipe fungsi pada awal program.

Materi Fungsi Bahasa C++ (English Version)


Arguments passed by value and by reference.


Until now, in all the functions we have seen, the arguments passed to the functions have been passed by value. This means that when calling a function with parameters, what we have passed to the function were copies of their values but never the variables themselves. For example, suppose that we called our first function additionusing the following code:

1
2
int x=5, y=3, z;
z = addition ( x , y ); 


What we did in this case was to call to function addition passing the values of x and y, i.e. 5 and 3 respectively, but not the variables x and y themselves.

 

This way, when the function addition is called, the value of its local variables a and b become 5 and 3 respectively, but any modification to either a or b within the function addition will not have any effect in the values of x and youtside it, because variables x and y were not themselves passed to the function, but only copies of their values at the moment the function was called.

But there might be some cases where you need to manipulate from inside a function the value of an external variable. For that purpose we can use arguments passed by reference, as in the function duplicate of the following example: 



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// passing parameters by reference
#include <iostream>
using namespace std;

void duplicate (int& a, int& b, int& c)
{
  a*=2;
  b*=2;
  c*=2;
}

int main ()
{
  int x=1, y=3, z=7;
  duplicate (x, y, z);
  cout << "x=" << x << ", y=" << y << ", z=" << z;
  return 0;
}
x=2, y=6, z=14


The first thing that should call your attention is that in the declaration of duplicate the type of each parameter was followed by an ampersand sign (&). This ampersand is what specifies that their corresponding arguments are to be passed by reference instead of by value.

When a variable is passed by reference we are not passing a copy of its value, but we are somehow passing the variable itself to the function and any modification that we do to the local variables will have an effect in their counterpart variables passed as arguments in the call to the function.

 

To explain it in another way, we associate a, b and c with the arguments passed on the function call (x, y and z) and any change that we do on a within the function will affect the value of x outside it. Any change that we do on bwill affect y, and the same with c and z. 

That is why our program's output, that shows the values stored in x, y and z after the call to duplicate, shows the values of all the three variables of main doubled.

If when declaring the following function:

 
void duplicate (int& a, int& b, int& c)


we had declared it this way:

 
void duplicate (int a, int b, int c)


i.e., without the ampersand signs (&), we would have not passed the variables by reference, but a copy of their values instead, and therefore, the output on screen of our program would have been the values of x, y and zwithout having been modified.

Passing by reference is also an effective way to allow a function to return more than one value. For example, here is a function that returns the previous and next numbers of the first parameter passed.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// more than one returning value
#include <iostream>
using namespace std;

void prevnext (int x, int& prev, int& next)
{
  prev = x-1;
  next = x+1;
}

int main ()
{
  int x=100, y, z;
  prevnext (x, y, z);
  cout << "Previous=" << y << ", Next=" << z;
  return 0;
}
Previous=99, Next=101  



Default values in parameters.

When declaring a function we can specify a default value for each of the last parameters. This value will be used if the corresponding argument is left blank when calling to the function. To do that, we simply have to use the assignment operator and a value for the arguments in the function declaration. If a value for that parameter is not passed when the function is called, the default value is used, but if a value is specified this default value is ignored and the passed value is used instead. For example: 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// default values in functions
#include <iostream>
using namespace std;

int divide (int a, int b=2)
{
  int r;
  r=a/b;
  return (r);
}

int main ()
{
  cout << divide (12);
  cout << endl;
  cout << divide (20,4);
  return 0;
}
6
5


As we can see in the body of the program there are two calls to function divide. In the first one:

 
divide (12)


we have only specified one argument, but the function divide allows up to two. So the function divide has assumed that the second parameter is 2 since that is what we have specified to happen if this parameter was not passed (notice the function declaration, which finishes with int b=2, not just int b). Therefore the result of this function call is 6 (12/2).

In the second call:



 
divide (20,4)


there are two parameters, so the default value for b (int b=2) is ignored and b takes the value passed as argument, that is 4, making the result returned equal to 5 (20/4).


Overloaded functions.

In C++ two different functions can have the same name if their parameter types or number are different. That means that you can give the same name to more than one function if they have either a different number of parameters or different types in their parameters. For example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// overloaded function
#include <iostream>
using namespace std;

int operate (int a, int b)
{
  return (a*b);
}

float operate (float a, float b)
{
  return (a/b);
}

int main ()
{
  int x=5,y=2;
  float n=5.0,m=2.0;
  cout << operate (x,y);
  cout << "\n";
  cout << operate (n,m);
  cout << "\n";
  return 0;
}
10
2.5


In this case we have defined two functions with the same name, operate, but one of them accepts two parameters of type int and the other one accepts them of type float. The compiler knows which one to call in each case by examining the types passed as arguments when the function is called. If it is called with two ints as its arguments it calls to the function that has two int parameters in its prototype and if it is called with two floats it will call to the one which has two float parameters in its prototype. 

In the first call to operate the two arguments passed are of type int, therefore, the function with the first prototype is called; This function returns the result of multiplying both parameters. While the second call passes two arguments of type float, so the function with the second prototype is called. This one has a different behavior: it divides one parameter by the other. So the behavior of a call to operate depends on the type of the arguments passed because the function has been overloaded.

Notice that a function cannot be overloaded only by its return type. At least one of its parameters must have a different type.


inline functions.

The inline specifier indicates the compiler that inline substitution is preferred to the usual function call mechanism for a specific function. This does not change the behavior of a function itself, but is used to suggest to the compiler that the code generated by the function body is inserted at each point the function is called, instead of being inserted only once and perform a regular call to it, which generally involves some additional overhead in running time.

The format for its declaration is:

inline type name ( arguments ... ) { instructions ... }
and the call is just like the call to any other function. You do not have to include the inline keyword when calling the function, only in its declaration.

Most compilers already optimize code to generate inline functions when it is more convenient. This specifier only indicates the compiler that inline is preferred for this function.



Recursivity.

Recursivity is the property that functions have to be called by themselves. It is useful for many tasks, like sorting or calculate the factorial of numbers. For example, to obtain the factorial of a number (n!) the mathematical formula would be:

n! = n * (n-1) * (n-2) * (n-3) ... * 1

more concretely, 5! (factorial of 5) would be:

5! = 5 * 4 * 3 * 2 * 1 = 120

and a recursive function to calculate this in C++ could be:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// factorial calculator
#include <iostream>
using namespace std;

long factorial (long a)
{
  if (a > 1)
   return (a * factorial (a-1));
  else
   return (1);
}

int main ()
{
  long number;
  cout << "Please type a number: ";
  cin >> number;
  cout << number << "! = " << factorial (number);
  return 0;
}
Please type a number: 9
9! = 362880  


Notice how in function factorial we included a call to itself, but only if the argument passed was greater than 1, since otherwise the function would perform an infinite recursive loop in which once it arrived to 0 it would continue multiplying by all the negative numbers (probably provoking a stack overflow error on runtime).

This function has a limitation because of the data type we used in its design (long) for more simplicity. The results given will not be valid for values much greater than 10! or 15!, depending on the system you compile it.


Declaring functions.

Until now, we have defined all of the functions before the first appearance of calls to them in the source code. These calls were generally in function main which we have always left at the end of the source code. If you try to repeat some of the examples of functions described so far, but placing the function main before any of the other functions that were called from within it, you will most likely obtain compiling errors. The reason is that to be able to call a function it must have been declared in some earlier point of the code, like we have done in all our examples.

But there is an alternative way to avoid writing the whole code of a function before it can be used in main or in some other function. This can be achieved by declaring just a prototype of the function before it is used, instead of the entire definition. This declaration is shorter than the entire definition, but significant enough for the compiler to determine its return type and the types of its parameters.

Its form is: 

type name ( argument_type1, argument_type2, ...);
It is identical to a function definition, except that it does not include the body of the function itself (i.e., the function statements that in normal definitions are enclosed in braces { }) and instead of that we end the prototype declaration with a mandatory semicolon (;).

The parameter enumeration does not need to include the identifiers, but only the type specifiers. The inclusion of a name for each parameter as in the function definition is optional in the prototype declaration. For example, we can declare a function called protofunction with two int parameters with any of the following declarations:

1
2
int protofunction (int first, int second);
int protofunction (int, int);
Anyway, including a name for each variable makes the prototype more legible.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// declaring functions prototypes
#include <iostream>
using namespace std;

void odd (int a);
void even (int a);

int main ()
{
  int i;
  do {
    cout << "Type a number (0 to exit): ";
    cin >> i;
    odd (i);
  } while (i!=0);
  return 0;
}

void odd (int a)
{
  if ((a%2)!=0) cout << "Number is odd.\n";
  else even (a);
}

void even (int a)
{
  if ((a%2)==0) cout << "Number is even.\n";
  else odd (a);
}
Type a number (0 to exit): 9
Number is odd.
Type a number (0 to exit): 6
Number is even.
Type a number (0 to exit): 1030
Number is even.
Type a number (0 to exit): 0
Number is even.


This example is indeed not an example of efficiency. I am sure that at this point you can already make a program with the same result, but using only half of the code lines that have been used in this example. Anyway this example illustrates how prototyping works. Moreover, in this concrete example the prototyping of at least one of the two functions is necessary in order to compile the code without errors.

The first things that we see are the declaration of functions odd and even: 


1
2
void odd (int a);
void even (int a); 


This allows these functions to be used before they are defined, for example, in main, which now is located where some people find it to be a more logical place for the start of a program: the beginning of the source code. 

Anyway, the reason why this program needs at least one of the functions to be declared before it is defined is because in odd there is a call to even and in even there is a call to odd. If none of the two functions had been previously declared, a compilation error would happen, since either odd would not be visible from even (because it has still not been declared), or even would not be visible from odd (for the same reason).

Having the prototype of all functions together in the same place within the source code is found practical by some programmers, and this can be easily achieved by declaring all functions prototypes at the beginning of a program.