Showing posts with label Functions. Show all posts
Showing posts with label Functions. Show all posts

Pointers in Functions (in C++)

In this tutorial from our C++ e-book, we will learn how to work with pointers in functions.
First, let's review a little of what we learned in the Functions section.

Passage by Value and Reference Variable

Run the following program, which squares a number entered by the user.
It shows the number entered, it squared and then the original value, again:
#include <iostream>
using namespace std;

int square(int num)
{
    num = num*num;
    cout << "Squared: " << num <<endl;
}

int main()
{
    int num;
    cout <<"Type a number: ";
    cin >> num;

    cout <<"Number typed: " << num << endl;
    square(num);
    cout <<"num value: " << num << endl;

    return 0;
}

C++ e-book for download

See that we pass the variable 'num' to the function, and inside it is squared. We show this value within the function, and then show it again when the function call is finished.

It did not change the value stored in 'num'.

This is because when we pass a variable to a function, the function makes a copy of its value. It will not use the variable directly, but its value only, so the original variable is not changed.

To give access directly to the variable, we can use the reference variables.
Which is basically passing the name of the variable, with the symbol & in front, see how it looks:
#include <iostream>
using namespace std;

int square(int &num)
{
    num = num*num;
    cout << "Squared: " << num <<endl;
}

int main()
{
    int num;
    cout <<"Type a number: ";
    cin >> num;

    cout <<"Number typed: " << num << endl;
    square(num);
    cout <<"num value: " << num << endl;

    return 0;
}

Now notice that the value of 'num' directly has been changed inside the square() function:

How to use pointers in Functions

This happened because we used the reference variable &num instead of just num.

And now that you've studied pointers and memory addresses, you know that by using & we are dealing directly with memory addresses. That is, the function will now have access to the memory address of variable num and will change that block of memory directly.

How to Use Pointers in Functions in C++

Another way to change the value of a variable, passing it to a function, is using pointers. In fact, it is important to know how to use this technique, as it is very useful in functions that deal with Strings and in several C++ libraries, for example.

Let's create a function, called doub(), that will double the value it receives, using pointers:
#include <iostream>
using namespace std;

int doub(int*);

int main()
{
    int num;
    cout <<"Type a number: ";
    cin >> num;

    cout <<"Number typed: " << num << endl;
    doub(&num);
    cout <<"num value: " << num << endl;

    return 0;
}

int doub(int *ptr_num)
{
    (*ptr_num) = (*ptr_num) * 2;
    cout << "Double: " << *ptr_num <<endl;
}
Its parameter is: int*
That is, it expects an int pointer. If it expects a pointer, we have to pass as a ... memory address! So we did: doub(&num);
Remember: a pointer is a variable that stores a memory address!

Within the function, 'ptr_num' is a pointer. Pointer to the memory address of the 'num' variable in the main() function.

We want to double the amount it points to. Now, how do you access the value stored in the location to which the pointer points? Using asterisk: *ptr_num

So, to double the value of the variable 'num', using the pointer 'ptr_num' that points to it, just do:
*ptr_num = *ptr_num * 2;

In order not to get confused with the operators, you can do it as soon as it gets more organized:
(*ptr_num) = (*ptr_num) * 2;

The power of pointers

A great advantage of working with pointers is that they can deal in a more 'global' way, so to speak, with the variables they point to.

For example, note that we always ask the user for a number within the main() function, and from there we send that value or its address to the most diverse functions.

Using pointers, we can get user values inside a function, like getNum(), see:
#include <iostream>
using namespace std;

void getNum(int *);
int doub(int*);

int main()
{
    int num;
    getNum(&num);
    cout <<"Number typed: " << num << endl;

    doub(&num);

    cout <<"num value: " << num << endl;

    return 0;
}

void getNum(int *ptr_num)
{
    cout <<"Type a number: ";
    cin >> *ptr_num;
}

int doub(int *ptr_num)
{
    (*ptr_num) = (*ptr_num) * 2;
    cout << "Double: " << *ptr_num <<endl;
}
We declare the variable 'num', and pass its address to the doub() variable, this address will be stored inside the ptr_num pointer.
Now, we want to change the value of ptr_num, so just use: *ptr_num

