Introduction to Variables
Introduction to Variables
Fundamentals of Variables
Introduction
A variable is a value you want to store in the computer memory. When asking the computer to do that, there are rules you must follow.
Introduction to Data Types
When you are asking the computer to store a certain value in its memory, the computer needs to know the amount of memory space that would be necessary to store or hold that value. The value itself can also be refered to as data. As you will see in future lessons, there are different categories of values used in the computer memory. A category of value can also be called a type. A type of value indicates the amount of memory space that would be used for the variable. Therefore, the information that specifies a category of value is called a data type.
As we will see in the next sections and future lessons, there exist many data types for various goals.
A Variable's Name
When you want the computer to store a value in its memory, the computer requires at least two pieces of information. We have seen that the computer wants to know the type of that value. The second piece of information you must provide is a name. The primary formula to follow is:
data-type name
The name will be used to refer to the value. There are rules you must follow for the name. The name of a variable:
data-type _data-type _
data-type _4A name can consist of one word such as country. A name could also be a combination of more than one word, such as firstname or dateofbirth.
The C and the C++ languages use some words for their own functionality. These words are referred to as reserved words or keywords. They are:
| alignas | alignof | and | and_eq | asm |
| auto | bitand | bitor | bool | break |
| case | catch | char | char8_t | char16_t |
| char32_t | class | compl | concept | const |
| const_cast | consteval | constexpr | constinit | continue |
| co_await | co_return | co_yield | decltype | default |
| delete | do | double | dynamic_cast | else |
| enum | explicit | export | extern | false |
| float | for | friend | goto | if |
| inline | int | long | mutable | namespace |
| new | noexcept | not | not_eq | nullptr |
| operator | or | or_eq | private | protected |
| public | register | reinterpret_cast | requires | return |
| short | signed | sizeof | static | static_assert |
| static_cast | struct | switch | template | this |
| thread_local | throw | true | try | typedef |
| typeid | typename | union | unsigned | using (declaration) |
| using (directive) | virtual | void | volatile | wchar_t |
| while | xor | xor_eq |
In our lessons:
Creating a C/C++ Statement
A statement is one or more symbols (operators, characters, or words) that perform a meaningful and valid opecation. As we will see in various lessons, there vaious types of statements in C and C++ programs. Among their many rules, some statements must end with a semicolons. That's a one of the rules with variables: You must end them with a semicolon. Therefore, to start a value, the primary formula to follow is:
data-type name;
Declaring a Variable
As seen so far, if you want the computer to store a value in its memory, you can write a data-type, followed by a space, followed by a name, and ending with a semicolo. This operation of asking the computer to store a value in its memory is referred to as declaring variable.
Introduction to Strings
Overview
A string is one or a combination of symbols.
A String to C Out
A string can be used directly on a cout << operation. To do this, add a double-quoted string after <<. Here is an example:
#include <iostream>
using namespace std;
int main()
{
cout << "Welcome to C++ Programming.";
}
This would produce:
Welcome to C++ Programming. Press any key to close this window . . .
Creating a Line Break
When a cout << operation ends, the caret remains on the line where it was written. Consider the following example:
#include <iostream>
using namespace std;
int main()
{
// A string to display
cout << "The C language.";
// Another string to display
cout << "Welcome to C++ Programming.";
}
This would produce:
The C language.Welcome to C++ Programming. Press any key to close this window . . .
Sometimes you want to create a line break at the end of a statement. To make this possible, the C++ language provides an operator named endl. There are two main ways you can use it. You can use it after cout << and end the statement with a semicolon. Here is an example:
#include <iostream>
using namespace std;
int main()
{
cout << "The C language.";
cout << endl;
cout << "Welcome to C++ Programming.";
}
This would produce:
The C language. Welcome to C++ Programming. Press any key to close this window . . .
Another way is to include the << endl operation after a cout << operation. Here is one example:
#include <iostream>
using namespace std;
int main()
{
cout << "The C language." << endl;
cout << "Welcome to C++ Programming.";
}
A String Type
You can declare a variable that would hold a string value. To do that, the C++ language (actually a C++ library) provides a word named string (string is not a keyword in C++ (it is a class; in later lessons, we will learn what classes are), but we will avoid using it when naming our variables). Therefore, to declare a basic variable, you can use the string type. Here is an example:
int main()
{
string something;
}
Initializing a Variable
When you have declared a variable, the computer reserves a memory space for that variable. At that time, that memory space is empty (actually, it contains garbage). As an alternative, if you want, you can provide a value and ask the computer to store that value in the memory space that was reserved. The operation that consists of storing a value immediately when declaring a variable is referred to as initiaizing the variable. The formula to follow is:
data-type variable-name = value
The = symbol is called the assignment operator. This operator is written after the name of the variable. The space between the variable name and the = operator is not required but it is recommended because it makes your code easy to read. After that operator, provide the desired value. The value depends on the data type. As a result, the value must follows some rules that depend on its type.
A Value for a String
As stated already, a string is one or a combination of symbols. As vague as it can be, there are still some rules and characteristics that a string follows. To start, (the value of) a string is included in double quotes: " and ". Inside those quotes, you can use a combination of characters. Here is an example:
#include <iostream>
using namespace std;
int main()
{
string _ = "Nicaragua";
}
Displaying a Value in C++
As far as users are concerned, the most basic operation of an application is to display a value. To do that, the C++ language provides a word named cout (pronounced "c out") (cout is not af C++ keyword, but in our lessons, we will avoid naming our variables with that word). Therefore, the primary formula to display a value in the C++ language is:
cout << variable-name;
Start by writing cout. This is followed by two < (pronounced Less Than) operators. An empty space between cout and the first < is not required but it is (strongly) recommended because it makes your code easy to read. There must not be an empty space between < and <. When both < operators are used together, they represent one operator. If a < operator is followed by an empty space or an operator other than <, that < element is considered as its own operator. This means that < is an operator, << is a separate operator. Both operators have nothing in common, they don't function the same way, and they don't accompish a similar goal.
After the << operator, type a name for a variable. An empty space between << and the name of the variable is not required but it is recommended because it makes your code easy to read. You must end the statement with a semicolon. Here is an example:
#include <iostream>
using namespace std;
int main()
{
string _ = "Nicaragua";
cout << _;;
}
This would produce:
Nicaragua Press any key to close this window . . .
In the above example, we declared only one variable. Whenever you judge it necessary, you can declare as many variables as you want. You can declare each on its own line, initialize it if necessary, an optionally display its value. Here is an example:
#include <iostream>
using namespace std;
int main()
{
// One variable
string _ = "Gertrude ";
// Another variable
string __ = "Monay";
cout << _;
cout << __;
}
This would produce:
Gertrude Monay Press any key to close this window . . .
Displaying many Values in one Statement
You can display the values of more than one variable using a single cout operator. The formula to follow is:
cout << variable-name_1 << variable-name_n;
Based on this formula, use one cout operator. After that, each variable name must be preceded by its own <<. Here is an example:
#include <iostream>
using namespace std;
int main()
{
string _ = "Gertrude ";
string __ = "Monay";
cout << _ << __;
}
In the above example, we used only two string variables and displayed their values using a single cout operator. Using the same approach, you can use as many variables as you want. Here is an example:
#include <iostream>
using namespace std;
int main()
{
string _ = "William ";
string __ = "Jefferson ";
string ___ = "Clinton";
cout << _ << __ << ___;
}
This would produce:
William Jefferson Clinton Press any key to close this window . . .
Other String Values
A string can be an empty space. In this case, that empty space must be included in double quotes. You can type such an empty double-quote after a cout << expression. Here is an example:
#include <iostream>
using namespace std;
int main()
{
cout << "Unites" << " " << "Nations";
}
This would produce:
Unites Nations Press any key to close this window . . .
In the same way, you can declare a string variable and initialize it with an empty string. You can then use the variable any way you like.
A string can contain just one symbol. In this case, include that symbol in double-quotes.
Requesting a Value
So far, to use a value, we declared a variable and assigned a value to the variable. In some or most cases, you will want the user to provide the value you want to use. To support this operation, the C++ language provides an operator named cin (pronounced "c in") (cin is not a C++ keyword but we will avoid using it when naming our variables).
To request a value from the user, type cin followed by two > (pronounced Greater Than) operators. An empty space between cin and the first > operator is not required but it is (strongly) recommended because it makes your code easy to read. There must not be an empty space or any character between > and >. When both > operators are used together, they represent one operator. If a > operator is followed by an empty space or something other than >, that > is an operator by itself. This means that > is an operator, >> is a separate operator. Therefore, the formula to use the cin is:
cin >> variable-name;
This means that, first declare a variable for the value you want to use, and type the above statement. When you execute the program, when the program gets to that line, the caret would blink, indicating that the user must type a value and press Enter. After that, if you want, you can display the value of the variable using a cout << statement. Here is an example:
#include <iostream>
using namespace std;
int main()
{
string name;
cin >> name;
cout << name;
}
If the value you are requesting is for a string, the user can type one or more symbols of any kind but must not type an empty space (we will deal with this issue of empty spaces in a later lesson). Here is an example of running the above program:
Welcome Welcome Press any key to close this window . . .
Requesting many Values
If you want a user to provide more than one value, you can declare more than one variable and create a cin statement for each. Here is an example:
#include <iostream>
using namespace std;
int main()
{
string firsName;
string lastName;
cin >> firsName;
cin >> lastName;
cout << firsName;
cout << endl;
cout << lastName;
}
Here is an example of running the program:
Jennifer Crittenden Jennifer Crittenden Press any key to close this window . . .
You can also request two values using one cin statement. In that case, separate the names of the variables with >> operators. Here is an example:
#include <iostream>
using namespace std;
int main()
{
string firsName;
string lastName;
cin >> firsName >> lastName;
cout << firsName;
cout << endl;
cout << lastName;
}
When requesting a value from the user, it is imporant to let the user that you are requesting a value. For this reason, most of the time, every cin >> statement should be preceded by a cout << statement that contains a clear sentence. Here are examples:
#include <iostream>
using namespace std;
int main()
{
string firsName;
string lastName;
cout << "Enter the following pieces of information.";
cout << endl;
cout << "First Name: ";
cin >> firsName;
cout << "Last Name: ";
cin >> lastName;
cout << "-------------------------------------------" << endl;
cout << "Full Name: " << firsName << " " << lastName << endl;
cout << "===========================================";
}
Here is an examle of running the program:
Enter the following pieces of information. First Name: Raymond Last Name: Kouma ------------------------------------------- Full Name: Raymond Kouma =========================================== Press any key to close this window . . .
Topics on Variables
When you are asking a computer to store a value, you may know the amount of memory space that will be necessary. As an alternative, you can ask the computer to figure out the amount of space that will be required for the variable. To assist you with that, the C++ language provides a keyword named auto. You can use it to declare a variable instead of using a specific data type.
A Required Initialization
In previous sections, we saw examples of declaring variables without giving them initial values. This is allowed with you declare a variable using a known data type such as string. On the other hand, if you declare a variable using the auto keyword, you must immediately assign a value to the variable, which is referred to as initializing the variable. Therefore, the primary formula to declare an automatic variable is:
auto variable-name = some-value;
Here are examples of variables declared using the auto keyword:
#include <iostream>
using namespace std;
int main()
{
auto _ = "William ";
auto __ = "Jefferson ";
auto ___ = "Clinton";
cout << _ << __ << ___ << endl;
cout << "=========================";
}
When a Variable Must Have a Value
In some previous examples, we saw that is you declare a variable with a known type such as string, you don't have to initialize the variable immediately, and we saw that if you declare a variable with the auto keyword, you must initialize that variable immediately. One of the requirements of the C++ language is that, whenever you decide to use a variable in a cout << operation, that variable must have a value, whether you had initialized the variable when declaring it or, at one time, you assigned a value to the variable. This means that you can declare a variable, perform other operations, and then on another line, specify the value of the variable. The rule to observe is that, if you decide to display the value of the variable, you must first specify its value. This can be done as follow:
#include <iostream>
using namespace std;
int main()
{
string firstName = "Martial";
string lastName;
cout << "Employee Record" << endl;
cout << "-------------------------------" << endl;
cout << "Employee Name: ";
cout << firstName;
lastName = "Engolo";
cout << " ";
cout << lastName << endl;
cout << "===============================";
}
This would produce:
Employee Record ------------------------------- Employee Name: Martial Engolo =============================== Press any key to close this window . . .
Updating a Variable
When declaring a variable with a known type such as string, you don't have to initialize that variable. Still, you can initialize a variable, perform other operations, and then specify a new value for the variable. This means that, at any time, you can change the value of a variable. This is also referred to as updating the variable. When you update a variable, its previous value is lost and it assumes the new value. Here are examples:
##include <iostream>
using namespace std;
int main()
{
string employeeName = "Jennifer Crittenden";
cout << "Employees Records" << endl;
cout << "-----------------------------------" << endl;
cout << "Employee Name: " << employeeName << endl;
employeeName = "Armando Borda";
cout << "Employee Name: " << employeeName << endl;
employeeName = "Francine Thalos";
cout << "Employee Name: " << employeeName << endl;
cout << "===================================";
}
This would produce:
Employees Records ----------------------------------- Employee Name: Jennifer Crittenden Employee Name: Armando Borda Employee Name: Francine Thalos =================================== Press any key to close this window . . .
Declaring Many Variables
As we have seen so far, you can declare as many variables as you want. Here are examples:
#include <iostream>
using namespace std;
int main()
{
string firstName = "Paul";
string middleName = "Bertrand";
string lastName = "Yamaguchi";
string dateHired = "22 September 2025";
cout << "Employee Record" << endl;
cout << "--------------------------------------" << endl;
cout << "Employee Name: " << firstName << " " << middleName << " " << lastName << endl;
cout << "Date Hired: " << dateHired << endl;
cout << "======================================";
}
This would produce:
Employee Record -------------------------------------- Employee Name: Paul Bertrand Yamaguchi Date Hired: 22 September 2025 ====================================== Press any key to close this window . . .
If you want to declare variables of the same type, you can use their common data type, followed by names separated by commas, and ending with a semicolon. Here is an example:
#include <iostream>
using namespace std;
int main()
{
string firstName, middleName, lastName;
string dateHired = "22 September 2025";
cout << "Employee Record" << endl;
cout << "--------------------------------------" << endl;
firstName = "Paul";
middleName = "Bertrand";
lastName = "Yamaguchi";
cout << "Employee Name: " << firstName << " " << middleName << " " << lastName << endl;
cout << "Date Hired: " << dateHired << endl;
cout << "======================================";
}
You can initialize each variable with its own value. You don't have to initialize all variables, only those whose values you want to specify. Here is an example of declaring many variables using the same type, initializing some of the variables while not initializing others:
#include <iostream>
using namespace std;
int main()
{
string firstName = "Paul", middleName, lastName = "Yamaguchi", dateHired;
cout << "Employee Record" << endl;
cout << "--------------------------------------" << endl;
middleName = "Bertrand";
dateHired = "22 September 2025";
cout << "Employee Name: " << firstName << " " << middleName << " " << lastName << endl;
cout << "Date Hired: " << dateHired << endl;
cout << "======================================";
}
Remember that, before involving a variable in an operation, such as before displaying its value in a cout << operation, the variable must hold a valid value.
Declaring a Variable When you Need it
As done above, you can first declare a variable, do some other things, then specify the value of the variable as long as you do this before using the variable. If your code is long, that approach can make your code difficult to read. The suggestion is to declare a variable only at the time you need it, namely at the time you are assigning a value to the variable for the first time. Here are examples:
#include <iostream>
using namespace std;
int main()
{
cout << "Employee Record" << endl;
cout << "--------------------------------------" << endl;
string firstName = "Paul";
cout << "Employee Name: " << firstName;
cout << " ";
string middleName = "Bertrand";
cout << middleName;
cout << " ";
string lastName = "Yamaguchi";
cout << lastName;
cout << endl;
string dateHired = "22 September 2025";
cout << "Date Hired: " << dateHired << endl;
cout << "======================================";
}
Avoiding Unnecessary Variable Declarations
As we saw in our introductions, the idea to declare a variable is to store a value in the computer memory. You do this because you anticipate that you will need to use that variable more than once. If you use a value only once, you may not need to declare a variable for it. You can use the value directly where it is needed.
|
|
|||
| Previous | Copyright © 1998-2026, FunctionX | Friday 26 September 2025, 09:40 | Next |
|
|
|||