Overview of C++ By Dr. Awad Khalil Computer Science & Engineering Department.

46
Overview of C++ By Dr. Awad Khalil Computer Science & Engineering Department

Transcript of Overview of C++ By Dr. Awad Khalil Computer Science & Engineering Department.

Overview of C++

By

Dr. Awad Khalil

Computer Science & Engineering Department

CSCI 106, Overview of C++, by Dr. Awad Khalil

2

C++ Language Elements Comments make a program easier to

understand // Used to signify a comment on a single

line /* Text text */ use if comments on multi

lines Don’t embed comments within /* */

comments

CSCI 106, Overview of C++, by Dr. Awad Khalil

3

Compiler Directives #include

Compiler directiveProcessed at compilation time Instructs compiler on what you want in the

program #include <iostream>

Adds library files to programUsed with < >Also “ “ user defined

CSCI 106, Overview of C++, by Dr. Awad Khalil

4

Compiler Directives

Stream data typeObject that is a stream of charactersDefined in iostreamEntered on the keyboard (cin)Displayed on monitor (cout)

CSCI 106, Overview of C++, by Dr. Awad Khalil

5

Declarations

Direct compiler on requirements Based on data needs (data identifiers) Each identifier needed must be declared Comma used to separate identifiers cin and cout are undeclared identifiers

Special elements called streamscin - input stream , cout - output stream Included with the iostream not declared

CSCI 106, Overview of C++, by Dr. Awad Khalil

6

Executable Statements

cout get outputcout << “Enter the fabric size in square meters: ”;

cin get inputcin >> sizeInSqmeters;

AssignmentsizeInSqyards = metersToYards * izeInSqmeters;

CSCI 106, Overview of C++, by Dr. Awad Khalil

7

Reserved Words and Identifiers Reserved words have special meanings

Can NOT be used for other purposes (const, float and void are some examples)

Identifiers (variables) Used to store data by the program (user

defined) Valid identifiers - letter, letter1, _letter Invalid identifiers - 1letter, const, hell o

Special symbols C++ has rules for special symbols= * ; { } ( ) // << >>

CSCI 106, Overview of C++, by Dr. Awad Khalil

8

Upper and Lower Case

C++ case sensitiveCompiler differentiates upper & lower

case Identifiers can be either Be careful though (cost != Cost)

Blank spacesUse space to make program readableUse care in placing spaces

CSCI 106, Overview of C++, by Dr. Awad Khalil

9

User-Defined Identifier An Identifier must always begin with a letter or

underscore symbol (not recommended)

An identifier must consist of letters, digits, or underscore only.

You cannot use a C++ reserved word as an identifier.

CSCI 106, Overview of C++, by Dr. Awad Khalil

10

User-Defined Identifier

Invalid Identifiers

1Letter

Float

Const

Two*Four

Joe’s

Two-dimensional

CSCI 106, Overview of C++, by Dr. Awad Khalil

11

Data Types and Declarations Predefined data types

int (integers) Positive or negative whole numbers 1000 12 199 100000 INT_MAX - largest int allowed by compiler

float (real numbers) Positive or negative decimal numbers 10.5 1.2 100.02 99.88

bool (boolean) true false

char (Characters) Represent characters

CSCI 106, Overview of C++, by Dr. Awad Khalil

12

Data Type: int The basic integer type is int

The size of an int depends on the machine and the compiler

On pc’s it is normally 16 or 32 bits Other integers types

short: typically uses less bits long: typically uses more bits

Different types allow programmers to use resources more efficiently

Standard arithmetic and relational operations are available for these types

CSCI 106, Overview of C++, by Dr. Awad Khalil

13

Data Type: float Floating-point types represent real numbers

Integer part Fractional part

The number 108.1517 breaks down into the following parts 108 - integer part 1517 - fractional part

C++ provides three floating-point types float double long double

CSCI 106, Overview of C++, by Dr. Awad Khalil

14

Data Type: char

char (characters)Individual character value (letter or

number)Character literal enclosed in single

quotes ‘A’ Character type char is related to the

integer types Characters are encoded using a scheme

where an integer represents a particular character

CSCI 106, Overview of C++, by Dr. Awad Khalil

15

Character Encoding Schemes

ASCII is the dominant encoding schemeExamples

' ' encoded as 32 '+' encoded as 43 'A' encoded as 65 'Z' encoded as 90 ’a' encoded as 97 ’z' encoded as 122

