|
|
|
Declaring
Variables
If you want to be able to store data for temporary use in a
program, you have to declare variables to put the data in.
Declaring a variable in C++ is very easy. You may have already
noticed this in the Basic Input and Output with C++ tutorial.
We made a simple program that gets the user's age as input and
displays it back to the screen. Here is the source code:
//Source code View
#include
using namespace std;
int main()
{
int age;
cout << "My Second C++ Program" << endl;
cout << "Please enter your age in years"
<< " followed by
: ";
cin >> age;
cout << "nYou are " << age <<
" years old." << endl;
return 0;
}
As you can see from above, to declare the variable
"age" we just type the data type (int) in front of
it. You will also notice that we can specify the type of data
that we want the function main to return.
Now, we will write a program that uses a few more variables.
We will not only get the user's age, but their height, weight,
hair color, and eye color as well.
//Source Code View
#include
#include
using namespace std;
int main()
{
int age, feet, inches, pounds;
string hair, eye;
cout << "My third c++ program.nn";
cout << "Please type your answer to each
question"
<< "followed by
." << endl;
cout << "What is your age (years)? ";
cin >> age;
cout << "nHow tall are you (ft in)? ";
cin >> feet >> inches;
cout << "nHow much do you weigh (lbs)? ";
cin >> pounds;
cout << "nWhat color is your hair? ";
cin >> hair;
cout << "nWhat color are your eyes? ";
cin >> eye;
cout << endl << "nYou are " << age
<< " years old, "
<< feet << " feet " << inches
<< " inches tall." << "nYou weigh
" << pounds << " pounds,"
<< " have " << hair << "
colored hair and "
<< eye << " colored eyes." << endl;
return 0;
}
Please copy the text of the program above from your browser to
your c++ compiler and compile and execute.
You should notice that we can declare different variables of
the same type in one line. We simple separate them by a comma.
You should also notice that we included a file called string
and used strings to store characters. We will talk more about
strings when we get to classes and Object-Oriented
Programming. A class is another data type in c++.
One thing that I haven't mentioned yet is data-handling and
error detection. When we have an integer as a variable, there
is nothing we can do to prevent a user from trying to enter
invalid (such as a character) data. You will learn this later.
Whenever i get a chance...
{I Hope That the test programs are helping you in some way}
-kolij-
|
|