Lecture 04
Lecture 04
A function is a block of code that performs a specific task. C++ program must contain
a main function to execute the other functions. Functions divide a complex problem
into smaller chunks and make our program easy to understand and reusable.
There are two types of function:
Standard Library Functions: Predefined in C++
User-defined Function: Created by users
int main() {
myFunction();
return 0;
}
# void means that the function does not have any return value.
Example of int-return type function:
int myFunction() {
int myVal1 = 10;
return myVal1;
}
int main() {
int myVal2 = 20;
cout << "Sum of two values = " << myFunction()+myVal2;
return 0;
}
int main() {
displaySum(10, 20);
displaySum(-5, 8);
return 0;
}
Example of int-return type function:
int max(int x, int y) {
if (x > y)
return x;
else
return y;
}
int main() {
int a = 10, b = 20;
int m = max(a, b);
cout << "Larger value is " << m;
return 0;
}
// function declaration
int max(int num1, int num2);
int main () {
int a = 100;
int b = 200;
int ret;
ret = max(a, b);
cout << "Max value is : " << ret << endl;
return 0;
}
// Function definition
int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Default parameter:
#include<iostream>
using namespace std;
//Function declaration
void addressFunction(string , int , string district="Gazipur");
int main()
{
addressFunction("Raja", 34);
return 0;
}
//Function definition
void addressFunction(string nickname, int age = 0, string district)
{
cout<<"Let's welcome "<<age<<" years old Mr/Ms "<<nickname<<"
from "<<district<<" in the C++ class.";
}