CodeBlanks Logo Icon CodeBlanks

Declaring arrays

Learn to declare and initialize arrays with int[] and double[].

Declaring arrays

An array holds several values of the same type under one name. In C the array size goes in square brackets; the type comes first.

int scores[5];
double prices[10];
char name[32];

Here scores holds 5 integers, prices 10 decimals, name 32 characters. Arrays occupy contiguous memory; this makes access fast. After declaring, you assign values by index using square brackets.

Initializing arrays

You can give values when you declare the array. Write the values in a list inside braces.

int scores[5] = {85, 92, 78, 90, 88};
double temps[3] = {36.5, 37.0, 36.8};
char vowels[5] = {'a', 'e', 'i', 'o', 'u'};

If you omit the size the compiler counts the list: int scores[] = {85, 92, 78}; makes a three-element array. With fewer values, the rest become zero; useful for safe initialization.

Practice Declare three scores and print

Write a C program. Declare int scores[3] = {85, 92, 78};. Print the three values with printf("%d %d %d\n", scores[0], scores[1], scores[2]);. Put #include <stdio.h> at the top.

Starter code

main.c
#include <stdio.h>

int main(void) {
    // Declare scores and print the three values
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int main(void) {
    int scores[3] = {85, 92, 78};
    printf("%d %d %d\n", scores[0], scores[1], scores[2]);
    return 0;
}

Expected output

85 92 78

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How many values does int scores[5]; hold?

main.c
int scores[5];
  • 1
  • 5 Correct answer
  • 4
  • 6

Explanation: [5] makes a five-element array.

2 Complete the array declaration

Question
int ____[5];
Answer
int scores[5];

Explanation: scores is the array name.

3 Match the array parts

Term Meaning
int Type
scores Name
[5] Size
{1,2,3} Initialization

All lessons in Beginner