lecture 2

Post on 22-May-2015

993 Views

Category:

Education

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

Programming Constructs in C++

TRANSCRIPT

AU/MITM/1.6

By Mohammed A. Saleh

1

ii. The FOR loop This is a loop structure that will perform

repetitive tasks The for loop has several parts that handle the

repeated actions:

a) Setting a value initially

b) Performing a test to see whether the loop should continue

2

c) Executing the loop actionsd) Updating value(s) used for the test The initialization (a), test (b), and update

actions(d) constitute a three-part control section enclosed in parentheses.

Each part is an expression, and semicolons separate the expressions from each other.

The statement following the control section is called the body of the loop, and it is executed as long as the test expression remains true.

3

The for loop syntax:

for (initialization; test-expression;

update-expression)

body Initialization is done just once. This is used

as an expression to set a variable to a starting value and then use the variable to count the loop cycles.

4

The test-expression determines whether the loop body gets executed. This is normally a relational expression, i.e, one that compares two values, e.g (i>5)

Example of a program used for a numeric test:

5

// num_test.cpp -- use numeric test in for loop

#include <iostream>

int main() {

int limit;cout << “Enter the starting countdown value: “; cin >> limit; int i; for (i = limit; i; i--) // quits when i is 0cout << “i = “ << i << “\n”;cout << “Done now that i = “ << i << “\n”;

return 0; }

6

Here is the output from the program: Enter the starting countdown value: 4i = 4 i = 3 i = 2 i = 1Done now that i = 0 The loop terminates when i reaches

0. 7

The for loop is an entry-condition loop. This means the test expression is evaluated before each loop cycle. The loop never executes the loop body when the test expression is false.

The update-expression is evaluated at the end of the loop, after the body has been executed. Typically, it’s used to increase or decrease the value of the variable keeping track of the number of loop cycles.

8

Figure 1.0: The FOR loop structure

9

iii. The DO… WHILE loop This is different from the other two loops

because it is an exit-condition loop. It first of all executes the body of the loop

and only then evaluates the test expression to see whether it should continue looping.

If the condition evaluates to false, the loop terminates; otherwise, a new cycle of execution and testing begins

10

This loop always executes at least once because its program flow must pass through the body of the loop before reaching the test.

The syntax for the do … while loop:do body while (test-expression); The body portion can be a single statement or

a brace-delimited statement block.

11

Figure 2.0: The DO … WHILE loop structure

12

An entry-condition loop is usually a better choice than an exit-condition loop because the entry-condition loop checks before looping.

A do … while example:

13

// dowhile.cpp -- exit-condition loop #include <iostream>int main() {

int n //variable declaration cout << “Enter numbers in the range 1-10 to find “;

cout << “my favorite number\n”; do

{ cin >> n; // execute body

}while (n != 7); // then test

cout << “Yes, 7 is my favorite.\n” ;

return 0; }

14

A sample run of the program:

Enter numbers in the range 1-10 to find my

favorite number

9

4

7

Yes, 7 is my favorite.

15

These are essentially equivalent loops. This for loop could be written this way:

for (init-expression; test-expression; update-expression)

{

statement(s)

}

could be rewritten this way:

init-expression;

while (test-expression)

{

statement(s)

update-expression; }

16

Similarly this while loop:while (test-expression)

body

could be rewritten this way:

for ( ;test-expression;)

body

17

Identify the condition that terminates loop execution.

Initialize that condition before the first test. Update the condition in each loop cycle,

before the condition is tested again.

18

➩Module 2Fundamentals of C++ - Operators & Expressions – Data I/O – Control Structures – Storage Classes – Arrays and Strings.

19

C++ Initiation C++ is case sensitive; that is, it discriminates

between uppercase characters and lowercase characters, e.g it uses cout and NOT Cout or COUT.

The compiler is also spelling sensitive, i.e using kout instead of cout.

The cpp filename extension is a common way to indicate a C++ program.

20

// Example 1.0// myfirst.cpp--displays a message

#include <iostream> // a PREPROCESSOR directiveint main() // function header{ // start of function body cout << “Come up and C++ me some time.”; // message cout << endl; // start a new

line cout << “You won’t regret it!” << endl; // more output return 0; // terminate

main()} // end of

function body

21

C++ programs are constructed from building blocks called functions. Typically, you organize a program into major tasks and then design separate functions to handle those tasks.

Example 1.0 contains a single function named main(). The myfirst.cpp program has the following elements:

22

Comments, indicated by the //prefix A preprocessor #include directive A function header: int main() A function body, delimited by

{and } Statements that uses the C++ cout

facility to display a message A return statement to terminate the

main() function 23

The main () Function Its fundamental structure:int main()

{

statements

return 0;

}

24

Figure 3.0: The main() Function

A function constitutes of a function definition, which has two parts i) function header and ii) function body

25

C++ Statements A C++ program is a collection of functions,

and each function is a collection of statements.

Kinds of statements:

a) Declaration statement – creates a variable

b) Assignment statement – provides a value for the variable

26

// carrots.cpp -- food processing program

// uses and displays a variable

#include <iostream>

int main()

{

int carrots; // declare an integer variable

carrots = 25; // assign a value to the variable

cout << “I have “;

cout << carrots; // display the value of the variable

cout << “ carrots.”;

cout << endl;

carrots = carrots - 1; // modify the variable

cout << “Crunch, crunch. Now I have “ << carrots << “ carrots.” << endl;

return 0;

} 27

// Example 1.1 - carrots.cpp -- food processing program

// uses and displays a variable

#include <iostream>