And ready, magically, the variable that was declared there in the main() function was changed inside the getNum() function.

Powerful, these pointers, right?

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?

List of C++ Function Exercises (Resolved and Commented)

We have reached the end of another section of our C++ course, about functions.
In the exercises below, you should use all your knowledge learned so far, such as the basics, loops, loopings, conditional tests and, of course, function.

Use and use again the functions. Create many functions.
Each function must do a single thing, in the simplest and most direct way possible.

Make them easily coupled, that is, you should receive and return information whenever possible. This allows you to use your function codes later.

Remember: a large program is nothing more than a series of small programs.
Your functions should be these little programs, making specific functionalities, ok?

Function Exercises in C++

01. Create a program that receives two smaller sides of a right triangle and a function returns the value of the hypotenuse.

02. Create a program that receives the three sides of a triangle, passes these values ​​to a function that says whether that triangle exists or not (due to the condition of the triangle's existence, each side must be greater than the subtraction module of the other two sides and must be less than the sum of the other two sides)

03. Make a program that asks the user for a positive integer 'n' and print a square of side 'n' filled with hashtags. For example, for n = 4, it should appear on the screen:

####
####
####
####

04. Program a software that receives three numbers, stops for a function and it returns the largest one. Make another function that receives the same numbers and returns the smallest one.


05. A number is said to be perfect when it is equal to the sum of its divisors.
For example, six is ​​perfect, because: 6 = 1 + 2 + 3
Programs a software that asks the user for a number and tells them if it is perfect or not.

06. Create software that receives a number from the user, passes that value to a function and it returns that number written in reverse. For example, you gave the value 1234, so it will return 4321. Tip: first, create a function that counts how many digits a number has.

07. Make a program to toss a coin. When we call a function, it must return heads or tails. In another function, make 'n' coin tosses, 'n' is the amount the user wants, and show the percentage of times he has heads and tails. If you flip the coin 10, 100, 1000, a million times ... what tends to happen?

08. Create data in C++. Roll the dice: that is, a function must draw a random number from 1 to 6. Now, make the previous die roll 100 times, a thousand times and 1 million times. Each time it runs, you must store the value it provided, at the end, you show how many times each number was drawn. Does it match the results of the statistic?

09. Create an odds and even game. You must choose 0 for even or 1 for odd, then provide a number. The computer generates a number from 0 to 10, adds the values ​​and says who won, besides showing the score and asking if you want to play another round.
How to program odds or even in C++

10. Like the odd or even game, create the Rock, Paper or Scissors game, in C ++.

11. Create a game where the computer draws a number from 1 to 10, and you try to guess what it is.

12.  Are we really going to make a cool and interesting game? Make the computer draw a number from 1 to 100. Each time you kick, it should tell you if you kicked below the real value, above or if you got it right. At the end, it tells you the number of attempts you had and whether or not you hit the record. Oh, at the end of each round, the program asks if you want to play again or not, displaying the current record.
Guess the number

The exit() Function

Learn about the C++ exit() function, what it is for, and how to use it in our  C++ course....

The exit() function

Of all the programs we developed throughout our course, they all ended after the return command from the main() function.

When we invoke a function, it saves in memory the location from which it was invoked to return to that stage after it has finished executing. Thus, the programs always returned to the main() function, even though we invoked millions of other functions.

But it would be interesting if we could quit, interrupt or terminate at any time, our programs, wouldn't you agree?

This is possible by simply calling the exit() function.
It is very simple.

First, include the library: cstdlib
The function is defined inside this library, so we need to add to use it.

Then, just pass an integer as an argument and call the function, see the code:
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    cout<<"The main() begins..."<<endl;
    cout<<"Calling exit()..."<<endl;
    exit(0);
    cout<<"After exit()"<<endl;

    return 0;
}
Note que o último cout nem aparece na tela:
Free online course C++

