Showing posts with label Array. Show all posts
Showing posts with label Array. Show all posts

Array of objects in C++

In this tutorial from our C++ e-book, we will learn how to create an array of objects, as well as how to manipulate them.

Creating an array with Objects in C++

In the past tutorial, we created a class that averaged two or three grades for students. We will do something similar in this tutorial.

Let's create the Student class, and initially it gets two grades. The constructor function correctly sets variables, and has a function called getAverage() that returns the average of the two grades:

#include <iostream>
using namespace std;
class Student
{
    private:
        double grade1, grade2;

    public:
        Student();
        Student(double, double);
        double getAverage();
};

Student::Student()
{
    grade1 = 0;
    grade2 = 0;
}
double Student::getAverage() { return (grade1+grade2)/2; } int main() { Student NeilPeart(10, 8); cout<<NeilPeart.getAverage()<<endl; return 0; }

Note that we created only one object, the student Neil Peart. But which school has only one student? There are thousands, but let's take it easy. We will now work with 5 students. We could do:

  • Student alu1, alu2, alu3, alu4, alu5;

But, what if it was a real project, with a thousand students? Would you do it up to the alu1000?
Of course not, right, buddy!

You studied by Progressive C++, you are a smart person and you will soon remember our beloved and beautiful arrays, to work with many variables at the same time.

To declare 5 integers, we do:

  • int num[5];

To declare 5 chars, we do:

  • char letter[5];

So guess what we do to create 5 objects of the Student class? That's right:

  • Student alu[5];

Array of Objects

Run the code to the code below:

#include <iostream>
using namespace std;

class Student
{
    private:
        double grade1, grade2;

    public:
        Student();
        Student(double, double);
        double getAverage();
};

Student::Student()
{
    grade1 = 0;
    grade2 = 0;
}

Student::Student(double g1, double g2)
{
    grade1 = g1;
    grade2 = g2;
}

double Student::getAverage()
{
    return (grade1+grade2)/2;
}


int main()
{
    Student alu[5];
    cout<<alu[0].getAverage()<<endl;

    return 0;
}

The result will be 0, as we don't initialize the array objects.

How to Initialize Objects from an Array

We could initialize the objects one by one, after declaring:

    Student alu[5];
    alu[0] = Student(10,9);
    alu[1] = Student(10,8);
    alu[2] = Student(10,7);
    alu[3] = Student(10,6);
    alu[4] = Student(10,5);

Or we could just initialize everything when instantiating objects:
    Student alu[5] = { Student(10,9),
                       Student(10,8),
                       Student(10,7),
                       Student(10,6),
                       Student(10,5) };
Or even directly:
    Student alu[5] = { {10,9},
                       {10,8},
                       {10,7},
                       {10,6},
                       {10,5} };
If you have other constructor functions (that receive one grade or 3, for example), you can also place them directly in the code, C++ will know how to call the correct constructor. And if you don't provide any information about any element of the array, C++ will invoke the default constructor (it's always good to have one in the class).

Accessing members of the Object Array

Ok, we have already declared and initialized several objects at once, now you need to learn how to access their members.

When we had an object named 'name', we accessed its members using a dot:
  • name.var
  • name.func()

Here's the same thing, but the variable is an array element:
  • arr[0].grade
  • arr[1].getAverage();
That is, the same thing, just use the cute array and the dot, followed by the member of the class / object.
The following program creates 5 objects, initializes with the students' grade and displays their averages with the getAverage() function:
#include <iostream>
using namespace std;

class Student
{
    private:
        double grade1, grade2;

    public:
        Student();
        Student(double, double);
        double getAverage();
};

Student::Student()
{
    grade1 = 0;
    grade2 = 0;
}

Student::Student(double g1, double g2)
{
    grade1 = g1;
    grade2 = g2;
}

double Student::getAverage()
{
    return (grade1+grade2)/2;
}


int main()
{
    Student alu[5] = { {10,9},
                       {10,8},
                       {10,6},
                       {10,5} };


    cout<<alu[0].getAverage()<<endl;
    cout<<alu[1].getAverage()<<endl;
    cout<<alu[2].getAverage()<<endl;
    cout<<alu[3].getAverage()<<endl;
    cout<<alu[4].getAverage()<<endl;

    return 0;
}
Note that we only initialized the first four students, so the fifth one was initialized by the default constructor. What was the average of the fifth student (alu[4])?

Now do another test: create a class, which only has the default constructor, displaying a message on the screen. Create an array of size 10, of these objects. What happens?

Tic-Tac-Toe in C++: How to Program


