You are on page 1of 39

Bachelor of Information Technology

PRG1002 - Programming I

Data Types and


Variables

Storing values in computer memory and using them.


● Data types and modifiers
Contents
● What is a Variable?

● Variable declarations and Initialization

● Scope of a Variable

● Output (cout <<)

● Input (cin >>)

● Stream manipulators for output formatting


Data types
Data Types

● A data type is a classification of data which tells the compiler or interpreter how the programmer
intends to use the data.

● Data Types in C++ is mainly divided into two types:


○ Primitive Data Types: These are predefined or built-in data types and can be used directly by
the programmer to declare variables. The following are the basic data types we could use:
■ Integer
■ Character
■ Boolean
■ Floating point
■ Double floating point

○ 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

Type Bit width Range

int 4 bytes -2147483648 to 2147483647

char 1 byte -127 to 128 or 0 to 255

bool 1 byte true or false

float 4 bytes +/- 3.4e +/- 38 (~7 digits)

double 8 bytes +/- 1.7e +/- 308 (~15 digits)


Data type modifiers

● Data type modifiers are used with the primitive data types to modify the length of data that a
particular data type can hold.

● Data type modifiers available in C++ are:


○ Signed
○ Unsigned
○ Short
○ Long

● signed, unsigned, long and short modifiers can be used for int.

● signed and unsigned can be used for char.

● long can be used for double.


Data type modifiers

Type Bit width Range

short int 2 bytes -32,768 to 32,767

unsigned short int 2 bytes 0 to 65,535

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

Type Bit width Range

char 1 byte -127 to 128 or 0 to 255

signed char 1 byte -128 to 127

unsigned char 1 byte 0 to 255

float 4 bytes +/- 3.4e +/- 38 (~7 digits)

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>

using namespace std;

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).

● Be careful storing unsigned values into signed variables.


Variables
What is a Variable?

● 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

char grade ‘C’

float score 4.32


Variable data type

● 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:

data_type name = value;

● 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

● A variable has a name that can consist of:


○ Alphabets (both upper and lower case), numbers and the underscore ‘_’ character.
○ The name is needed to uniquely identify and reference a variable, so as to assign a value to the
variable (e.g., radius = 3.2).
○ It can also be used to retrieve the value stored (e.g., circumference = 2* PI * radius).

● A name cannot begin with a number

● There are some defined naming conventions for C++ variables, but there is no particular standard
naming convention

○ Use the naming convention designated by your company or team


Variable values
● A variable can store a value of the declared data_type. For example, an int variable can store an
integer value such as 123, but a floating point number such as 12.354 is stored in a float variable.

● To use a variable, we need to first declare its name and type.

● Once a variable is declared, it can only store a value belonging to the declared type.

● =, known as assignment operator, can be used to assign a value to the variable.

// Syntax: Declare a variable of a type,


// and assign an initial value
// variable-type variable-name = initial-value
int sum = 0;
float radius = 1.4f;
Variable assignment

● 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.

// declare a variable named "number" of the type "int"


int number;
// assign an integer value of 78 to the variable "number"
number = 99;
// declare a variable named "sum" of type "int",
// and assign initial value of 0
int sum = 0;
// Evaluate "sum + number",
// and assign the result back to "sum"
sum = sum + number;

● Each variable can be declared once. A variable can be used inside the code as long as it is declared
before being used.

● Each declaration and assignment statement is terminated with semicolon (;)


Variable declaration and initialization

● 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.

int studentNo = 6000; // int variable storing whole value


float studentMark = 56.5f; // float variable storing floating point value
char grade = 'C'; // char variable storing a character value
bool hasStudentPassed = true; // boolean variable storing true or false

● To print out the values of the variable we use the name of the variable.

cout << studentNo << endl; // 6000


cout << studentMark << endl; // 56.5
cout << grade << endl; // C
cout << hasStudentPassed << endl; // 1
Activity - Create some variables

● Open Visual Studio

● Create a new C++ project named MyFirstC++Variables

● Create the following variables to store details of an employee:


○ An integer variable called empNo and assign a value of 10.
○ A float variable called empSalary and assign a value of 675.34.
○ A boolean variable called empEmploymentStatus and assign either true or false.
○ A character variable called empMartialStatus and assign either S or M.

● Print out all the variables on to the screen.

● Build the program.

● Run the program.


Variable Summary

● The syntax for declaring and initializing a variable is: data_type variable_name = value;

● A variable is a name or label for a stored value.

● A variable must be declared with a data type.

● Once we declare a variable, we cannot change its data type.


Variable Scope
Scope of a Variable

● There are two different types of variables based on the scope.


○ Global Variable
○ Local Variable

