473,394 Members | 1,766 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,394 developers and data experts.

Class 3: Hello, Variables!

Ganon11
3,652 Expert 2GB
So we've taken a short look at Hello World and can slightly understand some C++ code. But enough looking around at code, it's time to write our own! In order to start off with the basics, we're going to learn about a few data types, such as integers, doubles, strings, and streams. Once we know how to use these very simple tools, we can begin making some useful programs.

A Stream is the fancy word programmers use when talking about input or output. Now, suppose I ask you to enter a number, and you enter 8490. You type this on your keyboard and then hit enter. Somehow, this number gets to my program, and I can use it for calculations or anything else I need. Imagine that this information travels through the computer from they keyboard to my program in a stream - a digital stream of information, with little fishies of data. OK, so there aren't any fishies. But can you imagine now what a stream is? Similarly, if I tell my program to output the words, "Hello World!", this information has to travel through another stream - from my program to your moniter. The two types of streams are called input streams and output streams. Looking back at Hello World, can you figure out what the output stream is?

If you guessed cout, you're correct! This is the standard output device in C++ programs - it has been predefined for us, the programmer, so it is easy to use. All we need to do is include the necessary header file <iostream> (for Input/Output STREAM) and say we're using the group of variables called std. The corresponding predefined input stream variable is called cin - for Common INput.

In order to use input, you need to have some room in the computer to store the value the user gives you. This room is called a variable. If you've taken algebra in school, you already know the basics of a variable. A variable can hold any value, and the way a program runs depends on this value. The user can input the value of, say, an integer, and your program will output the number squared. Obviously, the program cannot know what the user will enter, and so we must use a variable to be able to have our code be applicable to many situations.But in order to use variables, we have to understand some simple data types. Simple data types come in three forms: integral, floating-point, and enumeration. We'll worry about enumeration data types later.

Integral data types come in a few forms. Following is the full name of the data type, followed by its C++ nickname, followed by a description:

Integer (int): An integer data type. An integer is any whole number, such as 5, 2000, or -32. An integer variable, however, cannot hold a decimal number, such as 43.34. The integer data type is very versatile, usually able to hold numbers anywhere from -2147483648 and 2147483647. Therefore, we will be using integers most commonly for number values. I said 'usually able' because the specific size of an integer is determined by different systems. The system I use (Windows XP) has a 4 byte integer (-2147483648 to 2147483647), but some systems use a 2 byte integer (-32,768 to 32,767).

In order to find out which int your system uses, run the following short program in your C++ compiler:
Expand|Select|Wrap|Line Numbers
  1. #include <limits>
  2. #include <iostream>
  3.  
  4. int main() {
  5.     std::cout << "Int values range from " << INT_MIN << " to " << INT_MAX << std::endl;
  6.     system("PAUSE");
  7.     return 0;
  8. }
Long (long): Another integer data type. This data type specifies to your system that you want to use the 4 byte int type, with values from -2147483648 to 2147483647.

Short (short): Like the long type, but specifying the 2 byte integer (values from -32,768 to 32,767).

Boolean (bool): If you have taken a precalculus class, you will be familiar with Boolean expressions. A boolean variable holds one of only two possible values - true or false. Boolean variables are used to control certain aspects of your program using if... statements and loops. We'll be going over these structures shortly.

Character (char): Believe it or not, you're already familiar with character data types. A character is any single unit of text - such as 'e', or a backslash '\', or even this period. The computer holds this data as an integer between -128 and 127, since there are only 255 standard characters used in output. Now, because the computer stores characters as numbers, a few irregularities occur. The character 'A' is not 1 - it is actually 65. Also, we can add a number to a character variable to change the symbol it represents - if I added 3 to the preceding 'A', the char variable would then be 68, or 'D'. Finally, the character value of '5' is not 5, so be careful when using characters to hold numbers.

Floating-point data types fill in the final gap - holding decimal numbers. Floating-point data types can also hold integers, but instead of holding 32, this data type would hold 32.0.

Floating-Point (float): An all-purpose decimal number type. This data type can hold any value between -3.4E38 and 3.4E38 (That is, -3.4 * 10^38 and 2.4 * 10^38). Floating-point variables ca hold up to 6 or 7 significant digits in any variable. Thus, if I wanted to store the value 3.141592653589... in a float, the variable would only hold 3.141592 - close enough for common purposes, but not for extremely accurate mathematical purposes. As versatile as the floating-point data type is, C++ programmers generally use...