int main()

{

int carrots; // declare an integer variable

carrots = 25; // assign a value to the variable

cout << “I have “;

cout << carrots; // display the value of the variable

cout << “ carrots.”;

cout << endl;

carrots = carrots - 1; // modify the variable

cout << “Crunch, crunch. Now I have “ << carrots << “ carrots.” << endl;

return 0;

} 28

Program output:I have 25 carrots.

Crunch, crunch. Now I have 24 carrots.

Declaration statements To store an item of information in a

computer, you must identify both the storage location and how much memory storage space the information requires.

29

Why Must Variables Be Declared? Comparing C, Pascal and C++ declaration.

30

Assignment statements Assigns a value to a storage location. For

example carrots = 25; Assigns the integer 25 to the location

represented by the variable carrots. The = symbol is called the assignment

operator The second assignment statement in Example

1.1 demonstrates that you can change the value of a variable: 31

carrots = carrots - 1; // modify the variable

(carrots - 1) is an arithmetic example. The computer will subtract 1 from 25.

32

Dealing with Data The essence of object-oriented programming

(OOP) is designing and extending your own data types. But before you can create your own types, you must know and understand the types that are built in to C++ because those types will be your building blocks.

The built-in C++ types come in two groups: fundamental types and compound types.

33

Simple Variables Programs typically need to store information,

to do that, the program must keep track of three fundamental properties:

i. Where the information is stored

ii. What value is kept there

iii. What kind of information is stored Example:int braincount;

braincount = 5; 34

These statements tell the program that it is storing an integer and that the name braincount represents the integer’s value, 5.

Names for Variables Use meaningful names. Naming rules: The only characters you can use in names are

alphabetic characters, numeric digits, and the underscore (_) character.

35

The first character in a name cannot be a numeric digit.

Uppercase characters are considered distinct from lowercase characters.

You can’t use a C++ keyword for a name. Names beginning with two underscore

characters or with an underscore character followed by an uppercase letter are reserved for use by the implementation—that is, the compiler and the resources it uses. 36

Names beginning with a single underscore character are reserved for use as global identifiers by the implementation.

C++ places no limits on the length of a name, and all characters in a name are significant.

Some valid and invalid C++ names: int poodle; int Poodle; int POODLE;

37

Int terrier; int my_stars3; int _Mystars3; int 4ever; int double; int begin; int __fools; int honky-tonk; int the_very_best_variable_i_can_be_112;

38

Data Types

i. Integer types Numbers with no fractional part, such as 2,

98, –5286, and 0. C++ provides several choices of integer types

to meet a program’s particular requirement. These integer types differ in the amount of

memory they use to hold an integer. Basic integer types, in order of increasing

width, are short, int, and long. 39

Each comes in both signed and unsigned versions.

By having several choices of integer types, C++ offers a flexible standard with some guaranteed minimum sizes.

A short integer is at least 16 bits wide. An int integer is at least as big as short. A long integer is at least 32 bits wide and at

least as big as int. 40

You use these type names to declare variables just as you would use int:

short score; // creates a type short integer variable

int temperature; // creates a type int integer variable long position; // creates a type long integer

variable

Initialization Combines assignment with declaration. For

example:int uncles = 5; // initialize uncles to 5 int aunts = uncles; // initialize aunts to 5

41

You can even initialize a variable to an expression, provided that all the values in the expression are known when program execution reaches the declaration:

int chairs = aunts + uncles + 4; // initialize chairs to 14

ii. The char Type Designed to store characters, such as letters

and numeric digits.42

It’s guaranteed to be large enough to represent the entire range of basic symbols—all the letters, digits, punctuation, and the like.

Example program:// chartype.cpp -- the char type #include <iostream> int main( ) { char ch; // declare a char variablecout << “Enter a character: “ << endl;cin >> ch; cout << “Holla! “;cout << “Thank you for the “ << ch << “ character.” << endl; return 0; }

43

Here’s the output from the program:

Enter a character: M Holla! Thank you for the M character.

iii. The bool type Represents a Boolean variable one

whose value can be either true or false.

bool isready = true; 44

The literals true and false can be converted to type int by promotion, with true converting to 1 and false to 0:

int ans = true; // ans assigned 1 int promise = false; // promise assigned

iv. Floating-point Types C++ has three floating-point types: float,

double, and long double They are described in terms of the number of

significant figures they can represent and the minimum allowable range of exponents 45

C++ has two ways of writing floating-point numbers.

Standard decimal- point notation12.34 // floating-point

939001.32 // floating-point 8.0 // still floating-point

E notation

3.45E6 - means that the value 3.45 is multiplied by 1,000,000. The E6 means 10 to the 6th power. 46

E notation is most useful for very large and very small numbers.

The const Qualifier C++ provides better way to handle symbolic

constants. The const keyword to modify a variable

declaration and initialization. Suppose, for example, that you

want a symbolic constant for the number of months in a year: 47

const int MONTHS = 12; // Months is symbolic constant for 12

Now you can use MONTHS in a program instead of 12.

The keyword const is termed a qualifier because it qualifies the meaning of a declaration.

General form:

const type name= value;

48

1. Why does C++ have more than one integer type?

2. Declare variables matching the following descriptions:

A short integer with the value 80 An unsigned int integer with the value 42,110 An integer with the value 3,000,000,000

3. What safeguards does C++ provide to keep you from exceeding the limits of an integer type?

49

4. What is the distinction between 33L and 33?

5. Consider the two C++ statements that follow:

char grade = 65;

char grade = ‘A’;

Are they equivalent?

50

top related