24
3 Data Types and Variables 3.1 The C++ Character Set 3.2 Keywords 3.3 Basic Data Types 3.3.1 Integer Data Types 3.3.2 Floating-Point Data Types 3.3.3 Character Data types 3.3.4 sizeof Operator 3.4 Identifiers 3.5 Variables 3.5.1 Declaring Variables 3.5.2 Initializing Variables 3.6 Constants 3.7 Other Data Types 3.8 Sample Programs 3.8.1 Sample Program 1 3.8.2 Sample Program 2 3.8.3 Sample Program 3 3.9 Summary 3.10 Exercises Learning Objectives Upon successful completion of this chapter, students will be able to: § Describe C++ character set and keywords § Demonstrate an understanding of basic data types, identifiers and variables constants needed to construct a C++ program § Discuss the limitations applied to identifiers § Illustrate the differences between integer and floating point § Discuss the assignment and initialization values to variables § Discuss other data types and sizeof operator

DIT210_Chapter03

Embed Size (px)

Citation preview

Page 1: DIT210_Chapter03

3 Data Types and Variables 3.1 The C++ Character Set 3.2 Keywords 3.3 Basic Data Types 3.3.1 Integer Data Types 3.3.2 Floating-Point Data Types 3.3.3 Character Data types 3.3.4 sizeof Operator 3.4 Identifiers 3.5 Variables 3.5.1 Declaring Variables 3.5.2 Initializing Variables 3.6 Constants 3.7 Other Data Types 3.8 Sample Programs 3.8.1 Sample Program 1 3.8.2 Sample Program 2 3.8.3 Sample Program 3 3.9 Summary 3.10 Exercises

Learning Objectives Upon successful completion of this chapter, students will be able to: § Describe C++ character set and keywords § Demonstrate an understanding of basic data types,

identifiers and variables constants needed to construct a C++ program

§ Discuss the limitations applied to identifiers § Illustrate the differences between integer and floating

point § Discuss the assignment and initialization values to

variables § Discuss other data types and sizeof operator

Page 2: DIT210_Chapter03

3

Fundamentals of Programming

