ECE1101 - Programming Fundamentals & Problem Solving
Lecture 2
Variables and Data Types
Dr. Mona Nashaat
Hello World
- A C++ program has a very specific structure in terms of how the
code is written.
- Let’s take a closer look at the Hello World program — line by line!
// This program outputs the message "Hello World!" to the
monitor
#include <iostream>
int main() {
std::cout << "Hello World!\n";
return 0;
}
- This program writes the phrase “Hello, World!” to your terminal.
2
Hello World
- C++ is a case-sensitive language.
- Case sensitivity means that your keywords and variable
declarations must match the case.
- For example, the C++ keyword for outputting is cout.
- If you were to type Cout or COUT, the compiler would not know
that your intention was to use the keyword cout.
- Let’s go over this hello.cpp program line by line:
// This program outputs the message "Hello World!" to the
monitor
- This is a single-line comment that documents this code. The
compiler will ignore everything after // to the end of the line.
3
Hello World
- Sometimes, you will find this comment to include the author’s
name or document what the code does.
#include <iostream>
- This is known as a pre-processor directive.
- It instructs the compiler to locate the file that contains code for a
library known as iostream.
- This library contains code that allows for input and output, such
as displaying data in the terminal window or reading input from
your keyboard.
4
Hello World
- Every C++ program must have a function called main().
- A function is basically a sequence of instructions for the
computer to execute.
- This main() function houses all of our instructions for our
program. This is where we will be writing our code.
int main() {
// Statements
}
5
Hello World
- This code uses a method known as cout (pronounced “see out”)
to send the text “Hello World!” to the terminal for output.
std::cout << "Hello World!\n";
- The return statement is used to end a function. If the program
reaches this statement, returning a value of 0 is an indication to
the operating system that the code executed successfully. This
line of code is optional.
return 0;
6
Code → Save → Compile → Execute
- C++ is a compiled language. That means that to get a C++
program to run, you must first translate it from a human-
readable form to something a machine can “understand.” That
translation is done by a program called a compiler.
- When you program in C++, you mainly go through 4 phases
during development:
• Code — writing the program
• Save — saving the program
• Compile — compiling via the terminal
• Execute — executing via the terminal
- And repeat (debug the errors if needed).
7
Variables
- A variable is a name that represents a particular piece of the
computer’s memory that has been set aside for storing,
retrieving, and using data.
• Declaring a variable
• Declaring multiple variables
• Constant variables
8
Creating a Variable
- In order to create a variable, three pieces of information need to
be present:
• Data type: The type of data the variable will store.
• Name: The unique name of the variable. Names cannot start with
a number and cannot be a C++ keyword.
• Value: The value the variable will store. This value must match the
type of the variable.
9
Declaring a Variable
- Declaration means to create a variable and assign a value to it.
This is also called initialization.
- The common expression is “initialize name to value”:
type name = value;
- Style tip: Variable names should be all lowercase, with
underscores between words.
- For example, student_id or result.
10
Defining a Variable
- Definition means to create a variable without assigning a value to
it:
type name;
11
Assigning a Variable
- To assign or change the value of an existing variable, state the
name of the variable followed by the assignment operator (=)
and the new value:
name = new_value;
- Note: changing the value of an existing variable will overwrite the
old value.
- Let’s look at some examples of variable declaration and
assignment in C++:
// Define a variable called letter
char letter;
// Declare a variable called x
int x = 100;
12
Declaring Multiple Variables
- Multiple variables of the same type can be declared in a single
statement using a comma-separated list. For example:
// Declare three integer variables
int a = 1, b = 2, c = 3;
- Avoid the two common mistakes that new programmers tend to
make when declaring multiple variables on a single line.
- The first mistake is giving each variable in the list a type:
// Incorrect syntax - no need to state int twice
int a = 1, int b = 2;
13
Declaring Multiple Variables
- The second mistake is trying to declare different types of
variables in the same statement:
// Incorrect syntax - we cannot declare int and double in
the same statement
int a = 1, double b = 2.3;
// Correct syntax
int a = 1;
double b = 2.2;
14
Constant Variables
- Constant variables are variables with values that cannot be
changed after initialization.
- The purpose of a constant variable is to protect its value from
being accidentally altered elsewhere in the program.
- Constant variables are declared with the const keyword. For
example:
const double pi = 3.14;
- It’s impossible to inadvertently change the value of a constant
variable after it has been declared:
const double pi = 3.14;
pi = 3.15; // Error: cannot assign value to const variable
15
Constant Variables
- Constant variables must be initialized when they are declared.
Declaring a constant variable without providing a value will
cause an error:
const double pi; // Error: cannot define const variable
without initialization
16
Data Types
- A variable in C++ must be assigned a specific type. Type is
important because it tells the compiler how to interpret the
content of a variable.
- There are 5 basic data types that every C++ programmer should
know about:
Type Usage Examples
int Integer numbers 0
-10
312
double Floating-point numbers 3.14
-200.0
char characters 'a’
'e'
string Sequence of characters “Hello World”
bool Truth values true
false
17
int
- int stores whole numbers without decimals.
- An int variable requires 4 bytes of memory space and ranges
from -2³¹ to 2³¹.
int moonLanding = 1969;
int age = 18;
- Byte = 8 bit
- Kilo byte = 1024 byte
- Mega byte= 1024 kilobyte
- Gigabyte= 1024 megabyte
- Terabyte = 1024 gigabyte
18
double
- double stores floating-point numbers with decimals.
- A double variable requires 8 bytes of memory space and is
sufficient for storing up to 15 decimal digits.
double pi = 3.1415;
double height = 1.75;
19
Type Conversion
- It is possible to convert int into double and vice versa.
- This is called a type conversion or a type casting.
- The notation (type) value means “convert value to type“. So for
example:
// Converting a double to an int
double a = 3.5;
int b = (int) a; // b is now 3
// Converting an int to a double
int c = 5;
double d = (double) c; // d is now 5.0
- Note: Going from double to int simply removes the decimal.
There’s no rounding involved.
20
char
- char stores a single character surrounded by single quotes ' ‘.
- A char variable requires 1 byte of memory space.
char first_letter = 'a';
21
string
- std::string stores a sequence of characters surrounded by double
quotes " ".
#include <string>
std::string message = "Hello World!";
- Note: std::string is not a built-in type; the <string> library must be
included before std::string can be used.
22
String Methods
- std::string comes with a lot of useful methods.
- Here are a few of them:
- The + operator can be used to combine strings together. This is
called concatenation:
std::string first_word = "Hello";
std::string second_word = "World";
std::string message = first_word + " " + second_word;
// message is now "Hello World"
23
String Methods
- The [] operator can be used to access the character at the
specified position in the string:
std::string message = "Hello World";
char letter = message[1];
// letter is now ‘e’
- Note: Index in C++ starts at 0, not 1.
24
String Methods
- The length() function can be used to get the length of a string:
std::string message = "Hello World";
int message_length = message.length();
// message_length is now 11
25
bool
- bool stores true or false boolean values. A bool variable requires
1 byte of memory space.
bool underaged = true;
bool certified = false;
- The main purpose of bool is to manage the flow of conditional
statements (ie. if-else, loop, etc.).
- Control Flow will be covered in more detail in the next section of
this course.
26
Example
- Calculate the Area of a Rectangle: create a program to
calculate the area of a rectangle (by multiplying the length and
width).
27
Example
- Calculate the Area of a Rectangle: create a program to
calculate the area of a rectangle (by multiplying the length and
width).
// Create integer variables
int length = 4;
int width = 6;
int area;
// Calculate the area of a rectangle
area = length * width;
// Print the variables
cout << "Length is: " << length << "\n";
cout << "Width is: " << width << "\n";
cout << "Area of the rectangle is: " << area << "\n"; 28