Beruflich Dokumente
Kultur Dokumente
3.9 Summary
3.10 Exercises
Fundamentals of Programming
A computer program accepts input from the keyboard. The keys entered from keyboard will
be encoded as values and store in computer memory. The values can be numeric or alphabetic.
A computer program use data types to differentiate the numerical values and alphabetical
values. The memoy locations where the values are stored are represented by complicated
memory addresses. To simplify the read operation from the memory locations and write
operation to the memory locations for the values, variables are used to represent the memory
address. In this chapter, we will explain the basics data types, identifiers and variables needed
to construct a C++ program.
3.2 Keywords
Keywords in C++ are also called reserved words, it is a vocabulary of commands that
humans can understand and that can be converted into machine language. The keywords have
standard, predefined meanings. The keywords should not be use for anything other than their
predefined purposes in the C++ language. Therefore, do not use them for variable name or
names for programmer-defined functions.
C++ Keywords
asm do inline short typeid
auto double int signed typename
bool dynamic_cast log sizeof union
break else mutable static unsigned
case enum namespace static_cast using
catch explicit new struct virtual
char extern operator switch void
class false private template volatile
const float protected this wchar_t
const_cast for public throw while
continue friend register true
default goto reinterpret_cast try
delete if return typedef
Table 3-1 C++ keywords
In addition to the keywords listed below, identifiers containing a double underscore (__) are
reserved for use by C++ implementations and standard libraries and should not be used in
your program.
48
Data Types and Variables
A computer program accepts input from the keyboard. The keys entered from keyboard will
be encoded as values and store in computer memory. The values can be numeric or alphabetic.
A computer program use data types to differentiate the numerical values and alphabetical
values.
The memoy locations where the values are stored are represented by complicated memory
addresses. To simplify the read operation from the memory locations and write operation to
the memory locations for the values, variables are used to represent the memory address.
Variables can hold different types of data. In general there are two categories of data types:
3
§ numeric data types
(Examples: -50, -25.6, -0.0123, 0, 1.68, 7.6, and 65536)
§ and character data types
C++ provides seven built-in data types and identifies them by keywords. These are also
called primitive types because they are simple and uncomplicated.
§ short
§ int
§ long
§ unsigned
§ float
§ double
§ char
49
Fundamentals of Programming
Every data type has a range of values. A number of bytes are required for each data type to
store value in memory, and their range is shown in Table 3-2 below. These are the highest
and lowest values that you can store in memory which limited by the size of a data types.
3
compiler 101
implementation) 127
50
Data Types and Variables
main()
{
// Variable declarations and initializations
short small_number = 25;
int medium_number = 25000;
long big_number = 500000000;
unsigned positive_number = 50000;
float quarter = 0.25;
double pi = 3.14159;
3
char letter = 'W';
// Output to screen
cout<<"small number (short) = "<<small_number<<endl;
cout<<"medium number (int) = "<<medium_number<<endl;
cout<<"big number (long) = "<<big_number<<endl;
cout<<"positive number (unsigned) = "<<positive_number<<endl;
cout<<"quarter (float) = "<<quarter<<endl;
cout<<"pi (long) = "<<pi<<endl;
cout<<"letter (char) = "<<letter<<endl;
return 0;
}
Program 3-1 Program that demonstrating data types
The seven built-in data types also serve as the building blocks for more complex data types,
called reference types or programmer-defined data types. These will be discussed in later
chapters.
Integers are referring to whole numbers with no fraction part. The types short,
unsigned and long are all variations of integer type. You can use short if you
known a variable will to hold only small values so you can save space in memory. You use
long if you know you will be working with very large values. You use unsigned if the
values are all positive.
51
Fundamentals of Programming
You can determine the actual number of btyes allocated by your computer for an integer
value by using the sizeof operator introduced in section 3.3.4. The valid value supported by
the memory allocation shown in Table 3-3 below.
3 Program 3-2 shows the limit on the smallest (most negative), and the largest (most positive)
integer values that can be used in a program.
main()
{
// Variable declarations and initializations
short min_number = -32768;
short max_number = 32767;
// Output to screen
cout<<"min_number = "<<min_number<<" (negative integer) "<<endl;
// Output to screen
cout<<"\nmax_number = "<<max_number<<" (positive integer) "<<endl;
// Add 1 to max_number
max_number = max_number + 1;
cout<<"min_number + 1 = "<<max_number
<<" (negative integer, over limit) "<<endl;
return 0;
}
Program 3-2 Program that demonstrating the largest and the smallest values limits
52
Data Types and Variables
A floating-point is a decimal number that contains the decimal point (.) or the exponent (e or
E) or both. For those who are not familiar with exponent, look at the different ways of writing
a decimal number as shown in Table 3-4 below:
3
654321 6.54321 x 105 6.54321e5
0.00734 7.34 x 10-3 7.34e-3
0.000627 6.27 x 10-4 6.27e-4
Table 3-4 Floating-point
In exponential notation the letter e stands for exponent. The number following the e
represents a power of 10.
C++ has two floating point data types: float and double. A float data type can hold
values up to six or seven significants digits of accuracy. A double data type can hold 14 or
15 significant digits of accuracy. The term significant digits refer to the mathematical
accuracy of a value. For example, a float given the value 0.324616777 will display as
0.324617 because the value is only accurate to sixth decimal positions.
main()
{
// Variable declarations and initializations
float float_number = 3.142857142857;
double double_number = 3.142857142857;
// Output to screen
cout<<"float number (3.142857142857) = "<<float_number<<endl;
cout<<"double number (3.142857142857) = "<<double_number<<endl;
return 0;
}
Program 3-3 Program that demonstrating significant digits of accuracy
53
Fundamentals of Programming
The following program tests the precision and range of values for floating-number.
// Program that testing the precision and range of values for floating-
number
#include <iostream.h>
main()
{
// Variable declarations and initializations
float float_number = 3.4e38;
double double_number = 3.4e38;
3
// Output to screen
cout<<"\nfloat number (3.4e38 or 3.4 * 10 ^38) = "
<<float_number<<endl;
cout<<"double number (3.4e38 or 3.4 * 10 ^38) = "
<<double_number<<endl;
return 0;
}
54
Data Types and Variables
You can use the char data type to hold any single character. A character is any character
enclosed using two single quotation marks (' and '). When several characters are enclosed
using two double quotation marks (" and "), it is called a string. Table 3-5 shows the
examples of character data types.
3
Character Data Types Examples
Character '$', '*', ' ', 'a', 'A', '8'
String "name", "Day of Birth", "Gender", "Tel. No:", "Address"
Table 3-5 Character data types
main()
{
// Character variable declaration and initialization
char letter = 'A';
return 0;
}
Program 3-4 Program that demonstrating character and string
A letter - A
One line - The quick brown fox jumps over the lazy dog.
C++ has a built-in operator called sizeof that gives the sizes of data in bytes. Programmers
can use the sizeof operater to find out the sizes of a data type on a machine, so that the know
the range of valid values can be assigned to a variable. This is illustrated in Program 3-5
below.
55
Fundamentals of Programming
main()
{
cout<<"Type short has a size of "<<sizeof(short)<<" bytes\n";
cout<<"Type int has a size of "<<sizeof(int)<<" bytes\n";
cout<<"Type unsigned has a size of "<<sizeof(unsigned)<<" bytes\n";
cout<<"Type long has a size of "<<sizeof(long)<<" bytes\n";
cout<<"Type float has a size of "<<sizeof(float)<<" bytes\n";
3
cout<<"Type double has a size of "<<sizeof(double)<<" bytes\n";
cout<<"Type char has a size of "<<sizeof(char)<<" bytes\n";
return 0;
}
Program 3-5 Program to illustrate the size of data types in bytes
The size used by the data types may be varied. It is depends on compiler implementation.
3.4 Identifiers
Identifiers are referring to memory locations which can hold values. They are formed by
combining letters (both uppercase and lowercase), digits, and underscore (_). Although
identifiers can be formed by freely combining letters, digits and underscores, you are
encourage to give them suggestive names that reflect the data items that they are going to
store. An identifier must start with either a letter or the underscore symbol, and all the rest of
the characters must be letters, digits, or the underscore symbol.
Identifiers can be of any length, however in practice, they seldom exceed 25 characters. C++
identifiers are case-sensitive, meaning that the lowercase and uppercase letters in identifiers
are treated as different characters. For example the identifier MONTH_RATE,
Monthly_Rate, Monthly_rate and monthly_rate are all different. They are
referring to different memory locations.
56
Data Types and Variables
Besides being used for naming variables, identifiers also used for naming constants,
functions, structures and classes. Descriptive identifiers make program easy to read. Table
3-7 shows the examples of non-descriptive and descriptive identifiers.
3
float value 2;// Principal float principal
3.5 Variables
Variables are identifiers. As mentioned earlier, the memory locations where the values are
stored are represented by complicated memory addresses. To simplify the read operation
from the memory locations and write operation to the memory locations for the values,
variables are used to represent the memory address.
Variable is most fundamental of all concepts in C++. The concept of a variable is borrowed
from mathematics. A statement such as
x=1
stores the value 1 in the variable x. From that point forward, the mathematician can use the
variable x in place of the constant 1.
Variables work the same way in C++. You can make the assignment
x = 1;
From that point forward in the program, until the value of x is changed, any references to x
are the same as referencing 1. That is, the value of x is 1. Unfortunately, C++ has a few more
concerns about variables than the mathematician does. This session deals with the care and
feeding of variables in C++.
pi = 3.14159;
gravity = 9.81;
max_score = 100;
min_score = 0;
letter = 'K';
name = "Elizabeth";
The values of variables may change during the course of execution of a program.
57
Fundamentals of Programming
Variables are used to store data of certain type. All variables must be declared prior to their
use. You declare a variable by telling the compiler the name of the variable as well as the
type of data it represents. This is called a variable declaration. Declaring a variable tells the
compiler to allocate appropriate memory space for the variable based on its data type. The
syntax for variable declarations is as follows:
3
type_name variable_name;
type_name variable_list;
If there are more than one variable of the same type, they may be placed in the same
statement, separated by commas.
int x, y, z;
short num1, num2;
long number1, number2;
unsigned day, month, year;
char ch, code;
float interest_rate, service_tax;
main()
{
// Variable declarations and initializations
int height, width, area;
return 0;
}
Program 3-6 Program that demonstrating variable declarations and manipulating variables
58
Data Types and Variables
Variables may be initialized by assigning values to them either at the time of their declaration
or at later time. When a declaration statement is used to store a value in a variable, the
variable is said to be initialized. 3
Table 3-8 shows some examples of variable declaration and initialization in one step.
The double quotation marks " and " are used to enclose
the string "lorry".
Table 3-8 Variable declaration and initialization in one step
59
Fundamentals of Programming
Program 3-7 shows the variable declarations and initializations in one step.
main()
{
// Variable declarations and initializations
int height = 4, width = 8, area = 0;
3
area = height * width;
return 0;
}
Program 3-7 Program that demonstrating variable declarations and initializations in one step
Height = 4
Width = 8
Area = 32
Another way to initialize variables is to assign them values after the variables have been
declared as shows below.
int x, y;
float rete, total;
char ch; Variable declaration
char vehicle[6];
y = 10
total = 0.0;
ch ='a'; Variable initialization
vehicle = "lorry";
60
Data Types and Variables
main()
{
// Variable declarations
int height, width, area;
// Variable initializations
3
height = 4;
width = 8;
area = 0;
return 0;
}
Program 3-8 Program that demonstrating variable declarations and initializations
Height = 4
Width = 8
Area = 32
3.6 Constants
Constants are values that do not change during program execution. They can be type of
integer, character or floating point. To declare constants, use the keyword const as in the
following example
Mathematical constants are good candidates for receiving const status. For example when pi
is defined as const double pi = 3.14159;, it appropriately becomes a constant that
should never take any value.
61
Fundamentals of Programming
main()
{
const double PI = 3.14159;
const double TWO = 2.0;
double area, circum, radius;
cout<<"\nEnter radius: ";
3
cin>>radius;
area = PI * radius * radius;
circum = TWO * PI * radius;
cout<<"Circumference = "<<circum;
cout<<"\nArea = "<<area;
return 0;
}
Program 3-9 Program to illustrate constant
A constant must be declared and initialized before it can be used. You cannot change a
constant’s value once it is declared.
In addition to the data types discussed in this chapter, C++ provides other data types derived
from the basic data types. These include arrays, pointer, and structures (will be discussed in
later chapters). Besides these, you can also define your own data types, called user-defined
types. These will be discussed in the later chapter.
62
Data Types and Variables
Program 3-10 begins with a comment that explains what the program does. The body of the
main function includes a declaration section where the constants freeze_pt and boil_pt,
and variable mid_pt are defined. It is follow by a sequence of executable statements. These
statement display a message, computes the midpoint, and finaly display result on screen.
// Program computes the midpoint between the freezing and boiling points
3
// of water
#include <iostream.h>
main()
{
// Constant variable declaration
const float freeze_pt = 0.0; // Freezing point of water
const float boil_pt = 100.0; // Boiling point of water
// Variable declaration
float mid_pt;
// Output to screen
cout<<"Water freezes at "<<freeze_pt;
cout<<" and boils at "<<boil_pt<<" degrees celsius. "<<endl;
// Display result
cout<<"The midpoint between the freezing and boiling points of water
is "<<mid_pt<<" degree celsius.";
return 0;
}
Program 3-10 Program computes the midpoint between the freezing and boiling points
63
Fundamentals of Programming
Program 3-11 begins with a comment that explains what the program does. The body of the
main function includes a declaration section where the constants government_tax and
service_tax, and variable amount and amount_after_tax are defined. It is follow
by a sequence of input and output statements. These statements display a message request for
an input for the variable amount, and display both the government tax and service tax
required for the figure entered. It is follow by an assignment statement that computes that
main()
{
// Constant declaration
const float government_tax = 0.05, service_tax = 0.1;
// Variable declaration
float amount = 0.0, amount_after_tax = 0.0;
return 0;
}
Program 3-11 Program that computes the amount after tax
64
Data Types and Variables
Program 3-12 begins with a comment that explains what the program does. The body of the
main function includes a declaration section where the variables name[40], day, month,
year, current_year and age are defined. It is follow by a sequence of executable
statements. These statement prompt for inputs, computes the age, and finaly display result on
screen.
3
// Program that computes the age
#include <iostream.h>
main()
{
// Variable declaration
char name[40] = "";
unsigned short day = 0, month = 0, year = 0;
unsigned short current_year = 0, age = 0;
// Output to screen
cout<<"\nHi "<<name<<", Now you are "<<age
<<" years old. Next year you will be "<<(age + 1)
<<" years old.";
return 0;
}
Program 3-12 Program that computes the age
Hi Peter, Now you are 18 years old. Next year you will be 19years old.
65
Fundamentals of Programming
3.9 Summary
§ The C++ character set includes the keyboard characters, namely, the uppercase letter
A through Z, the lowercase letters a through z, the digits 0 through 9, and other
special characters.
§ The keywords should not be use for anything other than their predefined purposes in
the C++ language. Therefore, do not use them for variable name or names for
3
programmer-defined functions.
§ The C++ provides seven built-in data types: short, int, long, unsigned,
float, double and char.
66
Data Types and Variables
'A'
§ C++ has a built-in operator called sizeof that gives the sizes of data in bytes.
§ Identifiers are used as names for variables and other items in a C++ program.
Identifiers must start with either a letter or the underscore symbol, and the remains
characters must be all be letter, digits, or the underscore symbol.
3
x "x" illegal character "
num2 2num illegal first character
month_rate month-rate illegal character -
email email@ illegal character @
Student_Name STUDENT NAME illegal blank
§ Variables (identifiers) are named memory location that your program can use to store
values. You can name a variable using any legal identifier. A variable name cannot be
any reserved word.
§ Variables may be initialized by assigning values to them either at the time of their
declaration or at later time.
67
Fundamentals of Programming
The double quotation marks " and " are used to enclose
3
the string "lorry".
§ C++ provides other data types such as arrays, pointers and structures which are
derived from the basic data types.
68
Data Types and Variables
3.10 Exercises
1. For each of the following C++ programming language identifiers, note whether they
are valid or ilvalid.
a. weekly_sales
b. last character
c. integer
3
d. surname
e. phone#
f. abcdefghijklmnopq
g. class_code
h. year2k
i. 2000car
j. _file
k. main
l. @email
2. Write appropriate declarations, assigning initial values (if any), for each of the
following
a. compilers
b. variables
c. address
d. applications
4. When data cannot be changed after a program is compiled, the data is ____________.
a. constant
b. variable
c. data type
d. memory location
5. Which of the following is not a basic data type in the C++ programming?
69
Fundamentals of Programming
a. int
b. byte
c. char
d. float
a. a type
3
b. an identifier
c. an assigned value
d. a semicolon
7. Which of the following values can you assign to a variable of type int?
a. 0
b. 98.8
c. 'W'
d. 9,000,000,000,000
8. Write a program compute and output the total of three integer numbers entered from
keyboard.
9. Write a program compute and output the average of two floating-point number
entered from the keyboard.
10. Write a program input a country’s name and capital’s name from the keyboard and
output the same.
70