Lesson 4 of 5

Functions and Arrays

Organising Code with Functions

A function in C is a named block of code with a declared return type and a list of typed parameters. Functions keep large programs manageable.

Defining and Calling a Function

#include <stdio.h>

int add(int x, int y) {
    return x + y;
}

int main(void) {
    int result = add(8, 5);
    printf("Sum is %d\n", result);   // Sum is 13
    return 0;
}

The word int before add is the return type — it states that the function gives back an integer. A function that returns nothing uses the type void.

Function Prototypes

If you define a function below main, the compiler needs a prototype near the top so it knows the function's shape in advance.

int multiply(int a, int b);   // prototype, note the semicolon

int main(void) {
    printf("%d\n", multiply(4, 6));
    return 0;
}

int multiply(int a, int b) {  // full definition
    return a * b;
}

Arrays: Many Values, One Name

An array stores a fixed number of values of the same type. You access each element by an index, and indexes start at 0.

int marks[5] = {70, 85, 90, 65, 80};

printf("First mark: %d\n", marks[0]);   // 70
printf("Third mark: %d\n", marks[2]);   // 90

An array of size 5 has valid indexes 0 to 4. Index 5 does not exist; using it reads memory outside the array and causes undefined behaviour.

Looping Over an Array

A for loop is the natural way to visit every element.

int marks[5] = {70, 85, 90, 65, 80};
int total = 0;

for (int i = 0; i < 5; i++) {
    total = total + marks[i];
}
printf("Total: %d\n", total);   // 390

Strings as Character Arrays

In C a string is simply an array of char that ends with a special '\0' null character marking the end.

char name[] = "DCCPS";
printf("%s\n", name);
C does not check array bounds for you. Reading or writing past the end of an array is a serious bug, so always keep your loop within the array size.
Next
How did you find this lesson?

Discussion

0
To join the discussion, comment and react, log in or create an account.

No comments yet — be the first to leave one!