Chapter 2 Introduction to C++

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

short int 2 bytes unsigned short int 2 bytes

- 32,768 to +32,767 0 to +65,535

long long int 8 bytes unsigned long long int 8 bytes

- 9,223,372,036,854,775,808 to + 9,223,372,036,854,775,807 0 to 18,446,744,073,709,551,615

int 4 bytes unsigned int 4 bytes long int 4 bytes unsigned long int 4 bytes

-2.147,483,648 to +2,147483,647 0 to 4,294,967,295 -2,147,483,648 to +2,147,483,647 0 to 4,294,967,295

A value is stored in a variable with an assignment statement.

For example, the following statement copies the value 12 into variable unitSold unitSold = 12;

( ) Opening and closing parentheses

Used in naming a function, as in int main()

There are many different types of data.

Variables are classified according to their data type, which determines the kind of information that may be stored in them.

An assignment operation assigns, or copies, a value into a variable.

When a value is assigned to a variable as part of the variable definition, it is called initialization

Cout is not part of the "core" of the C++ language. It is part of the input-output stream library. The header file, iostream, contains information describing iostream objects.

Without it, the compiler will not know how to properly compile a program that uses cout.

An identifier is a programmer-defined name that represents some element of a program. Variable names are examples of identifiers.

You may choose your own variable names in C++, as long as you do not use any of the C++ key words. The key words make up the "core" of the language and have specific purposes

\' Single quote Causes a single quotation mark to be printed.

\" Double quote Causes a double quotation mark to be printed.

A cout is classified as a STREAM OBJECT

which means it works with stream of data. To print a message on the scree, you send a stream characters to cout

Your primary considerations for selecting a numeric data type are

• The largest and smallest numbers that may be stored in the variable • How much memory the variable uses • Whether the variable stores signed or unsigned numbers • The number of decimal places of precision the variable has

+ - Binary - - Binary * - Binary / - Binary % - Binary

Addition Subtraction Multiplication Division Modulus

