0% found this document useful (0 votes)
36 views

DCIT22 2020 Lecture 2 Introduction To Programming Part4

The document discusses different types of computer memory including cache memory, RAM, and persistent storage. It also covers data types such as integers, floating point numbers, characters, strings, and Booleans. Common escape sequences and declaring variables are explained.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

DCIT22 2020 Lecture 2 Introduction To Programming Part4

The document discusses different types of computer memory including cache memory, RAM, and persistent storage. It also covers data types such as integers, floating point numbers, characters, strings, and Booleans. Common escape sequences and declaring variables are explained.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

MEMORY, DATA TYPE, VARIABLES & ARITHMETIC OPERATORS

KISS (Keep It Simple Software): Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is
better than insecure

MEMORY

Computer programs consist of instructions and data. Instructions, written in a programming language such
as C++ and then translated by the compiler and linker into machine language, give the computer step-by-step
directions on what to do. The data is the information that is the subject of the program. The computer
program’s instructions and data have to be in the computer’s memory for the program to work.

Types of Memory
There are three principal memory locations on your computer.
The central processing unit (CPU)
Random access memory (RAM)
Persistent storage

Cache Memory
The faster the CPU’s speed, the faster your computer runs.

A hertz, named after Heinrich Hertz, who first detected electromagnetic waves, represents one cycle per
second. CPU speed is measured in megahertz (MHz), which represents one million cycles per second, or
gigahertz (GHz), which represents 1 billion cycles per second. For example, a CPU that runs at 800 MHz
executes 800 million cycles per second. Each computer instruction requires a fixed number of cycles, so the
CPU speed determines how many instructions per second the CPU can execute.

The CPU, in addition to coordinating the computer’s operations, also has memory, called cache memory. The
CPU’s cache memory includes a segment called a register. This memory is used to store frequently used
instructions and data. The CPU can access cache memory extremely quickly because it doesn’t have far to
go; the memory is right on the CPU. However, the amount of available cache memory is quite small; there is
only enough room for the most frequently used instructions and data. The remainder of the instructions and
data have to be stored somewhere else.

Random Access Memory


The more RAM a computer has, the more programs it can run at one time, and the faster it runs.

The CPU can access RAM almost as quickly as cache memory. Additionally, the amount of RAM available to
store instructions and data is much larger than the amount of available cache memory. However, RAM, like
cache memory, is temporary. Instructions and data contained in main memory are lost once the computer is
powered down.

Persistent Storage

That other, persistent type of computer memory is called, naturally enough, persistent storage. This usually
is a hard drive, but also could be, among other devices, a CD-ROM or DVD-ROM, floppy or zip disk, or optical
drive. However, no matter what storage device is used, persistent storage is lasting; instructions and data
remain stored even when the computer is powered down. Thus, your computer can be turned off for
months, but when it is turned on, the files you previously saved are still there.

DCIT22- Computer Programming I Memory, Data Type and Variables


1
Persistent storage has a much larger capacity than RAM—about one hundred to one thousand times larger.
Since persistent storage is lasting and has a very large capacity, it is used to store both programs and data.
A computer program cannot execute instructions located in persistent storage. The instructions must be
loaded from persistent storage into RAM. Similarly, a computer program cannot manipulate data located in
persistent storage. This data likewise must be loaded from persistent storage into RAM.

Addresses

Locations in memory are identified by address. These addresses usually are expressed as hexadecimal (Base
16) numbers such as 0x8fc1.

DATA TYPES

Whole Number Data Types

Whole Number Data Types, Sizes, and Ranges


Data Type Size (in Bytes) Range
short 2 –32,768 to 32,767
unsigned short 2 0 to 65,365
int 4 –2,147,483,648 to 2,147,483,647
unsigned int 4 0 to 4,294,987,295
long 4 –2,147,483,648 to 2,147,483,647
unsigned long 4 0 to 4,294,987,295

Unsigned vs. Signed Data Type

