C++/Variables and User Input

From Wikiversity
< C++
Jump to navigation Jump to search

Variables[edit | edit source]

Variables are used by the computer, as specified by you in your program, to record the current state of play at each step of the execution of your program so that your computer can suspend execution of your program at any point, step away, attend to some other matter, return and then continue its execution of your program without losing any information in the process.

The amount of work that a computer does in each step depends on the architecture of the computer, that is to say, how the computer has been designed.

Where are they held?[edit | edit source]

Variables are located in the minds of programmers and in the memory of computers. Programmers uses symbolic names to describe variables in their minds, for instance: 'the depth of the snow on the mountain' or "the amount of money in the customer's bank account". Ultimately, for reasons of efficiency, locations in computer memory are referred to by numbers often represented in awkward hexadecimal notation, for example: 0xcafebabe. The compiler assists programmers by managing the relationship between the symbolic and numeric representations of the locations of variables to reduce the number of errors that programmers would surely make if there were required to refer to every variable they have in mind purely by its current location in the memories of their computers.

C++ requires the programmer to use names constructed solely from letters chosen from a through z, A through Z, and numbers chosen from 0 through 9. C++ considers upper case letters to be different from lower case lowercase letters. Names must start with a letter.

Thus C++ allows :

a

to be used as a variable name. Further examples of variable names that are permitted by C++ include: A, a1, alpha, abc22, snowDepth, amountInCustomerAccount etc. "Customer's account balance" is not a valid variable name in C++ because it contains spaces which are not allowed and because it contains an apostrophe which is also not permitted by C++ in variable names.

However, while the definition of the C++ language allows other letters to be used in variable names such as:

𝝰 

most C++ compilers and editors fail to support such letters reflecting a bias that unfortunately you will be required to perpetuate if you wish to publish the source code of your program.

How big are they?[edit | edit source]

Whilst in the imagination of programmers variables can be as big or as small as required, in reality, C++ programs are expected to execute on physical computers that only have a finite amount of memory. Worse, each bit of memory in a finite computer is also of finite size. Thus the smallest amount of memory that can be described by a C++ variable is one bit and the maximum is the size of the memory implemented by the architecture of the specific computer the program is executing on.

How many are there?[edit | edit source]

Again, in the mind of the programmer, the number of variables is unlimited, but on a real computer with a specific architecture there will be an upper limit which the computer industry has struggled to raise for decades with very little effect. As noted above, computers use numbers to name variables, the smallest amount of memory that can be used on a physical computer is one bit and compilers are programs that describe variables by connecting names to numbers, thus if you have a 32 bit architecture computer the maximum number of variables that you can hope to address in a C++ program is the number of possible numbers that can be described with 32 bits. Of course in reality due to poor coding technique, most compilers do not achieve this theoretical upper limit.

Declaring variables[edit | edit source]

Declaring variables is easy just <variable_type> <variable_name>.

Let's say you want to declare an integer.

int myInt;

Assigning values[edit | edit source]

What are variables without values? In order to use a variable you just need to declare it and give it a value.

myInt = 0;

Can't I just declare myInt and assign it a value in one go? The answer is Yes! we can as in the following way :

int myInt = 0;

Types of Variables[edit | edit source]

Boolean (bool)[edit | edit source]

The bool type is a 1 byte data type that is either true or false. A true being any number other than zero and false being zero. The true keyword uses the value 1 to assign true.

bool canJump = false;

Integers[edit | edit source]

An integer is a number that does not have any decimal places. It is a whole number, for example 1,2,3,4 are all integers. 4.3 is not. If you were to try and place the number 4.3 into an integer the number will be truncated to 4.

// short is normally defined as a 16-bit integer.
signed short int myVariableName1;  // stores from -32768 to +32767
signed short myVariableName2;  // same as signed short int
unsigned short int myVariableName3;  // stores from 0 to 65535
unsigned short myVariableName4;  // same as unsigned short int
short int myVariableName5;  // same as signed short int
short myVariableName6;  // same as short int

// long is normally defined as a 32-bit integer.
signed long int myVariableName7;  // stores from -2147483648 to +2147483647
signed long myVariableName8;  // same as signed long int
unsigned long int myVariableName9;  // stores from 0 to 4294967295
unsigned long myVariableName10;  // same as unsigned long int
long int myVariableName11;  // same as signed long int
long myVariableName12;  // same as long int

// int can be either a 16-bit or a 32-bit integer, depending on the compiler.
signed int myVariableName13;  // either signed short or signed long
unsigned int myVariableName14;  // either unsigned short or unsigned long
int myVariableName15;  // same as signed int

Now we can attribute reasons to the ranges of int , long and so on. for int : 2^16 = 65536. now this is the total range of a variable . Dividing by 2 we get , 32768. So -32768 to 32767 ( it should have been 32768 but 1 place is taken by 0 ).


Now the size of long is 4 bytes ( 32 bits) . So range is 2^32.

What is the difference between a "long" and a "signed long int"? In my mind, the only difference is 12 extra keystrokes. Pick one that works for you.

Char[edit | edit source]

A char is an 8 bit integer. This means that an unsigned char can store between 0 and 255, and a signed char can store between -128 and 127. Unsigned chars are commonly used to store text in ASCII format, and can be used to store strings of information. A char can be initialized to hold either a number or a character, but it will store only the ASCII value.

char myChar='A';
char myOtherChar=65;

Both characters that I have just initialized would be equal. The number 65 is the ASCII code for the letter 'A', so both characters would contain the 8-bit value of 65, or the letter 'A'. ASCII is a system where numerical value is assigned to every character you can think of. For a complete conversion chart visit http://ascii-code.com/

Floats[edit | edit source]

Floats are floating point numbers, which means that these numbers can hold decimal places. This allows us to store numbers such as "8.344" and "3432432653.24123".

float myFloat;  // Creates a floating point variable
myFloat = 8.3;  // Stores 8.3 in the new variable

Floating point numbers have a fixed size in memory. This means that a single float cannot possibly precisely store all of the decimal values in the real number system. While in many cases it will not matter, it is important to note the float data type usually stores only a good approximation of a decimal value, not an exact value.

Doubles[edit | edit source]

Doubles are like "floats", which means they can store decimal places. Doubles can generally store more information than a standard float.

double myDouble;   // Created myDouble
myDouble = 8.78;   // Stores 8.78 in myDouble

As noted with the float data type, double usually stores only an approximation of exact decimal values (albeit, usually a higher precision approximation than the smaller float data type).

Lesson 2 Program[edit | edit source]

Getting User Input[edit | edit source]

Let's start simple. We'll read in a char and put it back out.

#include <iostream>

int main()
{
    char myChar;

    std::cout << "Enter a character. ENTER: ";
    std::cin >> myChar;
    std::cout << "You entered: " << myChar << std::endl;
    std::cin.clear(); //ignore any superfluous input
    std::cin.sync();  //synchronize with the console
    std::cin.get();   //wait for the user to exit the program

    return 0;
}


you could also go with a namespace, as shown here:


#include <iostream>

using namespace std;

int main()
{
    char myChar;

    cout << "Enter a character. ENTER: ";
    cin >> myChar;
    cout << "You entered: " << myChar << endl;
    cin.clear();
    cin.sync();
    cin.get();

    return 0;
}

What if we want to read in an integer and put it back out.

#include <iostream>
using namespace std;
int main()
{
    int myInt;
    cout << "Enter an integer and press ENTER: ";
    cin >> myInt;
    cout << "You entered: " << myInt << endl;
    return 0;
}

Where To Go Next[edit | edit source]

Topics in C++
Beginners Data Structures Advanced
Part of the School of Computer Science