Example:
int add(int a, int b) {
return a+b;
}
The function add() takes two integer parameters and returns the sum of the two numbers.
To call the function, we use the function name followed by the arguments in parentheses.
Example:
int sum = add(3, 5);
cout << sum;
This will output 8.
There are many built-in functions in C++ that are provided by the standard library.
For example, the function cin
is used to read input from the user, and the function cout
is used to display output to the user.
Example:
int num;
cin >> num;
cout << num;
This will read a number from the user and display it back to the user.
Other built-in functions include sqrt()
, pow()
, rand()
, etc.
These functions are provided by the standard library and can be used in your program without having to define them.
Example:
int num = sqrt(16);
cout << num;
#include <iostream>
using namespace std;
bool isEven(int num) { // data type of function is bool, means boolean values (true or false) is returned by this function
if(num%2==0) {
return true;
} else {
return false;
}
}
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
if(isEven(num)) { // pass num to isEven(), returns true if num is even
cout << num << " is even";
} else { // if isEven() returns false, num is odd
cout << num << " is odd";
}
}
Example:
Enter a number: 7
7 is prime
Enter a number: 8
8 is not prime
Use this code as a template:bool isPrime(int num) {
// code here
}
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
if(isPrime(num)) {
cout << num << " is prime";
} else {
cout << num << " is not prime";
}
}