CSCI 106, Overview of C++, by Dr. Awad Khalil

16

Character Encoding Schemes

UNICODE

CSCI 106, Overview of C++, by Dr. Awad Khalil

17

string Class

String object data typeA literal string constant is a sequence of

zero or more characters enclosed in double quotes

"Are you aware?\n" Individual characters of string are stored

in consecutive memory locationsThe null character ('\0') is appended to

strings so that the compiler knows where in memory strings ends

CSCI 106, Overview of C++, by Dr. Awad Khalil

18

string Class

String literal“A”“1234”“Enter the distance”

Additional data types included in library

#include <string>Various operations on strings

CSCI 106, Overview of C++, by Dr. Awad Khalil

19

Declarations

Identifiers should be Short enough to be

reasonable to type (single word is norm)

Standard abbreviations are fine (but only standard abbreviations)

Long enough to be understandable

When using multiple word identifiers capitalize the first letter of each word

Examples char response; int minelement; float score; float

temperature; int i; int n; char c; float x;

CSCI 106, Overview of C++, by Dr. Awad Khalil

20

Constant Declarations

Types of constants integer floatcharboolstring objects

Associate meaningful termsconst float PAYRATE = 10.25;

CSCI 106, Overview of C++, by Dr. Awad Khalil

21

Hello.cpp// FILE: Hello.cpp// DISPLAYS A USER'S NAME#include <iostream>#include <string>

using namespace std;

int main (){ char letter1, letter2; string lastName;

// Enter letters and print message. cout << "Enter 2 initials and last name: "; cin >> letter1 >> letter2 >> lastName; cout << "Hello " << letter1 << ". " <<

letter2 << ". " << lastName << "! "; cout << "We hope you enjoy studying C++." << endl; return 0;}

CSCI 106, Overview of C++, by Dr. Awad Khalil

22

Executable Statements Memory status

Before and after Assignments

Form: result = expression;

sizeInSqyards = metersToYards * sizeInMeters;

sum = sum + item;

CSCI 106, Overview of C++, by Dr. Awad Khalil

23

Arithmetic Operators

+ Addition - Subtraction * Multiplication / Division % Modulus

CSCI 106, Overview of C++, by Dr. Awad Khalil

24

Input / Output Operations

Input

#include <iostream> library

cin >> sizeInSqmeters;

Output

#include <iostream> library

cout << squareArea;

CSCI 106, Overview of C++, by Dr. Awad Khalil

25

Program Input: cinForm: cin >> dataVariable;cin >> age >> firstInitial;

Extracted from cin (input stream) >> Directs input to variable cin associated with keyboard input (stdin) Used with int, float, char, bool and strings Leading blanks ignored (floats, int, char,bool and strings) Char read 1 at a time (1 non blank) Case issues int or float will read until space Stings same as int and float

CSCI 106, Overview of C++, by Dr. Awad Khalil

26

Program Output: cout

Form: cout << dataVariable;

cout << squareArea;

Output stream cout << Output operator (insertion operator)

cout << “my height in inches is: “ << height; Blank lines

endl; or “\n”;

CSCI 106, Overview of C++, by Dr. Awad Khalil

27

General Form of a C++ Program

General program formFunction basic unit (collection of related

statements)A C++ program must contain a main function

void main () int - function returns integer valuemain - lower case with (){ } - Braces define the function body

CSCI 106, Overview of C++, by Dr. Awad Khalil

28

General Form of a C++ Program General form of function body parts

Declaration statementsVariables and constants

Executable statementsC++ statements

CSCI 106, Overview of C++, by Dr. Awad Khalil

29

General Form of a C++ Program

General form// File: filename// Program description:#include directivesint main(){

Declarations sectionExecutable statements section

}

CSCI 106, Overview of C++, by Dr. Awad Khalil

30

Arithmetic Expressions int data type

+ - * /, Assignment, input and output on int% Only used with int

Examples of integer division15 / 3 = 5

15 / 2 = 7

0 / 15 = 0

15 / 0 undefined

CSCI 106, Overview of C++, by Dr. Awad Khalil

31

Modulus and Integer Used only with integer and yields remainder Examples of integer modulus

7 % 2 = 1

299 % 100 = 99

49 % 5 = 4

15 % 0 undefined

CSCI 106, Overview of C++, by Dr. Awad Khalil

32

Mixed-type Assignments

Expression evaluated Result stored in the variable on the left side C++ can mix types

float a, b, x;