Unsigned means the number is always zero or positive, never negative. Signed means the number may be
negative or positive (or zero). If you don’t specify signed or unsigned, the data type is presumed to be
signed. Thus, signed short and short are the same.

Floating-Point Data Types

The term floating point comes from the fact that there is no fixed number of digits before and after the
decimal point; that is, the decimal point can float. Floating-point numbers also are sometimes referred to as
real numbers.

Floating-point Number Data Types, Sizes, and Ranges


Data Type Size (in Bytes) Range (in E notation)
float 4 ±3.4E-38 to ±3.4E38
double 8 ±1.7E-308 to ±1.7E308
long double 10 ±3.4E-4932 to ±3.4E4932

Text Data Types

There are two text data types. The first is char, which stands for character. It usually is 1 byte, and can
represent any single character, including a letter, a digit, a punctuation mark, or a space.
The second text data type is string. The string data type may store a number of characters, including this
sentence, or paragraph, or page. The number of bytes required depends on the number of characters
involved.

DCIT22- Computer Programming I Memory, Data Type and Variables


2
Storage of Character Values

ANSI (American National Standards Institute) and ASCII (American Standards Committee for Information
Interchange) adopted for the English language a set of 256 characters, which includes all alphabetical
characters (upper- and lowercase), digits and punctuation marks, and even characters used in graphics and
line drawing. Each of these 256 different characters is represented by a number between 0 and 255 that it
corresponds to.

ASCII Values of Commonly Used Characters


Characters Values Comments
0 through 9 48–57 0 is 48, 9 is 57
A through Z 65–90 A is 65, Z is 90
a through z 97–122 a is 97, z is 122

Storage of Strings
The amount of memory required for a string depends on the number of characters in the string. However,
each memory address set aside for the string would store one character of the string.

The bool Data Type


There is one more data type, bool. This data type has only two possible values, true and false, and its size
usually is one byte. The bool data type is mentioned separately since it does not neatly fit into either the
number or text categories. It could be regarded as a numeric data type in that zero is seen as false, and one
(or any other non-zero number) as true. While it may not seem intuitive why zero would be false and one
would be true, remember that computers essentially store information in switches, where 1 is on, and 0 is
off.

ESCAPE SEQUENCES

“\n” is a special type of string called an escape sequence. C++ has many escape sequences, though this may
be the commonest one. This particular escape sequence causes the cursor to go to the next line for further
printing. Without it, all the output would be on one line. The “\n” in a string is not displayed literally by cout
even though it is encased in double quotes. The reason is that the backslash signals cout that this is an
escape sequence.

Common Escape Sequences


Escape Sequence Name What It does
\a Alarm Causes the computer to beep
\n newline Causes the cursor to go to the next line
\t Tab Causes the cursor to go to the next tab stop
\\ Backslash Causes a backslash to be printed
\' Single quote Causes a single quote to be printed
\” Double quote Causes a single quote to be printed

DCIT22- Computer Programming I Memory, Data Type and Variables


3
DECLARING VARIABLES

Declaring a variable not only reserves memory, but also gives a convenient way of referring to that reserved
memory when you need to do so in your program.

Syntax of Declaring Variables

[data type] [variable name] ;

The data type may be any of int, float, bool, char, or string. The variable name is an alias by which you can
refer in code to the area of reserved memory. Thus, when you name a variable that relates to a test score
testScore, you can refer in code to the reserved memory by the name testScore instead of by a hexadecimal
value such as 0012FED4.

Finally, the variable declaration ends with a semicolon. The semicolon tells the compiler that the statement
has ended.

Naming the Variable

Variables, like people, have names, which are used to identify the variable so you can refer to it in code.
Updatable
There are only a few limitations on how you can name a variable.
The variable name cannot begin with any character other than a letter of the alphabet (A–Z or a–z)
or an underscore (_). Secret agents may be named 007, but not variables. However, the second and
following characters of the variable name may be digits, letters, or underscores.
The variable name cannot contain embedded spaces, such as My Variable, or punctuation marks
other than the underscore character (_).
The variable name cannot be the same as a word reserved by C++, such as main or int.