Double (double): Like the floating point data type, a double holds a decimal number, but the range of a double is -1.7E308 to 1.7E308. That's a lot of values! In addition, the double type holds up to 15 significant digits. In our above example, that's all the digits I entered plus a few more! Obviously, the double data type is much more accurate (and thus useful) then its counterpart - consequently, we will use doubles any time we need a decimal number.

One final data type is called a string.

String (string): A collection of characters that is used to hold words, or text. In Hello World, the "Hello, World!" portion of the code was a string. Can you see how it is a collection of characters? First the character "H', then 'e', then 'l', and so on.

Now, in order to use a variable, we must first declare it. Below are a few examples of variable declarations, and a few statements showing how to set a value into a variable:

Expand|Select|Wrap|Line Numbers
  1. int x; // Integer variable called x
  2. long numOfBoxes; // Long variable called numOfBoxes
  3. bool isDone; // Boolean variable called isDone
  4. char decision; // Character variable called decision
  5. string someText;
  6. float pi;
  7. double betterPI;
  8.  
  9. x = 32; // Any time we use x, the value 32 is used instead.  This is called intialization, 
  10.  
  11. as it is the first value set into x.
  12. isDone = false; // Boolean variables can be set to either true or false - these are reserved words in C++.  Anytime you use true or false, the C++ compiler knows what you mean.  NOTE: False and True are different than false and true, since C++ is case-sensitive.
  13.  
  14. decision = 'Y'; // In order to let C++ know that Y is a character, we enclose the letter in single-quotation marks.
  15. someText = "This is a sample string."; // Like the character, we need to let C++ know that the following text is a string.  To do so, we enclose the text in double-quotation marks.
  16. pi = 3.141592;
  17. betterPI = 3.141592653589;
  18.  
  19. int y = 16; // This is the same as two statements - one to declare y, and another to set y to 16.  We can type it like this, however, to save some time.
Now for some more fancy things to do with our variables, such as getting user input and declaring multiple variables in one line.

Expand|Select|Wrap|Line Numbers
  1. int a = 0, b = 1; // Declares a and b, both integer types, and sets them to 0 and 1, respectively.
  2.  
  3. cin >> a; // This will wait for the user to enter in a value, and then store that value inside a.  Note that, since the user is inputting to a, any previous information a held is lost.  That is, a no longer holds 0 - that 0 is gone forever.
  4.  
  5. double q = 0.0; // Same as initializing to 0, but use a decimal number with doubles in order to remind yourself that it is a decimal.
  6.  
  7. bool amICool = true, amILame = false;
  8.  
  9. cin >> b >> q; // This waits for two values from the user.  The first goes into b, and whatever remains goes into q.
Now to explain some irregularities with cin.

cin skips all whitespace characters when determining input. A whitespace character is a space (' '), a newline character (represented as '\n', and made when you hit the 'enter' key), or a tab (represented as '\t'). Note that the tab key and newline character, even though they are represented to us as two characters - the backslash and a letter - are considered by C++ to be one character. These are called escape sequences, and will be explained next chapter. Since cin skips whitespace, it uses the positions of spaces and such to determine when a value starts or stops. For instance, consider the following examples:

Expand|Select|Wrap|Line Numbers
  1. // User is prompted for input
  2. cin >> a; // User enters 34 and hits enter; 34 goes into a
  3.  
  4. cin >> b; // User enters a space, then 4, then another space, then 7, then enter.  4 goes into b, 6 is still in the input stream
  5. cin >> a; // The 6 from the last input goes into a, since it was still in the stream
  6.  
  7. double m;
  8. cin >> q >> m; // User enters 12.3, then a space, then 65.77, then hits enter.  q gets 12.3 and m gets 65.77.
  9.  
  10. cin >> a >> q; // Inputting into two different data types!  Note that this is completely legal.  User enters 3, then a space, then 5; a gets 3, q gets 5.0 (since it is a double)
  11.  
  12. cin >> a >> q; // User enters 34.05, then enter.  You may think this would be wrong, but it actually works.  Since a is an integer, cin looks for the first integer - namely, 34.  a gets 34, and q gets the leftover - 0.05.
  13.  
  14. string myMessage;
  15. cin >> myMessage; // User enters "Sunshine", "Sunshine" goes into myMessage;
  16. cin >> someText; // User enters "The Rain in Spain."  Since cin skips whitespace, only "The" 
  17.  
  18. is stored in someText - the rest of the data is stored for later.
  19. // If we want to get the whole line inside someText, we have to use a function called getline, as follows:
  20. getline(cin, someText); // User enters "The Rain in Spain." and all this text is stored in someText.  getline gets all text from the start of the stream until the newline character.
  21. cin >> decision; // User enters a; decision now stores 'a'
  22. cin >> decision; // User enters abcd; decision now stores 'a', and 'bcd' is stored for later.
  23. cin >> decision >> a; // User enters 25; decision gets '2', and a gets 5.
