Functions
Functions
#include <iostream>
using namespace std;
// display a number
void displayNum(int n1, float n2) {
cout << "The int number is " << n1;
cout << "The double number is " << n2;
}
int main() {
int num1 = 5;
double num2 = 5.5;
return 0;
}
// program to add two numbers using a function
#include <iostream>
// declaring a function
int add(int a, int b) {
return (a + b);
}
int main() {
int sum;
return 0;
}
Default Arguments
A default argument is a value provided in a function
declaration that is automatically assigned by the compiler if
the calling function doesn’t provide a value for the
argument. In case any value is passed, the default value is
overridden.
// CPP Program to demonstrate Default Arguments
#include <iostream>
using namespace std;
// Driver Code
int main()
{
// Statement 1
cout << sum(10, 15) << endl;
// Statement 2
cout << sum(10, 15, 25) << endl;
// Statement 3
cout << sum(10, 15, 25, 30) << endl;
return 0;}
C++ program allow a user to input principal amount, time, and interest
rate, and then calculate and display the simple interest using a
customizable interest rate with a default value of 5.75%?
#include <iostream>
Actual parameter
Call by Value Method
Call by Reference Method
Call by value Call by reference
While calling a function, we pass the values of While calling a function, we pass the values of
variables to it. Such functions are known as “Call variables to it. Such functions are known as “Call
By Values”. While calling a function, instead By Values”. While calling a function, instead
of passing the values of variables, we pass the of passing the values of variables, we pass the
address of variables(location of variables) to the address of variables(location of variables) to the
function known as “Call By References. function known as “Call By References.
Original values remain unchanged outside the Original values can be modified inside the function.
function.
Requires additional memory for storing copies of More memory-efficient as it directly manipulates
parameters. original data.
This method is preferred when we have to pass some This method is preferred when we have to pass a large
small values that should not change. amount of data to the function.
Actual arguments remain safe as they cannot be Actual arguments are not Safe. They can be
modified accidentally. accidentally modified, so you need to handle
arguments operations carefully.
Write a C++ program to swap 2 values by writing
a function that uses call by reference technique.
#include <iostream>
using namespace std;
// Function prototype for swapping using call by reference
void swapNumbers(int &a, int &b);
int main() {
int num1 = 5;
int num2 = 10;
cout << "Before swapping: num1 = " << num1 << ", num2 = " << num2 <<endl;
int main() {
// Input three numbers
double num1, num2, num3;
return 0;
}