Tutorial 7 - Structures & Multidimensional Arrays //Learn by doing

in #programming8 years ago

header

Welcome to my seventh tutorial, this tutorial will go in depth to show you extra things that you can do.

These should be considered valuable, as you should know from science, as everything new, which may seem useless to some, eventually begins having a lot of applications.

First off I'm going to start with Multi Dimensional Arrays Which I will describe why they're useful.

img

#include <iostream>
#include <string>
using namespace std;
int main()
{
    system("cls");
    cout << "Welcome to my multi-dimensional array tutorial.\n"
         << "Since we've talked about games, let's say for instance...\n"
         << "That we would like to store the game \"Map\" in a more efficient manner.\n"
         << "An idea, good or bad, depending on what you're creating, \ncould be be using this:\n";
    //What is a Multi Dimensional array?
    //That's kind of simple, multiple dimensions.
    //Yeah except how do you do that in one single array?
    //Well it's easy for example, an array that stores ints looks like"
    //int array[2]; but this only has positions at 0, 1, 2.
    int array[2];
    array[0] = 20; //This is to remind you arrays start from 0.
    array[1] = 21; //This is where our size 2 array would end.
    cout << array[0] << endl;
    cout << array[1] << endl;
    cout << "Press enter to Continue...";
    cin.get(); // Hey, did you know you can avoid using system("pause")?
            //Since now you're more used to c++ you should, as it generates a lot of problems!
            //It should only be used for yourself!
    //Alright but that's a one dimensional array! it stores only 2 values.
    //How do we make a multi dimesional one? well we kinda multiply for example 2 x 2
    //makes a 2x2 array.
    system("cls");
    string map[2][2];//This in pseudo code would be the equivalent of 2x2
    map[0][0] = "0";
    map[0][1] = "1";
    map[1][0] = "2";
    map[1][1] = "3";
    cout << map[0][0];
    cout << map[0][1] << endl;
    cout << map[1][0];
    cout << map[1][1] << endl;
    cin.get();
    // This should show you exactly how it works, it doesn't have to be 2x2, 
    //  it can be just as well 2x10
    // Now, let's go to a more practical usage of multi dimensional arrays.
    // I've given you examples of a "Game Map Concept"  so I'm going to show you how to print them all.
    // The rest should be easy should you want to actually try and make a real one :).
    // Yet I strongly suggest you get into ncurses if you want to do such thing. Otherwise it will print too slowly.
    //cout << "\e[2J\e[H"; - Linux System("cls") alternative Or you could just spam /n ^_^;
    system("cls")
    string gamemap[10][10];
    //First we're going to fill the map with # for any "Unused" spaces.
    //While doing this we're going to assume player position is at 5,5
    //This method allows comparing the entire map to a file for example
    //File which could contain all the map info such as obstacles, enemies etc.
    //And this is why it would be a whole lot easier.
    for(int y = 0; y < 10; y++)
    {
        for(int x = 0; x < 10; x++)
        {
            if(x == 5 && y==5)
            {
                gamemap[x][y] = "P  "; //Assuming player position is at 5.
                cout << gamemap[x][y];
            }
            else
            {
                gamemap[x][y] = "#  ";
                cout << gamemap[x][y];
            }
        }
        cout << endl;
    }
    //Because now we can store anything in any coord of the array :), and once we store them, we can print it whole and all of them will show up properly!;
    return 0;
}

Some general examples I may not have mentioned so far.

I'm going to ask you, how would you make the computer tell if a number is evenly divided by 2?
Any idea?
Well schools and courses often tell you about this because you never used the mod operator %
While I personally never had to use it, I will show you how in this quite rude application which thinks you're testing it.

#include <iostream>
using namespace std;
int main()
{
    int number;
    cout << "Check if number is evenly divided by 2\nInput the number you want to check: \n";
    cin >> number;
    if(number % 2 == 0) // You can check if it divides evenly by any number, for example replace 2 with 15.
    {
        cout << "Yep, it divides evenly\n";
    }
    else
    {
        cout << "Nope, screw you. Testing me like that!\n";
    }
    system("pause");
    return 0;
}

Well that's quite nice, now you know something you'll probably never need.
But on the other hand knowing this might save you from doing something really stupid
And much more complicated! Seriously people find very complex solutions to easy problems! You'll most likely find yourself doing it once!

Let's talk about Structures

img
Structures, are very nice, and I'm sure you will understand why once seeing them in action:

//STRUCTURES
#include <iostream>
using namespace std;
//Let's assume we want to make a shop, and a database for all of the products in this shop.
struct product //Creating the structure for products
{
    int weight;
    string name;
    int quantity;
    float price;
}; // Notice that after structures, we do add a semicolon.
void structo(struct product *p) //I hope you learned pointers, we need them here for example.
{
    cout << "Name: " << p->name << endl
         << "Quantity: " << p->quantity << endl
         << "Price: " << p->price << endl;
}
int main()
{
    product cola; // Let's say we want to add cola to the products ^_^
    cout << "Name of Product: ";
    getline(cin,cola.name);
    cout << "Price: ";
    cin >> cola.price;
    cout << "Quantiy: ";
    cin >> cola.quantity;
    structo(&cola); //Adressing the current product to print.
}

Pretty easy huh?
Well it is, and it's very useful.
Now I really hope you didn't expect me to leave you with that half assed silly example.
Let's make a real product database, Aye. No bullshit structures that teach you nothing at all like you'll mostly find out there on the internet.
This is the real deal.
Guess what, you can have a structure array.
Which means? yep, you can have your own database from a file, just use the line splitting, etc.
I've shown you before on user authentication, so it should be easy now.
Here's how structure arrays work so you can do it in case you want to.

//STRUCTURES
#include <iostream>
using namespace std;
//Let's assume we want to make a shop, and a database for all of the products in this shop.
struct product //Creating the structure for products
{
    string name;
    int quantity;
    float price;
}; // Notice that after structures, we do add a semicolon.
void structo(struct product *p) //I hope you learned pointers, we need them here for example.
{
    cout << "Name: " << p->name << endl
         << "Quantity: " << p->quantity << endl
         << "Price: " << p->price << endl;
}
int main()
{
    int nr;
    cout << "How many products would you like to add?\n";
    cin >> nr;
    product products[nr];
    for(int i = 0; i<nr; i++)
    {
        cout << "Product " << i << endl;
        cout << "Name: ";
        cin >> products[i].name;
        cout << "Price: ";
        cin >> products[i].price;
        cout << "Quantity: ";
        cin >> products[i].quantity;
    }
    //Very nice, now how do we print say, a single product?
    cout << "What product do you want to view?\n";
    int id;
    cin >> id;
    structo(&products[id]);
    //How do we print all the stored products?
    cout << "Viewing ALL products.\n";
    int nrprods = sizeof(products)/sizeof(products[0]); //In order to get the size of the struct array.
    for(int IDZ = 0; IDZ < nrprods; IDZ++)
    {
        structo(&products[IDZ]);
    }
}

Very good, that concludes this tutorial, next we are moving on to classes and the beginning of object-oriented programming in c++.

Please don't forget to upvote & Foo if you enjoyed my work!

Everything written above is my own work
The header is of my own design.
List of images that are public domain:
multi dimensional arrays
Quote