Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Lecture material weeks 1-15

.pdf
Скачиваний:
14
Добавлен:
24.03.2015
Размер:
1.52 Mб
Скачать

LECTURE 11. PROGRAMMING LANGUAGES 4

Iteration structures (loops)

Loops have as purpose to repeat a statement a certain number of times or while a condition is fulfilled.

The while loop

Its format is:

while (expression) statement

and its functionality is simply to repeat statement while the condition set in expression is true. For example, we are going to make a program to countdown using a while-loop:

1

// custom countdown using

Enter the starting

2

while

number > 8

3

 

8, 7, 6, 5, 4, 3, 2, 1,

4

#include <iostream>

FIRE!

5

using namespace std;

 

6

 

 

7int main ()

8{

9int n;

10cout << "Enter the starting

11number > ";

12cin >> n;

13

14while (n>0) {

15cout << n << ", ";

16--n;

17}

18

19 cout << "FIRE!\n"; return 0;

}

When the program starts the user is prompted to insert a starting number for the countdown. Then the while loop begins, if the value entered by the user fulfills the condition n>0 (that n is greater than zero) the block that follows the condition will be executed and repeated while the condition (n>0) remains being true.

The whole process of the previous program can be interpreted according to the following script (beginning in main):

1.User assigns a value to n

2.The while condition is checked (n>0). At this point there are two possibilities:

*condition is true: statement is executed (to step 3)

*condition is false: ignore statement and continue after it (to step 5)

3.Execute statement: cout << n << ", ";

--n;

(prints the value of n on the screen and decreases n by 1)

4.End of block. Return automatically to step 2

5.Continue the program right after the block: print FIRE! and end program.

When creating a while-loop, we must always consider that it has to end at some point, therefore we must provide within the block some method to force the condition to become false at some point, otherwise the loop will continue looping forever. In this case we have included --n; that decreases the value of the variable that is being evaluated in the condition (n) by one - this will eventually make the condition (n>0) to become false after a certain number of loop iterations: to be more specific, when n becomes 0, that is where our while-loop and our countdown end.

Of course this is such a simple action for our computer that the whole countdown is performed instantly without any practical delay between numbers.

The do-while loop

Its format is:

do statement while (condition);

Its functionality is exactly the same as the while loop, except that condition in the do-while loop is evaluated after the execution of statement instead of before, granting at least one execution of statement even if condition is never fulfilled. For example, the following example program echoes any number you enter until you enter 0.

1

// number echoer

Enter number (0 to end):

2

 

12345

3

#include <iostream>

You entered: 12345

4

using namespace std;

Enter number (0 to end):

5

 

160277

6

int main ()

You entered: 160277

7

{

Enter number (0 to end):

8

unsigned long n;

0

9

do {

You entered: 0

10cout << "Enter number

11(0 to end): ";

12cin >> n;

13cout << "You entered: "

14<< n << "\n";

15} while (n != 0);

return 0;

}

The do-while loop is usually used when the condition that has to determine the end of the loop is determinedwithin the loop statement itself, like in the previous case, where the user input within the block is what is used to determine if the loop has to end. In fact if you never enter the

value 0 in the previous example you can be prompted for more numbers forever.

The for loop

Its format is:

for (initialization; condition; increase) statement;

and its main function is to repeat statement while condition remains true, like the while loop. But in addition, thefor loop provides specific locations to contain an initialization statement and

an increase statement. So this loop is specially designed to perform a repetitive action with a counter which is initialized and increased on each iteration.

It works in the following way:

initialization is executed. Generally it is an initial value setting for a counter variable. This is executed only once.

1.condition is checked. If it is true the loop continues, otherwise the loop ends and statement is skipped (not executed).

2.statement is executed. As usual, it can be either a single statement or a block enclosed in braces { }.

3.finally, whatever is specified in the increase field is executed and the loop gets back to step 2.

Here is an example of countdown using a for loop:

1

// countdown using a for

10, 9, 8, 7, 6, 5, 4, 3, 2,

2

loop

1, FIRE!

3#include <iostream>

4using namespace std;

5int main ()

6{

7for (int n=10; n>0; n--) {

8cout << n << ", ";

9}

10cout << "FIRE!\n";

11return 0;

}

The initialization and increase fields are optional. They can remain empty, but in all cases the semicolon signs between them must be written. For example we could write: for (;n<10;) if we wanted to specify no initialization and no increase; or for (;n<10;n++) if we wanted to include an increase field but no initialization (maybe because the variable was already initialized before).