It is a good idea to give your variables names that are meaningful. Use a variable name that is descriptive of
the purpose of the variable. For example, testScore is descriptive of a variable that represents a test score.

Naming Conventions

A naming convention is simply a consistent method of naming variables. Another naming convention is to
name a variable with a prefix, usually all lowercase and consisting of three letters, that indicate its data type,
followed by a word with its first letter capitalized, that suggests its purpose.

Some examples:
intScore Integer variable representing a score, such as on a test.
strName String variable representing a name, such as a person’s name.
blnResident Boolean variable, representing whether or not someone is a resident.

Assigning Values to Variables

A variable can be assigned a value supplied by the programmer in code. A variable also can be assigned a
value by the user, usually via the keyboard, when the program is running.

DCIT22- Computer Programming I Memory, Data Type and Variables


4
Assignment Operator

The assignment operator is used to assign a value to a variable. The syntax is

[variable name] = [value];

The assignment operator looks like the equal sign. However, in C++ the = sign is not used to test for equality;
it is used for assignment. The variable must be declared either before, or at the same time, you assign it a
value, not afterwards. Example:

int testScore;
testScore = 95;

The next example concerns initialization, which is when you assign a value to a variable as part of the same
statement that declares that variable:

int testScore = 95;

Using the cin Object

Thus far, the programmer has supplied the values that are assigned to variables. However, most programs
are interactive, asking the user to provide information, which the user then inputs, usually via the keyboard.

The syntax of a cin statement is

cin >> [variable name];

The cin object is followed by >>, which is the stream extraction operator. It obtains the input, usually from
the keyboard, and assigns that input to the variable to its right.

When your program reaches a cin statement, its execution halts until the user types something at the
keyboard and presses the ENTER key. Try running the following program. You will see a blinking cursor until
you type a number. Once you type a number and press ENTER, the program will output “Your test score is”
followed by the number you inputted. For example, if you inputted 100, the output will be “Your test score is
100.”

#include <iostream.h>
#include <conio.h>

void main()
{ clrscr();
int testScore;
cout << "Enter your test score: ";
cin >> testScore;
cout << "Your test score is " << testScore << "\n";
getch();
}

The program input and output could be

Enter your test score: 78

DCIT22- Computer Programming I Memory, Data Type and Variables


5
Your test score is 78

Inputting Values for Multiple Variables

If you are inputting values for several variables, you could input them one line at a time.

#include <iostream.h>
#include <conio.h>

void main()
{ clrscr();
int myWeight, myHeight;
string myName;
cout << "Enter your name: ";
cin >> myName;
cout << "Enter your weight in pounds: ";
cin >> myWeight;
cout << "Enter your height in inches: ";
cin >> myHeight;
cout << "Your name score is " << myName << "\n";
cout << "Your weight in pounds is " << myWeight << "\n";
cout << "Your height in inches is " << myHeight << "\n";
getch();
}

The output of the program, with the input of “Jeff” for the name, 200 for the pounds, and 72 for the height,
is

Enter your name: Jeff


Enter your weight in pounds: 200
Enter your height in inches: 72
Your name is Jeff
Your weight in pounds is 200
Your height in inches is 72

Instead of having separate prompts and cin statements for each variable, you can have one cin statement
assign values to all three variables. The syntax is

cin >> [first variable] >> [second variable] >>


[third variable];

are separated by the stream extraction operator >>.

When you use one cin statement to assign values to multiple variables, the user separates each input by one
or more spaces. The space tells the cin object that you have finished assigning a value to one variable and
the next input should be assigned to the next variable in the cin statement. As before, the user finishes input
by choosing the ENTER key.

#include <iostream.h>
#include <conio.h>