Tic-tac-toe game full code in C++In this tutorial, we will teach you the most absolute zero, how to program the tic-tac-toe game in C++, a super cool game that you can use to play with a friend.

C++ Tic-Tac- Toe logic

We will use a matrix, 3x3, of integers, to represent the moves.
If the block has the number 0, it is empty. If it have number 1 it is because player 1 played there, and if you have -1, it is because player 2 played in that position.

We will explain, in parts, the functions.

The init() function initializes the board, placing 0 in every block.


The show() function will display the board, print the cute board, with bars, underlines, correct spacing and, if there are X or 0 in each square. This last part does the printBlock() function.

The printBlock() function goes on each block of the board, if it has 0 there, it returns an empty space ''. If there is 1 there, it prints X. If there is -1 there, it is because player 2 played in that house, and there will be an O.

The playMove() function performs a move, that is, it asks for the row and column that the player will play.
Remembering that it will enter values ​​from 1 to 3, and the array goes from 0 to 2, so we have to subtract one unit from the data entered by the user (row-- and col--). We should also check if it is occupied (board[row] [col]), and if the user has entered correct values ​​(between 1 and 3). If everything is ok, it fills the square chosen by the player with 1 or -1.

The checkContinue() function will check if there is still white space, that is, if it is still possible to make a move. If there is blank space, returns 1, if not, returns 0.

The checkWin() function will check if anyone has won. To do this, just add each row, each column and each diagonal, if any of these rows has a sum of 3, player 1 won and we return 1. If the sum is -3, player 2 won, and we return -1. If no one has won, by that time, we return 0.

Now let's go to the main() function. It creates the 3x3 board, the cont variable (which will ask whether the player will want to play again or not, the player1 and player2 variables, which will store the scoreboard), and the result variable, which stores the information of who won the game.


The game will take place within a DO WHILE.
First, we initialize the board with values ​​0.
Now let's make a match, for that, we call the game() function.

The game() function is where the magic happens, the game unfolds.
First, we declare the turn variable, which will tell whether it is player 1 or 2 who will play. With each move, we must increase it by one (turn ++), to change the turn for the next player.

After saying whose turn it is, let's make the move, through the playMove() function. Note that we pass the information on who the player is, using the expression turn%2. If it gives 0, it's player 1's turn (and puts the number 1, represented by X on the board), if it gives 1, it's the player's 2 turn (and we fill the matrix with the number -1, which will be represented by character O on the board).

Then, we should check if the board still has empty positions, to play. If so, we store the number 1 in the cont variable, otherwise we store the value 0.

We should also check if someone has won after this play. If player 1 has won, we store 1 in the win variable. If player 2 has won, we store the value -1. If no one has won, we store the value 0.

Ready. A play is over. Will you have a next move? That depends.

If there is still empty space (cont = 1) and no one has won (win = 0, same as !win), there will be another move.

If there is no more empty space (cont = 0) or someone has won (win = 1 or win = -1), there will be no next move, and exit the DO WHILE loop.

After the loop, let's check what happened. If win = 1, player 1 won and the game function returns 1.
If win = -1, player 2 won and we returned 2. If none of them won, it is because the board is full (cont = 0) and we haw a draw, then we return 0.

This return goes to the main() function, in the result variable. He takes the result, and sends it to the scoreboard() function, along with the values ​​of player1 and player2, she is responsible for controlling the score.

After the scoreboard is displayed, we ask if you want to play the game again or leave.
If you type 1 (continue), the cont variable has a value of 1, the WHILE loop is true, and another game will start. Otherwise, if it is 0, the loop ends with the game.

Nice, isn't it?


Guys, the code below has almost 200 lines. There can be errors, no doubt.
If you find any, or any improvement, please write in the comments, ok?

Tic-Tac-Toe full code Game in C++

#include <iostream>
using namespace std;

void init(int board[][3]);          // Initializes the board with 0's
char printBlock(int block);         // Prints each square of the board
void show(int board[][3]);          // Show the board
void playMove(int board[][3], int); // Play one move
int checkContinue(int *board[3]);   // Check if there is still white space
int checkWin(int *board[3]);        // Check if anyone won
int game(int board[][3]);           // PLay an entire game
void scoreboard(int, int &, int &); // Show the scoreboard

int main()
{
    int board[3][3];

    int cont=0, player1=0, player2=0, result;
    do{
        init(board);
        result = game(board);
        show(board);
        scoreboard(result, player1, player2);

        cout<<"\n Again?"<<endl;
        cout<<"0. Exit"<<endl;
        cout<<"1. Play again"<<endl;
        cin >> cont;
    }while(cont);

    return 0;
}