Finally, a short explanation of output.

In order to output, you have to use cout, as in Hello World. You type cout, then the insertion operation (known in C++ as <<), then whatever you wish to display. You can display any of these simple data types, since C++ knows what they are and how to use them. You can also display text that is not stored inside a variable by enclosing this text in quotation marks. Hello World took advantage of this ability. One final note about cout is that different elements must be seperated by the << operation. Thus, if you want to display some text, you can type the text to be displayed, end the text using a final quotation mark, then <<, then type in a varible name, then <<, then endl to go to a new line. The moniter will display your text, the variables value, and then go to a new line. Consider some examples of simple output:

Expand|Select|Wrap|Line Numbers
  1. cout << "What's up?" << endl; // Moniter displays the text What's up?
  2. cout << "5 + 3 = " << 5 + 3 << endl; // Moniter displayes 5 + 3 = 8.  The left side of the equation was enclosed in quotation marks, so no operations are performed on the numbers.  The right side, however, was not enclosed - C++ adds these numbers together to get 8, and displays 8.
  3. cout << "a^2 = " << a * a << endl; // Moniter displays a^2 = , and then the value of a squared.  There is no ^ operation in C++, so if we want to, say, cube a, we must write a * a * a.  In C++, * means multiplicatiopn, instead of x or X.  Similarly, / means division.
  4. cout << "Please enter an integer: "; // Displays the text, but does not go to a new line!  This looks good if you want to follow this display with a prompt for user input, as the user's input will appear on the same line.
  5. string message = "Hello, World!";
  6. cout << message << endl; // Moniter displays Hello, World! - the value stored in message.
Hopefully, this short explanation of output, input, and variables has not utterly confused you! In order to see if you understand the basics, I'd like you to write a program that

does the following:

1) Declares 3 integer variables, a, b, and c
2) Displays a message asking the user for input
3) Prompt the user for input into a, b, and c
4) Displays a message including the values of a, b, and c
5) Declares 2 string variables
6) Displays a message asking the user for input into the string
7) Prompt the user for input using cin
8) Prompt the user for input into the second string using getline
9) Displays the text entered by the user
10) The final two lines of your program must be:

system("PAUSE");
return 0;

Use the basic shell of a C++ program below to get started:

#include <iostream>
using namespace std;

int main() {
// Variable declarations
// Other statements
// Display statements

system("PAUSE");
return 0;
}

and PM me your resulting code if you'd like to have me check your work.

Until next time, when we'll look at more stream functions and escape characters!
Jan 12 '07 #1
0 4439

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: nielson | last post by:
I have a class which contains (1) a class variable and (2) a method (e.g., methodA) which returns a reference to the class variable. If the variable has been assigned a value by a constant...
3
by: nikolai.onken | last post by:
Hello, I got following problem trying to inherit a variable from another class class Core { public $obj; function initialize($obj) {
34
by: SeeBelow | last post by:
I see the value of a class when two or more instances will be created, but Python programmers regularly use a class when there will only be one instance. What is the benefit of this? It has a...
4
by: Neil Zanella | last post by:
Hello, I would like to know whether it is possible to define static class methods and data members in Python (similar to the way it can be done in C++ or Java). These do not seem to be mentioned...
3
by: Neil Zanella | last post by:
Hello, It seems to me that using too many variables at class scope in C++ (e.g. private data members) can be just as bad as having a C program with lots of global variables. This is especially...
5
by: Diffident | last post by:
Hello All, I have written a webform which is by default derived from "Page" class. I have coded another utility class with few methods and an object of this class is instantiated from the webfom...
6
by: Tony Johansson | last post by:
Hello!! If you write private class Test {} you have a private class If you write public class Test {} you have a public class If you write protected class Test {} you have a protected class If...
3
by: shapper | last post by:
Hello, I created a simple class as follows: Public Class HelloWorld Public Function SayMessage() As String Return "Hello World!" End Function
4
by: chandu | last post by:
Hello, declaring class level variables is good approach or not in c#. in C++ we used prefer diclaring class level variables more than local variables. i had a discussion with somebody that...
5
by: Web Search Store | last post by:
Hello, I made a web page using visual studio. I also made a public class in the app_code folder called 'allvars' In the main web page durning the page startup, I can refer to public shared...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.