int m, n;

a=10;

b=5;

x = m / n;

CSCI 106, Overview of C++, by Dr. Awad Khalil

33

Expressions With Multiple Operators Operator precedence tells how to evaluate

expressions Standard precedence order

() Evaluated first, if nested innermostdone first

* / % Evaluated second. If there are several,

then evaluate from left-to-right+ - Evaluate third. If there are several,

then evaluate from left-to-right

CSCI 106, Overview of C++, by Dr. Awad Khalil

34

Mathematical Formulas in C++

a = bc not valid C++ syntax* Operator a = b * c;

m = y - b x - a

( ) And / m = (y - b) / (x - a);

CSCI 106, Overview of C++, by Dr. Awad Khalil

35

Example 1: Milesbatch.cpp// File: milesBatch.cpp// Converts distance in miles to kilometers.

#include <iostream>using namespace std;

int main() // start of main function{ const float KM_PER_MILE = 1.609; float miles, kms;

CSCI 106, Overview of C++, by Dr. Awad Khalil

36

Milesbatch.cpp

// Get the distance in miles. cin >> miles; cout << "The distance in miles is " <<

miles << endl;

// Convert the distance to kilometers. kms = KM_PER_MILE * miles;

// Display the distance in kilometers. cout << "The distance in kilometers is " <<

kms << endl;

return 0;}

CSCI 106, Overview of C++, by Dr. Awad Khalil

37

Milesbatch.cpp

Program output

The distance in miles is 10

The distance in kilometers is 16.09

CSCI 106, Overview of C++, by Dr. Awad Khalil

38

Example 2: Coin Collection Case Study

Problem statementSaving nickels and pennies and want to

exchange these coins at the bank so need to know the value of coins in dollars and cents.

AnalysisCount of nickels and pennies in totalDetermine total valueUse integer division to get dollar value

/ 100

CSCI 106, Overview of C++, by Dr. Awad Khalil

39

Coin Collection Case Study Analysis (cont)

Use modulus % to get cents value% 100

DesignPrompt for nameGet count of nickels and penniesCompute total valueCalculate dollars and centsDisplay results

CSCI 106, Overview of C++, by Dr. Awad Khalil

40

Coin Collection Case Study

ImplementationWrite C++ code of designVerify correct data types neededMixed mode types and promotion

TestingTest results using various input combinations

CSCI 106, Overview of C++, by Dr. Awad Khalil

41

Coins.cpp// File: coins.cpp// Determines the value of a coin collection

#include <iostream>#include <string>

using namespace std;

int main(){// Local data ... string name; int pennies; int nickels; int dollars; int change; int totalCents;

// Prompt sister for name. cout << "Enter your first name: "; cin >> name;

CSCI 106, Overview of C++, by Dr. Awad Khalil

42

Coins.cpp // Read in the count of nickels and pennies. cout << "Enter the number of nickels: "; cin >> nickels; cout << "Enter the number of pennies: "; cin >> pennies;

// Compute the total value in cents. totalCents = 5 * nickels + pennies;

// Find the value in dollars and change. dollars = totalCents / 100; change = totalCents % 100; // Display the value in dollars and change. cout << "Good work " << name << '!' << endl; cout << "Your collection is worth " <<

dollars << " dollars and " << change << " cents." << endl;

return 0;}

CSCI 106, Overview of C++, by Dr. Awad Khalil

43

Coins.cpp

Program output

Enter your first name and press return: Sally

Enter number of nickels and press return: 30

Enter number of pennies and press return: 77

Good work sally!

Your collection is worth 2 dollars and 27 cents.

CSCI 106, Overview of C++, by Dr. Awad Khalil

44

Interactive Mode, Batch and Data Files Two modes interactive or batch

Keyboard input interactive Batch mode data provided prior to start

File as input Input / output redirection

Direct input to program use ‘<‘ symbolDirect output to a file use ‘>‘ symbol

CSCI 106, Overview of C++, by Dr. Awad Khalil

45

Input / Output Redirection Program name < datafile

Metric < mydata Program name > outFile

Metric > outFile

Input and output redirection

Metric < inFile > outFile

CSCI 106, Overview of C++, by Dr. Awad Khalil

46

Common Programming Errors Syntax

Programs rarely compile Something always goes wrong Systematic solutions

Compiler not descriptive Look at line number before and after error Watch missing ; and }

Run-time errors Illegal operation (divide by 0)

Logic errors Program functions differently than you expect