You can place this exit(0) anywhere in the program, even within any other function, it will interrupt and terminate the program at that time and at that location.

Arguments of the exit() Function

The exit function has as an integer parameter only.
The argument we must provide is what will be returned to the operating system that ran your C++ program.

This argument is very important to warn anyone who called a program if it was executed and terminated correctly. In the future, you will program software that calls other programs, and you need to communicate with them.

One of these ways is through the exit() argument.
For example, 0 is the universal symbol for: "Everything ok, it's all right!"

That's why we always use: return 0 ; in the main() function, get it now?
When someone calls you a zero, don't be offended, in programming that's a compliment.

There are up to two commonly used constants to symbolize:

  1. success: EXIT_SUCCESS
  2. problem: EXIT_FAILURE


Use this: exit (EXIT_SUCCESS) or exit (EXIT_FAILURE) if the program terminated correctly or has a problem.

If your game program ends with a memory problem, do: exit(1), then you know 1 symbolizes a memory problem.
If the internet has dropped and the game is over, the program ends with exit(2), where 2 symbolizes problems with the internet.

And so on ... you will decide what each error number means so that you can know what is happening with a particular application. Leave the number 0 to symbolize success, that all went well in the execution of the program.

The number 2112 is the supreme number in the universe, respect and do not use it.
We should only revere the value 2112.

Function Overloading: Different Parameters and Arguments

In this tutorial from our C++ e-book, we will learn what function overloading is, what it is for, and how to use this important programming technique.

Parameter and Arguments Sizes in C++ Functions

In the Default Arguments tutorial, we saw that you can send a variety of arguments to a function as long as it is using reference parameters.

For example, the code below is from a function that calculates an arithmetic average:
#include <iostream>
using namespace std;

float average(float a, float b, float c, float d = 0.0)
{
    return (a+b+c+d)/4;
}

int main()
{
    cout<<"Average of 3 numbers: "<<average(10, 9, 7)<<endl;
    cout<<"Average of 4 numbers: "<<average(10, 9, 7, 6)<<endl;

    return 0;
}
It can take 3 or 4 arguments. If you submit only 3, the 4 argument is the default, with a value of 0.
However, note an error.

Even if we only send 3 arguments, the arithmetic average is calculated as if there were 4 notes.

It would be interesting if, if I submitted 3 arguments, it would return:
(a + b + c) / 3

And if I sent 4 arguments, it would return:
(a + b + c + d) / 4

And this is possible with overloading functions.

C++ Function Overloading

Overloading is the technique that allows us to have functions with the same name as long as their parameters are different, in some way.

Here's what the 3 and for grade average program looks like:
#include <iostream>
using namespace std;

float average(float a, float b, float c)
{
    return (a+b+c)/3;
}

float average(float a, float b, float c, float d)
{
    return (a+b+c+d)/4;
}

int main()
{
    cout<<"Average of 3 numbers: "<<average(10, 9, 7)<<endl;
    cout<<"Average of 4 numbers: "<<average(10, 9, 7, 6)<<endl;

    return 0;
}
Note that we invoke the average() function, the only difference is that in the first call we pass 3 arguments, and in the second call of the function we pass 4 arguments.

Because C++ is naughty and smart, it knows which function to run correctly.

It is so clever that even if there are the same number of parameters / arguments, it can differentiate through the type of data we are using.

Look:
#include <iostream>
using namespace std;

double average(double a, double b, double c)
{
    cout<<"Average of 3 doubles   : ";
    return (a+b+c)/3;
}

int average(int a, int b, int c)
{
    cout<<"Average of 3 integers  : ";
    return (a+b+c)/3;
}

int main()
{
    cout<<average(10.0, 9.0, 7.0)<<endl;
    cout<<average(10, 9, 7)<<endl;

    return 0;
}
When we pass double type variables, it calls average(double, double, double)
When we pass int variables, it calls average(int, int, int)

C++ can differentiate because the signatures of each function are different (either in the number of parameters or the type that will work).

In fact, even if the functions have the same name, the same number of parameters, and the same data types, we can overload functions as long as the order of the parameters is different:
#include <iostream>
using namespace std;

