38
Course Overview Course Name: programming Application. Instructor Name:Abdulaziz Hadi ([email protected],01112801680) Assessment methods: 1. Quizzes 20% 2. Tests 20% 3. Practical Exam 40% 4.Mini project 20% 1

Lect1

Embed Size (px)

Citation preview

Page 1: Lect1

Course Overview

• Course Name: programming Application.

• Instructor Name:Abdulaziz Hadi

([email protected],01112801680)

• Assessment methods:

1. Quizzes 20%

2. Tests 20%

3. Practical Exam 40%

4.Mini project 20%1

Page 2: Lect1

Course learning Method

• All course students divided into small groups .

• Three student in each.

• Each group will do class work , lab tasks, mini project together.

• each class work is done and delivered in same class time.

2

Page 3: Lect1

3

The following topics will be covered in this chapter:• Variables (identifiers)• Types• Assignment, arithmetic operations, and arithmetic expressions• Operators and precedence• Functions• Input and output using cin and cout• Formatted input and output using• Comments in programs

C++ Basics

Page 4: Lect1

4

Variable Rules• A variable name is referred to as an identifier• Must declare all variable names

– List name and type• Keep length to 31 characters although longer names are

possible– Older compiler restriction

• Give numeric values to variables with assignment statement

variable_name = value;

assignment operator

Example:

double x;

x = 24.5;

Declare x as a double (real number)

Assign a value to x

Page 5: Lect1

5

Naming Identifiers• First character must be letter

• Other characters may be letters (a-z, A-Z, _ ) or digits 0-9• Cannot use C++ keywords (reserved words – see next page)• Cannot have blanks within identifiers• Use descriptive names (Ex: Area_Of_Circle instead of x)

Examples: Valid Identifiers

Examples: Invalid Identifiers

Page 6: Lect1

6

Keywords• Invalid names for

identifiers• Reserved words

with special meaning to C++

• Note: You are only responsible for knowing keywords corresponding to instructions that we have used up until the time of a test.

Page 7: Lect1

7

Declaring Variables• Variables MUST be declared• List name and data type.• Data types include int, float, double, char, … (more details

later) • Variables of same type may be declared in same statement

(separate by comma).• Causes C++ compiler to know size of space to be reserved

for storing variable’s value

Examples:

Page 8: Lect1

8

Assignment Statementsvariable_name = value or expression;

� Variable name MUST appear on left� Equal sign is assignment operator

Note: be careful = does NOT mean equal

� Example: x = x + 2; means xnew = xold + 2

Examples: (Valid Assignments) Examples: (Invalid Assignments)

Page 9: Lect1

9

Constant Qualified Variables

• Use const qualifier

const double PI = 3.14159;• Cannot modify later in program• Good practice : use all uppercase characters to

name constant– Makes constants easy to identify

Examples:

Page 10: Lect1

10

C++ data typesVariables are typically assigned a data type.Example:

int x; //integer data typedouble y; //real number (floating point) data type

There are several data types available in C++, including:• Integers (including int, short int, long int, unsigned int, etc.)• Real numbers (including float, double, and long double)• Characters (char)• Boolean (bool)• Strings (string) - using the string class, string.h

More details to follow on data types

Page 11: Lect1

11

Integer data typesIntegers are numbers without decimal points.Exceeding the range may show unexpected results as values cycle through the range (see discussion in text).

Integer data type Number of bytes Range

intsigned intshort intsigned short int

2 -32768 to 32767

unsigned intunsigned short int

2 0 to 65535

long intsigned long int

4 -2147483648 to 2147483645

unsigned long int 4 0 to 4294967295

Examples:

Page 12: Lect1

12

Real data typesReal numbers are numbers with decimal points.They may be in scientific notation or in fixed-point notation.Exceeding the range may show “overflow” or “underflow” errors.

Real data type

Number of bytes

Number of sig. digits

Range

float 4 6 ±3.4e-38 to ±3.4e+38double 8 15 ±1.7e-308 to ±1.7e+308long double 10 19 ±3.4e-4932 to ±1.1e+4932

Examples: (include examples in scientific notation)

Page 13: Lect1

13

Character Data Type (char)• A character consists of any single symbol enclosed in single

quotation.• Escape sequences (such as \t, \n, \r, \v) are regarded as a single

character• C++ actually assigns the ASCII code (see Table 3.5 on next page)

for the character, so you can think of a character as essentially acting like an integer

Example: char c1 = ‘?’;char Middle_Initial = ‘W’;

Additional Examples:

Page 14: Lect1

14

Example:The following two commands have the same effect: char c1 = ‘A’;char c1 = 65;

Additional Examples:

Page 15: Lect1

15

Program Output using cout

• cout is referred to as an “object” in C++.• cout is an output object that sends data to a standard

output display device, such as the computer screen.• We will always use cout to send information to the

computer screen.• Form:

cout << [variable, expression, or text (in double quotation)]

• << is referred to as the “extraction operator”• Example:

cout << “Hello”;

Send the text “Hello” to the screen (cout)

Page 16: Lect1

16

Examples: Program Output using coutcout << “Hello”;cout << x;cout << sin(2*x+3);cout << x << y;cout << “x = “ << x;cout << “Angle =“ << Angle << “degrees”;

cout << x; cout << y; cout << z;

cout << x << y << z;equivalent

Page 17: Lect1

17

cout << “This will \continue on same line.” ;

Connecting Strings• The backslash (\) can be used at end of a line to indicate that a

string constant to continue with next line

• The following two statements are equivalent:

cout << “This will continue on same line.” ;

StringsIn the statement below, “Hello” is referred to as a string.

cout << “Hello”;

• String: Any combination of letters, numbers, and special characters enclosed in double quotes (a delimiter)

• Delimiter: A symbol that marks the beginning and ending of a string, but is not part of the string.

Page 18: Lect1

18

Program Output using cout (continued)

• C++ does not automatically advance the display to the next line after using cout.

• A “line feed” is created by using either of the following:• endl (endline)• \n (\ is used to start an “escape sequence” and n for

“newline”). Must be inside quotation marks.• Example:

cout << “John Doe” << endl; // Displayed on first linecout << “123 Main Street\n”; // Displayed on second line cout << “MyCity, VA”; // Displayed on third line

Page 19: Lect1

19

Table 2.4: Escape Sequences

Page 20: Lect1

20

Table 2.4: Escape Sequences (continued)

Page 21: Lect1

21

Escape Sequences

Discuss the escape sequences shown in Table 2.4Class work:Examples: What is displayed in each case below?(Write the output)

x = 2;y = 3;cout << x < y << endl;cout << x << “\n” << y “\n”;cout << x << “\t” << y << “\n” << y << “\t” << x << “\n”;cout << “x\\y < y\\x” << endl;cout << “\”What\’re you doing\?\””;

Page 22: Lect1

22

Program Input using cin

• cin is referred to as an “object” in C++.• cin is an input object that receives data from a

standard input display device, such as the keyboard.• We will always use cin to input information from

the keyboard.• Form:

cin >> value

• >> is referred to as the “insertion operator”• Example:

cout << “Please enter the value of x: ”;cin >> x;

Receive the value for x from the keyboard

Page 23: Lect1

23

Examples: Program Input using cin

cout << “Please enter x: ”;cin >> x;cout << “Please enter y: ”;cin >> y;

cout << “Please enter x and y: ”;cin >> x;cin >> y;

cout << “Please enter x and y: ”;cin >> x >> y;

cin >> “Please enter x” >> x; Invalid

Page 24: Lect1

24

Adding comments to programs• Comments: Explanatory remarks in the source code added

by the programmer • Line comment: Begins with // and continues to the end of

the line– Line comment can be on a line by itself, or at the end of

a line of code– Line comment cannot be longer than one line

• Examples:// Homework Problem 4-1#include <iostream> //library needed to use cin and coutint main(){

double Q = -1.6022E-19; //charge on electron

Page 25: Lect1

25

Adding comments to programs (continued)

• Block comments: Span across two or more lines– Begin with /* and ends with */

– Useful for:• Sections with many comments, such as problem background or

logos• Temporarily “commenting out” a section of a program while

you debug it.

– Example:

/* This is a block comment that

spans

across three lines */

Page 26: Lect1

26

Arithmetic Operations

• Look like algebraic expressions

• Expression consists of sequence of operand(s) and operator(s) – Operand (variable, constant, any value)– Most common operators (+, - , * , / , % )

Example: (describe the output of the program below)int a, b, c, d;a = 4;b = 2;c = (a+b)/(a-b); // algebraic expressiond = a*b-a/b; // algebraic expressioncout << “c = “ << c << endl;cout << “d = “ << d << endl;

Page 27: Lect1

27

Common Operators for Arithmetic Operations

• i/j and i%j are undefined for j = 0Class work:Example: What value is assigned to x in each case?

x = 7%3;x = 3%7;x = 7%7;

