🔄 Lesson 6: Loops (Repetition)
⏱️ Estimated time: 25 minutes | Difficulty: Beginner
Automation
Loops allow you to run the same block of code multiple times, which is essential for working with lists or performing repeated calculations.
What Are Functions?
Functions are reusable blocks of code that perform a specific task. They help organize your program and avoid repeating code.
Function Syntax:
return_type function_name(parameters) {
// function body
return value;
}
Creating Functions
#include <stdio.h>
// Function that returns a value
int add(int a, int b) {
return a + b;
}
// Function with no return value (void)
void greet(char name[]) {
printf("Hello, %s!\n", name);
}
// Function with no parameters
void printLine() {
printf("-------------------\n");
}
int main() {
int result = add(5, 3);
printf("5 + 3 = %d\n", result); // 8
greet("Alice"); // Hello, Alice!
printLine(); // -------------------
return 0;
}
Function Prototypes
If you define a function after main(), you need a prototype at the top:
#include <stdio.h>
// Prototype (declaration)
int multiply(int a, int b);
int main() {
printf("%d\n", multiply(4, 5)); // 20
return 0;
}
// Definition (after main)
int multiply(int a, int b) {
return a * b;
}
Pass by Value vs Pass by Reference
// Pass by value (copy)
void doubleValue(int x) {
x = x * 2; // Only changes the local copy
}
// Pass by reference (pointer)
void doubleRef(int *x) {
*x = *x * 2; // Changes the original!
}
int main() {
int num = 5;
doubleValue(num);
printf("%d\n", num); // Still 5!
doubleRef(&num);
printf("%d\n", num); // Now 10!
return 0;
}
Recursion
int factorial(int n) {
if (n <= 1) return 1; // Base case
return n * factorial(n - 1); // Recursive call
}
printf("%d\n", factorial(5)); // 120