void init(int board[][3])
{
    for(int i=0; i<3; i++)
        for(int j=0; j<3; j++)
            board[i][j]=0;

}

char printBlock(int block)
{
    if(block==0)
        return ' ';
    else if(block==1)
        return 'X';
    else
        return 'O';
}

void show(int board[][3])
{
    cout<<endl;
    for(int row=0 ; row<3 ; row++){
        cout<<" "<< printBlock(board[row][0]) <<" |";
        cout<<" "<< printBlock(board[row][1]) <<" |";
        cout<<" "<< printBlock(board[row][2]) <<endl;

        if(row!=2){
            cout<<"___ ___ ___\n"<<endl;
        }
    }
}

void playMove(int board[][3], int player)
{
    int row, col, check;
    do{
        cout<<"Row: ";
        cin >>row;
        cout<<"Column: ";
        cin >> col;
        row--; col--;

        check = board[row][col] || row<0 || row>2 || col<0 || col>2;
        if(check)
            cout<<"This spot isn't empty or out of 3x3 board"<<endl;

    }while(check);

    if(player==0)
        board[row][col]=1;
    else
        board[row][col]=-1;
}

int checkContinue(int board[][3])
{
    for(int i=0 ; i<3 ; i++)
        for(int j=0 ; j<3 ; j++)
            if(board[i][j]==0)
                return 1;
    return 0;
}

int checkWin(int board[][3])
{
    int row, col, sum;

    // Adding the lines
    for(row=0 ; row<3 ; row++){
        sum=0;

        for(col=0 ; col<3 ; col++)
            sum += board[row][col];

        if(sum==3)
            return 1;
        if(sum==-3)
            return -1;
    }

    // Adding the columns
    for(col=0 ; col<3 ; col++){
        sum=0;

        for(row=0 ; row<3 ; row++)
            sum += board[row][col];

        if(sum==3)
            return 1;
        if(sum==-3)
            return -1;
    }

    // Adding the diagonals
    sum=0;
    for(row=0 ; row<3 ; row++)
        sum += board[row][row];
    if(sum==3)
        return 1;
    if(sum==-3)
        return -1;

    sum=board[0][2]+board[1][1]+board[2][0];
    if(sum==3)
        return 1;
    if(sum==-3)
        return -1;

    return 0;
}

int game(int board[][3])
{
    int turn=0, cont, win;

    do{
        show(board);
        cout<<"Player "<<1+turn%2<<endl;
        playMove(board, turn%2);
        turn++;

        cont=checkContinue(board);
        win = checkWin(board);
    }while(cont && !win);

    if(win==1){
        cout<<"Player 1 won!\n"<<endl;
        return 1;
    }else
        if(win==-1){
            cout<<"Player 2 won!\n"<<endl;
            return 2;
    }else
        cout<<"Draw\n"<<endl;
    return 0;
}

void scoreboard(int result, int &player1, int &player2)
{
    if(result==1)
        player1++;
    if(result==2)
        player2++;

    cout<<"\nScoreboard: "<<endl;
    cout<<player1<<" x "<<player2<<endl;
}

C++ game challenge

Create a modified version of this game, which asks the user whether he wants to play with a friend or against the computer. If he chooses to play against the machine, make sure his code chooses a random block when it is the machine's turn.

Would someone be able to make and post in the comments, the result?

Matrix in Functions

In this tutorial from our C++ ebook, we will learn how to work with matrix and functions, learning to declare, invoke and use these two important topics together.

How to Pass a Matrix to a Function

In the study of arrays, we saw that there are some ways to declare the header of functions with arrays as parameters, as follows:
  • type func(tipo *array);
  • type func(tipo array[tamanho]);
  • type func(tipo array[]);

In other words, just pass the pointer (*array - we will study more ahead) or just with the pair of open brackets (array[]).

In the case of two-dimensional arrays, we need to specify the number of columns in the array we are sending:
  • void func(int arr[][COLUMN]);

You see, the number of rows is not mandatory (we can even pass), but the number of columns is.
Let's declare and initialize a 2x2 matrix and then send it to the show() function, which will simply display it as a table, see how our code looks:
#include <iostream>
using namespace std;

void show(int arr[][2], int row)
{
    for (int i=0 ; i<row ; i++){
        for(int j=0 ; j<2 ; j++)
            cout<<arr[i][j]<<"  ";
        cout<<endl;
    }
}

int main()
{
    int arr[][2]={ {1,2}, {3,4} };
    show(arr, 2);
    return 0;
}
Look some important things in the code above.