void main()
{ clrscr();
DCIT22- Computer Programming I Memory, Data Type and Variables
6
int myWeight, myHeight;
string name;
cout << "Enter your name, weight in pounds and height
in inches\n";
cout << "The three inputs should be separated by a
space\n";
cin >> name >> myWeight >> myHeight;
cout << "Your name is " << name << "\n";
cout << "Your weight in pounds is " << myWeight << "\n";
cout << "Your height in inches is " << myHeight << "\n";
getch();
}

The interaction between user input and the cin statement could be as follows:

 The user would type “Jeff,” followed by a space.


 The space tells the cin object that the first input has ended, so the cin object will assign “Jeff” to the
first variable in the cin statement, name.
 The user would type 200, followed by a space.
 The space tells the cin object the second input has ended, so the cin object will assign 200 to the next
variable in the cin statement, myWeight.
 The user would type 200, and then press the ENTER key.
 The ENTER key tells the cin object that the third and final input has ended, so the cin object will
assign 72 to the remaining variable in the cin statement, myHeight, which completes execution of the
cin statement.

The resulting program output would be

Enter your name, weight in pounds and height in inches


The three inputs should be separated by a space
Jeff 200 72
Your name is Jeff
Your weight in pounds is 200
Your height in inches is 72

Inputting Multiple Words into a String

Finally, cin will only take the first word of a string. If in the following program you input “Jeff Kent” at the
prompt, the output will be “Your name is Jeff” not “Your name is Jeff Kent.”

#include <iostream.h>
#include <conio.h>
#include <string.h>

void main()
{ clrscr();
string name;
cout << "Enter your name: ";
cin >> name;
cout << "Your name is " << name;
getch();
}

DCIT22- Computer Programming I Memory, Data Type and Variables


7
The reason why the value of name is outputted only as “Jeff,” omitting “Kent,” is that the cin object
interprets the space between “Jeff” and “Kent” as indicating that the user has finished inputting the value
of the name variable.

The solution involves using either the get or getline method of the cin object.

ARITHMETIC OPERATORS

An operator is a symbol that represents a specific action

Arithmetic Operators
Operator Purpose Example Result
+ Addition 5+2 7
- Subtraction 5–2 3
* Multiplication 5*2 10
/ Division (Quotient) 5/2 2
% Division (Remainder) 5%2 1

The % operator, also called the modulus operator, returns the remainder in division.

The Addition Operator

#include <iostream.h>
#include <conio.h>

void main()
{ clrscr();
int total, added;
cout << "Enter number of pre-registered students: ";
cin >> total;
cout << "Enter number of students adding the course: ";
cin >> added;
total = total + added;
cout << "Total number of students: " << total;
getch();
}

The input and output of the program could be

Enter number of registered students: 30


Enter number of students adding the course: 3
Total number of students: 33

Combined Assignment and Arithmetic Operator

There also is another way to express total = total + added: total += added;

Combining Arithmetic and Assignment Operators


Statement Combining Operators
a = a + 2; a +=2;
a = a – 2; a –=2;

DCIT22- Computer Programming I Memory, Data Type and Variables


8
a = a * 2; a *=2;
a = a / 2; a /=2;
a = a % 2; a %=2;

Adding Strings

While we think of addition as involving numeric operands, the addition operator also can be used with string
operands. The output of the following code is: “Your name is JeffKent.”

#include <iostream.h>
#include <string.h>
#include <conio.h>

void main()
{ clrscr();
string firstName = "Jeff";
string lastName = "Kent";
cout << "Your name is " << firstName + lastName;
getch();
}

Adding two strings has the effect of appending the second string operand to the first string operand.
Appending means adding the contents of the second string to the end of the first string.

The Subtraction Operator

#include <iostream.h>
#include <conio.h>

void main()
{ clrscr();
int total, added, dropped;
cout << "Enter number of pre-registered students: ";
cin >> total;
cout << "Enter number of students adding the course: ";
cin >> added;
total = total + added;
cout << "How many students dropped? ";
cin >> dropped;
total -= dropped;
cout << "Total number of students: " << total << endl;
getch();
}

