Function

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

Example1

#include<iostream>
using namespace std;
void myFun1(string name){
cout<<"my name is:"<<name;
}
int main()
{
myFun1("Abdi");
return 0;
}
Example2
#include<iostream>
using namespace std;
void myFun1(string name, string classroom, float mark){
cout<<"my name is:"<<name<<endl;
cout<<"my class room is:"<<classroom<<endl;
cout<<"my mark in C++ is:"<<mark<<endl;
}
int main()
{
myFun1("Abdi", "comp lab 2",83.5 );

return 0;
}
………………………………………………………………………

Passing by Value
#include<iostream>
using namespace std;
void area(int a){
a=a+5;
cout<<a<<endl;
}
int main()
{
int a=5;
area(5);
cout<<a<<endl;
return 0;
}

Return Values
The void keyword, used in the previous examples, indicates that the function should not return a
value. If you want the function to return a value, you can use a data type (such as int, string, etc.)
instead of void, and use the return keyword inside the function:
Passing by Value
#include<iostream>
using namespace std;
void area(int a){
a=a+5;
cout<<a<<endl;
}
int main()
{
int a=5;
area(5);
cout<<a<<endl;
return 0;
}

Example 2// with two variable


#include <iostream>
using namespace std;
int myFunction(int x, int y) {
return x + y;
}
int main() {
cout << myFunction(5, 3);
return 0;
}

Function by Reference
In the examples from the previous page, we used normal variables when we passed parameters to a
function. You can also pass a reference to the function. This can be useful when you need to change
the value of the arguments:
#include <iostream>
using namespace std;
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}
int main() {
int firstNum = 10;
int secondNum = 20;
cout << "Before swap: " << "\n";
cout << firstNum << secondNum << "\n";
swapNums(firstNum, secondNum);
cout << "After swap: " << "\n";
cout << firstNum << secondNum << "\n";
return 0;
}

You might also like