void func(int a, double b)
{
    cout<<"First is int    : "<<a<<endl;
    cout<<"Second is double: "<<b<<endl;
}

void func(double b, int a)
{
    cout<<"First is double : "<<b<<endl;
    cout<<"Second is int   : "<<a<<endl;
}

int main()
{
    func(1, 2.5);
    cout<<endl;
    func(2.5, 1);

    return 0;
}
In the example we have: func (int, double)
Also: func (double, int)

Simply signature from one function to another is different so we can use overload where signature is a set: function name, data type, data number and order of information.

For good programming practices, you should use function overloading whenever you need to use functions with the same purpose and logic, but for different number and / or types and / or order of data.

Reference Parameters and Variables

In this tutorial of our C++ course, we will learn how to pass arguments by reference into functions.

Pass by Value

We have already learned how to send information to functions through arguments and parameters.
And we saw that this pass is called pass by value, because we only pass the value to the function.

If we send a variable to a function, and within that function that variable is changed, it is not changed outside the function. Test the following code, which squares a number:
#include <iostream>
using namespace std;

void square(int num);

int main()
{
    int number = 6;

    cout<<"Before  : num = "<<number<<endl;
    square(number);
    cout<<"After   : num = "<<number<<endl;

    return 0;
}

void square(int num)
{
    num = num*num;
    cout<<"During  : num = "<<num<<endl;
}
When we invoke the function: square (number), we are actually passing a copy of the value of the variable number.

Within the function, the num variable will receive a copy of the value of number. That is, it will not have access to the original variable number, only its value! Therefore, passing by value.

Reference Parameter: &

Be the variable declaration:
  • int num = 6;

What we are doing is allocating, reserving, a space in the memory of your computer.

So when we use num, C++ understands that we must go to the address this variable points to and get the number inside that memory location.

As we have seen, when we pass this normal variable to a function that expects a normal variable, it takes only a copy of its value, and does not mess with the original content.

However, there is another special type of variable, the reference variable.

It is special because if we pass a variable to a function and the function wants to get the reference variable through a reference parameter, it will have access to the memory address (the reference) where this variable is originally stored.

That is: we will actually have access to the variable, not just its copy.

To get the reference of a variable, just use the & operator before the variable name, in the function parameter! It is the reference parameter. Both in the prototype and in the function declaration.

So the previous code example looks like this:
#include <iostream>
using namespace std;

void square(int &);

int main()
{
    int number = 6;

    cout<<"Before  : num = "<<number<<endl;
    square(number);
    cout<<"After   : num = "<<number<<endl;

    return 0;
}

void square(int &num)
{
    num = num*num;
    cout<<"During  : num = "<<num<<endl;
}
See now the result:
Parameter reference

In fact, the function was able to change the value of the variable because this argument pass to the parameter was by reference parameter.

What happens here is that the parameter will not capture the value of the argument but its reference to where it is pointing in memory. Speaking of pointing to an address, we will study more about it in the pointers and arrays (vectors) sections in C++, where we will study about passing by reference using pointers.

More about C++ Reference Parameters

Some programmers also prefer to declare the prototype like this:
  • square (int&);

You can also use it like this in the prototype:
  • square(int &num);
  • square(int& num);

Also, the important thing is that & is in both the prototype and function declaration, ok?

Remember that if your parameter is reference, it can only work with reference variable.
It would be a mistake if you use an argument that is not a variable, such as a literal, an expression, or a constant, for example:
  • square(10); // must use square (number);
  • square(number+1); // it's an expression, avoid
When we do: square (int &num)

Read: "num is a reference to an integer", that is, it is referencing, pointing, indicating a memory location where an integer is stored. Since you have the location of the original variable, you can change this value.

Value passing and reference exercise

Create a program that prompts the user for an integer. Then it must turn this value into its cube. Do this by using a function that receives pass by value and another that uses parameter and reference variable. Make it clear that one changes the value only within the function (value) and the other changes the original value of the variable (reference).

Paste in the comments, your solution.