C++ 2. Variables
C++ 2. Variables
PRG1002 - Programming I
● Scope of a Variable
● A data type is a classification of data which tells the compiler or interpreter how the programmer
intends to use the data.
○ Abstract or user defined data type: These data types are defined by the user.
Primitive Data Types
● Integer: Used for storing whole numbers (100, 20, 4, and so on...). Keyword is int.
● Character: Used for storing a single character (4, b, $, and so on…). Keyword is char.
● Boolean: Used for storing boolean or logical values (true or false). Keyword is bool.
Represented in memory as 1 for true and 0 for false.
● Floating point: Used for storing values with decimal point (3.1415927). Keyword is float.
Can have upto 7 decimal places.
● Double floating point: Used for storing values with decimal point (3.141592653589794).
Keyword is double.
Can have upto 15 decimal places.
Primitive Data Types
● Data type modifiers are used with the primitive data types to modify the length of data that a
particular data type can hold.
● signed, unsigned, long and short modifiers can be used for int.
unsigned int
4 bytes 0 to 4,294,967,295
unsigned long int
int
-2,147,483,648 to
4 bytes
long int 2,147,483,647
Data type modifiers
double
8 bytes +/- 1.7e +/- 308 (~15 digits)
long double
Data type modifiers
● Unsigned short int can hold values between 0 to 65,535, whereas signed short int can values hold
from -32,767 to 32,767.
#include <iostream>
int main()
{
// a signed short integer - signed by default
short int signInt = 0;
// an unsigned short integer
short unsigned int unSignInt = 0;
// changing the value of unsigned variable to 50000
unSignInt = 40000;
// changing the value of signed variable with the value of unsigned variable
signInt = unSignInt;
// printint out the value of singed and unsigned variables
cout << "Unsigned integer value: " << unSignInt << endl; // Output: 40000
cout << "Signed integer value: " << signInt << endl; // What do you expect?
}
Data type summary
● The basic data types in C++ are: int, double, float, bool, & char.
● We can modify the range of basic data types using data type modifiers (signed, unsigned, long &
short).
● Each data type requires a specific amount of memory (between 1 byte and 8 bytes).
● Variables are used to store information that can be referenced and manipulated by a computer
program. It is called variable because we can change the value stored.
● It is a way of labelling data with a descriptive name, so our program is easier to understand.
● Variables are like containers that hold information. The purpose of them is to label and store data in
computer memory (RAM).
● Different types of variables require different amounts of memory, and have a specific set of
operations which can be applied to them.
○ Imagine a large warehouse with lots of storage bay, tables, shelves, special room etc. We can
store different type of items in each of these places.
MEMORY
int sum 348
● C++ is a strongly-typed programming language, so it requires every variable to be declared with its
type before its first use. A typical variable declaration and initialization is of this form:
● A variable has a valid C++ data type, like the primitive data types we just saw. Examples are:
○ int number = 3;
○ float value = -23.45;
○ bool finished = false;
○ char letter = ‘a’;
Variable naming
● There are some defined naming conventions for C++ variables, but there is no particular standard
naming convention
● Once a variable is declared, it can only store a value belonging to the declared type.
● Once a variable is declared, you can assign different values to it via the assignment operator =, as long
as the data type of the value does not change.
● Each variable can be declared once. A variable can be used inside the code as long as it is declared
before being used.
● In the below example, we are creating 4 different types variables that can store 4 different types of
values. Note, the float values always end with f.
● To print out the values of the variable we use the name of the variable.
● The syntax for declaring and initializing a variable is: data_type variable_name = value;
● Global variables have their scope throughout the program, they can be accessed anywhere in the
program.
#include <iostream>
int main()
{
// changing the value of the global variable to 13
globalVar = 13;
// printing out the value to the screen
cout << globalVar << endl; // 13
}
Local Variable
int main()
{
int number = 5;
std::cout << number << endl; // 5
}
● A block of code is defined by curly braces. In this example, the number variable that is declared inside
of the main function can only be used inside of that function (inside of that block of code). We will get
a compilation error if we try to use number outside of main().
Using Variable Scope
● If a variable is only used inside of block of code, it should be declared inside of that code block (it
should have local scope)
● If a variable is used by multiple functions, it may be appropriate to give it global scope (declare it
outside of the main function)
● Using global scope can be dangerous if you are not careful, so use local scope whenever possible
Variable Scope Summary
● If a variable is declared outside of any function, it has global scope and is available to all functions in
the program file.
● If a variable is declared between curly braces (inside of a code block), it has local scope and it is only
available within that code block
Input and Output
Output (cout <<)
● Output in C++ is done via cout and the stream insertion operator << chains items.
cout << "Hello " << "world!" << endl;
● We can also use \n, which denotes a newline character just like endl. Similarly, you could use \t
which denotes tab character, to move the cursor to the next tab position.
int number = 3;
char letter = ‘a’;
● Input in C++ is done via cin and the stream extraction operator >> reads input from the keyboard and
store the value into a variable.
#include <iostream>
int main()
{
// creating a float variable with a default value
float studentMark = 100.0f;
// get input from the user to change the student's mark
cin >> studentMark; // user gives a value of 65.2
// print out the student's mark on the screen
cout << studentMark << endl; // Output: 65.2
}
Stream Manipulators
● C++ offers a number of stream manipulators that can be used to alter input and output values.
● While manipulators can be applied to input or output streams, many of them are only applicable to
one or the other.
showpoint Display decimal point and trailing zeros for all real numbers
noshowpoint Hide decimal point and trailing zeros for whole numbers
setprecision(p) Display p fractional digits for all subsequent output of real values
Output formatting examples
// setprecision will set digits after decimal point for fixed floats
cout << fixed << setprecision(5);
cout << 123.34645 << "\n";
// 123.34645
Activity - Play with formatting
● Getting data from the user is done using cin follow by the stream extraction operator >>.
● Outputting data to the screen is done using cout followed by the stream insertion operator <<.
● We can format and manipulate output printed with cout using stream manipulators.
Grimes, R (2017). Beginning C++ Programming. (1st ed.). United Kingdom: Packt Publishing Ltd