Today, I’m going to show you some basic input and output in C++.

On masteries 1 & 7 we learned some basic output, which is used as “cout”. cout is used when the program prints information you gave it to it in the program. When you want to input information from the terminal, while the program is running, you need a variable and the “cin” command. 

In order to do this, we will create a program that asks the user for two integer numbers, and then the program will add those numbers and then print the result.

So, you will need our “basic code” that we learned on masteries 1 & 7:

image

Now that we have our basic code, we will write the program inside the braces. 

The first thing we need to do, is to establish the variables we are going to use. We need two variables for the numbers the user is going to input in the program and another variable that will work as the result. 
The variables need to be established inside the braces, and are written as:
int FIRSTVARIABLE, SECOND, THIRD;

image

Now that we have our variables, we can tell the program what it needs to do. For that, we will simply do as follows:

  1.  Print (cout) a question where the program asks the user for the variables (cin) 
  2. Write a math operation with the variables 
  3. Print the result:
image

And that’s it. You can use this principle to perform other math operations:

image

Now, run your program in the terminal. Remember to change the directory, compile your program and then run it:

You now know how to do a basic program with inputs and outputs, congrats! 😀

CC BY 4.0 Mastery 10 by Omar Peza is licensed under a Creative Commons Attribution 4.0 International License.