Course Notes 2

52
CEN 111 Introduction to Algorithms and Programming 2013-2014 Spring Term Faculty of Engıneerıng and Information Technologies

Transcript of Course Notes 2

Page 1: Course Notes 2

CEN 111

Introduction to Algorithms and Programming

2013-2014 Spring Term

Faculty of Engıneerıng and Information

Technologies

Page 2: Course Notes 2

Output and input in C++ are accomplished with streams of characters. Thus, when the

preceding statement is executed, it sends the stream of characters “Welcome to C++!”

to the standard output stream object cout (std::cout) which is “connected” to the

screen by the default value. cout is a predefined identifier for the the standard output

stream object that stands for console output.

Standard Output operation

cout << "Welcome to C++!"<<endl;

The << operator is referred to as the stream insertion operator. When this program

executes, the value to the operator’s right, the right operand, is inserted in the output

stream. Notice that the operator points in the direction of where the data goes. The

right operand’s characters normally print exactly as they appear between the double

quotes.

Page 3: Course Notes 2

Values used in codes are called literal constants. A literal constant is a value that is typed directly into the source code

Literal constant values

Integer literals An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal. An integer literal can also have a suffix that is, U for unsigned and L for long and a combination of U and L for unsigned long which can be in any order. The suffix can be uppercase or lowercase.

A constant written without a decimal point is recognized by the compiler as an integer number. Integer constants can be written in three different variations: • A constant starting with any digit other than 0 is interpreted as a decimal integer. Decimal constants can contain the digits 0 through 9 and a leading minus or optionally plus sign. • A constant starting with the digit 0 is interpreted as an octal integer. Octal constants can contain the digits 0 through 7 and a leading minus or optionally plus sign. • A constant starting with 0x or 0X is interpreted as a hexadecimal constant. Hexadecimal constants can contain the digits 0 through 9, the letters A through F, and a leading minus or optionally plus sign.

Page 4: Course Notes 2

# include <iostream> using namespace std; int main() { cout << 431 << endl; // (decimal) integer literal cout << 431u << endl; // (decimal) unsigned integer literal cout << 431Lu << endl; // (decimal) unsigned long integer literal cout << 431ul << endl; // (decimal) unsigned long integer literal cout << 0x1aF << endl; // hexadecimal integer literal cout << 0657 << endl; // octal integer literal system("pause"); return 0; }

Integer literals

Page 5: Course Notes 2

Floating-point literals

Floating-point literals are the decimal numbers which are can be used either in decimal form or exponential form. Any number with decimal dot is recognized by the compiler as a floating-point literal constant. # include <iostream> using namespace std; int main() { cout << 3.1415 << endl; // floating-point literal cout << .1415 << endl; // floating-point literal cout << 3.0 << endl; // floating-point literal cout << 3. << endl; // floating-point literal cout << 31415E-4 << endl; // floating-point literal cout << 31415E-4L << endl; // floating-point literal cout << 31E2 << endl; // floating-point literal system("pause"); return 0; }

Page 6: Course Notes 2

Boolean literals

Boolean literals can be taken the values of either true or false. Uppercase form of them are not be considered as Boolean literals.

# include <iostream> using namespace std; int main() { cout << true << endl; // Boolean literal cout << false << endl; // Boolean literal system("pause"); return 0; }

Page 7: Course Notes 2

Character literals and String literals

