Easy Tutorial: Computer Programming for DUMMIES -- very easy!

Hey guys! This is a continuation of my programming tutorials in C++. If you need to catch up, here are links to the others:

Part 1: Hello World!

Part 2: Variables

Part 3: Functions

Part 4: if(), else, else if()

Part 5: Loops

Part 6: Arrays <-- Definitely check that one out before this tutorial

Part 7: Basic Input/Output

Part 9: Sorting Arrays

Part 10: Random Numbers

Part 11: Colored Text in your Terminal

Part 12: Recursion

Part 13: Binary Search

This tutorial is about 2D arrays. As you know, an array is a list or set of elements. A 2D array is like a list of lists (or a set of sets). Here are a few different ways you can declare a 2D array:

int arr[10][5];
int arr1[][4] = { {1,2,3,4},
                  {5,6,7,8},
                  {9,0,1,2} };
int arr2[3][4] = { {1,2,3,4},
                   {5,6,7,8},
                   {9,0,1,2} };
  • arr1 and arr2 are equivalent.
  • If you equate the array to values on the same line as you declare it, then the first set of brackets does not need a number, meaning its size being declared (although, the second set of brackets does).

Here is an example of how a 2D array is called:

cout << arr1[1][2];

This will print the value 7 (1 represents the second set; 2 represents the third value of the set)

More examples:

  • arr1[0][0] --> 1
  • arr1[0][2] --> 3
  • arr1[2][3] --> 2
  • arr1[2][0] --> 9
  • arr1[3][3] --> 2

An integer array is pretty much just a matrix.

... not that kind of matrix! Like this one:

That is the basics of a 2D array. Here is a little program I wrote implementing 2D arrays:

#include
using namespace std;

int main()
{
    int arr1[][4] = { {1,2,3,4},
                      {5,6,7,8},
                      {9,0,1,2} };

    for(int x = 0; x < 3; x++)
    {
        for(int y = 0; y < 4; y++)
            cout << arr1[x][y] << " ";
        cout << endl;
    }
    
    char str[][10] = { {'T','h','i','s','\0'},
                       {'i','s','\0'},
                       {'a','\0'},
                       {'s','t','r','i','n','g','\0'},
                       {'a','r','r','a','y','\0'} };

    for(int x = 0; x < 5; x++)
        cout << str[x] << " ";
    cout << endl;

    return 0;
}

Output:

[cmw4026@omega test]$ g++ 2d.c
[cmw4026@omega test]$ ./a.out
1 2 3 4
5 6 7 8
9 0 1 2
This is a string array
[cmw4026@omega test]$

Notice how I could print str[x] as a string. A string is just a character array... So a 2D character array is really just an array of strings!

I hope this helped! Leave suggestions in the comments!

H2
H3
H4
3 columns
2 columns
1 column
4 Comments