Declare a Function
Part of the Fundamentals section of Coddy's C journey — lesson 46 of 63.
A function in C is a block of code that performs a specific task. Functions help organize code, make it reusable, and improve readability. Here's the basic structure of a function declaration in C:
return_type function_name(parameter1_type parameter1_name, parameter2_type parameter2_name, ...) {
// code to be executed
return value; // if the return_type is not void
}For example, a simple function that greets the user might look like this:
void greet() {
printf("Hello, welcome to C programming!");
}To use (call) this function in your main program, you would write:
int main() {
greet();
return 0;
}Functions can also take parameters and return values, which we'll explore in later lessons.
Challenge
EasyCreate a function named printNumbers that prints the numbers from 1 to 5. Then, in the main function, call this function twice.
Your output should look like this:
1 2 3 4 5
1 2 3 4 5Make sure not to include any spacing after the number 5, and also add a new line after the number 5 (\n)
Cheat sheet
A function in C is a block of code that performs a specific task. Functions help organize code, make it reusable, and improve readability.
Basic function structure:
return_type function_name(parameter1_type parameter1_name, parameter2_type parameter2_name, ...) {
// code to be executed
return value; // if the return_type is not void
}Example of a simple function:
void greet() {
printf("Hello, welcome to C programming!");
}To call a function:
int main() {
greet();
return 0;
}Try it yourself
#include <stdio.h>
// Declare your function here
int main() {
// Call your function twice here
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Control Flow
If StatementIf - ElseElse-IfSwitch CaseTernary Conditional OperatorRecap ChallengeNested If - Else7Functions
Declare a FunctionReturn TypesParametersRecap Challenge #1Recursion BasicsFunction PrototypesRecap Challenge #23Operators
Arithmetic OperatorsModulo OperatorIncrement/DecrementAssignment OperatorsRelational OperatorsLogical Operators Part 1Logical Operators Part 2Logical Operators Part 3Recap Challenge