Showing posts with label Receive Information. Show all posts
Showing posts with label Receive Information. Show all posts

The RETURN Command in C++: Getting Information from a Function

Now that you have learned what functions are and what they are for, let's see how to communicate with functions by receiving data and information from them using the return command.

Exchanging Data with C++ Functions

In the previous tutorial, from our C++ Functions section, we looked at how to create and invoke a function.
Just call by the name: hello(), it came quickly and executed immediately.

We could call 1 million times, that it would execute 1 million times without having to repeat code, just call the function whenever we need to do what it intends to do.

But there is a problem ... when we call a function, the execution leaves the place where the call was made and goes to another memory location, where the function instructions are, executes everything, and comes back. In this previous case, there is no communication between the caller and the function.

Let's look at a C ++ code where we invoke a function that asks for the number and displays its double:
#include <iostream>
using namespace std;

void doub()
{
    float num, doubl;

    cout<<"Type a number: ";
    cin >> num;

    dobl = 2*num;

    cout<<"Double: "<<dobl<<endl;

}

int main()
{
    doub();
    return 0;
}
Cool huh? However, we do not have access to this information 'doubl', we can not get it to use in another calculation, for example, it is simply displayed within the function and at the end of it, this value is lost. Function internal variables are created locally, and then deleted.

If you try to use 'doubl' outside the function you will see that it gives a compilation error.

We need to find another way to make the function communicate with the outside, to send information out, do you agree that this is important?

The RETURN Command in Functions

Whenever we want to send information from within a function to where it was called, we use the return command.

First, in the function declaration header, we need to enter the data type the function will return. In the previous example is void because it returns nothing.

If the data type it will return is a float, for example, its header should be:
float doub() {...}

And within the scope of the function we should do: return info;
Where info must be a float.

Ready, the info 'info' will be returned, returned to the place where the function was invoked.

Let's create a function that asks for a number, doubles it, and returns its double:
#include <iostream>
using namespace std;

float doub()
{
    float num, doubl;

    cout<<"Type a number: ";
    cin >> num;

    doubl = 2*num;

    return doubl;
}

int main()
{
    float res;
    res = doub();

    cout<<"Double: "<<res<<endl;
    return 0;
}
Now when we call the function: doub()
A value is returned to the caller, back a float, in this case.

Then we store the result of this return in the res variable (obviously it must be float):
res = doub();

And that's it, this variable will be twice the value that the user enters inside the function.
We can even make the code leaner, see:
#include <iostream>
using namespace std;

float doub()
{
    float num;

    cout<<"Type a number: ";
    cin >> num;

    return (2*num);
}

int main()
{
    cout<<doub()<<endl;
    return 0;
}

Note that we can return an expression directly: return 2*num;

Example of Using RETURN in Functions

Let's now create an odd or even function.
If it is even, it should return 0, if it is odd it should return 1.

Here's how our C ++ code looks:
#include <iostream>
using namespace std;

int odd_even()
{
    int num;

    cout<<"Type a number: ";
    cin >> num;

    if(num%2==0)
        return 0;
    else
        return 1;
}

int main()
{
    if(odd_even()==0)
        cout<<"It's even!\n";
    else
        cout<<"It's odd!\n";
    return 0;
}
Note now that there are two return statements inside our odd_even() function, that's possible, but see that only one or the other can happen, never an IF and an ELSE is executed both, it's always one of them.

Let's clean this code?
#include <iostream>
using namespace std;

int odd_even()
{
    int num;

    cout<<"Type a number: ";
    cin >> num;

    return (num%2);
}

int main()
{
    if(!odd_even())
        cout<<"It's even!\n";
    else
        cout<<"It's odd!\n";
    return 0;
}
Got a good understanding?

Good programming practices

First, function names: There is no right or wrong way to use them, but we recommend being consistent with their names.

Preferably create named functions in the following style: c_progressive(), project_progressive(), van_der_graaf_generator() ... - all lowercase, separated by _

Or: cProgressive(), projectProgressive(), vanDerGraafGenerator() ...- first lowercase letter, and uppercase for beginning of next words, ok?

