← C++ from Scratch
Lesson 28 of 62 · 10 XP
Functions
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
A function is a named piece of code that can be called many times:
int square(int x) // the result type, the name, the parameters
{
return x * x; // return — give back a value and exit
}
void greet() // void — returns nothing
{
std::cout << "Hi!\n";
}
int main()
{
std::cout << square(7) << '\n'; // 49
greet();
}
A function must be declared before it's called. If you want to write it below main, a
prototype goes at the top: int square(int x); — "there will be such a function".
Task. Write bool isPrime(int n) — whether a number is prime (divisible only by 1 and itself; 0 and 1 aren't prime).
Read n and print all the prime numbers from 2 to n separated by spaces.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.