48

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.1 The C++ Character Set A character set is an encoding scheme in which each character is represented by a different binary value for computer identification. C++ supports a number of character sets. The C++ character set includes the keyboard characters listed below. § The uppercase letter A though Z § The lowercase letters a through z § The digits 0 through 9 § Special characters (such as {, }, [, ], !, #, , %, , &, |, <, >, ;, :and *) § The blank and white space

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. Here is a list of standard keywords in C++. 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.

Page 3: DIT210_Chapter03

3

Data Types and Variables

49

3.3 Basic Data Types 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: § 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

Page 4: DIT210_Chapter03

3

Fundamentals of Programming

50

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. Basic Data Type

C++ Keywords

Bytes Minimum Value

Maximum Value

Examples

short integer

short 2 (may be 1,

depends on compiler

implementation)

-32,768 32,767 -99 -24 048 101 127

integer

int 4 (may be 2,

depends on compiler

implementation)

-2,147,483,648 2,147,483,647 -9999 -1 0

566 32767

long integer

long 4

-2,147,483,648 2,147,483,647 -222 0

3333 65536

9999999

unsigned integer

unsigned 2 or 4 (may be 2,

depends on compiler

implementation)

0 4294967295 1 256

1200 14400 60000

floating point

float 4

-3.4 * 1038 3.4 * 1038 -0.056 -0.017

0.0 1.234

100.567

double floating point

double 8

-1.7 * 10308 1.7 * 10308 -0.0568 -0.0173

0.01 41.234

100.5678

character char 1 0 255 '$' '*' ' ' 'a' 'A

' Table 3-2 Basic Data Types

Page 5: DIT210_Chapter03

3

Data Types and Variables

51

Program 3-1 demonstrates the uses of data types in a program. // Program that demonstrating data types #include <iostream.h> 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; 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 Here is the output. small number (short) = 25 medium number (int) = 25000 big number (long) = 500000000 positive number (unsigned) = 50000 quarter (float) = 0.25 pi (long) = 3.14159 letter (char) = W

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.

3.3.1 Integer Data Types 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.

Page 6: DIT210_Chapter03

3

Fundamentals of Programming

52

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. Word Size Minimum Integer Value Maximum Integer Value 1 byte -128 127 2 bytes -32,768 32,767 4 bytes -2,147,483,648 2,147,483,647 Table 3-3 Integer values and word size 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. // Program that demonstrating the largest and the smallest // integer values limits #include <iostream.h> main() { // Variable declarations and initializations short min_number = -32768; short max_number = 32767; // Output to screen cout<<"min_number = "<<min_number<<" (negative integer) "<<endl; // Substract 1 from min_number min_number = min_number - 1; cout<<"min_number - 1 = "<<min_number <<" (positive integer, over limit) "<<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 Here is the output. min_number = -32768 (negative integer) min_number - 1 = 32767 (positive integer, over limit) max_number = 32767 (positive integer) min_number + 1 = -32768 (negative integer, over limit)

Page 7: DIT210_Chapter03

3

Data Types and Variables

53

3.3.2 Floating-Point Data Types 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: Decimal Notation Scientific Notation Exponential Notation 1628 1.628 x 103 1.628e3 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. However, the significant digits of accuracy may be varied depend on compiler implementation. Program 3-3 below demonstrates the significant digits of accuracy for both float and double. // Program that demonstrating significant digits of accuracy #include <iostream.h> 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 Here is the output. float number (3.142857142857) = 3.14286 double number (3.142857142857) = 3.14286

Page 8: DIT210_Chapter03

3

Fundamentals of Programming

54

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; // 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; // Assigns new values float_number = 3.5e38; double_number = 3.5e38; // Output to screen cout<<"\nfloat number (3.5e38 or 3.5 * 10 ^38) = "<<float_number <<" (Invalid Value)"<<endl; cout<<"double number (3.5e38 or 3.5 * 10 ^38) = " <<double_number<<endl; // Assigns new values float_number = 1.7e308; double_number = 1.7e308; // Output to screen cout<<"\nfloat number (1.7e308 or 1.7 * 10 ^308) = "<<float_number <<" (Invalid Value)"<<endl; cout<<"double number (1.7e308 or 1.7 * 10 ^308) = " <<double_number<<endl; // Assigns new values float_number = 2.7e308; double_number = 2.7e308; // Output to screen cout<<"\nfloat number (2.7e38 or 2.7 * 10 ^308) = "<<float_number <<" (Invalid Value)"<<endl; cout<<"double number (2.7e38 or 2.7 * 10 ^308) = "<<double_number <<" (Invalid Value)"<<endl; return 0; }

Here is the output. float number (3.4e38 or 3.4 * 10 ^38) = 3.4e+038 double number (3.4e38 or 3.4 * 10 ^38) = 3.4e+038 float number (3.5e38 or 3.5 * 10 ^38) = 1.#INF (Invalid Value) double number (3.5e38 or 3.5 * 10 ^38) = 3.5e+038 float number (1.7e308 or 1.7 * 10 ^308) = 1.#INF (Invalid Value) double number (1.7e308 or 1.7 * 10 ^308) = 1.7e+308 float number (2.7e38 or 2.7 * 10 ^308) = 1.#INF (Invalid Value) double number (2.7e38 or 2.7 * 10 ^308) = 1.#INF (Invalid Value)

Page 9: DIT210_Chapter03

3

Data Types and Variables

55

3.3.3 Character Data types 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. Character Data Types Examples Character '$', '*', ' ', 'a', 'A', '8' String "name", "Day of Birth", "Gender", "Tel. No:", "Address" Table 3-5 Character data types Program 3-4 demonstrates the character and string. // Program that demonstrating character and string #include <iostream.h> main() { // Character variable declaration and initialization char letter = 'A'; // String variable declarations and initialization char one_line[60] = "The quick brown fox jumps over the lazy dog."; cout<<"A letter - "<<letter<<endl; cout<<"One line - "<<one_line<<endl; return 0; } Program 3-4 Program that demonstrating character and string Here is the output. A letter - A One line - The quick brown fox jumps over the lazy dog.

3.3.4 sizeof Operator 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.

Page 10: DIT210_Chapter03

3

Fundamentals of Programming

56

// program to illustrate the size of data types in bytes #include <iostream.h> 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"; 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 program outputs the following: Type short has a size of 2 bytes Type int has a size of 4 bytes Type unsigned has a size of 4 bytes Type long has a size of 4 bytes Type float has a size of 4 bytes Type double has a size of 8 bytes Type char has a size of 1 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. Valid Identifier Invalid Identifier 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 Table 3-6 Valid and invalid identifiers 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.

Page 11: DIT210_Chapter03

3

Data Types and Variables

57

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. Name Non Descriptive Identifier Descriptive Identifier Day, month, year int a; // Day

int b; // Month int c; // Year

int day; int month; int year;

Interest rate, principal float value1;// Interest rate float value 2;// Principal

float interest_rate; float principal

Name, gender, salary

char oneline[40]; // Name char letter; // Gender float num; // Salary

char name[40]; char gender; float salary;

Table 3-7 Non-descriptive and descriptive identifiers

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++. Here are more examples

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.

Page 12: DIT210_Chapter03

3

Fundamentals of Programming

58

3.5.1 Declaring Variables 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:

type_name variable_name; type_name variable_list;

Here are some examples of variable declarations.

float amount; // Declares amount as a floating-point variable int number; // Declares number as a integer variable char ch; // Declares ch as character variable

If there are more than one variable of the same type, they may be placed in the same statement, separated by commas. Here are some examples of declaring a list of variables.

int x, y, z; short num1, num2; long number1, number2; unsigned day, month, year; char ch, code; float interest_rate, service_tax;

Program 3-6 shows the variable declarations and manipulations. // Program that demonstrating variable declarations and variables manipulation #include <iostream.h> main() { // Variable declarations and initializations int height, width, area; // Prompt for input cout<<"Enter the height: "; cin>>height; cout<<"Enter the width: "; cin>>width; // Computes height * width, then assigns result to area area = height * width; // Output result to screen cout<<"Area = "<<area; return 0; } Program 3-6 Program that demonstrating variable declarations and manipulating variables

Page 13: DIT210_Chapter03

3

Data Types and Variables

59

Here is the result of sample run. Enter the height: 4 Enter the width: 8 Area = 32

3.5.2 Initializing 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. Table 3-8 shows some examples of variable declaration and initialization in one step. Variable declaration and initialization in one step

Description

int x = 5, y = 10; Both x and y are declared as integer variables. x is initialized to 5 and y is initialized to 10

float rate, total = 0.0; Variable total is initialized to 0.0 char ch = 'a'; ch is declared as a character variable and is given initial

value 'a'. char vehicle[6] = "lorry"; vehicle is declared as a character variable that cannot

store more than six characters. It is given the initial value "lorry". The square brackets [ ] are used to indicate the size of the character variable vehicle. This is the way to declare variables for storing strings. The double quotation marks " and " are used to enclose the string "lorry".

Table 3-8 Variable declaration and initialization in one step

Page 14: DIT210_Chapter03

3

Fundamentals of Programming

60

Program 3-7 shows the variable declarations and initializations in one step. // Program that demonstrating variable declarations and initializations #include <iostream.h> main() { // Variable declarations and initializations int height = 4, width = 8, area = 0; // Computes height x width, then assigns result to area area = height * width; // Output result to screen cout<<"Height = "<<height<<endl; cout<<"Width = "<<width<<endl; cout<<"Area = "<<area<<endl; return 0; } Program 3-7 Program that demonstrating variable declarations and initializations in one step Here is the output. 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; char vehicle[6];

Variable declaration

y = 10 total = 0.0; ch ='a'; vehicle = "lorry";

Variable initialization

Page 15: DIT210_Chapter03

3

Data Types and Variables

61

Here is the sample program. // Program that demonstrating variable declarations and initializations #include <iostream.h> main() { // Variable declarations int height, width, area; // Variable initializations height = 4; width = 8; area = 0; // Computes height x width, then assigns result to area area = height * width; // Output result to screen cout<<"Height = "<<height<<endl; cout<<"Width = "<<width<<endl; cout<<"Area = "<<area<<endl; return 0; } Program 3-8 Program that demonstrating variable declarations and initializations Here is the output. 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

const double pi = 3.14159; const float service_tax = 0.1; const int days_of_year = 365; const char grade1 = 'A';

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.

Page 16: DIT210_Chapter03

3

Fundamentals of Programming

62

Here is an example using constant. // To calculate the circumference and the area of a circle #include <iostream.h> main() { const double PI = 3.14159; const double TWO = 2.0; double area, circum, radius; cout<<"\nEnter radius: "; 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 Here is a sample run: Enter radius: 6.00 Circumference = 37.6991 Area = 113.097

A constant must be declared and initialized before it can be used. You cannot change a constant’s value once it is declared.

3.7 Other Data Types 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.

Page 17: DIT210_Chapter03

3

Data Types and Variables

63

3.8 Sample Programs

3.8.1 Sample Program 1 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 // 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; // Computes the midpoint mid_pt = (freeze_pt + boil_pt) / 2.0; // 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 Here is the output. Water freezes at 0 and boils at 100 degrees celsius. The midpoint between the freezing and boiling points of water is 50 degree celsius.

Page 18: DIT210_Chapter03

3

Fundamentals of Programming

64

3.8.2 Sample Program 2 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 amount_after_tax. Finaly, it display the result to screen. // Program that computes the amount after tax #include <iostream.h> main() { // Constant declaration const float government_tax = 0.05, service_tax = 0.1; // Variable declaration float amount = 0.0, amount_after_tax = 0.0; // Input and output statement cout<<"Enter the amount: "; cin>>amount; cout<<"Government Tax (5%) = $ "<<(amount * government_tax)<<endl; cout<<"Service Tax (10%) = $ "<<(amount * service_tax)<<endl; // Computes the amount after tax amount_after_tax = amount + (amount * government_tax) + (amount * service_tax); // Display the result cout<<"You have to pay $ "<<amount_after_tax; return 0; } Program 3-11 Program that computes the amount after tax Here is the result of sample run. Enter the amount: 100.00 Government Tax (5%) = $ 5 Service Tax (10%) = $ 10 You have to pay $ 115

Page 19: DIT210_Chapter03

3

Data Types and Variables

65

3.8.3 Sample Program 3 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. // 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; // Prompt for inputs cout<<"Enter your name: "; cin>>name; cout<<"Enter your birthday (dd mm yyyy): "; cin>>day>>month>>year; cout<<"Enter current year (yyyy): "; cin>>current_year; // Computes the age age = current_year - year; // 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 Here is the result of sample run. Enter your name: Peter Enter your birthday (dd mm yyyy): 12 12 1989 Enter current year (yyyy): 2007 Hi Peter, Now you are 18 years old. Next year you will be 19years old.

Page 20: DIT210_Chapter03

3

Fundamentals of Programming

66

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 programmer-defined functions.

§ The C++ provides seven built-in data types: short, int, long, unsigned,

float, double and char. Basic Data Type C++

Keywords Bytes Minimum

Value Maximum Value

Examples

short integer (depends on compiler implementation)

short 1 (2) -128 127 -99 -24 048 101 127

integer (depends on compiler implementation)

int 2 (4) -32,768 32,767 -9999 -1 0

566 32767

long integer (depends on compiler implementation)

long 4 (8) -2,147,483,648 2,147,483,647 -222 0

3333 65536

9999999 unsigned integer (depends on compiler implementation)

unsigned 2 (4) 0 65,536 1 256

1200 14400 60000

floating point (approximately 6 digits of precision)

float 4 -3.4 * 1038 3.4 * 1038 -0.056 -0.017

0.0 1.234

100.567 double floating point (approximately 14 digits of precision)

double 8 -1.7 * 10308 1.7 * 10308 -0.0568 -0.0173

0.01 41.234

100.5678 character char 1 0 255 '$'

'*' ' ' 'a'

Page 21: DIT210_Chapter03

3

Data Types and Variables

67

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

Valid Identifier Invalid Identifier 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 § All variables must be declared before they are used.

Variable Decalaration Variable Decalration in a List short num1; short num2;

short num1, num2;

int x; int y; int z;

int x, y, z;

long number1; long number2;

long number1, number2;

unsigned day; unsigned month; unsigned year;

unsigned day, month, year;

float interest_rate; float service_tax;

float interest_rate, service_tax;

double price; double rate;

double price, rate;

char ch; char code;

char ch, code;

§ 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. Variable declaration and initialization in one step

Description

int x = 5, y = 10; Both x and y are declared as integer variables. x is initialized to 5 and y is initialized to 10

float rate, total = 0.0; Variable total is initialized to 0.0 char ch = 'a'; ch is declared as a character variable and is given initial

value 'a'.

Page 22: DIT210_Chapter03

3

Fundamentals of Programming

68

char vehicle[6] = "lorry"; vehicle is declared as a character variable that cannot store more than six characters. It is given the initial value "lorry". The square brackets [ ] are used to indicate the size of the character variable vehicle. This is the way to declare variables for storing strings. The double quotation marks " and " are used to enclose the string "lorry".

§ Constants are values that do not change during program execution.

§ C++ provides other data types such as arrays, pointers and structures which are

derived from the basic data types.

Page 23: DIT210_Chapter03

3

Data Types and Variables

69

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 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. Integer variable: index b. Unsigned integer variable: num c. Double-precision variables: gross, tax, net d. Character variables: first, last e. Character variable code = 'A' f. Character variable num = '9' g. Character variable: eol = newline character h. Floating-point variable: result1 = 0.005, result2 = -7.8 i. Long integer variable: bignum = 123456789 j. Short integer variable: month k. Integer constant: size = 100 l. Double-precision constant: gravity = 9.81

3. Programmer-named computer memory locations are called _____________.

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?

Page 24: DIT210_Chapter03

3

Fundamentals of Programming

70

a. int b. byte c. char d. float

6. Which of the following elements is not required in a variable declaration?

a. a type 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.