Line 6 contains a single, solitary character: { This is called a left-brace, or an opening brace, and it is associated with the beginning of the function main.

All the statements that make up a function are enclosed in a set of braces. If you look at the third line down from the opening brace you'll see the closing brace. Everything between the two braces is the contents of the function main.

You probably have noticed the mixture of uppercase and lowercase letters in the name itemsOrdered.

Although all of C++'s key words must be written in lowercase, you may use uppercase letters in variable names.

#include <iostream> using namespace std; int main() { char letter; letter = 'A'; cout << letter << endl; letter = 'B'; cout << letter << endl; return 0; } A B

Although the char data type is used for storing characters, it is actually an integer data type that typically uses 1 byte of memory. (The size is system dependent. On some systems, the char data type is larger than 1 byte.). The reason an integer data type is used to store characters is because characters are internally represented by numbers. Each printable character, as well as many nonprintable characters, is assigned a unique number. The most commonly used method for encoding characters is ASCII, which stands for the American Standard Code for Information Interchange.

Another way to cause cout to go to a new line is to insert an escape sequence in the string itself.

An escape sequence starts with the backslash character ( \) and is followed by one or more control characters. It allows you to control the way output is displayed by embedding commands within the string itself.

At the end of the line is a semicolon.

Just as a period marks the end of a sentence, a semicolon marks the end of a complete statement in C++

Variables represent storage locations in the computer's memory.

Literals are constant values that are assigned to variables.

; Semicolon

MARKS THE ENDS of a complete programming statement.

C++ has several primitive data types or data types that are defined as a basic part of the language

bool, char, unsigned char, short int, int, long int, unsigned short int, unsigned int, unsigned long int, float, double, and long double

Although C++ offers many data types,

in the very broadest sense there are only two: numeric and character

Numeric data types are broken into two additional categories:

integer and floating point.

The sizeof operator maybe used to determine the size of data type on any system

If you are not sure what the sizes of data types are on your computer, a C++ provides a way to find out. A special operator called sizeof will report the number of bytes of memory used by any data type or variable

C++ is a case-sensitive language. That means it regards uppercase letters as being entirely different characters than their lowercase counterparts.

In C++, the name of the function main must be written in all lowercase letters. C++ doesn't see "Main" the same as "main," or "INT" the same as "int." This is true for all the C++ key words.

Floating-point data types are used to define variables that can hold real numbers.

In programming terms, these are called floating-point numbers. Internally, floating-point numbers are stored in a manner similar to scientific notation. Take the number 47,281.97. In scientific notation this number is 4.728197 * 10 4

When both operands of a division statement are integers, the statement will result in integer division. This means the result of the division will be an integer as well. If there is a remainder.

In the previous code, it doesn't matter that the number variable is declared as a double because the fractional part of the result is discarded before the assignment takes place. In order for a division operation to return a floating-point value, one of the operands must be of a floating-point data type

Standard C++ provides a special data type for storing and working with strings.

Because a char variable can store only one character in its memory location, another data type is needed for a variable able to hold an entire string. Although C++ does not have a built-in data type able to do this, standard C++ provides something called the string class that allows the programmer to create a string type variable.

The iostream file contains code that allows a C++ program to display output on the screen and read input from the keyboard.

Because this program uses cout to display screen output, the iostream file must be included

\\ Backslash

Causes a backslash to be printed.

\b Backspace

Causes the cursor to back up, or move left one position.

\r Return

Causes the cursor to go to the beginning of the current line, not the next line.

\n Newline

Causes the cursor to go to the next line for subsequent printing

\t Horizontal tab

Causes the cursor to skip over to the next tab stop.

" " Opening and closing quotation marks

Encloses a STRING OF CHARACTERS, such as a message that is to be printed on the screen.

<> Opening and closing brackets

Encloses a file name when used with the # include directive.

{ } Opening and closing braces

Encloses a group of statements, such as the contents of a function.

Let's look at an example of how a string literal is stored in memory. S e b a s t i a n \0

First, notice the quotation marks are not stored with the string. They are simply a way of marking the beginning and end of the string in your source code. Second, notice the very last byte of the string. It contains the null terminator, which is represented by the \0 character.

A named constant is like a variable, but its content is read-only and cannot be changed while the program is running.

Here is a definition of a named constant: const double INTEREST_RATE = 0.069;

The second type of comment in C++ is the multi-line comment.

Multi-line comments start with /* (a forward slash followed by an asterisk) and end with */ (an asterisk followed by a forward slash). Everything between these markers is ignored

An advantage of using named constants is that they make programs more self-documenting. Another advantage to this approach is that widespread changes can easily be made to the program.

Named constants can also help prevent typographical errors in a program's code.

C++ introduces an alternative way to define variables, using the auto key word and an initialization value

Notice that this statement uses the word auto instead of a data type. The auto key word tells the compiler to determine, the variable's data type from initialization value

A literal is a piece of data that is written directly into a program's code.

One of the most common uses of literals is to assign a value to a variable

An assignment operation assigns, or copies, a value into a variable. When a value is assigned to a variable as part of the variable's definition, it is called an initialization. unitSold - 12;

The = symbol is called the assignment operator. Operators perform operations on data. The data that operators work with are called operands. The assignment operator has two operands. In the previous statement, the operands are unitsSold and 12

Boolean variables are set to either true or false

The bool data type allows you to create small integer variables that are suitable for holding true or false values

Because char variables are only large enough to hold one character, you cannot assign string literals to them. For example, the following code defines a char variable named letter.

The character literal 'A' can be assigned to the variable, but the string literal "A" cannot. char letter; letter = 'A'; // This will work. letter = "A"; // This will not work!

Single-Line Comments. Two forward slashes ( //) where you want the comment to begin.

The compiler ignores everything from that point to the end of the line

A variable's scope is the part of the program that has access to the variable. Every variable has a scope. The scope of a variable is the part of the program where the variable may be used.

The first rule of scope you should learn is that a variable cannot be used in any part of the program before the definition.

In C++ there are three data types that can represent floating-point numbers. They are float double long double

The float data type is considered single precision. The double data type is usually twice as big as float, so it is considered double precision.

The #include directive causes the contents of another file to be inserted into the program.

The following line has appeared near the top of every example program. The header file iostream must be included in any program that uses the cout object.

The contents of the iostream file are included in the program at the point the #include statement appears.

The iostream file is called a header file, so it should be included at the head, or top, of the program

int main() This marks the beginning of a function. A function can be thought of as a group of one or more programming statements that collectively has a name.

The name of this function is main, and the set of parentheses that follows the name indicate that it is a function.

In C++ terminology, the operand on the left side of the = symbol must be an lvalue. It is called an lvalue because it is a value that may appear on the left side of an assignment operator. An lvalue is something that identifies a place in memory whose contents may be changed. Most of the time this will be a variable name.

The operand on the right side of the = symbol must be an rvalue. An rvalue is any expression that has a value. The assignment statement takes the value of the rvalue and puts it in the memory location of the object identified by the lvalue. You may also assign values to variables as part of the definition. This is called initialization

The C++ programs have parts and components that serve specific purposes. Every C++ program has an anatomy.

The parts of C++ programs are not always in the same place. Nevertheless, the parts are there, and your first step in learning C++ is to learn what they are

A function can be thought of as a GROUP of ONE or more programming statements that collectively has a name. The name of this function is MAIN, and the set of parentheses that follows the name indicate that it is a function.

The word int stands for "integer." It indicates that the function sends an integer value back to the operating system when it is finished executing

Because this line starts with a #, it is called a PREPROCESSOR DIRECTIVE. The preprocessor reads your program before it is compiled and only executes those lines beginning with a # symbol.

Think of the preprocessor as a program that "sets up" your source code for the compiler. The #include directive causes the preprocessor to include the contents of another file in the program.

When a floating-point value is assigned to an integer variable, the fractional part of the value (the part after the decimal point) is discarded. . int number; number = 7.5; // Assigns 7 to number

This code attempts to assign the floating-point value 7.5 to the integer variable number. As a result, the value 7 will be assigned to number, with the fractional part discarded. When part of a value is discarded, it is said to be truncated.

int main() { int number; { number = 5; cout << "The value in number is " << number << endl; return 0; } }

This is called an assignment. The equal sign is an operator that copies the value on its right (5) into the variable named on its left ( number). After this line executes, number will be set to 5. cout << "The value in number is " << number << endl; The second item sent to cout is the variable name number. When you send a variable name to cout it prints the variable's contents. Notice there are no quotation marks around number.

It is important that you do not confuse character literals with string literals. Strings, which are a series of characters stored in consecutive memory locations, can be virtually any length.

This means that there must be some way for the program to know how long a string is. In C++ an extra byte is appended to the end of string literals when they are stored in memory. In this last byte, the number 0 is stored. It is called the null terminator or null character, and it marks the end of the string. Don't confuse the null terminator with the character '0'.

The char data type is used to store individual characters. A variable of the char data type can hold only one character at a time. Here is an example of how you might declare a char variable: char letter;.

This statement declares a char variable named letter, which can store one character. In C++, character literals are enclosed in single quotation marks

cout << "Programming is great fun!";

To put it simply, this line displays a message on the screen. You will read more about cout and the << operator later in this chapter. The message "Programming is great fun!" is printed without the quotation marks. In programming terms, the group of characters inside the quotation marks is called a string literal or string constant

#include <iostream> using namespace std; int main() { int apples; apples = 20; cout << "Today we sold " << apples << " bushels of apples.\n"; return 0; }

Today we sold 20 bushels of apples (5 integer literal "bushels of apples" string literal

There are many operators for manipulating numeric values and performing arithmetic operations. C++ offers a multitude of operators for manipulating data. Generally, there are three types of operators: unary, binary, and ternary.

Unary operators only require a single operand. For example, consider the following expression: −5 Of course, we understand this represents the value negative five. The literal 5 is preceded by the minus sign. The minus sign, when used this way, is called the negation operator. Since it only requires one operand, it is a unary operator. Binary operators work with two operands. The assignment operator is in this category. Ternary operators, as you may have guessed, require three operands. C++ only has one ternary operator

Use the cout (Console Output) object to display information on the computer's screen. In this section you will learn to write programs that produce output on the screen.

cout << "Programming is great fun!"; Notice that the << operator is used to send the string "Programming is great fun!" to cout. When the << symbol is used this way, it is called the stream insertion operator. The item immediately to the right of the operator is sent to cout and then displayed on the screen.

The first is to send cout a stream manipulator called endl (which is pronounced "end-line" or "end-L"). The manipulator can be inserted anywhere in the stream of characters sent to cout, outside the double quotes

cout << "The following items were top sellers" << endl; cout << "during the month of June:" << endl; cout << "Computer games" << endl; cout << "Coffee" << endl; cout << "Aspirin" << endl;

The statement using namespace std;

declares that the program will be accessing entities whose names are part of the namespace called std. (Yes, even namespaces have names.)

Let's review some important points regarding characters and strings:

• Printable characters are internally represented by numeric codes. Most computers use ASCII codes for this purpose. • Characters normally occupy a single byte of memory. • Strings are consecutive sequences of characters that occupy consecutive bytes of memory. • String literals are always stored in memory with a null terminator at the end. This marks the end of the string. • Character literals are enclosed in single quotation marks. • String literals are enclosed in double quotation marks. • Escape sequences such as '\n' are stored internally as a single character.

• short int can be abbreviated as short • unsigned short int can be abbreviated as unsigned short • unsigned int can be abbreviated as unsigned

• long int can be abbreviated as long • unsigned long int can be abbreviated as unsigned long • long long int can be abbreviated as long long • unsigned long long int can be abbreviated as unsigned long long


Set pelajaran terkait

Maternity and Peds: 13 Adaptations to Pregnancy

View Set

Chatter Review (Entire Training)

View Set

Introduction To Java Programming

View Set

APUSH ch 13 and 14 pre/post test, exam

View Set

Pharm Ch 24 - Natural/Herbal Products and Dietary Supplements, CHAPTER 24 (Natural/Herbal Products and Dietary Supplements)

View Set

Week 12: Neuron Structure and Function

View Set

Quality Engineering: Final Review

View Set

Tema 1: Agua (Quimica Alimentos)

View Set