Functions and collections · Lesson 6 of 21
Functions
Defining and returning, default arguments, and overloading.
A function is named code you call when needed. In C++ you write the type it returns before the name (int, double, or void for nothing) and the type of every parameter.
#include <iostream>
#include <string>
double average(int total, int count) {
if (count == 0) return 0;
return static_cast<double>(total) / count;
}
void greet(const std::string& name, const std::string& greeting = "Welcome") {
std::cout << greeting << ", " << name << "!\n";
}
int main() {
std::cout << average(17, 4) << "\n";
greet("Omar");
greet("Nour", "Good morning");
return 0;
}greeting has a default value, so leaving it out gives "Welcome". Defaults must come last in the parameter list.
Overloading: same name, different types
#include <iostream>
#include <string>
int twice(int x) { return x * 2; }
double twice(double x) { return x * 2; }
std::string twice(const std::string& s) { return s + s; }
int main() {
std::cout << twice(21) << "\n";
std::cout << twice(1.25) << "\n";
std::cout << twice(std::string("ha")) << "\n";
return 0;
}twice(21)
the compiler sees the type: int
picks int twice(int)
The choice happens at compile time, not while running.
Complete the code
Complete the function that returns the larger of two numbers.
#include <iostream> larger(int a, int b) { a > b ? a : b; } int main() { std::cout << larger(3, 8) << "\n"; }
Exercise
Write bool isPrime(int n) and use it to print the primes from 2 to 30 on one line, separated by spaces.
Expected output: 2 3 5 7 11 13 17 19 23 29
#include <iostream>
bool isPrime(int n) {
}
int main() {
for (int i = 2; i <= 30; i++) {
if (isPrime(i)) std::cout << i << " ";
}
std::cout << "\n";
return 0;
}Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.