First, we pass the array arr[][2] to the function, with the number of columns.
But what about the number of lines? How will the function know how many lines to print the table?
It doesn't know, so we pass another parameter in the function, the integer 'row'.

C++ Matrix: Passing by Reference

All data passing to functions that involve arrays and matrix is by reference. Ever.
That is, passed an array to a function? It will directly access the array and its data, directly into memory. It is not a copy that goes to function, it is not a pass for value, ok?

That means one thing: watch out! Functions can modify the arrays, always remember that.
The code below introduces the 'init' function, which will receive an array and initialize each element of it, asking the user:
#include <iostream>
using namespace std;
const int COLS = 3;
const int ROWS = 3;

void init(int arr[][COLS], int ROWS)
{
    for(int i=0 ; i<ROWS ; i++)
        for(int j=0 ; j<COLS ; j++){
            cout << "matrix["<<i+1<<"]["<<j+1<<"]: ";
            cin  >> arr[i][j];
        }
}

void show(int arr[][COLS], int ROWS)
{
    for (int i=0 ; i<ROWS ; i++){
        for(int j=0 ; j<COLS ; j++)
            cout<<arr[i][j]<<"  ";
        cout<<endl;
    }
}

int main()
{
    int arr[ROWS][COLS];
    init(arr, ROWS);
    show(arr, ROWS);
    return 0;
}
To improve the organization, we have already defined the rows (ROWS) and columns (ROLS) as global variables of the constant type, so that there is no danger of anyone, anywhere in the code, changing their values. This makes the code clearer and safer for maintenance.

Array of arrays in C++

Matrix Exercise in C ++

Create a 4x4 matrix, where each row represents a student's grades, and each column is a different subject. You must create a function that will fill in the students' grades, one by one, indicating which is the subject and which is the student.

Then, your program should display, in an organized manner, the grades of each student, as well as the average of each, the class average for each subject, and the general average, of all students of all grades.

Post your solution in the comments.

Matrix in C++: Array of Arrays

In this tutorial from our C++ Course, we will learn the important concept of matrix in C++.

Array of Arrays - What is it? What is it for?

So far, in our arrays section, we have created arrays of integers, float, doubles, char etc.
That is, we create arrays that store numbers or characters.
However, it is also possible to store other things in arrays.

A curious thing to store in arrays are other arrays.

For example, imagine that you were hired by a school to do a C++ program that will, among other things, store students' grades. Each student has, for example, 5 different grades.

You can, first of all, reason like this: create an array to store students.
For example: students[10]

However, each student has 5 grades. So each student will have an array of grades:
notes[5]

You see: we have an array of students, each block represents a student. And within each block, that is, each student, there is a kind of internal array, with the grades of each student. Each student has his own array of grades, and each student is part of the student array.

Shall we formalize this?

How to declare an Array in C++

We call it a matrix, an array of arrays, or multidimensional arrays.
So far, we only work with arrays of one dimension, just a 'line' of blocks, which form an array.

To increase the number of dimensions of an array, just add pairs of square brackets, for example:

  • To declare an array of one dimension, we do: float grade[5];
  • To declare an array of two dimensions, we do: float students[10][5];


Come on. When we do 'float grade[5]' we mean: 5 float blocks.
When we do: 'float students[10][5]', we mean: 10 blocks, where each block has an array inside, of 5 floats.

We say that this is a 10x5 matrix (10 rows and 5 columns, where each row represents a student, and each column represents a different grade).

To make it easier, let's imagine a 3x3 matrix, we declare it like this:

  • int matrix[3][3];


The expression 'matrix[3]' means: an array of 3 elements.
What does each element contain? An integer? A float? A char? No, each element is another array, of size [3].

See the representation of this matrix:
Matrix in C++

The first element of our matrix is: matrix[0]
It is an array, of 3 elements, which are represented by:
First element: matrix[0][0]
Second element: matrix[0][1]
Third element: matrix[0][2]


The second element of our matrix is: matrix[1]
It is an array, of 3 elements, which are represented by:
First element: matrix[1][0]
Second element: matrix[1][1]
Third element: matrix[1][2]

The third element of our matrix is: matrix[2]
It is an array, of 3 elements, which are represented by:
First element: matrix[2][0]
Second element: matrix[2][1]
Third element: matrix[2][2]

That is, to declare an array of 'i' rows and 'j' columns, we do:

  • type matrix[i][j];


If you have studied matrix and determinants at school, you should remember how to use a matrix, how to flag each element, etc. The only difference here is that the count starts from index 0, instead of 1.

How to initialize a Matrix in C++

