#include <iostream>
using namespace std;
void greet() {
cout << "Hello from a function!" << endl;
}
int main() {
greet(); // call the function
greet(); // call again
return 0;
}
Output:
Hello from a function!
Hello from a function!
Parameters and Arguments
void printInfo(string name, int age) {
cout << name << " is " << age << " years old." << endl;
}
int main() {
printInfo("Alice", 30);
printInfo("Bob", 25);
return 0;
}
int add(int a, int b) {
return a + b;
}
double circleArea(double r) {
return 3.14159 * r * r;
}
int main() {
cout << add(5, 3) << endl; // 8
cout << circleArea(5.0) << endl; // 78.54
return 0;
}
Function Overloading
Multiple functions can share the same name if they have different parameter lists:
int multiply(int a, int b) { return a * b; }
double multiply(double a, double b) { return a * b; }
cout << multiply(3, 4); // 12 (int version)
cout << multiply(2.5, 3.0); // 7.5 (double version)
Exercise
Write a function isPrime(int n) that returns true if n is prime. Use it to print all primes from 2 to 50.
Show Solution
#include <iostream>
using namespace std;
bool isPrime(int n) {
if (n < 2) return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) return false;
}
return true;
}
int main() {
for (int i = 2; i <= 50; i++) {
if (isPrime(i)) cout << i << " ";
}
cout << endl;
return 0;
}
Quiz
What keyword is used for a function that does not return a value?
A) null
B) none
C) void
D) empty
Answer
C) void
What is function overloading?
A) Calling a function too many times
B) Defining multiple functions with the same name but different parameters
C) A function calling itself
D) Running a function in parallel
Answer
B) Overloading allows the same function name to handle different argument types/counts.
Summary
Functions are reusable code blocks with a name, parameters, and return type.
Use void for functions that return nothing.
Default parameters allow optional arguments.
Function overloading enables same name, different signatures.