Function
Function
Syntax:
Data_type function_name(){
//block of code
}
Example:
void myFunction() {
// code to be executed
Example:
#include <iostream>
using namespace std;
void myFunction() {
cout << "object oriented programming\n";
}
int main() {
myFunction();
myFunction();
myFunction();
return 0;
}
Output:
object oriented programming
object oriented programming
object oriented programming
Syntax:
DataType FunctionName(parameter1,parameter2,parameter3){
//code to be executed
}
Example:
int c = a+b;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
myFunction("Sachin");
myFunction("virat");
myFunction("kapil");
return 0;
}
Output:
Hello, Sachin
Hello, virat
Hello, kapil
#include <iostream>
using namespace std;
int main() {
int a=10;
int b=20;
cout<<"before swap "<<”a =”<<a<<"b="<<b<<endl;
swap(a,b);
Output:
#include <iostream>
using namespace std;
void swap(int*a,int*b){
int temp =*a;
*a=*b;
*b=temp;
}
int main() {
int a=10;
int b=20;
cout<<"before swap "<<”a =”<<a<<"b="<<b<<endl;
swap(&a,&b);
cout<<"before swap "<<”a =”<<a<<"b="<<b;
return 0;
}
Ouput:
before swap a=10 b=20
after swap a=20 b=10
#include <iostream>
using namespace std;
class MyClass {
public:
void myMethod() {
cout << "Hello World!";
}
};
int main() {
MyClass myObj;
myObj.myMethod();
return 0;
}
Output:
Hello Wrold!
This is done by specifiying the name of the class, followed the scope
resolution :: operator, followed by the name of the function.
Example:
#include <iostream>
using namespace std;
class MyClass {
public:
void myMethod();
};
void MyClass::myMethod() {
cout << "Hello World!";
}
int main() {
MyClass myObj;
myObj.myMethod();
return 0;
}
Output:
Hello world!