Module 5 C - Function
Module 5 C - Function
C++ Function
Samin, Maylene V.
11:11PM
User-defined
Function
A function is a block of code
which only runs when it is called.
You can pass data, known as
parameters, into a function.
Functions are used to perform
certain actions, and they are
important for reusing code:
Define the code once, and use it
many times.
How to call a
fuction? · Declared functions are not
executed immediately. They are
"saved for later use", and will be
executed later, when they are
called.
· To call a function, write the
function's name followed by two
parentheses () and a semicolon ;
Example:
#include<iostream>
using namespace std;
void myFunction()
{
cout << "Hello!";
}
int main()
{
myFunction();
}
n Header • Section Header • Section Header • Section Header • Section Header • Section Header • Section Header • Section H
Function with
Parameters
Back to Agenda Page
n Header • Section Header • Section Header • Section Header • Section Header • Section Header • Section Header • Section H
Function with Parameters
Information can be passed to functions as a parameter.
Parameters act as variables inside the function.
Parameters are specified after the function name, inside
the parentheses. You can add as many parameters as
you want, just separate them with a comma:
11:11PM
Syntax:
11:11PM
Example:
int addition(int a, int b)
{
int sum;
sum=a+b;
return sum;
}
*function add has two parameters (a)(b) which means it is expecting two
inputs, the function body returns the value of the sum, where sum = a+b.
11:11PM
Problem 1: Write a program with 1 user-defined function (add) and will
let the user input two numbers. Compute and print the sum of the two
inputted numbers using function add.
11:11PM
#include<iostream>
using namespace std;
int add(int a, int b)
{
int sum;
sum=a+b;
return sum;
}
int main()
{
int s, n1, n2;
cout<<"Enter first number:";
cin>>n1;
cout<<"Enter second number:";
cin>>n2;
s=add(n1,n2);
cout<<"Sum is "<<s;
}
Seatwork:
Write a program with 2 user-defined
functions (add)(multiply) and will accept
two numbers. Print the sum and
product of the two inputted numbers
using function add and multiply.
11:11PM
#include<iostream>
using namespace std;
int add(int a, int b)
{
int sum;
sum=a+b;
return sum;
}
int multiply(int a, int b)
{
int product;
product=a*b;
return product;
}
int main()
{
int s,p, n1, n2;
cout<<"Enter first number:";
cin>>n1;
cout<<"Enter second number:";
cin>>n2;
s=add(n1,n2);
p=multiply(n1,n2);
cout<<"Sum is "<<s;
cout<<"Product is "<<p;