Functions in C++
#include <iostream>
using namespace std;
// 1. Definition: Creating the "recipe"
void greetUser(string name) {
cout << "Hello, " << name << "!" << endl;
}
int main() {
// 2. Calling: Executing the "recipe"
greetUser("Ram");
greetUser("Sameer");
return 0;
}
Write a function to add two numbers.
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
int main() {
cout << "Sum = " << add(10, 5);
return 0;
}
Write a function to find the maximum of two numbers.
#include <iostream>
using namespace std;
int maximum(int a, int b) {
if (a > b)
return a;
else
return b;
}
int main() {
cout << "Maximum = " << maximum(12, 20);
return 0;
}
Write a function to check whether a number is even or odd.
#include <iostream>
using namespace std;
bool isEven(int n) {
return (n % 2 == 0);
}
int main() {
int num = 7;
if (isEven(num))
cout << "Even";
else
cout << "Odd";
return 0;
}
Write a function to check prime number.
#include <iostream>
using namespace std;
bool isPrime(int n) {
if (n <= 1)
return false;
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0)
return false;
}
return true;
}
int main() {
int num = 11;
if (isPrime(num))
cout << "Prime";
else
cout << "Not Prime";
return 0;
}
Write a function to reverse a number.
#include <iostream>
using namespace std;
int reverseNumber(int n) {
int rev = 0;
while (n != 0) {
rev = rev * 10 + n % 10;
n /= 10;
}
return rev;
}
int main() {
cout << "Reverse = " << reverseNumber(1234);
return 0;
}
Swap two numbers using function.
#include <iostream>
using namespace std;
void swapNumbers(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 5, y = 10;
swapNumbers(x, y);
cout << "After Swap: x = " << x << ", y = " << y;
return 0;
}
Pass by Value & Pass by Reference
#include <iostream>
using namespace std;
// Pass by Value: 'num' is a local copy
void squareByValue(int num) {
num = num * num;
}
// Pass by Reference: 'num' is an alias for the original variable
void squareByReference(int &num) {
num = num * num;
}
int main() {
int x = 5;
int y = 5;
squareByValue(x);
cout << "Value of x: " << x << endl; // Output: 5 (unchanged)
squareByReference(y);
cout << "Value of y: " << y << endl; // Output: 25 (changed!)
return 0;
}
Built-in and User-Defined Functions
#include <iostream>
#include <cmath> // Required for built-in math functions
using namespace std;
// --- USER-DEFINED FUNCTION ---
double calculateHypotenuse(double a, double b) {
return sqrt((a * a) + (b * b)); //Built-in function : sqrt
}
int main() {
double side1, side2;
cout << "Enter the length of side A: ";
cin >> side1;
cout << "Enter the length of side B: ";
cin >> side2;
// Calling our user-defined function
double result = calculateHypotenuse(side1, side2);
cout << "The hypotenuse is: " << result << endl;
return 0;
}