Functions
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
A function in C declares the type of its result, its name and its parameters with their types:
int square(int x)
{
return x * x;
}
int main(void)
{
printf("%d\n", square(5)); // 25
return 0;
}
If a function returns nothing, its type is void:
void greet(void)
{
printf("Hello!\n");
}
In C a function must be declared before its first use. That's why helper functions are usually written above main (or declared in advance — that's the "Declaring functions" lesson).
return ends the function immediately. In a function of type int, every path of execution must end with a return with a value; otherwise the result is undefined.
Task. Write a function int is_prime(int n) that returns 1 if n is prime and 0 otherwise. In main, read a number and print prime or not prime.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.