Wednesday, February 4, 2026

Popular C++ Function Practicals

Followings are popular C++ Function Practicals that every beginners must know.


1. Function to find Sum of Two Numbers.
Concept: Function with arguments and return value

#include <iostream>
using namespace std;

int add(int a, int b) {
    return a + b;
}

int main() {
    int x, y;
    cout << "Enter two numbers: ";
    cin >> x >> y;
    cout << "Sum = " << add(x, y);
    return 0;
}

Output:

Enter two numbers: 5 6
Sum = 11

2. Function to check Even or Odd numbers.
Concept: Function with argument, no return value

#include <iostream>
using namespace std;

void checkEvenOdd(int n) {
    if (n % 2 == 0)
        cout << "Even number";
    else
        cout << "Odd number";
}

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;
    checkEvenOdd(num);
    return 0;
}

Output:
Enter a number: 5
Odd number

3. Function to find Factorial of a Number.
Concept: Recursive function

#include <iostream>
using namespace std;

int factorial(int n) {
    if (n == 0)
        return 1;
    return n * factorial(n - 1);
}

int main() {
    int n;
    cout << "Enter a number: ";
    cin >> n;
    cout << "Factorial = " << factorial(n);
    return 0;
}

Output:
Enter a number: 4
Factorial = 24

4. Function to find Maximum of Two Numbers
Concept: Function with arguments and return value

#include <iostream>
using namespace std;

int maxNumber(int a, int b) {
    if (a > b)
        return a;
    else
        return b;
}

int main() {
    int a, b;
    cout << "Enter two numbers: ";
    cin >> a >> b;
    cout << "Maximum = " << maxNumber(a, b);
    return 0;
}

Output:
Enter two numbers: 5 6
Maximum = 6

5. Function to Swap Two Numbers (Call by Value)
Concept: Function basics (introduction before pointers)

#include <iostream>
using namespace std;

void swapNumbers(int a, int b) {
    int temp = a;
    a = b;
    b = temp;
    cout << "Inside function: a = " << a << ", b = " << b;
}

int main() {
    int x = 5, y = 10;
    swapNumbers(x, y);
    cout << "\nOutside function: x = " << x << ", y = " << y;
    return 0;
}

Output:

Inside function: a = 10, b = 5
Outside function: x = 5, y = 10


* * * * *

No comments:

Post a Comment