[Legacy Content] This page contains very old information, which might not be valid anymore, they are only kept here for legacy purposes.
if you have any inquiries, feel free to contact me! Click here

Arrays

Created: Monday, 12 August 2013 Written by Ehab Eldeeb

An Array is simply a "column" or a "row" of data of the same type

Arrays can have one dimension, or N dimensions

 

Arrays having one dimension are called "1D Arrays"

 

How to define a 1D array?

Define it just like any normal variable, you define integer x as "int x;"

Defining an array is similar, but you put the length of the array "number of variables in the row or column"

define it as  int x[10]; ... Like that we defined an array of integers called x with length of 10 (we can add 10 integers in this array)

 

To deal with an array, you MUST use a for loop like this
for(int i = 0; i < SIZE; i++) ... Where SIZE is the size of the array

Now let's write a program that reads an array of 5 integers and find the maximum number in them

 

#include <stdio.h>
#include <conio.h>

void main(){
    int array[5];
    int i,j,k,max;
    for(i = 0; i < 5; i++){
        printf("Enter Number %d: ", i + 1);
        scanf("%d", &array[i]);
    }
max = array[0]; // set maximum number to first slot
        for(k = 0; k < 5; k++){
            if(array[k] > max) // if that k is larger than max, set it to be the max
                max = array[k];
        }

        printf("Max number is: %d", max);
        getch();
}

 

2D Arrays

2D arrays have the same concept of 1D array, but with two dimensions (rows and columns together)

#include <stdio.h>
#include <conio.h>

int main(){
    int x[5][5], y[5][5]; // two 2D arrays of row=5 and column=5

    // Read both 2D arrays
    for (int i = 0; i < 5; i++){ // Rows
        for (int j = 0; j < 5; j++){ // Columns
            printf("Enter Both Values for 2D arrays: ");
            scanf("%d%d", &x[i][j], &y[i][j]);
        }
    }
    getch();
    return 0;
}

 

ND Arrays

You can create multi-dimension arrays, there's no restriction! 3D 4D 5D .......... etc.

for each dimension you will need an extra for loop to deal with the array

You don't have to know more than that :)