The input and output of the program could be

Enter number of pre-registered students: 30


Enter number of students adding the course: 3
How many students dropped? 5
Total number of students: 28

The Multiplication Operator

DCIT22- Computer Programming I Memory, Data Type and Variables


9
#include <iostream.h>
#include <conio.h>

void main()
{ clrscr();
int total, added, dropped;
cout << "Enter number of pre-registered students: ";
cin >> total;
cout << "Enter number of students adding the course: ";
cin >> added;
total = total + added;
cout << "How many students dropped? ";
cin >> dropped;
total -= dropped;
cout << "Total number of students: " << total << endl;
cout << "Total tuition owed: $" << (total + dropped) * 72 << endl;
getch();
}

The input and output of the program could be

Enter number of preregistered students: 30


Enter number of students adding the course: 3
How many students dropped? 5
Total number of students: 28
Total tuition owed: $2376

The variables total and dropped are added so that total reflects all students ever enrolled, even if they are no
longer in the class, because all students owe tuition even if they don’t show up or later drop the course.

Precedence Between Arithmetic Operators

Precedence of Arithmetic Operators


Precedence Operator
Highest – (unary negation)
Middle */%
Lowest +–

The Division Operator

#include <iostream.h>
#include <string.h>
#include <conio.h>

void main()
{ clrscr();
int firstOp = 10, secondOp = 4;
float result = firstOp / secondOp;
cout << firstOp << " / " << secondOp << " = " << result;
getch();
}

DCIT22- Computer Programming I Memory, Data Type and Variables


10
However, the value of 10.0 / 4 is 2.5 in C++. When at least one of the operands is a floating point data type,
and 10.0 would be interpreted as floating point, then the result is a floating point as well. The output of the
following program is 10 / 4 = 2.5 because we changed the data type of firstOp from int to float:

#include <iostream.h>
#include <conio.h>

void main()
{ clrscr();
float firstOp = 10, result;
int secondOp = 4;
result = firstOp / secondOp;
cout << firstOp << " / " << secondOp << " = " << result;
getch();
}

#include <iostream.h>
#include <conio.h>
#include <string.h>

void main()
{ clrscr();
int total, added, dropped, tuition;
cout << "Enter number of preregistered students: ";
cin >> total;
cout << "Enter number of students adding the course: ";
cin >> added;
total = total + added;
cout << "How many students dropped? ";
cin >> dropped;
total -= dropped;
cout << "Total number of students: " << total << endl;
tuition = (total + dropped) * 72;
cout << "Total tuition owed: $" << tuition << endl;
cout << "Average tuition per enrolled student: $"
<< (float) tuition / total;
getch();
}

The input and output could be

Enter number of preregistered students: 30


Enter number of students adding the course: 3
How many students dropped? 5
Total number of students: 28
Total tuition owed: $2376
Average tuition per enrolled student: $84.8571

The casting of one of the operands to a float is necessary. Otherwise, the average tuition would be $84
instead of $84.8571.

Whether you use the / or the % operator, you cannot divide by zero. The result is an error.

DCIT22- Computer Programming I Memory, Data Type and Variables


11
Exponents

C++it has a built-in function named pow, which is defined in the standard library cmath. The name pow is
shorthand for power, since with exponents one number is raised to the power of another.

The following program calculates the area of a circle based on a radius inputted by the user.

#include <iostream.h>
#include <cmath.h>
#include <conio.h>

void main()
{ clrscr();
double radius, area;
cout << "Enter radius of circle: ";
cin >> radius;
area = 3.14159 * pow(radius, 2);
cout << "The area is " << area << endl;
getch();
}

The input and output could be

Enter radius of circle: 6


The area is 113.097

DCIT22- Computer Programming I Memory, Data Type and Variables


12

You might also like