Operator Operation Operands Notes

+ Addition, unary plus Real or integer

Overloaded operator has two functions

- Subtraction, unary minus

Real or integer

Overloaded operator has two functions

* Multiplication Real or integer

Overloaded operator has two functions

/ Real and integer division

Real or integer

Overloaded operator has two functions

% Modulus Integer Remainder for integer division

Page 28: Lect1

28

Operator PrecedenceKey Rule: Evaluate multiplication and division before addition and subtraction.

Class work:Example: Evaluate each expression below:

a = 12/2+4*3;b = 12/(2+4)*3;c = 20%6%4;d = 4*-3;

Precedence Operator Order of operation

Highest ( ) parentheses Innermost first

Unary plus (+) or unary minus (-)(+

+,_ _)

Right to left

Multiplication (*) or Division (/) orModulus (%)

Left to right

Lowest Addition (+) or Subtraction (-)

Left to right

Page 29: Lect1

29

Increment and decrement operators

• ++ is the increment operator. - - is the decrement operator.• x++ means x = x + 1• x- - means x = x – 1• When used with assignment:

– When placed in front, incrementing or decrementing occurs BEFORE value assigned

– When placed in back, occurs AFTER value assigned

Class work:Example: Evaluate each expression below:

int a = 3, b = 4, c = 5, d = 6;int e, f, g, h;a++;b--;e = c++;f = ++c; g = d--; h = --d;

Page 30: Lect1

30

Arithmetic OperatorsTable 3.8 in the text provides a more complete list of arithmetic operators and operator precedence.

Page 31: Lect1

31

Compound Assignment Operators (Shortcut Operators)Several shortcut operators are available in C++.The examples below explain how the operators function.

Shortcut Operator Meaning

A += B; A = A + B;

A -= B; A = A - B;

A *= B; A = A * B;

A /= B; A = A / B;

A %= B; A = A % B;

Class work:Example: Evaluate each expression below:

int a = 2, b = 3, c = 4, d = 5, e= 6;a +=3;b -=3;c *= 3;d /= 3;

e %= 3;

Page 32: Lect1

32

Math Functions• Need cmath or cstlib headers

#include <cmath> or #include <cstlib>

• Note what type and form parameters take

– Trig functions use radians not degrees

• Table 3.11 lists math library functions

• Note that

so this is implemented in C++ as

y = pow(x,1.0/3.0);

3

13 x == xy

Page 33: Lect1

33

Math FunctionsExample using functions from cmath:

Sample Program Output:This program will calculate the area of a circleEnter the radius of the circle: 20The area of the circle is 1256.64Press any key to continue . . .

Page 34: Lect1

34

Math FunctionsExample: Write C++ expressions corresponding to each of the mathematical expressions below(home work).

( )

( ) degreesin result with thesin

)(log

)log(

ln

5

)30sin(2

2

1

2

3

)1(2

3 33

22

x

hg

hg

bg

eC

yxz

yxz

y

x

+−

=

==

=

=

+=

+=

°==

θ

πβα

Page 35: Lect1

35

Formatting Output • Output values are formatted in C++ by inserting I/O manipulators (parameterized)

into cout statements for printing

• Example: cout << setprecision(6) << x << y;

• Usually affects all outputs from that point on (no need to include in every cout statement), but might be compiler dependent.

• We must include the header iomanip as follows: #include <iomanip>

• Basic form: cout << manipulator(parameter);

• The table below lists several common I/O manipulators:

I/O Manipulator

Page 36: Lect1

36

setw( )• Sets field width• Right justifies contents• C++ automatically expands if set width too small

Example: int num = 5;cout<<“number =“<<setw(7)<<num<<endl;

number = 5******* Field size

Output:

Page 37: Lect1

37

setfill( )

• Specifies character for blank space in field

• Single quotes required around character enclosed in parentheses

Example:num = 5.34;cout<<setw(10)<<setfill(‘*’)<<num;

Output:******5.34

Page 38: Lect1

38

Example:num = 5.34;cout<<setiosflags(ios::left) << setfill(‘*’)<<setw(10)<<num;

Output:5.34****** (note that the output is left justified)

Example:float x = 421.0, y = 0.0123456789;cout << setprecision(2) << setiosflags(ios::scientific) << " x = " << x << "\ty = " << y << endl;cout << setprecision(6) << setiosflags(ios::scientific) << " x = " << x << "\ty = " << y << endl;

Output:x = 4.21e+002 y = 1.23e-002x = 4.210000e+002 y = 1.234568e-002