c > arrays > arrays

Arrays

Arrays are a way for us to store many values of a certain datatype under the same name. Other languages have sets, lists and dictionaries which serve a similar purpose. This saves us the time and energy of having to create unique names for each value we want to store.

The format for defining an array is:

type array_name[number_of_values];

Integer arrays

We can populate an integer array by including the values in curly braces:


#include <stdio.h>
#include <math.h>

int main(){
    int numbers[90] = {9,4,5};

    for (int i=0;i<10;i++){
        printf("The number at index %d is %d\n",i,numbers[i]);
    }

    return 0;
}

↗ Open 📋 Copy c/arrays/populating_an_integer_array.c


#include <stdio.h>
#include <math.h>

int main(){
    int numbers[90];
    

    for (int i=0;i<90;i++){
        numbers[i] = pow(i+1,3);
    }

    for (int i=0;i<30;i++){
        printf("The number at index %d is %d\n",i,numbers[i]);
    }

    return 0;
}

↗ Open 📋 Copy c/arrays/traversing_an_integer_array.c

Strings (character arrays)

An array of characters is known as a string. We can declare a string using double quotations:

char name[10] = "John Doe";

We do not need to specify the number of characters if we use the double quotations:

char name[] = "John Doe";

We can traverse a string:


#include <stdio.h>
#include <string.h>

int main(){
    // there is no need to manually count the string size so we use []
    char word[] = "Hello there comrade";
    int count = 0;

    // traversing the string in the forward direction
    for (int i=0;i<strlen(word);i++){
        
        // printing the current letter
        printf("The letter at index %d is %c\n",i,word[i]);
        
        // incrementing count if the current letter is an 'a'
        if (word[i]=='a'){
            count++;
        }
    }
    printf("We found %d a's in \"%s\"\n",count,word);

    // traversing the string in reverse
    printf("The reverse of the word is ");
    for (int i=strlen(word)-1;i>=0;i--){
        printf("%c",word[i]);
    }

}

↗ Open 📋 Copy c/arrays/traversing_a_string.c