Intermediate · C PROGRAMMING

Arrays and bounds

What you will learn

Store and traverse a fixed sequence of values.

Understand the concept

An array contains elements of one type in consecutive storage. Indexing starts at zero. sizeof the complete local array divided by sizeof one element gives its element count. size_t is an unsigned type used for sizes and indexes.

Read the example

The complete program appears below. Read it first, predict the output, then run it.

Expected output

Sum: 60

Practise

Add a fourth reading and calculate the average as a double.

Common mistake

The last valid index is count – 1. An out-of-bounds access has undefined behavior. The sizeof calculation does not work on an array parameter that has become a pointer.

Lesson discussion

Log in to participate.

#include <stdio.h>

int main(void) {
    int readings[] = {10, 20, 30};
    size_t count = sizeof readings / sizeof readings[0];
    int sum = 0;
    for (size_t i = 0; i < count; ++i) sum += readings[i];
    printf("Sum: %d\n", sum);
    return 0;
}
PRACTICE LAB

Read. Edit. Run.

C source · .c

Experiment with the program below. Your code and input are sent to the selected compiler only when you run it.

Tab indents · Shift+Tab unindents · Esc then Tab leaves the editor · Ctrl/Cmd+Enter runs · Ctrl/Cmd+S saves a draft

Changes save automatically to your account.

Input / output example

Example input
No input required.
Expected output for the original program
Sum: 60
Output will appear here.

Log in to save your progress

Ready when you are

Need help with your laptop or computer?

Send us the model and fault details. Start your repair request online or contact TCS Pune directly.

WA