Second, use a lot of functions, and make them very communicative, whenever possible by returning and receiving (we'll see in the next tutorial) data in a very logical and clear manner.

Just as every part of your car or every organ in your body does its specific task, they also communicate and exchange information with each other, this is essential for the proper functioning of the system.

The functions of a system should do the same! This is good programming practice, don't forget it! Make your functions easily 'coupled' with other functions, it will be essential for you to be able to create large and robust systems such as business software, operating systems, games, etc.

User Input Data - The cin C++ Object

In this tutorial of our C++ course, we will learn how to receive user information from the keyboard at the command terminal using the cin << command.

Exchanging Information

To access a website, you need to enter the URL address and hit enter key.
To open a photo, you need to browse the file in the middle of the folders and click on it.
To listen to a song or video, you must do the same.

Want to type a text? You have to open the text editor and type, letter by letter, and hit the buttons, menus, and program options to format and make it pretty.

That is, you need to pass information to the computer (type something, click here or there, enter a URL etc). And based on what you do, it will do something.

If you click a button, it does one thing.
If you click another button, it does something else entirely different.
It reacts differently depending on the information the user gives.

This is what we are going to start learning how to do in C ++, and the first step is to learn how to receive user information from the keyboard. Come on?

How to Receive User Data: cin >>

Until now, all the information needed for our programs to function was given in code, such as initialization of variables with their values.
If we wanted to make the program run with other values, we had to change them in code, compile and run all over again. Imagine having to fiddle with the code of each program you use?

Now, let's learn how to make the user enter information and the program work on that data, whatever it is.

To do this, we use the cin object (let's learn in the object orientation section, what is an object, don't worry), which is an input stream object followed by the >>  symbol (stream extraction operator) and a variable:
  • cin >> variable_name;

What C ++ will do when it gets into this code is simply stop and wait for something to be typed on the keyboard, and when you press ENTER, the value you type will be stored in the variable_name variable.

Numbers User input with cin >>

Well, let's go.

The program below asks the user for an integer, their age value, stores it in the age variable and then displays the value entered:

#include <iostream>
using namespace std;

int main()
{
    int age;

    cout << "Type your age: ";
    cin >> age;
    cout << "Your age is " << age;

    return 0;
}

Then
C++ free tutorial


Already the program below asks two numbers to the user. Stores in variables num1 and num2.
Sum these values and store them in the sum variable, then display the sum value:

#include <iostream>
using namespace std;

int main()
{
    float num1, num2, sum;

    cout << "First number: ";
    cin >> num1;
    cout << "Second number : ";    cin >> num2;

    sum = num1 + num2;

    cout << "The sum is: " << sum;

    return 0;
}

Results:
How to sum two numbers in C++

We can also receive multiple user values by simply placing one or more >> operators next to each other. Let's redo the previous example.

Enter a number, hit space and enter another number:

#include <iostream>
using namespace std;

int main()
{
    float num1, num2, sum;

    cout << "Type two numbers: ";
    cin >> num1 >> num2;
    sum = num1+num2;

    cout << "The sum is: " << sum;

    return 0;
}


User input texts (strings)

A string (text, in programming) is nothing more than a group of characters.
Therefore, to read a string that the user types, we must declare a group of characters.

For example, to store a space of 50 characters, we declare:
char name[50];

In our Strings section we will study better why the statement is like this.
The program below asks your name and greets you:

#include <iostream>
using namespace std;

int main()
{
    char name[50];

    cout << "Type your name : ";
    cin >> name;

    cout << "Hello, " << name <<"! Are you fine?";

    return 0;
}

The result is:
User input in C++

Now test a full name that has white space.
What happened? We will better understand this in the string section of our course.

User Input Boolean Data in C ++

Finally, we can also receive boolean values.

#include <iostream>
using namespace std;

int main()
{
    bool val;

    cout << "Type something : ";
    cin >> val;

    cout << "This means, in boolean value: " << val;

    return 0;
}

Test by entering the value 0. What appeared?
Test by entering any other integer value. What happened?
Enter a character. What returns?

Exercises using cin>>

1. Run the code below.
Did it give worked correctly? What's his problem?

#include <iostream>
using namespace std;

int main()
{
    float num1, num2, sum;
    sum = num1 + num2;

    cout << "First number: ";
    cin >> num1;
    cout << "Second number : ";    cin >> num2;

    cout << "The sum is " << sum;

    return 0;
}


2. Write a program that asks for a number and displays the twice value.

3. Make a program that takes the side of a square and returns the value of its area.

4. Create a C ++ program that takes both sides of a rectangle and calculates its area (just use one cin command)

5. Make a program that gets its full name (including spaces) and prints it on the screen. Study and learn how to do this using the referral site link.


Study Reference

http://www.cplusplus.com/doc/tutorial/basic_io/