● The scope of a variable is determined by where in the program is is declared.


Global Variable

● A variable declared outside of main() is called a global variable.

● Global variables have their scope throughout the program, they can be accessed anywhere in the
program.
#include <iostream>

using namespace std;

int globalVar = 20; // a global integer variable

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

● Variables declared inside of a block of code have local scope.

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

● The point in a program where a variable is declared determines its scope.

● 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;

● In the above example,


○ The endl can be used to produce a newline. Whenever an endl is printed, the cursor moves to the beginning of
the next line without any visible output.
○ A string is enclosed by a pair of double quotes (“any_text”), will be printed as it is, including punctuation marks
within the double quotes.

● 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.

cout << "hello world, again!\n";


cout << "\thello,\none\tmore\ttime.\n";
Output (cout <<)

● cout can print out numbers too.

cout << 1 << 2 << 3 << endl;

● We can also print out the value stored in a variable.

int number = 3;
char letter = ‘a’;

cout << number << letter << endl;


Input (cin >>)

● 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>

using namespace std;

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.

● The iostream and iomanip libraries offer stream manipulators.

● While manipulators can be applied to input or output streams, many of them are only applicable to
one or the other.

● We will look at using stream manipulators for output in this lesson.


Input/Output formatting

● C++ offers several output manipulators from iostream:

Format value Meaning

left Display values left justified within a field

right Display values right justified within a field (default).

showpoint Display decimal point and trailing zeros for all real numbers

noshowpoint Hide decimal point and trailing zeros for whole numbers

fixed Use fixed-point notations for real values

scientific Use scientific notations for real values

boolalpha Display boolean values as strings true or false

width(w) Sets the width of the output field


Input/Output manipulation

● C++ also offers output manipulators from iomanip:

Format value Meaning

setw(w) Display the next values in a field of size w (default 1).

setprecision(p) Display p fractional digits for all subsequent output of real values
Output formatting examples

double a = 3.1415926534; bool b = true;


double b = 2006.0; cout << boolalpha << b << "\n";
double c = 1.0e-10; // true
cout << noboolalpha << b << "\n";
cout << "default:\t"; // 1
cout << a << "\t" << b << "\t" << c << "\t";
cout << "\n";
int n = -77;
// default: 3.14159 2006 1e-10
cout.width(6);
// internal separates sign from digits
cout << "fixed:\t" << fixed;
cout << internal << n << "\n";
cout << a << "\t" << b << "\t" << c << "\t";
// - 77
cout << "\n";
cout.width(6);
// fixed: 3.141593 2006.000000 0.000000
cout << left << n << "\n";
// -77
cout << "scientific:\t" << scientific;
cout.width(6);
cout << a << "\t" << b << "\t" << c << "\t";
cout << right << n << "\n";
// scientific: 3.141593e+00 2.006000e+03 1.000000e-10
// -77
Output manipulation examples
// Set width of output field to 10 characters
// Holds until another width is set
cout << setw(10);
// By default output is right-justified
cout << 77 << endl;
// 77
// Use ‘left’ to left-justify text in the field
cout << left << 77 << endl;
// 77

// setprecision will set total digits for non-fixed floats


cout << setprecision(5);
cout << 123.34645 << "\n";
// 123.35

// setprecision will set digits after decimal point for fixed floats
cout << fixed << setprecision(5);
cout << 123.34645 << "\n";
// 123.34645
Activity - Play with formatting

● Open Visual Studio

● Create a new C++ project named Menu

● Create the following variables to store details for a menu:


○ A float variable called coffeePrice and assign a value of 3.50.
○ A float variable called teaPrice and assign a value of 3.00.

● Print a menu to the screen formatted as follows:


Menu
---------------------
Item Price
coffee 3.50
tea 3.00

● Build and run the program.


Input/Output Summary

● 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.

● There are many stream manipulators available in the iostream library.

● There are also manipulators available in the iomanip library.


○ You must #include <iomanip> to use these (setw, setprecision).
References

Grimes, R (2017). Beginning C++ Programming. (1st ed.). United Kingdom: Packt Publishing Ltd

Mikeblome. 2019. Microsoftcom. [Online]. [4 July 2019]. Available from:


https://docs.microsoft.com/en-us/cpp/cpp/fundamental-types-cpp

Beginnersbookcom. 2017. Beginnersbookcom. [Online]. [4 July 2019]. Available from:


https://beginnersbook.com/2017/08/cpp-variables/

Tutorialspointcom. 2019. Wwwtutorialspointcom. [Online]. [4 July 2019]. Available from:


https://www.tutorialspoint.com/cplusplus/cpp_variable_types

You might also like