Optionally, using the comma operator (,) we can specify more than one expression in any of the fields included in afor loop, like in initialization, for example. The comma operator (,) is an expression separator, it serves to separate more than one expression where only one is generally expected. For example, suppose that we wanted to initialize more than one variable in our loop:

1for ( n=0, i=100 ; n!=i ; n++, i-- )

2{

3// whatever here...

4}

This loop will execute for 50 times if neither n or i are modified within the loop:

n starts with a value of 0, and i with 100, the condition is n!=i (that n is not equal to i). Because n is increased by one and i decreased by one, the loop's condition will become false after the 50th loop, when both n and i will be equal to 50.

LECTURE 12. PROGRAMMING LANGUAGES 5

Functions (I)

Using functions we can structure our programs in a more modular way, accessing all the potential that structured programming can offer to us in C++.

A function is a group of statements that is executed when it is called from some point of the program. The following is its format:

type name ( parameter1, parameter2, ...) { statements }

where:

type is the data type specifier of the data returned by the function.

name is the identifier by which it will be possible to call the function.

parameters (as many as needed): Each parameter consists of a data type specifier followed by an identifier, like any regular variable declaration (for example: int x) and which acts within the function as a regular local variable. They allow to pass arguments to the function when it is called. The different parameters are separated by commas.

statements is the function's body. It is a block of statements surrounded by braces { }.

Here you have the first function example:

1 // function example

The result is 8

2#include <iostream>

3using namespace std;

5int addition (int a, int b)

6{

7int r;

8r=a+b;

9return (r);

10}

11

12 int main ()

13{

14int z;

15z = addition (5,3);

16cout << "The result is " <<

17z;

18return 0;

}

In order to examine this code, first of all remember something said at the beginning of this tutorial: a C++ program always begins its execution by the main function. So we will begin there.

We can see how the main function begins by declaring the variable z of type int. Right after that, we see a call to a function called addition. Paying attention we will be able to see the similarity between the structure of the call to the function and the declaration of the function itself some code lines above:

The parameters and arguments have a clear correspondence. Within the main function we called to additionpassing two values: 5 and 3, that correspond to the int a and int b parameters declared for function addition.

At the point at which the function is called from within main, the control is lost by main and passed to functionaddition. The value of both arguments passed in the call (5 and 3) are copied to the local variables int a and int b within the function.

Function addition declares another local variable (int r), and by means of the expression r=a+b, it assigns to rthe result of a plus b. Because the actual parameters passed

for a and b are 5 and 3 respectively, the result is 8. The following line of code:

return (r);

finalizes function addition, and returns the control back to the function that called it in the first place (in this case,main). At this moment the program follows its regular course from the same point at which it was interrupted by the call to addition. But additionally, because

the return statement in function addition specified a value: the content of variable r (return (r);), which at that moment had a value of 8. This value becomes the value of evaluating the function call.

So being the value returned by a function the value given to the function call itself when it is evaluated, the variable z will be set to the value returned by addition (5, 3), that is 8. To explain it another way, you can imagine that the call to a function (addition (5,3)) is literally replaced by the value it returns (8).

The following line of code in main is:

cout << "The result is " << z;

And here is another example about functions:

1

// function example

The first result is 5

2

#include <iostream>

The second result

3

using namespace std;

is 5

4

 

The third result is

5

int subtraction (int a, int b)

2

6

{

The fourth result is

7

int r;

6

8r=a-b;

9return (r);

10}

11

12 int main ()

13{

14int x=5, y=3, z;

15z = subtraction (7,2);

16cout << "The first result is " <<

17z << '\n';

18cout << "The second result is "

19<< subtraction (7,2) << '\n';

20cout << "The third result is " <<

21subtraction (x,y) << '\n';

22z= 4 + subtraction (x,y);

cout << "The fourth result is "

<<z << '\n';

return 0;

}

In this case we have created a function called subtraction. The only thing that this function does is to subtract both passed parameters and to return the result.

Nevertheless, if we examine function main we will see that we have made several calls to function subtraction. We have used some different calling methods so that you see other ways or moments when a function can be called.

In order to fully understand these examples you must consider once again that a call to a function could be replaced by the value that the function call itself is going to return. For example, the first case (that you should already know because it is the same pattern that we have used in previous examples):

1 z = subtraction (7,2);

2 cout << "The first result is " << z;

If we replace the function call by the value it returns (i.e., 5), we would have:

1 z = 5;

2 cout << "The first result is " << z;

As well as

cout << "The second result is " << subtraction (7,2);

has the same result as the previous call, but in this case we made the call to subtraction directly as an insertion parameter for cout. Simply consider that the result is the same as if we had written:

cout << "The second result is " << 5;

since 5 is the value returned by subtraction (7,2). In the case of:

