DCIT22 2020 Lecture 2 Introduction To Programming Part4
DCIT22 2020 Lecture 2 Introduction To Programming Part4
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.
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.
Addresses
Locations in memory are identified by address. These addresses usually are expressed as hexadecimal (Base
16) numbers such as 0x8fc1.
DATA TYPES
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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:
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 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();
}
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
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
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:
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();
}
The solution involves using either the get or getline method of the cin object.
ARITHMETIC OPERATORS
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.
#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();
}
There also is another way to express total = total + added: total += added;
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.
#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();
}
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 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.
#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();
}
#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 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.
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();
}