In this section, we will learn how to write a program that allows us to input data and use it.
Let's start by writing a program that asks for your age and then displays it on the screen. Here's the code for this program:
In previous lessons, we learned to create programs that can output information to the screen.
Today let's try to write a smarter program. We will create a program that will ask for your age and then tell you how old you are.
Let's start with the first part of the program, which will display the question: "How old are you?"
In previous lessons, we studied the int keyword, the main() function, and the int return value in the function signature: int main().
What is int? In programming, int represents an integer. You can think of your program as a factory with many storage cells where you can store different things. Each cell has its own name and contains a specific object. For example, you might have cell number two, or a cell named the coolest cabinet, and different things can be stored inside this cell. You can say that this cabinet is only for chocolate, and nothing else can be put in it. The same idea exists in programming. You can create so-called variables that will store information.
Let's look at the int data type. We will learn to create variables that can store integers. To do this, we write int and then specify the variable name. Let's simply call it A. Now our program knows that it has a variable A that can store integers.
In the last lesson, we studied the cout structure, which allows us to output information to the screen. Today we need not only to output information, but also to receive data from the user. For this purpose, there is a cin structure.
Most important: don't confuse the directions of cin and cout. While cout uses double angle brackets << to output data to the screen, cin uses >> to input data from the keyboard. Note the semicolon at the end of the command; this is important.
cout << - output FROM program TO screencin >> - input FROM user INTO programNow our program can ask you a question about your age and accept the number you enter. All that remains is to display this age on the screen.
Let's write the phrase "Your age:", and then output the value of variable A (your age) using cout. The endl command adds a newline character to make the output more readable.
Thus, you have created a program that asks for your age, saves it, and displays the phrase "Your age:" with your age on the screen.
Here's what our complete program looks like:
When you run this program, it will:
#include <iostream>
using namespace std;
int main() {
cout << "How old are you?" << endl;
int A;
cin >> A;
cout << "Your age: " << A << endl;
return 0;
}
cout << "How old are you?" << endl;
int A;
cin >> A;
cout << "Your age: " << A << endl;
#include <iostream>
using namespace std;
int main() {
cout << "How old are you?" << endl;
int A;
cin >> A;
cout << "Your age: " << A << endl;
return 0;
}