cout << "The third result is " << subtraction (x,y);

LECTURE 13. DESIGN TOOLS AND MANAGMENT OF DATABASES 1

Introduction

A computer would have saved me much time. But then, I didn't really mind typing when the alternative was burning my fingers on hot wires. Nonetheless, what I needed was a database system. A database is a collection of structured information; like the 200 order forms, all with the same information. Contrast this to unstructured information, like the text of a book.

A database system would have allowed me to enter my information into a grid, but it would have been stored in a computer, rather than on paper. Once stored, I could sort the orders, organize and manipulate the data anyway I like, print various reports based on conditions such as: "print the name, phone number and order size for all orders where total_amount > $1000000". This would represent our biggest customers, and potential new golf buddies for George and my father. In database terminology, the grid is called a table. The information corresponding to one order (or row in the grid) would be stored in a record. The individual data elements, for example, name, phone number, order size (stored in the columns) are called fields.

Most databases consist of more than one table. In fact, it is the norm to have multiple tables in order to, among other things, avoid storing redundant data. For example, maybe several of the 200 Plastronics orders are all from the same customer. It's inefficient to store the name, address, and other contact information multiple times, as shown in the following with Fred Yo:

One of the things we most want to avoid in designing our databases is redundant data. Here is a more efficient structure:

Notice each table has a field that contains a distinct identifier for each record. These are called primary keys. A primary key is a field or combination of fields that uniquely identify a record in a table, so that an individual record can be located without confusion.

Such keys make it possible to relate the tables to one another, so we can, for example, find the customer information given a key value in the order table. A foreign key is a key used to link two tables together. Typically you take the primary key field from one table (customer) and insert it

into the other table (order) where it becomes a foreign key (it remains a primary key in the original (customer) table). This type of structure is called a relational database: we have multiple tables that connect to one another via keys.

How Not to Design a Database

When we talk about database design, we mean the organization of the fields in each table, and how keys are used to relate the tables. It's surprisingly easy to create a bad database design. Watch me do it right now.

Let's go back to that summer at Plastronics, only this time George gives me a computer and a database system to organize his orders. This was long before I knew anything about computers, databases or programming. So, my first pass would probably mimic the paper grid. We saw earlier that this was a bad idea because of the redundant customer information. We created a customer table and related it via a customer number.

The following diagram shows the actual contents of the order grid, once we have broken out the customer information.

This second design has some serious problems too.

Practice: Take a moment and see if you can fix the problems in this table by normalizing, that is, coming up with a design that is free of redundant data and that can be consistently and correctly modified.

This is better, but we still have the problem of inconsistent prices ($740 vs. $750 for item #21), and having to change a price increase or decrease in multiple places. We can try breaking out the pricing information into its own table:

LECTURE 14. DESIGN TOOLS AND MANAGMENT OF DATABASES 2

What is MySQL?

MySQL is an open-source database system with which we can do the following things:

design the structure of the tables (called schema) and how they relate to one another

add, edit and delete data

sort and manipulate data

query the database (that is, ask questions about the data)

produce listings based on queries

To interact with MySQL, we enter commands on a command line. These commands, such as CREATE, INSERT, UPDATE, etc. are based on a more general language called SQL (Structured Query Language). SQL has a long and colorful history, starting at IBM in the 70's (based on the research of E.F. Codd who developed the relational data model in 1970), and later through the work of a small company called Relational Software, Inc. In 1979, this group produced the first commercially available relational database system and implemented SQL as its query language. They called the product Oracle.

Getting Started with MySQL

The first thing you need to do to start learning MySQL is get access. We'll assume that you have access and can start up the command line interface. It will look something like:

mysql -uroot -ppassword

You should see the following:

Welcome to the MySQL monitor. Commands end with ; or \q.

Your MySQL connection id is 2129621 to server version: 3.23.58

Type 'help;' or '\h' for help. Type '\c' to clearthe buffer.

mysql>

In the exercises that follow, we will create a database and a set of tables for Plastronics orderprocessing. Then, we'll learn the basic commands for entering, editing and manipulating orders, customers, etc. We will spend most of our time learning how to query these tables, since that's the most interesting part.

If you have worked with other SQL systems or with MySQL in other environments, the following articles and documents may be helpful:

Comparison of SQL Server and MySQL

Comparison of Oracle SQL and MySQL

MySQL Documentation

Setting Up the Tables

Step one is to create a database which is a container for our tables. Enter the following command:

create database plastronics;

Note that the commands and names are not case-sensitive. Also, note that the ending semi-colon is required or you'll see something like this:

mysql> create database plastronics

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]