We will create a matrix to store the grades of 3 students, where each student has two grades.
That is, we will have a matrix of 3 rows (one for each student) and 2 columns (each column represents a grade). We declare this matrix, then:

  • grade float[3][2];


We will now initialize a 3x3 matrix, for example, with the notes:
float grade[3][3] = {{9.5, 9.1},
                                {8.8, 8.4},
                                {10.0, 10.0}};


The first student's grade array is: {9.5, 9.1}
The second student's grade array is: {8.8, 8.4}
The third student's grade array is: {10.0, 10.0}

For example, what is the second student's first grade? Second student is student 1, first grade is index 0, so that grade is stored in: grade[1][0] = 8.8
The second grade of the second student is: grade[1][1] = 8.4

Simple, isn't it?

Sorting Array Elements in C++

In this tutorial of our C++ course, we will learn how to order the elements of an Array.

Sort elements (sorting)

Sorting, that is, placing elements (such as numbers) in a certain order (such as increasing or decreasing, for example), is one of the most important and studied subjects in computing, due to its importance.

At your school or university, the list of students is sorted alphabetically.
The polling stations where you are going to vote also use some kind of order.
Bank accounts also organize everything according to numbers, as well as the numbers on a lottery card.
When you are a professional C++ programmer, your company will ask you to organize several things, in some kind of order, such as names, salaries, identifications, positions, size or weight of products, etc. etc.

That is, it is an absurdly used subject, too important indeed, that you will use a lot, several times, in your career, and we will introduce now in this tutorial, a little of the subject.

How to sort an Array in C ++

We will use the Selection Sort algorithm to order the elements of the Array.
First, we created the gen() function, which will generate random numbers from 1 to 100.

Let's create an array of size=10 and name 'num'.

We will then fill each position in this array with a random number, and then print this array of random values. Next step now is to order this array,

The logic is as follows: we take the first element of the array, and compare it with all the others. That is, we compare element 0 with index 1, then 0 with index 2 ... until it reaches 0 with index 9.
If these other elements are less than index 0, we invert the values ​​of these two elements. Okay, at the end of this operation, the lowest value of the array will be at position 0.

Now we are going to place the second smallest value at index position 1.
For this, we will compare element 1 with 2, then 3, then 4 ... until we compare element 1 with element 9, the last. Again, if this other element is less than index 1, we invert their position.

At the end of this step, the second lowest value will be in position 1. Now just do this for elements 2, 3, ... 7 and 8. In the last 'round' of comparisons, we compare element 8 with 9 to decide which is bigger and which is smaller.

The first looping, using a for loop, is what controls the first element, and inside it we are going to compare with all the other indexes.
We will use the 'prev' variable to receive the first index. It ranges from 0 to 'size-2' (from 0 to 8, that is: for (prev=0; prev<size -1; prev++)).

The second loop, a nested loop, will compare the 'prev' index with all the other elements in the array.
The second index will be stored in the variable 'next', it always starts with the value 'prev + 1' (when the first element is 0, it starts from 1 ... when the first element is index 1, it starts at index 2, etc etc ... until the first element is index 8 and it will be index 9), until 'size-1' (ie for (next=prev+1; next<size; next++) ) .

Within this inner loop, we use an IF conditional test to find out if the second element is less than the first, if it is, we invert the values ​​of these elements.

See how our code looks:
#include <iostream>
#include <random>
using namespace std;

int gen()
{
    std::random_device rd;
    std::mt19937 gen_numb(rd());
    std::uniform_int_distribution<> dis(1, 100);

    return dis(gen_numb);
}

int main()
{
    int size=10, prev, next, aux;
    int num[size];

    for(aux=0 ; aux<size ; aux++){
        num[aux] = gen();
    }

    cout<<"Original Array: "<<endl;
    for(aux=0 ; aux<size ; aux++)
        cout<<num[aux]<<" ";
    cout<<endl;

    // Selection sort algorithm
    for(prev=0 ; prev<size-1 ; prev++)
        for(next=prev+1 ; next<size ; next++){
            aux=num[prev];

            if(num[next]<num[prev]){
                num[prev]=num[next];
                num[next] = aux;
            }
        }

    cout<<"Ordered Array: "<<endl;
    for(aux=0 ; aux<size ; aux++)
        cout<<num[aux]<<" ";
    cout<<endl;

    return 0;
}

Array Exercises

01. Make an algorithm that orders the elements of an array from major to minor, that is, decreasing order.

02. Place the previous code inside functions: function that fills the array, function that inverts two values, function that makes the selection sort and function that displays arrays. Use function prototypes, to make your code very professional.

Solution in the e-book