Examples of functions in c++ programing

0

The function is a block of code that performs a specific task.

All Contributions

Write a program in function prototype :

#include <iostream>
using namespace std;
// function prototype
int add(int, int);
int main() {
    int sum;
    // calling the function and storing
    // the returned value in sum
    sum = add(150 , 85 );
    cout << "150 + 85 = " << sum << endl;

    return 0;
}
// function definition
int add(int a, int b) {
    return (a + b);
}

Write a Program to Find the Square Root of a Number :

#include <iostream>
#include <cmath>
using namespace std;
int main() {
    double number, squareRoot;   
    number = 25.0;
    // sqrt() is a library function to calculate the square root
    squareRoot = sqrt(number);
    cout << "Square root of " << number << " = " << squareRoot;

    return 0;
}

Write a program to add two numbers :

#include <iostream>
using namespace std;
// declaring a function
int add(int a, int b) {
    return (a + b);
}

int main() 
{
    int sum;   
    // calling the function and storing
    // the returned value in sum
    sum = add(100, 78);
    cout << "100 + 78 = " << sum << endl;

    return 0;
}

Function with parameters :

#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;
    // calling the function
    displayNum(num1, num2);

    return 0;
}

Write a program to print a message :

#include <iostream>
using namespace std;
// declaring a function
void greet() {
    cout << "Hello there!";
}
int main() {
    // calling the function
    greet();

    return 0;
}

total contributions (5)

New to examplegeek.com?

Join us