Character literal is any single symbol. There are some certain characters in C++ which are can be used with escape sequence. String literals are a sequence of the characters. While the single quote character (') is a delimiter for a character literal, double quote character (") is a delimiter for a string literal.

# include <iostream> using namespace std; int main() { cout << 'A' << endl; // character literal cout << 'f' << endl; // character literal cout << '5' << endl; // character literal cout << '+' << endl; // character literal cout << "Hello" << endl; // string literal cout << "A" << endl; // string literal cout << "Well come to C++" << endl; // string literal system("pause"); return 0; }

Page 8: Course Notes 2

Special Characters (Escaped Characters)

There are some certain characters in C++ which are can be used with the escape sequence (\) why they are also called escape characters or backslash (\) keys.

Control characters:

•\a = alert (bell)

•\b = backspace

•\t = horizonal tab

•\n = newline (or line feed)

•\v = vertical tab

•\f = form feed

•\r = carriage return

Punctuation characters:

•\" = quotation mark (backslash not required for '"')

•\' = apostrophe (backslash not required for "'")

•\? = question mark

•\\ = backslash

Numeric character references:

•\ up to 3 octal digits

•\x up to 2 hex digits

•\u up to 4 hex digits (Unicode BMP, new in C++11)

•\U up to 8 hex digits (Unicode astral planes, new in

C++11)

\0 = \00 = \000 = octal escape for null character

Page 9: Course Notes 2

Special Characters (Escaped Characters)

# include <iostream> using namespace std; int main() { cout << "Hello" << " everybody!"<<endl; cout << "\"Hello\"" << endl; cout << "A\t+\tB\t=" << endl; cout << 'F' << '\n'; cout << "A+B" << '\r'<<"C-\n"; cout << "Hello\n"; cout << "It is OK\?\n"; cout << "'" << endl; cout << "Its" << '\b'<<" is OK\?\n"; cout << "\x41+\x42=A+B\n"; system("pause"); return 0; }

Page 10: Course Notes 2

Arithmetic operators and expressions

In Microsoft C++, the result of a modulus expression is always the same as the sign of the first operand.

* If the operands of the division operator are both integers result will be

integer.

Operator in C++ Meaning In math

+ Addition X + Y

- Subtraction X - Y

* Multiplication X x Y, or xy

/ Division * X / Y, or X

% Modulus (Remainder) x mod y

Page 11: Course Notes 2

Arithmetic operators and expressions

# include <iostream> using namespace std; int main() { cout << 10+3 <<endl; cout << 10-3 << endl; cout << 10*3 << endl; cout << 10/3 << '\n'; cout << (int)11/5 << '\n'; cout << (float)11/5 << '\n'; cout << 10.0/3 << '\n'; cout << 10/3.3 << '\n'; cout << 10%3 << '\n'; cout << "10+3=" << 10+3 <<'\n'; cout << 5<<'+'<<1<<'='<<5+1 <<endl; system("pause"); return 0; }

Page 12: Course Notes 2

Priority (precedence) of the operators

C++ operators can be divided into levels according to their precedence: Firstly *, / and % Secondly +, -

Page 13: Course Notes 2

Priority (precedence) of the operators

4*6/2 = 12 6/3*2 = 4 9/3/2 = 1.5 3+5-2= 6 9-6-2= 1 9-(6-2)= 5 9/3+3*3=12 12/(3+3)*3= 6 3*2/2+2-5= 0 3*2/2+2-8/4= 3

Subexpressions of the same precedence are evaluated from left to right.

Subexpressions of the same precedence are evaluated from left to right.

Subexpressions of the same precedence are evaluated from left to right.

Subexpressions of the same precedence are evaluated from left to right.

Subexpressions of the same precedence are evaluated from left to right.

Parenthesised expressions have the highest priority

Firstly division, then multiplication and then addition.

Firstly parenthesis, then division and then multiplication.

Firstly multiplication, then division, then addition and then subt.

Page 14: Course Notes 2

C++ Program Screen Output

Page 15: Course Notes 2

becomes in C++

becomes in C++

221

1

x

becomes in C++ 1 / (1 + 2 * x * x)

Arithmetic expressions in C++ must be entered into the computer in straight-line form.

Page 16: Course Notes 2

Write the following mathematical expressions in C++ language

Page 17: Course Notes 2

Write statements in C++ which correctly express each of the following mathematical expressions.

Page 18: Course Notes 2

DATA TYPES

Alfa-numerical Data Numerical Data

Integer numbers: Whole numbers

Decimal numbers: Fractional numbers

-3, 0, 99

- 3.5, 5.001, 4.0, 0.003

Characters: any single letter, numbers, symbols

Strings: sequence of the characters

'A', 'c', '?' , '+', '6'

“Hello C++”, “A+B”

Page 19: Course Notes 2

COMPUTER MEMORY

STORAGE OR SECONDARY

MEMORY

MAIN OR SYSTEM MEMORY

Temporary storage space like RAM Usually permanent storage space like hard disk, memory stick.

In programming, this memory space can be used by the way of files.

In programming, this memory space can be used by the way of variables.

Page 20: Course Notes 2

Variable

A variable is a temporary memory space which stores a value of the declared type

and is identified by a name. It is reserved in the memory when they have declared

and later they can be used to store temporally data during the execution of the

program.

Every variable has three properties: i. Name of the variable (identifier of the variable) ii. Type of the variable iii. Value of the variable.

Page 21: Course Notes 2

I - Name of the variable

You can give any name to your variable only by considering the naming rules of the

identifiers. Give variables meaningful names, which will help to make the

program easier to read and follow. This simplifies the task of error correction.

• Identifiers can be from one to several characters long. The first 1024 characters will be significant. • Variable names may start with any letter of the alphabet or with an underscore. Next may be either a letter, a digit, or an underscore. The underscore can be used to enhance the readability of a variable name, as in first_name. Don’t use space for this purpose. • Uppercase and lowercase are different; that is, to C++, number1 and Number1 can be used as the separate names. • You cannot use any of the C++ keywords as identifier names. Also, you should not use the name of any standard function, such as abs, for an identifier.

Naming Rules

Page 22: Course Notes 2

II - Type of the variable

1. Integer variables store whole numbers (-4, 3, 51, etc). Unsigned integer type variables cannot have negative values, whereas other integer type variables (signed integers) may have negative and positive values. 2. Floating-point variables store decimal numbers (3.5, -5,123, 4.0, etc). 3. Logical variables store the result of logical expressions and get only the values true and false. False is represented with 0 and true is represented with 1 in C++. Logical expressions are usually used in decision and repetition structures to control the flow of the program. 4. Character variables are used to store characters (any single letter, number, punctuation character, etc). Characters are enclosed with a pair of single quotes in C++, like 'a', 'B', '7', '+', etc.

Basic (Built-in) types

5. Strings are used to store text longer than one characters. Strings are enclosed with a pair of double quotes in C++, like " Hello world ", "College", etc.

Derived types

Page 23: Course Notes 2

Variables according to their type can get any values in the ranges which is listed in the following table.

III - Value of the variable:

Page 24: Course Notes 2

Using Variables in C++

To use variables in C++ you should i. Declare the variables and optionally you can initialize them during the declaration. ii. Assign values to the variables. I - Declaration of the Variables To define or identify the name and type of the variables is called declaration of the variables. Some declarations are shown here, for example: int A; int B,C; char ch, chr ; float f, balance; double d;

Page 25: Course Notes 2

II – Assigning values

To give values to decelerated variables are called assigning values. In C++, we use equal sign as the assignment operator =. In a C++ program, you can declare your variables where you want.

int A; float B; char C; string D; A= 9; B=3.3; C= '$'; D='' College '';

When assigning values to char variables, enclose inside single quotes( ' ' ). When assigning values to string variables, enclose inside double quotes( '' '' ).

Using the variables

Page 26: Course Notes 2

II - Initialize and assign values to the variables

To give any value to a variable is called assigning value. Giving the initial value (first value) to the variable during the declaration is called initialization. Initializing is optional if you want you can assign a value later to a variable any where in your program codes. But declaration should done before assignment. The following statements demonstrates how to declare type for a identified variable name, then to initialize it.

int A=3;

Name of the variable is A. Decelerated type of

the variable is int.

Initial value of A is 3.

Page 27: Course Notes 2

Initialization of Variables

int A=3, B, C=5;

At the same time you can declare (define) more variables;

int A, B, C;

int A,B; A=3; B=2; int C=A+B;

You can mix declaration (definition) and initialization;

You can declare (define) just before calculation;

Page 28: Course Notes 2

1. #include <iostream> 2. using namespace std; 3. int main() 4. { 5. int a=0; 6. int b; 7. int c=5; 8. b=3; 9. c=c+6; 10. system("pause"); 11. return 0; 12. }

Value of c at line 7 is equal to 5

Value of c at line 9 is equal to 11, value of a variable as its name implies can be changed.

c=c+6; is always valid in C++. Because = means assignment operator which assigns the value of the right hand side to the left hand side.

c=c+6 is not valid in math, = means equation operator. It can be valid only if c=0.

Page 29: Course Notes 2

Using the variables

Every variable has a size together with the a name, a type, and a value of it. When you declare (define) variables, complier reserve space in RAM memory depending on the type of the variable. If you look at the table you can see how many bytes space you need for a specific variable. But size of the variables can change depending on the complier and the computer you are using.

int A, B, C; A=3; B=5; C=A+B;

Complier reserves 2 bytes space For each integer variables in RAM

Values of A,B,C is stored in RAM temporarily

Page 30: Course Notes 2

Determining the size of the variable types on your computer

The sizes of variables might be different from those shown in the table, depending on the compiler and the computer you are using. Use sizeof() operator to find out the sizes of variable types in your system. The sizeof() operator returns the number of bytes in variable or type.

Page 31: Course Notes 2

Input Operation

Data is often input from the standard input stream object cin (std::cin) which is normally the keyboard and the stream extraction operator, >>, in C++.

• cin >> ……;

The std::cout and std::cin stream objects facilitate interaction between the user and the computer. Because this interaction resembles a dialog, it’s often called conversational computing or interactive computing.

Page 32: Course Notes 2

Input Operation

Syntax of cin

When using cin , you must identify variable or a list of variables next to the extraction (>>) operator.

cin >> variable;

The first statement declares a variable of type int called a, and the second one waits for an input from cin (the keyboard) in order to store it in this integer variable. cin can only process the input from the keyboard once the enter key has been pressed. Extraction (getting data) from cin will not be done until the user presses enter key after the typing completed.

Page 33: Course Notes 2

Input Operation

Using cin

or

Typical screen inputs and outputs

or

A sample program codes

As seen on the typical screen outputs, cin extract (get in) data after pressing ENTER key and every cin extraction stops reading as soon as if finds any blank space character.

Page 34: Course Notes 2

Input Operation

Using cin

is equivalent to

Page 35: Course Notes 2

Using ASCII codes

ASCII Codes

Character encoding (character set) tables are used to represent the characters with number codes . ASCII (1963) and EBCDIC (1964) are two international standard character sets. ASCII (Pronounced ask-ee) is an acronym for American Standard Code for Information Interchange. In ASCII, every letter, number, and punctuation symbol has a corresponding number, or ASCII code. For example, the character for the number 1 has the code 49, capital letter A has the code 65, and a blank space has the code 32. This encoding system not only lets a computer store a document as a series of numbers, but also makes it possible to transfer data from one computer to another. In an ASCII file, each alphabetic, numeric, or special character is represented with a 7-bit binary number (a string of seven 0s or 1s). 128 possible characters are defined. There are also ASCII extensions in use which utilize 8 bit codes to represent international characters in addition to the standard ASCII scheme.

Page 36: Course Notes 2

Using ASCII codes

EBCDIC (Extended Binary Coded Decimal Interchange Code) is an 8-bit character

encoding (code page) used on IBM mainframe operating systems as well as IBM

minicomputer operating systems. It is also employed on various non-IBM platforms

such as Fujitsu-Siemens and Unisys MCP. Although it is widely used on large IBM

computers, most other computers, including PCs and Macintoshes, use ASCII codes.

Page 37: Course Notes 2

Using ASCII codes

cout prints the ASCII character of an ASCII code with “char” casting. The following program prints ASCII code of the number 65 as a character.

ASCII code of the capital letter A is number 65.

Page 38: Course Notes 2

Using ASCII codes

The following program reads an ASCII code (an integer) and prints its character.

Page 39: Course Notes 2

ASCII code table part I

Page 40: Course Notes 2

ASCII code table part II

Page 41: Course Notes 2

Extended ASCII code Table

Page 42: Course Notes 2

Using ASCII codes

The following program demonstrates how to draw a table by using extending ASCII code characters.

Page 43: Course Notes 2

Constant

Symbolic constant Literal Constant

Integer literals

Floating point literals

-3, 0, 99

- 3.5, 5.001, 4.0, 0.003, 5. , .9

1st method: using #define directive

2nd method: using the const keyword

Example: #define PI 3.14159

const float PI = 3.14159; Boolean literals

Character and string literals

true, false

'A', '?', "Well come to C++"

float area; area = PI * (10)*(10);

Symbolic constant Integer literal constants

Like a variable, a constant is a data storage location used by your program. Unlike a variable, the value stored in a constant can't be changed during program execution.

A literal constant is a value that is typed directly into the source code wherever it is needed.

A symbolic constant is a constant that is represented by a name in your program.

Page 44: Course Notes 2

A literal is the source code representation of a fixed value; literals are represented directly

in your code without requiring computation. As shown below, it's possible to assign a literal

(fixed-value) to a variable of a primitive type:

boolean condition= true;

char choice= 'A';

int i = 10;

Literals

Page 45: Course Notes 2

Using constants

Like variables, constants are data storage locations. Unlike variables, values of the constants can not be change. You must initialize a constant when you declare (define) it, and you cannot assign a new value later. Most of the common constants have already been defined in C++. For the user defined constants, there are two main techniques used to define constant values: i. using the define pre-processor directive

#define PI 3.14 ii. using the const keyword const float PI= 3.14;

Page 46: Course Notes 2

Using constants

In this method, constant is defined with const keyword.

1st METHOD

Page 47: Course Notes 2

Using constants

In this method, constant is defined with #define pre-processor directive. There is no need to declare a particular type. Because the preprocessor runs before the compiler and in this example substitute PI with 3.14 and then compiler never sees PI constant; it sees the number 3.14.

2nd METHOD

Page 48: Course Notes 2

Assignment Operators

Assignment

Compound assignment Simple assignment // Example int a,b; a=3; b=a+5;

Multiple assignment // Example int a,b; a=b=7;

+=, -=, *=, /=, %=

Page 49: Course Notes 2

49

int score;

cin >> score; Write a statement to add 1 to score.

score= score+ 1 ;

OR,

score+= 5 ;

Page 50: Course Notes 2

Write a statement to raise value 25%

float value;

cin >> value;

value = value + value * .25 ;

OR,

value = 1.25 * value;

OR,

value *= 1.25 ;

Page 51: Course Notes 2

Increment and Decrement Operators

Operator name Sample expression Explanation ++ preincrement ++a Increment a by 1, then use the new value in the expression ++ postincrement a++ Use the current value of a in the expression, then increment a by 1. -- predecrement --b Decrement b by 1, then use the new value in the expression in -- postdecrement b-- Use the current value of b in the expression, then decrement b by 1.

Page 52: Course Notes 2

Reference book : C++ : How to program P.J. Deitel, H.M. Deitel. -- 8th ed.