Informatics. Study Guide. Mathcad. Matlab. VC++

308
UDC 681.3.06+519.6 Informatics: Mathcad, Matlab softwares and Visual C++ environment. / A. Sokolov, T. Korchak, O. Morozova. – Course study guide. – Kharkov: National Aerospace University named after N. E. Zhukovsky “KhAI”, 2009. – 255 pages. Theory of high level languages programming technique are introduced. This study guide provides a student-friendly, highly readable introduction to Mathcad, Matlab and Visual C++ programming for beginning programming students especially those majoring in Information Systems and Control Systems. Complete and clear descriptions of sample programs, with a wealth of exercises included along the way to help reinforce the important points are included. For students of higher school foreign departments. Number of tables 0. Рictures 67. Bibliography 10 n. R e v I e w e r s: 2

Transcript of Informatics. Study Guide. Mathcad. Matlab. VC++

Page 1: Informatics. Study Guide. Mathcad. Matlab. VC++

UDC 681.3.06+519.6

Informatics: Mathcad, Matlab softwares and Visual C++ environment. / A. Sokolov, T. Korchak, O. Morozova. – Course study guide. – Kharkov: National Aerospace University named after N. E. Zhukovsky “KhAI”, 2009. – 255 pages.

Theory of high level languages programming technique are introduced. This study guide provides a student-friendly, highly readable introduction to Mathcad, Matlab and Visual C++ programming for beginning programming students especially those majoring in Information Systems and Control Systems. Complete and clear descriptions of sample programs, with a wealth of exercises included along the way to help reinforce the important points are included.

For students of higher school foreign departments.

Number of tables 0. Рictures 67. Bibliography 10 n.

R e v I e w e r s:

©National Aerospace Universitynamed after N. E. Zhukovsky “Kharkov Aviation Institute”, Ukraine, Kharkov, 2009

2

Page 2: Informatics. Study Guide. Mathcad. Matlab. VC++

Laboratory work 1

INTRODUCTION TO MATHCAD

Objective – get to know with Mathcad; learn the basics of working with Mathcad and constructs that you can use during calculation.

Problem statement – learn to do calculations and display result in the view of values of all variables.

Theoretical information

Mathcad basics. Whenever you open Mathcad, a blank worksheet opens. You can liken this worksheet to a clean sheet of calculation paper waiting for you to add information to it. Simply type the equations as you would write them on paper.

Additional resources. This book is written as a supplement to the Mathcad Help and the Mathcad User’s Guide. It adds insights not contained in these resources. You should become familiar with the use of both these resources prior to beginning an earnest study of this book. To access the Mathcad Help, click Mathcad Help from the Help menu, or press the F1 key. The Mathcad User’s Guide is a PDF file located in the Mathcad program directory in the “doc” folder. In addition to the Mathcad Help and the Mathcad User’s Guide, the Mathcad Tutorials provide an excellent resource to learn Mathcad. The Mathcad Tutorials are accessed by clicking Tutorials from the Help menu. Take the opportunity to review some of the topics covered by the tutorials.

Variables. Variables are one of the most important features of Mathcad. As in Algebra, variables define constants and create relationships. Your Mathcad worksheet will be full of variables. It is therefore important to quickly gain a solid foundation in their use.

Types of variables. Variables can consist of numbers or constants such as: , or . They can consist of equations such as: , or . You can set one variable equal to another such as . Variables can also consist of strings of characters such as

.Variables can even have logic programs associated with them so that

the value of the variable depends on the outcome of Boolean logic. As you go through this book you will see that variables can be very simple or be very complex.

Defining variables. To define a variable, type the variable name followed by pressing the colon : key. This inserts the definition symbol, “:=” and a placeholder ( ▪). The placeholder is a small black box that indicates that the expression is incomplete. Click on the placeholder and complete the definition by typing in a number or an equation. To view the

3

Page 3: Informatics. Study Guide. Mathcad. Matlab. VC++

value assigned to a variable, type the variable name followed by the equal sign.

Chemistry notation. Mathcad provides a means to have your variable names look like an expression or an equation. It is a special mode called Chemistry Notation. To activate the Chemistry Notation type CTRL+SHIFT+j. This inserts a pair of brackets with a placeholder between them. You are now free to insert whatever letters, numbers, and operators you want between the brackets. Chemistry Notation is useful when you have a long equation with many parts. You may want to separate the equation into smaller parts. In order to do this you need to give each part of the equation a variable name. With Chemistry Notation, each part can be given the variable name to match the part of the equation as in the next example.

Creating simple math expressions. There are two ways to create a simple expression. The first way is to type an operator such as +, −, *, or /. This will create empty placeholders that you can then click to fill in the numbers or operands. For example, if you press the + key anywhere in your worksheet, you will get the following:

You can use the above procedure with any operator. Let’s try the exponent operator. Press to create the exponent operator. You can also click on the calculator toolbar. You should have the following:

A second way to create a simple expression is to just type as you would say the expression. For example you would say 2 plus 5, so you would type the following 2 + 5. You would say 2 to the 4th power, so you would type 2 ˆ 4. These methods work very well for creating simple expressions.

Creating more complex expressions. Creating more complex math expressions is very easy once you learn the concept of the editing lines. These are similar to a two-dimensional cursor with a vertical and a horizontal component.

4

Page 4: Informatics. Study Guide. Mathcad. Matlab. VC++

Pressing the spacebar will cause the editing lines to grow to hold more of the expression. For example, if you type 2+5 spacebar, you get the following:

Whatever is held between the editing lines becomes the operand for the next operator. So, if you type 2+5 spacebar ˆ 3, you get the following:

In this case (2+5) is the x operand for the operator x to the power of y. Notice how the editing lines now only contain the number 3. This means that if you type any operator, the number 3 is the operand for the operator. Thus, if you type + 4, then you get the following:

But, if you type the spacebar first, the editing lines expand to enclose the whole expression. This expression becomes the operand for the next operator. Thus, if you now type + 4, you get the following:

The whole expression became the operand for the addition operator. It is very important to understand this concept of using the editing lines to determine what the operand is of your next operator. You can also use parenthesis to set the operand for operators. Pressing the single quote (') adds a pair of opposing parenthesis.

The following example will help reinforce these concepts. Let’s create the following expression:

To create this expression, use the following steps:1. Type 1 / 2 spacebar. The editing lines now hold the fraction 1/2. This becomes the operand for the subtraction operator.2. Type – 1 / 3 spacebar spacebar. The editing lines should now hold both fractions. This becomes the operand for the power operator.3. Type ˆ 2 spacebar. The editing lines should now hold the entire numerator. This becomes the operand for the division operator.4. Type / (or use the square root icon on the math toolbar) 4 / 5 spacebar spacebar. This makes everything under the radical the operand for the addition operator.5. Type + 2 / 7. This completes the example.

Notice how during each step, the spacebar was used to enlarge the editing lines to include the operand for the following operator. The Mathcad tutorial has additional examples that provide worthwhile practice.

5

Page 5: Informatics. Study Guide. Mathcad. Matlab. VC++

Built-in functions. Built-in functions range from very simple to very complex. Examples of simple built-in Mathcad functions are: sin(), cos(), ln(), and max(). Every Mathcad function is set-up in a similar way. The function name is given, followed by a pair of parenthesis.

The information that is typed within the parenthesis is called the argument. Every function has a name and an argument. The function takes the information from the argument (contained within the parenthesis) and processes the information based on rules that are defined for the specific function, returning a result. To see a list of all the built-in functions that Mathcad has, select Function from the Insert menu.

A Mathcad expression can have an unlimited number of functions included. To insert a function within an expression, simply highlight the placeholder and use the Insert Function dialog box to insert the function. If you are familiar with the function and its arguments, you do not need to use the dialog box.

Remember that function names are case sensitive. If you type a function name and Mathcad does not recognize it, use the Insert Function dialog box to see if the first letter is upper case or lower case. Next example shows an expression using multiple built-in functions.

User-defined functions. User-defined functions are very similar to built-in functions. They consist of a name, a list of arguments, and a definition giving the relationship between the arguments. The name of the user-defined function is simply a variable name. The same rules that apply to naming variables also apply to naming functions. The arguments used in the user-defined function do not need to be defined previously in your worksheet. The function is simply telling Mathcad what to do with the function arguments, thus the arguments are not defined prior to using the function. The following is a simple user-defined function:

In the above example, “SampleFunction” is the name of the function, and “x” is the argument. When you type: SampleFunction(2)=, Mathcad takes the value of the argument (2), and applies it everywhere there is an occurrence of the argument in the definition. So in the above example, Mathcad replaces “x” with the number “2” and squares the number, returning the value of 4. Below you can see examples of this function with various arguments.

6

Page 6: Informatics. Study Guide. Mathcad. Matlab. VC++

Notice that the argument may also be the result of an expression. Any expression is allowed as long as the result of the expression is a value that is expected by the function. Let us look at some sample user-defined functions. See next example.

You can even use characters as arguments if you switch to the special text mode (CTRL+SHIFT+k).

Once a user-defined function is defined, it can be used over and over again. This makes user-defined functions very useful and powerful. User-defined functions are useful if you are repeatedly doing the same steps over and over again in your calculations. See example.

7

Page 7: Informatics. Study Guide. Mathcad. Matlab. VC++

You are also allowed to use a variable in your function definition that is not a part of your argument list; however, this variable must be defined prior to using it in your user-defined function. The value of the variable – at the time you define your user-defined function – becomes a permanent part of the function.

When you evaluate a previously defined user-defined function, the values you put between the parentheses in the argument list may also be previously defined variables. This is illustrated in the next example.

VariantsTask 1. For all variants: - add 10 simple variable definitions from your field of study, include some subscript names. - add 10 variable definitions that are two words or more. Use two different methods for differentiating between words.- add 10 variable definitions that include characters requiring the use of the special text mode.- add 10 variable definitions that use the Chemistry Notation.- add 10 string variable definitions.Task 2. Take a variant according to your number in the list. Define all needed variables and solve equation.

8

Page 8: Informatics. Study Guide. Mathcad. Matlab. VC++

1.

2.

3.

4.

5.

6.

7.

8.

9.

10.

11.

12.

13.

14.

15.

16.

17.

18.

19.

20.

21.

22.

23.

24.

25.

26.

27.

28.

29.

30.

Task 3. Define needed variables and solve equation Y.

1. Y= ;

2. Y=

9

Page 9: Informatics. Study Guide. Mathcad. Matlab. VC++

3. Y=

4. Y=

5. Y=

6. Y= ;

7. Y=

8. Y=

9. Y=

10. Y= ;

11. Y= ;

12. Y= ;

13. Y= ;

14. Y= ;

15. Y= ;

10

Page 10: Informatics. Study Guide. Mathcad. Matlab. VC++

16. Y= ;

17. Y= ;

18. Y=

19. Y= ;

20. Y=

21. Y= ;

22. Y=

23. Y=

24. Y=

25. Y= ;

26. Y= ;

27.Y= ;

28. Y= ;

11

Page 11: Informatics. Study Guide. Mathcad. Matlab. VC++

29. Y= ;

30. Y= ;

Laboratory work 2

MATRIX OPERATIONS IN MATHCAD

Objective – to understand how to use vectors and matrices that will help you make engineering calculations much more effective; to illustrate the benefits that can be had by using simple vectors and matrices in engineering calculations.

Problem statement – learn to perform many complex vector and matrix operations.

Theoretical information

Creating vectors and matrices. It is very easy to create a vector or matrix by using the Insert Matrix dialog box. See Figure 2.1. This dialog box can be accessed in three ways. The first way is by selecting Matrix from the Insert menu. The second way is by typing the shortcut CTRL+m. The third way is by opening the Matrix toolbar and selecting the matrix icon showing a three by three matrix.

Figure 2.1. Insert matrix icon on Matrix toolbar

Once the Insert Matrix dialog box is open, change the number of rows and columns to the desired numbers and click OK. For example, if you type 4 and 4 in the Rows and Columns boxes you will get a matrix as shown in Figure 2.2.

12

Page 12: Informatics. Study Guide. Mathcad. Matlab. VC++

Figure 2.2. Blank 4×4 matrix

Now, simply fill in the placeholders with numbers or expressions. Use the tab key or arrow keys to move from placeholder to placeholder. See Figure 2.3 for two sample matrix definitions using numbers and expressions.

Figure 2.3. Sample matrix definitionsOnce you create a vector or matrix, you can add additional rows or

columns by using the Insert Matrix dialog box. To do this, select an element in the vector or matrix, and then open the Insert Matrix dialog box. Mathcad will insert additional rows below the selected element, and insert additional columns to the right of the selected element. Tell Mathcad how many additional rows and/or columns you want to add. If you want to add one additional row, but not an additional column, then type 1 for row and 0 for column. If you want to add rows above or columns to the left, then select the entire vector or matrix prior to using the Insert Matrix dialog box. After entering the number of rows and/or columns, click OK or Insert. If you select Insert first, be sure to click Close to close the box. If you click OK to close the box, additional rows and/or columns will be added.

You can also use the Insert Matrix dialog box to remove rows and columns. To do this, select an element in the row or column that you want to delete.

ORIGIN. The value of ORIGIN tells Mathcad the starting index of your array. The Mathcad default for this variable is 0. This means that a vector or matrix begins indexing with zero. In other words, the first element is the 0th element. Thus, in Matrix_1 of Figure 2.3, the value of the 0th element of the matrix (Matrix_1(0,0)) would be 1. For engineering

13

Page 13: Informatics. Study Guide. Mathcad. Matlab. VC++

calculations, it is suggested that you change the value of ORIGIN from 0 to 1. With the value of ORIGIN set at 1, the first element of a matrix is the 1st element. Thus, in Matrix_1 of Figure 2.3, the value of the first element of the matrix (Matrix_1(1,1)) would be 1. For the remainder of this book, the value of ORIGIN will be set at 1. If you want to change the value of ORIGIN you should select Worksheet Options from the Tools menu. On the Built-In Variables tab, change the “Array Origin” from 0 to 1. Next, click on the Calculation tab. Add a check in the “Use ORIGIN for string indexing” box. This tab should look like Figure 2.4.

Figure 2.4. Settings for the Calculation tabArray subscripts (subscript operator). A literal subscript

becomes part of the variable name. When using arrays, we use a different subscript called an array subscript. It is also called an array subscript operator.

An array subscript allows Mathcad to display the value of a particular element in an array. In this case, the subscript does not become part of the variable name. It is used to refer to a single element in the array.

The array subscript is created by using the [ key. This is referred to as the subscript operator. Thus, if you want Mathcad to display the value of the first element in Matrix_1 Figure 9.3 you would type:

Matrix_1[1,1= Matrix_1 1,1 = 1.00.

If you want Mathcad to display the value of the element in the 3rd row, 4th column, you would type Matrix_1[3,4= Matrix_1 3,4 = 12.00. In the above example, the name of the variable was Matrix_1.

The array subscript is not part of the variable name. It is only used to display an element of the array.

You can also use an array subscript to assign elements of an array. If you type Matrix_1[1,1:20 then the value of the 1st element in Matrix_1 will be changed from 1 to 20.

14

Page 14: Informatics. Study Guide. Mathcad. Matlab. VC++

Figure 2.5 shows how to use array subscripts for a vector. Figure 9.6 shows how to use array subscripts to assign new values to vectors and arrays.

Figure 2.5. Using array subscripts

You can add additional elements to an array, by defining them with array subscripts.

Figure 2.6. Using array subscripts

Range variables. A range variable is similar to a vector in that it takes on multiple values. It has a range of values. The range of values has a beginning value, an ending value and uniform incremental values between the beginning and ending values. Range variables are used to iterate a calculation over a specific range of values, and to plot a function over a specific range of values. They are often used as subscripts for defining arrays. A range variable looks like this:

15

Page 15: Informatics. Study Guide. Mathcad. Matlab. VC++

This range variable begins with 1.0. The second number in the range variable sets the increment value. Mathcad takes the difference between the first and second numbers and uses this as the incremental value. In the above case, the increment is 0.5. The last number in this range is 5.0.

Thus, this range variable has the values: 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, and 5.0. To define a range variable, type the variable name followed by the colon :. This creates the variable definition. In the placeholder, type the beginning value, and then type a comma. This adds a second placeholder in the expression. Now enter the second value in the placeholder. The second number sets the incremental value. Now type a semicolon ;. This places two dots in the worksheet, and adds a third placeholder.

Enter the ending value in the placeholder. If the second value is less than the beginning value, then the range variable will be decreasing, and the last value sets the lower limit to the range variable. See Figure 2.7 for sample range variables and their displayed results.

Column and row labels. Column and row labels appear along the top and left side of an output table. To turn the labels on or off, right-click within the table and select Properties. This opens the Component Properties dialog box. To turn the labels on, place a check in the “Show column/row labels” check box. To turn the labels off, clear the check box. The Mathcad default is to have labels turned on for vectors and matrices, and to have labels turned off for range variables (see Figure 2.8).

Figure 2.7. Sample range variables

16

Page 16: Informatics. Study Guide. Mathcad. Matlab. VC++

Figure 2.8. Sample output – matrix form and table form

Output table size when a vector or matrix becomes too large, Mathcad will only display a portion of the output table. In order to view all the output data, you must click inside the table. This will cause scroll bars to appear at the right side and/or bottom of the table. Use the scroll bars to view the remaining output data. In order to display more of the output table, you can make the table larger by clicking and dragging one of the black anchor boxes located in the corners and at midpoints of the table.

See Figure 2.9. If the table crosses the right margin, you will not be able to print the entire table if you have “Print single page width” selected from the Page Setup menu. If this is the case, you can try to make the column widths narrower.

17

Page 17: Informatics. Study Guide. Mathcad. Matlab. VC++

Figure 2.9. Output table with scroll bars

You can only make the columns narrower if the column and row labels are turned on. Move your cursor to the column label and place it on top of a line between columns. The cursor should change to a vertical line with arrows either side. Click and drag to the left to make the columns narrower.

Output table font size and font properties. You can also decrease the font size in the output table in order to display more table cells on one page. To change the output table font size, right-click within the table and select Properties. This opens the Component Properties dialog box. Click on the Font button to open the Font dialog box. From this box, you may change the font style, font properties, and font size. If you want a size different from what is listed, then type the font size in the “Size” box. Remember that the changes you make to this output table will not affect other output tables. See Figure 2.10.

Figure 2.10. Output table with a smaller font

Calculating with arrays. Mathcad allows to use many math operators with arrays just as it can be done with scalar variables. For example, you can add and subtract arrays just as you would other variables as long as the arrays are the same size. If they are different size arrays, Mathcad will give you an error warning. You can multiply a scalar and an array. The result will be each element of the array multiplied by the scalar.

If you multiply two array variables, Mathcad assumes that you want a matrix dot product and gives a result (assuming that the two arrays are compatible with the dot product rules). There is a way to tell Mathcad that you want the matrix cross product. There is also a way to tell Mathcad that you want to multiply two arrays on an element-by-element basis and return a similar size array. These will be discussed shortly.

Addition and subtraction. If vectors and matrices are exactly the same size, you may add or subtract them as you would any Mathcad variable. The addition and subtraction is on an element-by-element basis. Warning: arrays must be the same size (see Figure 2.11).

18

Page 18: Informatics. Study Guide. Mathcad. Matlab. VC++

Figure 2.11. Addition and subtraction

Multiplication. There are several different ways to multiply arrays. These are discussed below.

Scalar multiplication. You can multiply any vector or matrix by a scalar number. Mathcad multiplies each element in the array by the scalar and returns the results. The scalar can be before or after the array. See Figure 2.12.

Figure 2.12. Scalar multiplication

Dot product multiplication. When you multiply two arrays, Mathcad assumes that you want the matrix dot product of the two arrays. (The dot product is calculated by multiplying each element of the first vector by the corresponding element of the complex conjugate of the second vector, and then summing the result. Refer to a text on matrix math for a discussion of the matrix dot product.) In order for the dot product to work, the number of columns in the first matrix must match the number of rows

19

Page 19: Informatics. Study Guide. Mathcad. Matlab. VC++

in the second matrix. In other words, the matrices must be of the size m×n and n×p. See Figure 2.13.

Figure 2.13. Array dot product multiplication

Vector cross product multiplication. Mathcad can perform a vector cross product on two column vectors. Each vector must have three elements. The result is a vector perpendicular to the plane for the first two vectors. The direction is according to the right-hand rule. Use the matrix toolbar to insert the vector cross product operator, or type CTRL+8. See Figure 2.14.

Element-by-element multiplication (vectorize). In order to do an element-by-element multiplication, you need to use the vectorize operator. This will tell Mathcad to ignore the normal matrix rules and perform the operation on each element. To vectorize the multiplication operation, select the entire expression, and then type CTRL+MINUS.

Figure 2.14. Vector cross product

This places an arrow above the expression and tells Mathcad to perform the operation on an element-by-element basis. When using a dot product multiplication, the number of columns in the first array needs to match the number of rows in the second array. When using the vectorize operation, the arrays must be exactly the same size because the multiplication is being done on an element-by-element basis. See Figure 2.15 for examples of using the vectorize operator.

20

Page 20: Informatics. Study Guide. Mathcad. Matlab. VC++

Figure 2.15. Array element-by-element multiplication

Division. For the case of X/Y, the result is dependant on whether X or Y are scalars or arrays. The result is also dependant on whether Y is a square matrix. Here are the rules:• If Y is a square matrix, the result is the dot product of X*Y−1, where Y−1 is the inverse of the square matrix Y.• If either X or Y is a scalar, then the division is done element-by-element.• If both X and Y are arrays, then both arrays must be of the same size. If they are not square matrices, then Mathcad does an element-by-element division. • If both X and Y are square matrices, then in order to do an element-by-element division, you must use the vectorize operator. To do this, select the expression and type CTRL+MINUS. See Figures 2.16–2.19 for examples of array division.

21

Page 21: Informatics. Study Guide. Mathcad. Matlab. VC++

Figure 2.16. Scalar division

Figure 2.17. Array division

Figure 2.18. Array division

22

Page 22: Informatics. Study Guide. Mathcad. Matlab. VC++

Figure 2.19. Array division

VariantsTask 1.

1. Open the Insert Matrix dialog box. Create a 4×5 matrix. Fill in the matrix with some numbers.

2. In the matrix created above, insert a new column between the 3rd

and 4th columns. Insert a new row between the 2nd and 3rd rows. Fill-in new data.

3. In the above matrix, delete the 3rd row. Delete the 5th column.4. Create 10 different arrays. Practice inserting and deleting rows

and columns in the different arrays. Have two arrays larger than 20×20.5. Assign variable names to the above arrays. Display each array in

matrix form, in an output table with row and column labels, and in an output table without row and column labels. If the entire matrix does not display in table form, then enlarge the output table. Practice changing the column widths, row heights, and table font. Task 2. Use task from the laboratory work 1 (Task 3). Define needed variables as arrays of 10 values and find the solutions of equation Y for each 10 values.

Laboratory work 3

PLOTTING IN MATHCAD

Objective – get to know with an important part of engineering calculations as plots because they allow visualization of data and equations and they can help you select an initial guess for a solution.

Problem statement – using 2D plots as a tool for visualization and solving of equations complete four tasks that are given at the end of the theoretical information.

Theoretical information

Creating a simple X-Y QuickPlot. To create a simple X-Y QuickPlot, type @, or hover the mouse over Graph on the Insert menu

23

Page 23: Informatics. Study Guide. Mathcad. Matlab. VC++

and click X-Y Plot. This places a blank X-Y plot operator on the worksheet.

Click on the bottom middle placeholder to type the x-axis variable. Type the name of a previously undefined variable. The variable is allowed to be “x” but can be any Mathcad variable name. Next, click on the middle left placeholder, and type an expression using the variable named on the x-axis. Click outside the operator to view the X-Y plot.

Mathcad automatically selects the range for both the x-axis and the y-axis. There is a way to change the plot range, which will be discussed shortly. Another shortcut is to only type the expression in the left placeholder. Mathcad automatically adds the independent variable in the bottom placeholder. See Figure 3.1.

Figure 3.1. X-Y QuickPlot of equations

Creating a simple Polar plot. Creating a simple Polar QuickPlot is very similar to creating a simple X-Y QuickPlot. Open the Polar plot operator by typing CTRL+7, or hover the mouse over Graph on the Insert menu, and select Polar Plot.

Click on the bottom middle placeholder to type the angular variable. Mathcad assumes the variable to be in radians. Type the name of a previously undefined variable. Next, click on the middle left placeholder and type an expression using the angular variable defined on the x-axis. This sets the properties of the radial axis. Click outside of the operator to view the plot. For every angle from 0 to 2 , Mathcad plots a radial value. Mathcad automatically selects the radial range. See Figure 3.2.

24

Page 24: Informatics. Study Guide. Mathcad. Matlab. VC++

Figure 3.2. Polar QuickPlot of functionsYou may also use a previously defined function in a simple Polar

QuickPlot. Open the Polar plot operator by typing CTRL+7. Type the name of the angular variable in the bottom placeholder. Type the name of the function on the left placeholder using the angular variable name as the argument of the function. See Figure 3.3.

Figure 3.3. Polar QuickPlot of functions

Using range variables. Range variables are used to tell Mathcad what range of values to use when graphing an expression or function.

25

Page 25: Informatics. Study Guide. Mathcad. Matlab. VC++

When you create simple X-Y QuickPlots and Polar QuickPlots, Mathcad sets the range of values. By using range variables, you can control the range of values. To graph using a range variable, create the range variable before using the plot operator. Next, open the plot operator, and type the name of the range variable in the placeholder on the x-axis. In the left placeholder, type the name of a function or expression using the range variable. See Figures 3.4 and 3.5.

Figure 3.4. Using range variables to set plot range

Setting plotting ranges. There is another way to set the plot range. You may have noticed additional placeholders when you opened an X-Y plot operator or a Polar plot operator. These additional placeholders set the lower and upper limits of the plot.

26

Page 26: Informatics. Study Guide. Mathcad. Matlab. VC++

Figure 3.5. Using range variables to set plot range

For an X-Y plot, the placeholders on the bottom set the lower and upper limits on the x-axis. The placeholders on the left set the lower and upper limits on the y-axis. To change the default values, click on the limit placeholder and delete the value. Next, add a new plot limit. You can tell which plot limits still have the default values because there will be small brackets on the bottom sides of the default values. Once you change the default values, the brackets are no longer displayed. See Figures 3.6 and 3.7.

For a Polar plot, the limits of the radial axis are set by the two placeholders on the right. You can experiment with changing the lower placeholder, but it seems to work best when this placeholder is left at zero. See Figures 3.8 and 3.9.

27

Page 27: Informatics. Study Guide. Mathcad. Matlab. VC++

Figure 3.6. Setting plot range

Figure 3.7. Setting plot range

Graphing multiple functions. You can graph up to 16 multiple functions or expressions on the same plot. To graph multiple expressions using the same x-axis variable, type a comma after entering the function or expression in the left middle placeholder. This places a new placeholder below the original placeholder.

Figure 3.8. Setting plot range

28

Page 28: Informatics. Study Guide. Mathcad. Matlab. VC++

Figure 3.9. Setting plot range

You can now type a new function or expression. You can repeat the process until you have up to 16 functions or expressions. Each plot is called a trace. See Figure 3.10.

Figure 3.10. Multiple plots

This figure 3.10 is a plot of 4 expressions, each using the same x-axis variable. The x-axis limits are set at -10 and 10. The y-axis limits are set at -100 and 100.

In Mathcad you can create a secondary y-axis on the right-hand vertical axis of an X-Y plot. Which can be used to graph additional traces at a different scale than the primary y-axis. To create a secondary y-axis, double-click on the plot. This opens a plot formatting dialog box. Place a check in the box “Enable secondary Y axis.” This will add new placeholders on the right side of the plot. You can now type expressions, functions, and range limits in the new placeholders. See Figure 3.11. The primary and secondary y-axis plots can have different limits.

29

Page 29: Informatics. Study Guide. Mathcad. Matlab. VC++

Figure 3.11. Mulitple plots using secondary Y-axis

Formatting plots. Mathcad allows you to customize many aspects of your plots. You can add grid lines; change the spacing of the grid lines; plot with equal x- and y-axes; change the color, line weight, or line type of each trace or add symbols to the trace. You can even plot in log scale. To make customizations, double-click on the plot. This opens a plot formatting dialog box. The features in this box will depend on whether you are working with an X-Y plot or a Polar plot.

Axes tab. This tab will be either the X-Y Axes tab, or the Polar Axes tab depending on the type of plot you have open. This tab controls the appearance of the axes and grids (see Figures 3.12 and 3.13).

This allows you to:• Change an axis to log scale, add grid lines to an axis.• Display or not display numbers on the axes.• Tell Mathcad whether the axis limits are set at the data limits or whether the axis limits are set to the next major tick mark beyond the end of the data (Auto scale).• Add horizontal, vertical, or radial marker lines at values that you set. The marker lines are dashed horizontal or vertical lines that can be set at specified locations. Each plot axis may have two marker locations.• Change the spacing of the grid lines, change from axes on the sides of the plot to axes in the center of the plot.

Traces tab. This tab allows you to change how each trace appearsv (line type, line weight, and line color, add a legend giving titles to the different traces). You can also change the type of plot from a line plot to various forms of bar graphs. You can also add symbols for the data points.

Labels tab. The Labels tab allows you to apply titles to your plot and to each of the axes. In order for your titles to be visible, the check box associated with each title must be checked. The font used in the plot title and axis labels comes from the “Math Text Font” variable style. To change the font, size, color, or style of your title and labels, change the “Math Text Font” style. To do this, click Equation from the Format menu.

30

Page 30: Informatics. Study Guide. Mathcad. Matlab. VC++

Figure 3.12. Formatting examples

31

Page 31: Informatics. Study Guide. Mathcad. Matlab. VC++

Figure 3.13. Formatting examples

Plotting data points. Mathcad also allows you to plot data points. These data points can be created by using range variables, or they can be from a vector or matrix.

Range variables. Mathcad created a data point for each value in the range variable, and then plotted the corresponding value on the y-axis. Mathcad drew a line between all the points (see Figures 3.14).

32

Page 32: Informatics. Study Guide. Mathcad. Matlab. VC++

Figure 3.14. Plotting data points

Data vectors. See Figure 3.15 for an example of plotting a vector of data points. See Figure 3.16 for an example of plotting matrix data points.

Figure 3.15. Plotting vector data points

33

Page 33: Informatics. Study Guide. Mathcad. Matlab. VC++

Figure 3.16. Plotting matrix data points

Numeric display of plotted points (Trace). You can get numeric display of plotted points by using the Trace dialog box. To open the Trace dialog box, right-click within the plot and choose Trace.

34

Page 34: Informatics. Study Guide. Mathcad. Matlab. VC++

Place a check in the Track data points box. Click and drag your mouse along the trace whose coordinates you want to see. You should see a dotted crosshair move from top point along the trace. The coordinates of each data point will be displayed in the dialog box. If you release the mouse button, you can use the left and right arrows to move to the previous and next data points.

Using plots for finding solutions to problems. One great use of plots is to find the intersection of two functions. You can use a plot to get a quick guess for the required input in the find function. Using the trace feature above, you can also get a quick approximation of the solution. See Figure 3.17 for an example.

Figure 3.17. Using trace to find approximate solutions

Parametric plotting. A parametric plot is one in which a function or expression is plotted against another function or expression that uses the same independent variable. See Figure 3.18 for an example.

3D plotting. Mathcad can create many types of three-dimensional plots such as a: surface plot, contour plot, 3D bar plot, 3D scatter plot, and vector field plot. These topics are beyond the scope of this book. The Mathcad Help and Mathcad Tutorial are excellent resources to learn more about these topics.

35

Page 35: Informatics. Study Guide. Mathcad. Matlab. VC++

Figure 3.18. Example of parametric plot

Variants

Task 1. Plot the following equations and use the Trace dialog box to find approximate solutions where the plots intersect. Change the plot with using Formatting dialog box. Do the next: add grid lines; change the spacing of the grid lines; plot with equal x- and y-axes; change the color, line weight, or line type of each trace or add symbols to the trace;plot in log scale.1) , .2) , .3) , .4) , .5) , .6) , .7) , . 8) , .9) , .

36

Page 36: Informatics. Study Guide. Mathcad. Matlab. VC++

10) , .11) , .12) , . 13) , . 14) , .15) , .16) , .17) , .18) , .19) , .20) , .21) , .22) , .23) , .24) , .25) , .26) , .27) , .28) , .29) , .30) , .

Task 2. Find equations for the figure from your variant. Define found formulas in Mathcad and build graphs for them.

1 2 3

4 5 6

37

Page 37: Informatics. Study Guide. Mathcad. Matlab. VC++

7 8 9

10 11 12

13 14 15

16 17 18

19 20 21

38

Page 38: Informatics. Study Guide. Mathcad. Matlab. VC++

22 23 24

25 26 27

28 29 30

Task 3.Build graphs:

where is a number of your variant.

Laboratory work 4

SIMPLE LOGIC PROGRAMMING IN MATHCAD

Objective – get to know with simple logic programming in Mathcad; learn the basics of programming with using the if function; cope with programs that allow Mathcad to choose a result based on specific parameters.

Problem statement – perform your variants in a way to logically reach conclusions based on data calculated.

39

Page 39: Informatics. Study Guide. Mathcad. Matlab. VC++

Theoretical information

Introduction to the programming toolbar. The purpose of this chapter is to get you comfortable with the concept of Mathcad programming. We will use simple examples. You will soon see that you do not need to be a computer programmer to use the Mathcad programming features. You do not need to learn complex programming commands. All the operators you need to use are contained on the Programming toolbar.

To open the Programming toolbar, hover your mouse over Toolbars on the View menu and click on Programming. You may also click on the Programming Toolbar icon on the Math toolbar. The programming toolbar contains the operators you will use when writing a Mathcad program.

One important thing to remember when using Mathcad programming is that all the programming operators must be inserted using the Programming toolbar, or by using keyboard shortcuts. You cannot type “if,” “otherwise,” or “return.” They are operators and must be inserted.

Creating a simple program. You begin a Mathcad program by clicking on “Add Line.” This inserts a vertical line with two placeholders. This is called the Programming Operator. We will place a conditional statement in the top placeholder. In the bottom placeholder, we will place a statement about what to do if the conditional statement is false. Let’s look at a two simple examples.

Example 1.

To create this program follow these steps:1. Open the Programming toolbar.2. Type the variable name followed by the colon.3. Click the Add line button on the Programming toolbar.

4. Select the top placeholder and click the if button on the Programming toolbar.

40

Page 40: Informatics. Study Guide. Mathcad. Matlab. VC++

5. Select the bottom placeholder and click the otherwise button on the Programming toolbar.

6. Fill in the placeholders.

The logic used by the previous program is “Do this if this statement is true, otherwise do this.”

Example 2. The if function could just as easily been used in place of the program. The benefit of using the program operator comes when there are multiple if statements. There are different methods:

1. Use an expression with a range variable and vector to get multiple results.

2. Use a function. Use different arguments in the function.

3. Use a function with a vector as the argument.

41

Page 41: Informatics. Study Guide. Mathcad. Matlab. VC++

Vectorize operator CTRL+MINUS needs to de added to the function so that Mathcad recognize the vector with the function.

When using multiple if statements in a program, it is important to understand how Mathcad treats the if statements. Mathcad evaluates every if statement. If a statement is false, the statement is not executed, but Mathcad proceeds to the next line. If the statement is true, the statement is executed, and Mathcad proceeds to the next line. The otherwise statement is executed only if all previous if statements are false. If there are more than one true if statements, Mathcad returns the last true if statement. This is important to understand, or you may get incorrect results. Let’s consider a few examples.

Let’s write a program as a user defined function (using the calculated factor as an argument) so that Mathcad will choose a final factor between 0.5 and 2.0.

0.5<Factor<2.0Consider two examples of a program. The first example creates

inaccurate results.

For the correct result should be 2.0. It returned incorrect result because Mathcad evaluates every if statement, and executes it if it is true. The final true if statement is returned. For the final true statement that is encountered is “if x is greater than 0.5 then return x.” Since 3>0.5, Mathcad returned 3.

We can rewrite the program so that it creates correct result. Do this by ensuring that the first two statements cannot both be true.

In wood design there is a depth factor that needs to be applied to different depth of wood joists. Here is two examples of a conditional

42

Page 42: Informatics. Study Guide. Mathcad. Matlab. VC++

program to determine the proper depth factor are considered. The first example creates incorrect result.

It returned incorrect result because Mathcad evaluates every if statement, and executes it if it is true. The final result is the last true statement that is encountered is d<=11.25in. Most of the depth were less than 11.25in., so 1.0 is the value assigned to Factor1.

The next program will show the correct result.

Return operator. The return operator is used in conjunction with an if statement. When the if statement is true, the return operator tells Mathcad to stop the program and return the value, rather than proceed to the next line in the program. Figure 10.5 shows how to use the return statement to make the examples from Figure 10.4 more intuitive. Rewrite the program from the previous example with using the return statement.

43

Page 43: Informatics. Study Guide. Mathcad. Matlab. VC++

A return could have been placed in front of the last line to make it read more consistent, but it is not required.

Boolean operators. Boolean operators are very useful when writing logical Mathcad programs. The Boolean operators are located on the Boolean toolbar. To open the Boolean toolbar, hover your mouse over Toolbars on the Format menu and select Boolean. You may also click the button on the Math toolbar. To use the Boolean operators you need to use the buttons on the Boolean toolbar or use keyboard shortcuts. The exception is the Greater Than and Less Than operators, which can be entered from the keyboard.

The first six icons on the toolbar are obvious. The last four are not as obvious.

Boolean Not. This is true if x is zero, and false if x is non-zero. Boolean Not operator returns true (1) if the value is zero and false (0) if the value is non-zero. Here is the examples of using the Not operator.

This is the same result as using if x=0.

44

Page 44: Informatics. Study Guide. Mathcad. Matlab. VC++

Boolean And. This is true if both statements are true.

Boolean Or. This is true if either statement is true. Warning: If the first statement is true, then the second statement is not evaluated. Therefore, the second statement may contain an error that is not initially detected because Mathcad stopped evaluating after the first statement.

When using the OR operator, if the first statement is true, the second statement will not be checked. This could prevent an error from being detected.

45

Page 45: Informatics. Study Guide. Mathcad. Matlab. VC++

The divide by zero error is not caught, unless the first statement is false.

Boolean Xor (exclusive Or). This is true if either the first or the second statement is non-zero, but not both. Thus if both statement are non-zero, the result is false.

Adding lines to a program. It is possible to add nested programs inside a program. Creative use of nested programs sometimes makes it easier to create conditional programs. If you are inside a program, Mathcad will add a new programming line or a new placeholder when you click the Add Line button. The location of the new line or placeholder depends where the vertical editing line is located and what information is selected.

In the next two examples we try to arrive at consistent results using different forms of the programming lines. In these examples, we use a range variable and vector math. This program uses the “And” Boolean operator. Both statements must be true in order for the line to be true.

46

Page 46: Informatics. Study Guide. Mathcad. Matlab. VC++

This form of the program allows you to have an additional conditional statement branching off of the first conditional statement.

In the following program the if statement has two condition lines.

Regardless of the first answer, the second condition will always be evaluated. If the second statement is true, then it does not matter whether or not the first the first statement is true. There is not an And function that

47

Page 47: Informatics. Study Guide. Mathcad. Matlab. VC++

will tie the two statements together. For this reason, use a string in the first line as a comment line.

Using conditional programs to make and display conclusions. Having Mathcad display a statement at the conclusion of a problem is a great feature. You can have Mathcad display statements such as: “Passes” or “Fails,” depending on whether or not the calculation worked. You can create other string variables that Mathcad can display. Let’s look at an example.

VariantsTask 1 is for all variants.

1. Use the if function for the following logic:a. Create variable x = 3.b. If x = 3 the variable “Result” = 40.c. If x is not equal to 3 then “Result” = 100.

2. Create a Mathcad program to achieve the same result as above.3. Rewrite the program to place the if operator in a different location.4. Write three Mathcad programs that use the Boolean operator And.5. Write three Mathcad programs that use the Boolean operator Or.6. Write three Mathcad programs that use the Boolean operator Xor.7. Use the if function for the following logic:

a. Create variable x = 5.b. If x = 5 the variable “Result” = 20.c. If x is not equal to 5 then “Result” = 200.

8. Use the if function for the following logic:a. Create variable x = 7.

48

Page 48: Informatics. Study Guide. Mathcad. Matlab. VC++

b. If x = 7 the variable “Result” = 80.c. If x is not equal to 7 then “Result” = 150.

9. Use the if function for the following logic:a. Create variable x = 9.b. If x = 9 the variable “Result” = 50.c. If x is not equal to 9 then “Result” = 70.

Task 2. Define variables x and a. Calculate the value of the expression Y with using if operator. Check all abnormal situations in which function does not exist.

1.

2.

3. 4.

5.

6.

7. 8. 9. 10. 11. 12. 13. 14. 15.

16.

17.

18.

19. 20.

21.

22. 23.

24.

25. 26.

49

Page 49: Informatics. Study Guide. Mathcad. Matlab. VC++

27. 28.

29.

30.

Laboratory work 5

ADVANCED PROGRAMMING IN MATHCAD

Objective – get to know with Mathcad programs that can be much more powerful than the logic programs discussed in previous laboratory work 5.

Problem statement – develop programs that use programming commands such as for, while, break, continue, return, and on error. Illustrate the use of programs within programs and the use of subroutines. Give examples which combine the features of programming, user-defined functions, and solving.

Theoretical information

Local definition. Mathcad allows you to define new variables within a program. These variables will be local to the program, meaning they will be undefined outside of the program. These are called local variables, and they are assigned with the local assignment operator. The local assignment operator is represented by an arrow pointing left ←. It can be found on the Programming toolbar, or inserted by pressing {. Let’s look at a simple example of a program that uses local variables.

Let’s create a user-defined function that will find the two roots of a quadratic equation. Use local variables to simplify the program. Use the left arrow button on the Programming toolbar to insert the local variable operator. The local variables are only defined within the program. They are not defined outside the program.

50

Page 50: Informatics. Study Guide. Mathcad. Matlab. VC++

The values of x1 and x2 are the output results of the function, but these local variables will not be recognized outside of the program.

In order to make the results of the function available later on, the variable “Roots” was defined equal to the function FindRoots.

As you can see from the above example, local variables can help simplify a program by breaking the program down into smaller pieces. In the next example, the function is very long, but each numerator is the same. By assigning a local variable, the function definition can be simplified. For typing the next example use CTRL+ENTER to break the expression at an addition operator.

G1 2 6 3( ) 2.614

The next example shows how you can simplify the expression by defining a local variable.

51

Page 51: Informatics. Study Guide. Mathcad. Matlab. VC++

You can also use local variable as counters to count how many times certain things are done in a program, or to count how many true statements are in a program. Next example illustrates this concept. See example. First we defined a local variable m equal to zero. Then program adds 1 to the local variable m for every true statement.

In order to check the program for several different arguments, you can use a range variable or a vector. The example below uses both a range variable and a vector to provide different arguments to the function “Counter.”

52

Page 52: Informatics. Study Guide. Mathcad. Matlab. VC++

Looping. Looping allows program steps to be repeated a certain number of times, or until a certain criteria is met. This book will introduce the concept of looping. An in-depth study of looping is beyond the scope of this book. The Mathcad Help and Tutorial provide excellent coverage on this subject. There are two types of loop structures. The first allows a program to execute a specific number of times. This is called a for loop. The second type of loop structure will execute until a specific condition is met. This is called a while loop.

For loops. You insert the for loop into a program by clicking on the for button on the Programming toolbar. Do not type the word “for.” Mathcad evaluates z for each value of x over the range y. The placeholders have these meanings:

x is a local variable within the program defined by the for symbol. It initially takes the first value of y. The value of x changes for each step in the value of y.

y is referred to as an iteration variable. It is usually a range variable, but it can be a vector, or a series of scalars or arrays separated by commas. Each time the program loops, the next value of y is used and this value is assigned to the variable x.

z is any valid Mathcad expression or sequence of expressions.The number of times a for loop executes is controlled by y. Let’s first

look at two examples using range variables. In the examples, think of the symbol as a local variable definition. The local variable “i” is a range variable, and the value of variable “i” increments for each loop. There are two examples. In both examples we define a local variable a equal to zero and i is a local range variable that takes on the values 1,2,3… until x.

For the first program I is not used anywhere.

It only controls when the loop stops. From the result of the function ForLoop1(x) we can see that:

1) For the first loop, variable a takes the value 0+1=1;

53

Page 53: Informatics. Study Guide. Mathcad. Matlab. VC++

2) For the second loop variable i increments to 2, and a becomes 1+1=2;

3) For the third loop i increments to 3, and a becomes 2+1=3.

The loop continues until i reaches the value of x.In the second program increment a by the value of i.

From the result of the function ForLoop2(x) we can see that:

1) For the first loop, i is one and a takes the value 0+1=1;2) For the second loop variable i is 2, and a becomes

1+2=3;3) For the third loop i is 3, and a becomes 3+3=6;4) For the fourth loop i is 4, and a becomes 6+4=10;5) For the fifth loop i is 5, and a becomes 10+5=15.

The next example shows a for loop using a list as the iteration variable.

Notice that the list of numbers is not consecutive, and the numbers do not increment by the same value every time. When Mathcad loops, it moves to the next value in the list and assigns the value in the list to the local variable “i.”

54

Page 54: Informatics. Study Guide. Mathcad. Matlab. VC++

In the following program the iteration variable is a list that controls the number of loops. The list also sets the assigned values of i. The local variable a is incremented by the value of i and then multiplied by the argument x.

The next example is exactly the same as in previous program except that the iteration is controlled by a previously defined vector.

The next example uses two local variables. It uses the second variable b as a means to sum all the different values of a.

55

Page 55: Informatics. Study Guide. Mathcad. Matlab. VC++

From the result of the function ForLoop5(x) we can see that: 1) For the first loop, i is one and a takes the value 0+1=1.

Thus b=0+1=1.2) For the next loop i is 2, and a becomes 1+2=3 and

b=1+3=4;3) For the third loop i is 3, and a becomes 3+3=6 and

b=4+6=10;4) For the fourth loop i is 4, and a becomes 6+4=10 and

b=10+10=20;5) For the fifth loop i is 5, and a becomes 10+5=15 and

b=20+15=35.The method of converting a range variable to a vector is illustrated in

the following example. Function Range2Vec() converts a range variable into a vector. Ones it is a vector, each element can be accessed. The for loop creates a range variable for iterating from the three input arguments. The vector Vec is a local variable.

56

Page 56: Informatics. Study Guide. Mathcad. Matlab. VC++

While loops. The while loop is different than the for loop. A for loop executes a fixed number of times, based on the size of the iteration variable. A while loop continues to execute while a specified condition is met. Once the condition is not true, the execution stops. If the condition is always true, Mathcad will go into an infinite loop. For this reason, you must be careful in using a while loop. You insert the while loop into a program by clicking on the while button on the Programming toolbar. Do not type the word “while.” Figure 11.9 shows a simple while loop. The program continues to loop until “a” is equal to or greater than the argument x. When this happens, the loop stops and Mathcad returns the value of a.

From the result of the function For_Loop1(x) we can see that for the first loop a is zero, so the while statement is true and the program continues to the next line where a is incremented to the value 1. On the second loop a is now 1 and the while statement is checked again. If it is true, then the program continues to the next line, and a is incremented to

57

Page 57: Informatics. Study Guide. Mathcad. Matlab. VC++

the value 2. If the statement is false, then the program execution stops and the value of a is returned (1). The loop continues until a>=x.

Next example uses local variable a to control the number of loops. Local variable b is multiplied by 2 every time the program loops. Once a becomes equal to or greater than the argument x, the loops stops and the program returns the value of b.

From the result of the function WhileLoop1(x) we can see that for the first loop a is zero, so the while statement is true and the program continues to the next line where a is incremented to the value 1. On the second loop a is now 1 and the while statement is checked again. If it is less then x, then the program continues to the next line, and a is incremented to two and b becomes 2*2=4. If a in not less then x, then the program execution stops and the value of b is returned (4).

Now let’s discuss three ways to create a user-defined function for factorial. Mathcad already has the factorial operator on the Math toolbar, but it is interesting to use factorial to demonstrate the while loop.

First example. Assuming x=4. On the first loop, f is assigned f=4-1=3. Since f is greater then zero, x=4*3=12, and f is reduced by one to f=3-1=2, and the program returns to the while statement. On the next loop, f=2 is greater then zero, so x=12*2=24, and f=2-1=1. On the next loop, f=1 is greater then zero, so x=24*1=24, and f=1-1=0. On the next loop, f is not greater then zero (the statement is false), so the execution stops and the value of x=24 is returned.

58

Page 58: Informatics. Study Guide. Mathcad. Matlab. VC++

Second example.

Third example is a recursive function.

The while loop in the next example will cause an infinite loop because the condition will always be true. If this condition happens, you can interrupt the loop by pressing the escape [esc] key. After pressing [esc] key a window with suggestion to interrupt processing will appear.

Break and continue operators. The break and continue operators give more control to programs. They tell Mathcad what to do if specific conditions are met and usually precede an if statement. These operators are used to check for specific conditions during the time that Mathcad is looping with either the for loop or the while loop. The break operator

59

Page 59: Informatics. Study Guide. Mathcad. Matlab. VC++

stops the loop if the condition is true, while the continue operator allows Mathcad to skip the current loop iteration if a true statement is encountered. The continue operator is useful if you want to continue looping even if a condition is true. For example, you may want to extract only even numbers.

By using the continue operator, you can skip over odd numbers. Without the continue operator, Mathcad would stop if it encountered an odd number.

See next program for an example of the break operator. To add the break operator, add the if statement first, then click on the first placeholder and add the break operator. The break operator stops the loop if x<=0.

See next program for an example of the continue operator. It shows how the continue operator can skip over certain conditions within a loop and skips over elements that are not integers. The function uses arguments x to divide into integers from 1 to argument y, and selects only integers.

When you see the continue operator, it means, “Continue with the loop if this statement is false. If the statement is true, then stop this loop and go back to the top of the loop.” This statement is checking to see if j is an integer.

60

Page 60: Informatics. Study Guide. Mathcad. Matlab. VC++

Return operator. This operator is used in conjunction with an if statement. It stops program execution when the if statement is true, and returns the value listed.

On error operator. This operator is very useful to tell Mathcad what to do if it encounters an error. A very common error occurs when Mathcad tries to divide by zero. There will be many times when an input value to a function causes this to occur. The on error operator gives you the ability to tell Mathcad what to do when this occurs.

See next blocks for several examples of using the on error operator. There are three methods of dealing with the function 24/x. To insert the built-in constant infinity type CTRL+SHIFT+z.

61

Page 61: Informatics. Study Guide. Mathcad. Matlab. VC++

Let’s discuss the results. Example 1 produces errors. Example 2 returns a string. Example 3 returns Mathcad’s numeric equivalent of infinity.

Variants

Task 1. From your field of study, create 10 programs that use the features discussed in this work. Task 2. Create five functions or expressions that use the on error operator.

Laboratory work 6

ELEMENTARY MATLAB CONSTRUCTS

Objective – get to know with the grammar and syntax of MatLab; learn how to converse with MATLAB and understand its responses.

Problem statement – learn to do calculations with basic arithmetic operations and display result in the view of matrices.

Theoretical information

The elementary MATLAB operations can be divided roughly into five classes:

- Arithmetic operations- Logical operations- Mathematical functions

62

Page 62: Informatics. Study Guide. Mathcad. Matlab. VC++

- Graphical functions- I/O (Input/Output) operations (data transfer)

In essence, all these operations involve operations on matrices and vectors. These in turn are kept as variables which, with very few restrictions, can be defined freely in the MATLAB command interface. The MATLAB command interface shows up at the start of MATLAB in the form shown in Fig. 6.1.

Figure 6.1. The MATLAB command interface

The main elements of this command interface are:1. the command window,2. the command-history window,3. the current directory window or (hidden in this view) the workspace(variable window),4. the file information window,5. the icon toolbar with the choice menu for the current directory,6. the shortcut toolbar, 7. the start button.

Command window displays the most important user interface during interactive operation. In the command window (1) MATLAB awaits the

63

Page 63: Informatics. Study Guide. Mathcad. Matlab. VC++

user’s commands, which are to be directly interpreted and executed by MATLAB following an input prompt >> (in the student version EDU>>). Thus, the user normally communicates with the MATLAB system interactively.

MATLAB Variables. A MATLAB variable is an object belonging to a specific data type. As noted at the beginning, the most basic data type is one from which MATLAB takes its name, the matrix. For the sake of simplicity, from here on a MATLAB variable is basically a matrix. Matrices can be made up of real or complex numbers, as well as characters (ASCII symbols). The latter case is of interest in connection with the processing of strings (text).

Defining MATLAB Variables. In general, the matrix is defined in the MATLAB command interface by input from the keyboard and assigned a freely chosen variable name in accordance with the following syntax:>> x = 2.45

With this instruction, after a MATLAB prompt the number 2.45 (a number is a 1×1 matrix!) will be assigned to the variable x and can subsequently be addressed under this variable name. MATLAB responds to this definition with x = 2.4500 and, in the interactive mode, confirms the input. An error message appears if there are any errors of syntax.

Numbers are always represented by 4 digits after the decimal point by default (format short). The default can be changed in the menu command File - Preferences ... under the listing Command - Window - Numeric Format. In most cases, however, the default representation is the best choice. The following commands define a row vector of length 3 and a 2×3 matrix. The response of MATLAB is also shown for each case:>> vector = [1 5 -3]vector =1 5 -3>> thematrix = [3 1+2*i 2; 4 0 -5]thematrix =3.0000 1.0000 + 2.0000i 2.00004.0000 0 -5.0000

Note that the matrix thematrix contains a complex number as an element. Complex numbers can be defined this way in the algebraic representation using the symbols i and j that have been reserved for this purpose. Therefore, if possible, these symbols should not be used for other variables. As the above example shows, the delimiters for the entries in the columns of the matrix are spaces (or, alternatively, commas) and the rows are delimited by semicolons. A column vector can, therefore, be defined as follows:>> colvector = [2; 4; 3; -1; 1-4*j]colvector =

64

Page 64: Informatics. Study Guide. Mathcad. Matlab. VC++

2.00004.00003.0000-1.00001.0000 - 4.0000iIf no variable name is set, MATLAB assigns the name ans (answer) to the result, as the following example shows:>> [2,3,4; 3,-1,0]ans =2 3 43 -1 0

All of the defined variables will be stored in the so-called workspace of MATLAB. You can check the state of the workspace at any time. The command who returns the names of the saved variables and the command whos provides additional, perhaps vital, information, such as the dimension of a matrix or the memory allocation.This command yields the following for the preceding examples:>> whoYour variables are:ans colvector thematrix vector x

A very practical way of getting an overview of the content of the workspace is provided by the workspace browser, which can be selected using the menu command Desktop - Workspace. In Fig. 1.1 the workspace browser has already been opened and is firmly docked in the command interface.

If some variables are no longer needed, it is easiest to erase them with the command clear in the command interface. For example,>> clear thematrix yields>> whoYour variables are:ans colvector vector xor the erasure of thematrix. The entire workspace is erased using clear or clear all. These operations are also possible in the workspace browser.

Reconstructing commands. The commands that have been set previously are saved. In this way you can conveniently repeat or modify a command. For this only the arrow keys ↑ and ↓ have to be pressed. The earlier commands show up in the MATLAB command window and can (if necessary, after modification) be brought up again using the return key. For instance, the definition of the recently erased matrix thematrix can be recovered and reconstructed in this way. In long MATLAB

65

Page 65: Informatics. Study Guide. Mathcad. Matlab. VC++

sessions this keying through earlier commands becomes rather tedious. If you know the first letters of the command, you can shorten the search. Thus, for example, to find the matrix thematrixyou need only type>> themand then press the arrow key ↑. Only commands beginning with them will be searched for. If the beginning is unique, the command is found at once. Other convenient possibilities employing the so-called history-mechanism are provided by the command-history window.

In Fig. 6.1 this command-history window (2) can be seen at the lower left. In this window the commands set in the past are listed under the corresponding date of the MATLAB session. By scrolling, it is also very easy to find commands from even further back. A double click on the command is sufficient to activate it again.

The choice of command reconstruction capabilities ultimately depends on the preference of the user and practical considerations.

Other possibilities for defining variables. The problem often arises of expanding a matrix or vector by adding extra components or of eliminating columns and rows. An expansion can be done in the way described above by adding to the variable name. Thus, the matrix thematrix can be expanded by an extra row using the following command:>> thematrix = [thematrix; 1 2 3]thematrix =3.0000 1.0000 + 2.0000i 2.00004.0000 0 -5.00001.0000 2.0000 3.0000Another column could be added using the following command:>> thematrix = [thematrix, [1;2;3]]thematrix =3.0000 1.0000 + 2.0000i 2.0000 1.00004.0000 0 -5.0000 2.00001.0000 2.0000 3.0000 3.0000or with>> v = [1;2;3]v =123>> thematrix = [thematrix, v]thematrix =3.0000 1.0000 + 2.0000i 2.0000 1.0000

66

Page 66: Informatics. Study Guide. Mathcad. Matlab. VC++

4.0000 0 -5.0000 2.00001.0000 2.0000 3.0000 3.0000

If you want to delete the second column, then you must fill it with an empty vector [ ]. The second column in the variable thematrix will then be addressed in accordance with the conventional matrix indexing. Since the row index is arbitrary in this case, it is indicated by the place holder: (colon). This yields>> thematrix(:,2) = []thematrix =3 2 14 -5 21 3 3The first row can thus be deleted using>> thematrix(1,:) =[]thematrix =4 -5 21 3 3Likewise, a row or column vector can be selected and another variable can be assigned. Thus, with>> firstrow = thematrix(1,:)firstrow =4 -5 2the first row of the remaining residual matrix is selected.

Rather than carrying out specified commands in the command window, the operations described above can, of course, also be performed within the array editor. However, with a little practice, working in the command plane is significantly faster. In addition, these operations can also be applied within MATLAB programs; that is, in a no interactive mode. They are then the only way of obtaining the desired results. Thus, these techniques are of great importance for using the functionality of MATLAB as a programming language.

When it is necessary to process large matrices or vectors, outputting the results is often very inconvenient. An example is the following definition of a vector consisting of the numbers from 1 to 5000 in steps of 2. It can be defined simply in MATLAB by the following command, which specifies the starting value, step size, and final value:>> largevector = (0:2:5000)largevector =Columns 1 through 120 2 4 6 8 10 12 14 16 ...Columns 13 through 2424 26 28 30 etc.

67

Page 67: Informatics. Study Guide. Mathcad. Matlab. VC++

Of course, the vector is not displayed here in full. In order to suppress the output of a MATLAB calculation, the command must be ended with a semicolon. The statement>> largevector = (0:2:5000);lets MATLAB proceed without response in the above case. If it is desired not to suppress the MATLAB answer entirely, but to show the result on the screen, the command>> more onwill let the output in the full command window be suspended when the user ends the execution of the screen display by pressing a key. This function then enables the further progress of the interactive MATLAB session. But it can also be shut off again by entering>> more offas a command.

Variants

Define the following matrices according to MATLAB and classify the corresponding variables. Expand the matrix M to a 6×6 matrix V of the form

.

Delete row 2 and column 3 from the matrix . Create a new vector z from row 4 of the matrix . Modify the entry (4, 2) in the matrix to j+5. Define vectors . Add two times meaning of at the end of vector

. Unite vectors in matrix .

1.

2.

3.

4.

68

Page 68: Informatics. Study Guide. Mathcad. Matlab. VC++

5.

6.

7.

8.

9.

10.

11.

12.

13.

14.

15.

69

Page 69: Informatics. Study Guide. Mathcad. Matlab. VC++

16.

17.

18.

19.

20.

21.

22.

23.

24.

25.

70

Page 70: Informatics. Study Guide. Mathcad. Matlab. VC++

26.

27.

28.

29.

30.

Laboratory work 7

MATHEMATICAL OPERATIONS

Objective – learn the mathematical operations like arithmetic, matrix, field, division, logical and relational, special i/o operations with MatLab and constructs that you can use during calculation.

Problem statement – complete tasks by defining vectors and matrices, apply suitable operations.

Theoretical information

Arithmetic Operations. The arithmetic operations (+,−,*, etc.) in MATLAB have an important characteristic to which the beginner must become accustomed early on.

Matrix Operations. Since the fundamental data structure of MATLAB is the matrix, these operations must, above all, be understood as matrix operations. This means that the computational rules of matrix algebra are assumed, with all the associated consequences. Thus, for

71

Page 71: Informatics. Study Guide. Mathcad. Matlab. VC++

example, the product of two variables A and B is not defined according to MATLAB if the underlying matrix product A · B is not defined; that is, if the number of columns in A is not equal to the number of rows in B. An exception to this rule occurs only if one of the variables is a 1×1 matrix, or scalar. Then the multiplication is interpreted as multiplication by a scalar in accordance with the rules of linear algebra. The following examples of MATLAB commands5 will make this clearer:>> M = [1 2 3; 4 -1 2] % define 2x3-Matrix MM =1 2 34 -1 2>> N = [1 2 -1; 4 -1 1; 2 0 1] % define 3x3-Matrix NN =1 2 -14 -1 12 0 1>> V = M*N % trying the product M*NV =15 0 44 9 -3>> W = N*M % trying the product N*M??? Error using ==> mtimesInner matrix dimensions must agree.

Thus, MATLAB responds to the attempt to multiply the 2×3 matrix M by the 3×3 matrix N with the 2×3 product matrix V. The attempt to switch the factors fails, since the product of a 3×3 matrix and a 2×3 matrix is not defined. MATLAB quits this with the error message inner matrix dimensions must agree, which even experienced MATLAB programmers will encounter again and again.

Field operations. Besides the matrix operations, in many cases there is a need for corresponding arithmetic operations, which must be carried out term-by-term (component wise). Operations that are to be understood as term-by-term, which are known as field operations or array operations in MATLAB, must at the very least be given a new notation as they might otherwise be confused with matrix operations.

This is solved in MATLAB syntax by placing a period (.) before the operator symbol. An * alone, therefore, always denotes matrix multiplication, while a .* always denotes term-by-term multiplication (array multiplication). This leads to other rules about the dimensionality of the objects, as the following example shows:>> M = [1 2 3; 4 -1 2] % define 2x3-Matrix MM =1 2 3

72

Page 72: Informatics. Study Guide. Mathcad. Matlab. VC++

4 -1 2>> N = [1 -1 0; 2 1 -1] % define 2x3-Matrix NN =1 -1 02 1 -1>> M*N % Matrix product M*N??? Error using ==> mtimesInner matrix dimensions must agree.>> M.*N % term-by-term multiplicationans =1 -2 08 -1 -2

As you can see, the matrix product M*N is not defined this time. Instead, the product is defined term-by-term. To each entry in M there is a corresponding entry in N, with which the product can be formed. Another common example is the squaring of the components of a vector:>> vect = [ 1, -2, 3, -2, 0, 4]vect =1 -2 3 -2 0 4>> vect^2 % squaring the vector vect??? Error using ==> mpowerMatrix must be square.>> vect.^2 % vect-squared, term-by-termans =1 4 9 4 0 16

In the first case MATLAB could again carry out a matrix operation. Squaring a matrix, however, is only possible if the matrix is square (i.e., it has the same numbers of columns and rows) which is not so here. But, the components themselves can be squared in any case.

Division operations. The division sign has special significance. In MATLAB we distinguish between right division / and left division \. The fact that there are two division operations is again a consequence of the matrix algebra interpretation. Division of two matrices A and B (i.e., A/B) is normally not defined. In the case of square matrices, the quotient can only be interpreted meaningfully as X = A · B−1 if the inverse matrix B−1 exists. If A−1 exists, then “left division” X = A\B is also meaningful, interpreted in this case as X = A−1 · B. MATLAB takes these two situations into account by defining left and right division. Let us clarify this with a simple example involving two invertable 2 × 2 matrices.>> A = [2 1 ;1 1] % Matrix AA =2 11 1

73

Page 73: Informatics. Study Guide. Mathcad. Matlab. VC++

>> B = [- 1 1;1 1] % Matrix BB =-1 11 1>> Ainv = [1 -1; -1, 2] % inverse of AAinv =1 -1-1 2>> Binv = [-1/2 1/2; 1/2, 1/2] % inverse of BBinv =-0.5000 0.50000.5000 0.5000>> X1 = A/B % right divisionX1 =-0.5000 1.50000 1.0000>> X2 = A*Binv % checkingX2 =-0.5000 1.50000 1.0000>> Y1 = A\B % left divisionY1 =-2.0000 -0.00003.0000 1.0000>> Y2 = Ainv*B % checkingY2 =-2 03 1

The next example shows, however, that MATLAB goes one step further in the interpretation of the division operations:>> A = [2 1 ;1 1] % Matrix AA =2 11 1>> b=[2; 1] % column vector bb =21>> x = A\b % left division of A "by" bx =1.00000.0000>> y = A/b % right division of A "by" b

74

Page 74: Informatics. Study Guide. Mathcad. Matlab. VC++

??? Error using ==> mrdivideMatrix dimensions must agree.

Here “left division”, , obviously yields a solution (in this case unique) of the linear system of equations , as the following test shows:>> A*xans =2.00001.0000

Logical and relational operations. We shall not go into logical and relational operations in detail here, but only consider the most basic elements. In principle this involves operators that act as field operators (i.e., they operate component wise on the entries in a vector or matrix) and yield logical (truth) values as the result. For example, you can check whether the components of two matrices in the same terms have an entry ≠ 0 (=logically true). The following MATLAB sequence shows how this is done using the logical operator & (logical AND) and what the result of this operation is.>> A=[1 -3 ;0 0]A =1 -30 0>> B=[0 5 ;0 1]B =0 50 1>> res=A&Bres =0 10 0

The resulting matrix res only contains a single 1 (logically true), where the corresponding components of the two matrices are both ≠ 0 (logically true), and is 0 (logically false) everywhere else. The relational operators or comparison operators work in a similar fashion. The following sequence checks which components of matrix A are greater than the corresponding components of matrix B. The matrices from the preceding example are used.>> comp = A>Bcomp =1 00 0

The comparison matrix comp shows that only the first component of A is greater than that of B. It hardly needs to be pointed out that here, as

75

Page 75: Informatics. Study Guide. Mathcad. Matlab. VC++

with all field operators, the dimensions of the matrices must be identical. Other relational operators include ≥ and ≤ (in MATLAB syntax these are <= and >=) and < , as well as == (equal) and ~= (unequal). Besides the above mentioned logical AND, we have the logical operators logical OR (|), logical negation (~), and exclusive OR xor. Further information on this topic, as well as on the other operations and functions, is available in MATLAB-help. For comments relating to this section, you can, for example, search for the keyword operators under the menu command Help - MATLAB help. Alternatively, you can enter help ops in the MATLAB command window. In both cases you obtain a list of MATLAB operators that includes the logical and relational operators, among others. As an illustration of the capabilities of this operator class we give an example that shows up in many simulations. The problem is to select each component from a result vector which exceeds a particular value, say 2, and form a vector out of them. This can be done with the following sequence:>> vect=[-2, 3, 0, 4, 5, 19, 22, 17, 1]vect =-2 3 0 4 5 19 22 17 1>> compvect=2*ones(1, 9)compvect =2 2 2 2 2 2 2 2 2>> comp=vect>compvectcomp =0 1 0 1 1 1 1 1 0>> res=vect(comp)res =3 4 5 19 22 17

The comparison vector is set up here using the MATLAB command ones, which initially yields a matrix containing ones (corresponding to the given components). The comparison with compvect yields the places in which the condition (> 2) is satisfied for the vector vect. The command res=vect(comp) collects these components with the aid of the vector comp. In this way only the indices for which this vector ≠ 0 are employed. A technique of this sort is often used when values which exceed or lie below a certain threshold (so-called outliers) have to be eliminated from measurement data. In principle, vectors and matrices that are connected by relational operators must have the same dimension (field operation!). For this reason the vector compvect was constructed in the above example. But if, as in this case, the comparison is with only one value, this construction can be avoided.In this example,>> comp=vect>2

76

Page 76: Informatics. Study Guide. Mathcad. Matlab. VC++

comp =0 1 0 1 1 1 1 1 0also yields the desired result.

It should be noted that the result of a logical operation is no longer a numerical field. The input>> whosshows that comp is a logical field (logical array) (i.e., a field of logical (truth) values). The selection operation res=vect(comp) would lead to an error message with a suitably occupied numerical field. Logical fields do not only arise as a result of comparison operations.

The functions true and false can be used to define entire fields with the logical value “true” or “false.” The call without an argument, as above, produces exactly one logical value. Numerical arrays can also be converted into logical arrays using the function logical. As in the above example, components from numerical fields can be selected very simply by means of indexing with logical arrays. Here is another example of this, in which every other component is selected from a vector:>> vect = [1; i; 2; 2+j; -1; -j; 0; i+1]vect =1.00000 + 1.0000i2.00002.0000 + 1.0000i-1.00000 - 1.0000i01.0000 + 1.0000i>> selct = logical([0 1 0 1 0 1 0 1])selct =0 1 0 1 0 1 0 1>> selection = vect(selct)selection =0 + 1.0000i2.0000 + 1.0000i0 - 1.0000i1.0000 + 1.0000i

Mathematical functions. MATLAB has an enormous number of different preprogrammed mathematical functions, especially when the functionality of the toolboxes is taken into account.

For the beginner, however, only the so-called elementary functions are relevant. These include well-known functions, such as the cosine, sine, exponential function, logarithm, etc., from real analysis. Given the data structure concept of MATLAB, which essentially relies on matrices, it

77

Page 77: Informatics. Study Guide. Mathcad. Matlab. VC++

might seem as though there might be a problem because these functions are not defined for matrices at all. Another glance, however, shows that the solution to this problem is immediately obvious in the examples that have already been discussed. Naturally, the action of an elementary function on a vector or a matrix is again only meaningful in a term-by-term sense. The following sequence shows what is meant by the sine of a vector.>> t=(0:1:5)t =0 1 2 3 4 5>> s=sin(t)s =0 0.8415 0.9093 0.1411 -0.7568 -0.9589

The sine of the specified vector _t is again a vector, specifically, the vector . The full significance of this technique will only become clear to the MATLAB user in the course of extensive simulations. It should be kept in mind that the above sequence replaces a programming loop. Thus, in the C++ programming language, the sequence would be implemented as follows:

double s[6];for(i=0; i<6; i++)s[i] = sin(i);

The advantage is not obvious in this little example, but the same technique can produce very elegant solutions for large simulations in MATLAB. At this point we cannot discuss all the elementary functions. An overview of the available functions can be obtained by entering the command help elfun in the MATLAB command interface. This gives a list of the names of the functions together with brief descriptions of each.More direct information is obtained with help <functionname>. Thus,help <asin> yields>> help asinASIN Inverse sine. ASIN(X) is the arcsine of the elements of X. Complex results are obtained if ABS(x) > 1.0 for some element.

Here, we should point out that function names and call syntax in help are always in capital letters. This merely serves as emphasis in the help text. When the functions are used in the command window, the commands must generally be written in lowercase letters. Unlike in earlier versions, MATLAB 7 distinguishes strictly between upper and lowercase letters (and is case sensitive). In the above example the two calls>> x = 0.5;>> ASIN(X)??? Undefined function or variable 'X'.

78

Page 78: Informatics. Study Guide. Mathcad. Matlab. VC++

>> X = 0.5;>> ASIN(X)??? Undefined command/function 'ASIN'.each yield error messages, since in the first the variable X does not exist and in the second the function ASIN is unknown. A correct call looks like>> x = 0.5;>> asin(x)ans =0.5236

Besides the functions from the elfun group, the so-called special mathematical functions, which are listed using help specfun, are also of interest. These, however, require a more profound mathematical knowledge and will not be discussed further here.

Two more examples illustrate the manipulation of elementary functions in MATLAB. First, the magnitude and phase, in radians and in degrees, of a vector of complex numbers is to be determined. This problem is frequently encountered in connection with the determination of the so-called transfer function of linear systems.>> cnum=[1+j, j, 2*j, 3+j, 2-2*j, -j]cnum =Columns 1 through 31.0000 + 1.0000i 0 + 1.0000i 0 + 2.0000iColumns 4 through 63.0000 + 1.0000i 2.0000 - 2.0000i 0 - 1.0000i>> magn=abs(cnum)magn =1.4142 1.0000 2.0000 3.1623 2.8284 1.0000>> phase=angle(cnum)phase =0.7854 1.5708 1.5708 0.3218 -0.7854 -1.5708>> deg=angle(cnum)*360/(2*pi)deg =45.0000 90.0000 90.0000 18.4349 -45.0000 -90.0000

In the following example all the terms in a matrix (say, many series of measurements of a voltage signal) are to be converted into decibels (dB). For a voltage signal U this means that the value must be converted into so that:>> meas=[25.5 16.3 18.0; ...2.0 6.9 3.0; ...0.05 4.9 1.1]meas =25.5000 16.3000 18.00002.0000 6.9000 3.0000

79

Page 79: Informatics. Study Guide. Mathcad. Matlab. VC++

0.0500 4.9000 1.1000>> dBmeas=20*log10(meas)dBmeas =28.1308 24.2438 25.10556.0206 16.7770 9.5424-26.0206 13.8039 0.8279

The above example shows how a too-long MATLAB command can be broken up without being erased when the return key is pressed. Just type three periods (. . .) before pressing the return key and the command can be continued in the next line.

In the next example a list of points in the first quadrant of the cartesian R2 are to be converted to polar coordinates. The list is in the form of a matrix of (x, y) values. As is well known, the polar coordinates (r, φ) in this case are given by

The calculation is carried out by the following MATLAB sequence, using the elementary mathematical functions sqrt and atan:>> points = [ 1 2; 4 3; 1 1; 4 0; 9 1]points =1 24 31 14 09 1>> r = sqrt(points(:,1).^2 + points(:,2).^2)r =2.23615.00001.41424.00009.0554>> phi = atan(points(:,2)./points(:,1))phi =1.10710.64350.785400.1107>> polarc = [r,phi]polarc =2.2361 1.1071

80

Page 80: Informatics. Study Guide. Mathcad. Matlab. VC++

5.0000 0.64351.4142 0.78544.0000 09.0554 0.1107

Note the use of the : operator and the field operations used for calculating r and phi, which make it possible to perform the calculation on the whole vector in a single stroke. Finally, it should be noted that the preceding calculation could be shortened using the following instructions:>> points = [ 1 2; 4 3; 1 1; 4 0; 9 1]points =1 24 31 14 09 1>> polarc = [sqrt(points(:,1).^2 + points(:,2).^2), ... atan(points(:,2)./points(:,1))]polarc =2.2361 1.10715.0000 0.64351.4142 0.78544.0000 09.0554 0.1107

Elementary matrix manipulations. Among the most often used MATLAB commands are some of the so-called elementary matrix manipulations. The command help elmat provides a complete survey of these commands. In earlier sections we have already used a couple of these commands, such as zeros and ones to create matrices of zeros or ones. These are very useful, mainly for initializing vectors or matrices. Here, a 2×2 matrix with zeros and a 3×2 matrix with ones are created, and a vector with the length of the previously defined vector is initializedto zeros.>> M = zeros(2,2)M =0 00 0>> N = ones(3,2)N =1 11 11 1>> x1 = [1,2,3,4,5,6];>> v=zeros(length(x1),1)

81

Page 81: Informatics. Study Guide. Mathcad. Matlab. VC++

v =000000The command eye is often useful for generating a unit matrix. Here is anexample:>> E5 = eye(5)E5 =1 0 0 0 00 1 0 0 00 0 1 0 00 0 0 1 00 0 0 0 1

The length of a vector and the size of a matrix can be determined automatically using the commands length and size. This is of great importance, especially in programs. Next the length of the just defined vector is determined this way:>> length(x1)ans =6

The following sequence of commands eliminates the second column of the unit matrix E5 created above and then determines the size of the resulting matrix:>> B = E5; % store the matrix E5>> B(:,2) = [ ] % empty the second columnB =1 0 0 00 0 0 00 1 0 00 0 1 00 0 0 1>> [rows, columns] = size(B) % determine sizesrows =5columns =4

Other commands for the generation of special matrices and special variables and constants are included in the commands listed in help elmat for MATLAB. We leave it to the reader to explore these commands, but we do not want to omit special mention of the command why.

82

Page 82: Informatics. Study Guide. Mathcad. Matlab. VC++

The operator ' for transposition of a matrix or vector should be mentioned in connection with the elementary matrix operations, although this operator is not listed under the corresponding rubric.

A matrix is transposed when the ' symbol is placed after the matrix that is to be transposed.

For example, the following sequence of commands yields identicalcolumn vectors and :>> x1 = [1; 2; 3; -1; 4; 5] % column vector definitionx1 =123-145>> x2 = [1 2 3 -1 4 5]' % row vector transposex2 =123-145and the sequence of commands>> M = [1 2; 3 -2; -1 4] % a 3x2 matrixM =1 23 -2-1 4>> N = M'N =1 3 -12 -2 4operating on the 3×2 matrix

generates the transposed matrix

In accordance with the rules of mathematics, complex matrix terms subjected to the operator ' will be folded and their conjugates taken:>> M = [i 2; 3 -j] % a 2x2 matrix with complex termsM =

83

Page 83: Informatics. Study Guide. Mathcad. Matlab. VC++

0 + 1.0000i 2.00003.0000 0 - 1.0000i>> N = M' % the transposed matrixN =0 - 1.0000i 3.00002.0000 0 + 1.0000i

Thus, yields also.

If taking the conjugate of the terms is to be avoided, then the transposition operator has to be redefined as a field operator:>> K = M.'K =0 + 1.0000i 3.00002.0000 0 - 1.0000i

Then, in this case, yields as desired.

We have already learned about the : operator in Section 1.2.1 in connection with access to columns and rows in a matrix. The following application of this operator, with which a column vector with the same terms can be created from a matrix, is also very useful:>> M = [1 2; 3 -2; -1 4] % a 3x2 matrixM =1 23 -2-1 4>> mVec = M(:)mVec =13-12-24

In this way the columns of the matrix are organized one above the other. The function repmat can be used to copy and duplicate matrix entries.

The instruction>> N = repmat(M,2,2)N =1 2 1 23 -2 3 -2-1 4 -1 41 2 1 23 -2 3 -2

84

Page 84: Informatics. Study Guide. Mathcad. Matlab. VC++

-1 4 -1 4

reproduces the above matrix M four times in a 2 × 2 arrangement and saves it as the variable N. In conclusion, we mention the end operator, which is especially useful in MATLAB programming. This operator evaluates the last index of a vector. The following sequence of instructions can thus be used to erase the last term of a vector without explicitly specifying the index:>> zVec = [0, 3, -1, 0, 1, 99]zVec =0 3 -1 0 1 99>> zVec(end) = [ ]zVec =0 3 -1 0 1

This technique can be used especially within programs (see Section 1.6) when the size of a vector changes during execution of a program so that the last index is not known explicitly during programming. A vector can also be lengthened in this way, as the following instructions show:>> yVec = [0, 3, -1, 0, 1, 99]yVec =0 3 -1 0 1 99>> yVec(end+1:end+3) = [-1 -2 -3]yVec =0 3 -1 0 1 99 -1 -2 -3>> yVec(end+1) = 100yVec =0 3 -1 0 1 99 -1 -2 -3 100In this example, end is used in an indexing expression.A = magic(5)A = 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9B = A(end,2:end)B = 18 25 2 9

Variants

Task 1. For all variants complete next tasks:

85

Page 85: Informatics. Study Guide. Mathcad. Matlab. VC++

1. Calculate the standard scalar product of the vectors

and

using a matrix operation and a field operation,2. Calculate the product of the matrices

and ,

3. Calculate using a suitable field operation calculate the matrix

from the matrix

4. Test left division with the matrix

and the vector and interpret the result.

5. Test right division with the matrix

and the vector and interpret the result.6. Calculate the inverse matrix of

using right (or left) division.7. Test to see how the logical operations OR (|), negation (~), and exclusive OR (xor) work on the matrices A and B of Section 1.2.3. If necessary, consult MATLAB-help. Interpret the result.8. Test to see how the relational operations <=, >=, <, ==, and ~= operate on the vectors

and .If necessary, consult MATLAB-help.9. Consider the matrix

.

Using relational operators set all the terms of this matrix, which are > 10 and < −10 equal to 0. Hint: First make the comparison and then use the

86

Page 86: Informatics. Study Guide. Mathcad. Matlab. VC++

results of this comparison in order to set the appropriate terms equal to 0 using suitable field operations.10. Consider the matrix

.

Use logical fields to select the diagonal of this matrix and save it as a vector diag.11. Calculate the values of the signal (function)

for a time vector of times between 0 and 10 with a step size of 0.1.12. Calculate the values of the signal (function)

for the time vector of Problem k.13. Round off the values of the vector

for the time vector of Problem k, once up and once down. Find the corresponding MATLAB functions for this. For this, use the MATLAB help mechanisms.14. Round the values of the vector

to the nearest integer for the time vector of Problem k using a suitable MATLAB function. Also, give the first 6 values of s(t) and the corresponding rounded values in a matrix with two rows and interpret the somewhat surprising result.15. Define the vector

in MATLAB as a column and row vector.Laboratory work 8

GRAPHICAL FUNCTIONS

Objective – get to know with one of the most powerful elements of MATLAB its excellent plotting facilities which allow us to easily and rapidly visualize the results of calculations graphical functions in MatLab.

Problem statement – learn basic examples of the plotting facilities available within MATLAB, complete task and display result in the view of graphs of functions.

Theoretical information

87

Page 87: Informatics. Study Guide. Mathcad. Matlab. VC++

One of the outstanding strengths of MATLAB is its capability of graphical visualization of computational results. For this, MATLAB has available very simple but powerful graphical functions. MATLAB is thus able to represent ordinary functions in two-dimensional plots (xy plots) and functions of two variables in three-dimensional plots with perspective (xyz plots).

A complete survey of all the graphical functions can be obtained by entering help graph2d, help graph3d, and help graphics in the command window or in the corresponding entries of MATLAB help. In this section we shall discuss only the most useful and important of these functions.

Two-dimensional plots. By far the most important and the most commonly used graphical function is the function plot. Entering help plot provides the following information (excerpt):>> help plotPLOT Linear plot.PLOT(X,Y) plots vector Y versus vector X. If X or Y is amatrix, then the vector is plotted versus the rows orcolumns of the matrix, whichever line up ...

MATLAB help (of which we present only part of the full display for reasons of space) shows the basic capabilities of plot. Beyond that, there are many other possibilities and options for plot. A discussion of this topic is beyond the scope of this book. As the help function shows, in principle, two vectors are required in order to plot a graph. The first vector represents the vector of x values and the second, the corresponding vector of y values. The vectors must, therefore, have the same length. If this is not so, MATLAB produces an appropriate error message unless x is a scalar (see help plot). This message shows up in practice, even for experienced MATLAB users, but the error is easily corrected.

Many functions can also be plotted simultaneously, either by writing the x, y pairs one after the other in the parameter list or, when the same x vector will always be used, by combining the y vectors into a corresponding matrix. In addition, the form of the graphs in terms of the type of line and color can be varied by using suitable parameters. Our first example again uses the variables s and t from the example in Section 1.2.4, and plots the result obtained there:>> t = (0:1:5);>> s = sin(t);>> plot(t,s)

Note that in this example numerical output of the variables t and s is suppressed.

The plot command opens a window with the plot shown in Fig. 8.1.

88

Page 88: Informatics. Study Guide. Mathcad. Matlab. VC++

Figure 8.1. A MATLAB example of a simple x, y plot

Here and in the following graphs the scales on the axes are enlarged for the sake of clarity relative to the default. For the same reason, the thickness of the lines is also somewhat greater than the original display.

You can see that the result is normally in the form of a polygonal sequence. This often leads to erroneous interpretations of graphs, especially when the abscissa values are far apart. In addition, only numbers are placed on the axes automatically. You have to put in grids, axis labels, and titles yourself using the appropriate MATLAB commands.

In the next example a sine of amplitude 1 with frequency 5 Hz, a cosine of amplitude 2 and frequency 3 Hz, and the exponential function e−2t are calculated for the time vector t=(0:0.01:2) and plotted:>> t=(0:0.01:2);>> sinfct=sin(2*pi*5*t);>> cosfct=2*cos(2*pi*3*t);>> expfct=exp(-2*t);>> plot(t,[sinfct; cosfct; expfct])

This yields the graph shown in Fig. 8.2.

89

Page 89: Informatics. Study Guide. Mathcad. Matlab. VC++

Figure 8.2. x, y plot with multiple functions

In Fig. 8.3 this graph is shown again, but using some of the possibilities for different line shapes in order to distinguish the plots of the functions from one another. The corresponding plot statement is>> plot(t,sinfct,'k-', t, cosfct, 'b--', t, expfct, 'm.')

Here the variable t has to be repeated anew each time. The sine is plotted with the above settings, a black (black) solid curve (-), while the cosine is plotted in blue (blue) with a dashed curve (--), and the exponential function is in magenta (magenta) with a dotted curve (.).

Besides these most frequently used plot functions, MATLAB also has a number of other two-dimensional plot functions. In signal processing the function stem is often used. It presents discrete signals in the form of a fence plot. This function, however, is only suitable for sparse data sets, for otherwise the lines come too close to one another and the small circles at the ends of the lines can overlap in an unsightly manner. In these cases plot is more intuitive. Fig. 8.4 shows the results of the following MATLAB sequence:>> t=(0:0.05:2);>> cosfct=2*cos(2*pi*t);>> stem(t,cosfct)>> box

90

Page 90: Informatics. Study Guide. Mathcad. Matlab. VC++

Figure 8.3. x, y plot with multiple functions and different line colors and styles

Figure 8.4. x, y plot using the stem plot function

One function that is specially suited to displaying time-discrete signals is the function stairs, which represents the signal in the form of a stair function. Fig. 8.5 shows the result of the call>> stairs(t,cosfct)for the cosine signal defined above. A suitable labelling of the axes and a title line are also important for the documentation of graphs of this sort. In addition, it is often also necessary to provide a grid for the graph in order better to compare the values or to enlarge segments of a graph. MATLAB, of course, has functions for this purpose. For the axis labels there are

91

Page 91: Informatics. Study Guide. Mathcad. Matlab. VC++

xlabel, ylabel, and title, for the grid there is the function grid, and for magnification there is the function zoom, which allows the enlargement of a segment with the mouse, as well as the command axis, for which the x and y ranges must be specified explicitly. Labels can be inserted inside the graph using the function text.

Figure 8.5. x, y plot using the stairs function

The graphs in Figs. 8.6 and 8.7 show the result of the following MATLAB command sequence, in which the above capabilities are used:>> t=(0:0.05:2);>> cosfct=2*cos(2*pi*t);>> plot(t,cosfct)>> xlabel('time / s')>> ylabel('Amplitude / V')>> text (0.75,0,'\leftarrow zero crossing','FontSize',18)>> title('A cosine voltage with frequency 1 Hz')>> figure % open a new window !>> plot(t,cosfct)>> xlabel('time / s')>> ylabel('Amplitude / V')>> grid % set grid frame>> axis([0, 0.5, 0, 2]) % detail within interval [0, 0.5],% but only amplitudes within% the interval [0, 2]>> title('Detail of the cosine voltage with frequency 1 Hz')

We shall not discuss the other two-dimensional plot functions at this point. The reader can find out more about these possibilities in the help menu or in the book by Marchand and experiment with them.

92

Page 92: Informatics. Study Guide. Mathcad. Matlab. VC++

Figure 8.6. A labelled x, y plot using the plot function

Figure 8.7. A segment of Fig. 8.6 using the ''axis'' command

In the following we shall, however, briefly discuss the possibilities for processing graphs, which are specially available during interactive operation.

Graphical processing. MATLAB has extensive improvements in the user interface compared to its predecessors. Thus, it offers some convenient possibilities for the processing and export of graphics in the interactive mode. Since this is of great importance for the documentation of MATLAB computations, we shall discuss it briefly at this point.

93

Page 93: Informatics. Study Guide. Mathcad. Matlab. VC++

The plot window of a MATLAB graphic as seen by the user has the form shown in Fig. 8.8. The essential functions for manipulation of graphics can be selected using the so-called toolbar located below the pull-down menus. These functions can, of course, also be reached through the pull-down menu itself. Besides the conventional Windows icons for save, print, etc., in the left-hand third of the toolbar, in the middle third of the toolbar you can see the magnifier symbol, with which a graphic can be enlarged or shrunk, as well as a symbol for rotating a graphic. The latter is especially practical for viewing three-dimensional graphics (see the next subsection) and is very useful. The icons in the right-hand third of the toolbar provide access to other useful functions, such as the so-called data cursor, with which the (x, y) coordinates of a point in the graph can be displayed by clicking on the given point. There is also a button with which the graphics can be provided interactively with a legend.

The show plot tools icon on the far right extends the plot window to a wider window with tools for graphical processing. A detailed presentation of the possibilities at this point would go beyond the scope of this introduction. Instead, we shall illustrate the functionality with a small example.

Figure 8.8. The MATLAB plot window with a sample graph

94

Page 94: Informatics. Study Guide. Mathcad. Matlab. VC++

If, for instance, you want to change the title label, select and click on the title text with the plot editing arrow and make your change. Similarly, by double clicking on the lines it is possible to change the line style. A double click on the axes makes it possible to change the axis scale and other properties of the axes. With a mouse click the plot window can be expanded at any time into a configuration window where the desired settings can be chosen. All the configuration possibilities can be obtained in a single view if, as mentioned above, you press the show plot tools icon. Fig. 8.9 shows the plot window when it is expanded in this way.

Figure 8.9. The plot-tools window

A selection of tools for manipulating a plot are also available. This is otherwise context dependent. Thus, the property editor - axes window is opened below when the intersection of the axes is clicked. If the function graph is clicked, then this window will be replaced by the corresponding property editor window.

Besides these, many more functions can be obtained through the menu items insert and tools, which make it possible to modify the appearance of a graphic afterward. This calls on the experimental playfulness of the reader.

Given the innumerable possibilities offered by the plot window for changing graphics in MATLAB in the interactive mode, the preceding discussion of the plot commands may seem to be of somewhat dubious

95

Page 95: Informatics. Study Guide. Mathcad. Matlab. VC++

utility for this purpose. In fact, processing plots with the tools in the plot window is simpler and more intuitive.

Moreover, no commands have to be learned in combination with their syntax. It has already been pointed out that MATLAB is a programming language. If you want to prepare completed graphics within a program, the above MATLAB commands provide the only way to do it.

Finally, the important functionalities for graphics export from MATLAB 7 should be mentioned at this point. In the plot window various formats, such as encapsulated postscript, TIFF, portable network graphics, etc., into which a graphic can be converted and saved, may be chosen using the menu command File - Save as .... Of course, the graphics can be exported into other applications via the Windows interface using Edit - Copy figure command.

Three-dimensional plots. Here again, we shall not discuss all the capabilities of MATLAB in detail. The most important three-dimensional graphics functions are certainly mesh and surfsurf for the representation of a three-dimensional mesh or surface-mesh plot and contour for a contour plot. In the following example the two-dimensional function is plotted using the function mesh or surf within the square [−3, 3]×[−3, 3], which is provided with a rectangular grid with a step size (edge length) of 0.1. To do this the value of the function is calculated at every grid point:

The value of the function is attached to a surface mesh (tile) and the entire graph is plotted in perspective with respect to a viewpoint specified by MATLAB (which, of course, can easily be changed using the methods described in the preceding section).

The following sequence of commands produces the plots shown in Figs. 8.10 and 8.11:>> x=(-3:0.1:3); % grid frame in x direction>> y=(-3:0.1:3)'; % grid frame in y direction>> v=ones(length(x),1); % auxiliary vector>> X=v*x; % grid matrix of the x values>> Y=y*v'; % grid matrix of the y values>> % function value>> f=sin(X.^2+Y.^2).*exp(-0.2*(X.^2+Y.^2));>> mesh(x,y,f) % mesh plot with mesh>> mxf = max(max(f)); % maximum value of the function>> mif = min(min(f)); % minimum value of the function>> axis([-3,3,-3,3,mif,mxf])% adjust axes>> xlabel('x-axis'); % label axes>> ylabel('y-axis');>> figure % new plot>> surf(x,y,f) % surface mesh plot with surf

96

Page 96: Informatics. Study Guide. Mathcad. Matlab. VC++

>> axis([-3,3,-3,3,mif,mxf])% adjust axes>> xlabel('x-axis'); % label axes>> ylabel('y-axis');

Figure 8.10. A three-dimensional plot using the mesh command

Figure 8.11. A three-dimensional plot using the surf command

The technique for generating the x, y grid is of some interest. Here, elegant use has been made of matrix algebra, avoiding the need to write a double loop as would have to be done in the C++ programming language. In order to compare the plot results from mesh and surf, the graph of Fig.

97

Page 97: Informatics. Study Guide. Mathcad. Matlab. VC++

8.12 shows a three-dimensional contour plot of the function. It was generated using the following MATLAB commands:>> contour3(x,y,f,30)>> axis([-3,3,-3,3,mif,mxf]) % adjust axes>> xlabel('x-axis'); % label axes>> ylabel('y-axis');

The number 30 represents the number of contours to be plotted.

Figure 8.12. A three-dimensional plot using the contour3 command

Subplots and overlay plots. Besides being able to plot graphs in different individual windows, MATLAB can also plot multiple (overlay) graphs in a single window. This can be done, for example, using the subplot command. The following example shows how the magnitude and phase of the complex function can be plotted with the two plots one above the other:>> t=(0:0.1:5);>> f=(t.^2).*exp(j*t).*(j.^t); % * and ^ are field operations.>> subplot(211) % plot the top graph>> plot(t,abs(f))>> subplot(212) % plot the bottom graph>> plot(t,angle(f))

Fig. 8.13 shows the result.Here we see that the command subplot only sets the axes of the

graph in the right place. The plot, itself, is still provided by the plot command. The parameters of the subplot command specify how many graphs are to be drawn altogether in the vertical (the first number) and horizontal (second number) directions. The third number specifies which

98

Page 98: Informatics. Study Guide. Mathcad. Matlab. VC++

of the subgraphs is meant, going from upper left to lower right. For example subplot(325) signifies the fifth plot in an array of 3×2 graphs (for the next plot command).

Figure 8.13. A graph with two plots using the subplot command

Besides the ways described previously, multiple graphs can be plotted on top of one another using the hold command. This freezes the current graph so that the next graph is not plotted in its own window, but in the same window. Here is an example:>> t = (0:0.5:10);>> sinfct = sin(2*pi*5*t);>> cosfct = 2*cos(2*pi*3*t);>> plot(t,sinfct)>> hold>> plot(t,cosfct)

Here, the current graph is always the graph whose plot window is “on top,” and, therefore, the last one processed. Before using the hold command, you have to make sure that the correct graph is being written over by clicking the corresponding window.

Variants

Plot the functions with labels on graphics over the interval according from the variant given by the teacher.

Laboratory work 9

99

Page 99: Informatics. Study Guide. Mathcad. Matlab. VC++

MATLAB PROGRAMMING

Objective – get to know with MatLab Programming language; learn constructs as loops and branches and provides for the writing of functions and procedures.

Problem statement – using new constructs complete task according to your variant .

Theoretical information

MATLAB Procedures. The first step in programming is to provide script files, in which MATLAB command sequences are collected into simple procedures.

This involves writing the MATLAB command sequences with a text editor that can be opened, e.g., with the menu entry File - new - m-file in the MATLAB workspace, into a file and then saving this file under a name (e.g., proced.m) or as a so-called m-file in a path accessible to MATLAB.

The sequence of commands can then be executed in the command window with the command proceed. In order to avoid problems, whenever possible you must not use any previously employed command name. You can check whether such a command name already exists by, for example, just typing help <name> in the command window. An even more reliable method is to use the function exist. If the call exist <name> returns a value of 0, then no function with that name exists in the search path. We now illustrate the procedure for writing script files with an example.>> t=(0:0.01:2);>> sinfct=sin(2*pi*5*t);>> cosfct=2*cos(2*pi*3*t);>> expfct=exp(-2*t);>> plot(t,[sinfct; cosfct; expfct])and written an m-file with the name fnExample.m:t=(0:0.01:2);sinfct=sin(2*pi*5*t);cosfct=2*cos(2*pi*3*t);expfct=exp(-2*t);plot(t,[sinfct; cosfct; expfct])xlabel ('time / s')ylabel('Amplitude')title('three gorgeous signals')With>> fnExample

100

Page 100: Informatics. Study Guide. Mathcad. Matlab. VC++

this sequence can then be executed fully. At this point it is especially important to mention the heading of the file. With % placed in front, a documenting commentary can be provided ahead of the command sequence.

The particular point here is not that the meaning of the program will still be understandable years later–documentation of this sort is part of good programming style and readers should get used to this early on in their own interest—but that this text can be read in the MATLAB command window by entering help fnExample.

The help mechanism for all MATLAB functions, including for those you have written yourself, is set up so that help <function name> displays all the comment lines in the script or function file up to the first empty line or until the first MATLAB instruction. In order to save space, of course, we shall not fully reproduce all the comments for programs printed in this book. For this, refer to the accompanying software. The complete comments can, as noted above, also be displayed by entering help <function name> in the MATLAB command window.

Finally, it should be noted that, once the program is executed, the variables defined in the script file are known in the MATLAB workspace. This is an important distinction regarding the behavior of the MATLAB functions to be discussed below.

MATLAB functions. It is far more flexible to define MATLAB functions rather than simply combine MATLAB commands in script files, since these will be able to pass on parameters.

With this mechanism a program can be executed under different conditions. This is most easily clarified with the aid of an example. To do this, we first modify the script file fnExample.m of the above example as follows:function [t, sinfct, cosfct, expfct]= fnExample2(f1, f2, damp)t=(0:0.01:2);sinfct=sin(2*pi*f1*t);cosfct=2*cos(2*pi*f2*t);expfct=exp(-damp*t);plot(t,[sinfct;cosfct; expfct])xlabel ('time / s')ylabel('Amplitude')title('three gorgeous signals')

and save it under the name fnExample2.m. Function names and file names must always be in agreement. What has changed in fnExample2.m compared to fnExample.m? First of all, the three parameters f1, f2, and damp have been added. These correspond to the frequencies of the sine

101

Page 101: Informatics. Study Guide. Mathcad. Matlab. VC++

and cosine signals, plus a (damping) parameter for the exponential function.

These parameters, the input parameters, appear immediately after the function name as a list, separated by commas, in parentheses. Another list of names stands in front of the function name, this time in the square brackets typical of vectors. In the preceding example this list takes the vector names of the vectors used in the function core, which contain the results of the calculations. The equals sign in between signifies that we are dealing with output parameters. One should make sure that input and output parameters are described in detail in the comments preceding the actual instructions; this can be indicated with the help mechanism in MATLAB. This makes later use of the function much easier, especially for other users. Specifying the call syntax or giving an example of a call in the help commentary is also very practical. This can, for example, be copied directly into the command level after it is found with help ..., changed, if necessary, and then executed.

The following function call clarifies the significance of the difference between input and output parameters:>> clear>> [time, s1, c1, e1] = fnExample2(3, 5, 4);>> whosName Size Bytes Classc1 1x201 1608 double arraye1 1x201 1608 double arrays1 1x201 1608 double arraytime 1x201 1608 double arrayGrand total is 804 elements using 6432 bytes

You can tell that the names in the parameter list are merely place holders for the true values that will be set in the list when the function is called. The variables are thus only known and valid within the function core and while the function is being executed. The variables are said to be local.

This is shown by calling whos after the function call. Of course, variables rather than numbers can also be assigned to the function, and if one is no longer interested in the calculated vectors, but only in the graphic provided by the function for the case at hand, no return vector is needed. This is shown in the following example:>> clear>> whos>> frq1=6;>> frq2=1;>> dmpng=7;>> fnExample2(frq1,frq2,dmpng);

102

Page 102: Informatics. Study Guide. Mathcad. Matlab. VC++

>> whosName Size Bytes Classans 1x201 1608 double arraydmpng 1x1 8 double arrayfrq1 1x1 8 double arrayfrq2 1x1 8 double arrayGrand total is 204 elements using 1632 bytes

As can be seen, the input parameters are now known (they were previously defined in the workspace) and the return vector is saved in the variable ans, which is customarily used as the return variable if no other has been specified. Certainly, the parameters f1, f2, and damp are not known from the source text for the function. These are, as already noted, place holders for the actual delivered variables. Of course, one should not be deceived by this example. The input parameters are, as before, local. The following example makes this clear:function [sum] = fnExample3(a,b)% Calculates the sum of two vectors a and b,% which must, of course, also have the same dimensions,% but which will not be checked in this version of the program.sum = a+b; % It should do this.% And now a little experiment.a = a.^2; % squaring the components of aWe now call these functions and see what happens:>> clear>> v1 = [1 2 3];>> v2 = [-2 2 5];>> thesum = fnExample3(v1, v2)thesum =-1 4 8>> whosName Size Bytes Classthesum 1x3 24 double arrayv1 1x3 24 double arrayv2 1x3 24 double arrayGrand total is 9 elements using 72 bytes>> v1v1 =1 2 3>> v2v2 =-2 2 5

As we can see, the function fnExample3 calculates the sum of and in good form. These are still not changed here, although within the

103

Page 103: Informatics. Study Guide. Mathcad. Matlab. VC++

program the place holder of is squared term by term. This is also done, but only with a local variable. The input parameters themselves are protected. In conclusion we should add that, as opposed to the script files, within a function there is no access to variables in the workspace. This is also a consequence of the concept of local variables.

MATLAB language constructs. As pointed out above, MATLAB is also a programming language and thus is endowed with program language-like constructs. If you type in help lang (language) in the MATLAB command window, you will get a survey of these constructs.

Control flow.1. if - Conditionally execute statements.2. else - IF statement condition.3. elseif - IF statement condition.4. end - Terminate scope of FOR, WHILE, SWITCH, TRY5. and IF statements.6. for - Repeat statements a specific number of times.7. while - Repeat statements an indefinite number of times.8. break - Terminate execution of WHILE or FOR loop.9. continue - Pass control to the next iteration of FOR or WHILE loop.10. switch - Switch among several cases based on expression.11. case - SWITCH statement case.12. otherwise - Default SWITCH statement case.13. try - Begin TRY block.14. catch - Begin CATCH block.15. return - Return to invoking function.

Evaluation and execution.1. eval - Execute string with MATLAB expression.2. feval - Execute function specified by string.

MATLAB thus distinguishes six classes of language constructions. For this introduction, the control flow constructs are of particular interest. They are typical of all higher program languages and can be used to control the running of a sequence of commands within a program.

The next example should clarify how these constructs are manipulated. The reader is urged to first type in help <keyword> in order to become informed about their syntax.

If construct – converting complex numbers. A simple example of a conditional distinction that can be handled using the if construct is the conversion of complex numbers into their polar (algebraic exponential) representation.

As is generally known, in this conversion a correct calculation of the argument (phase, amplitude) requires a distinction The following MATLAB program convertComplex carries out this task and provides the modulus

104

Page 104: Informatics. Study Guide. Mathcad. Matlab. VC++

(magnitude) and argument of a complex number, which is entered as a parameter. The argument is given both in radians and in degrees.function [magn, radians, degrees]= convertComplex(cmplxNum)% This example calculates the modulus and argument% of the complex number cmplxNum specified in the% algebraic representation (standard for MATLAB)% Calculate the modulusmagn = abs(cmplxNum);% Calculate the real and imaginary partscmplxNumRe = real(cmplxNum);cmplxNumIm = imag(cmplxNum);% Determine the quadrantif cmplxNumRe > 0if cmplxNumIm >= 0 % first quadrantradians = atan(cmplxNumIm/cmplxNumRe);else % fourth quadrantradians = atan(cmplxNumIm/cmplxNumRe) + 2*pi;end;elseif cmplxNumRe < 0 % second and third quadrantsradians = atan(cmplxNumIm/cmplxNumRe) + pi;else % special case: real part = 0if cmplxNumIm >= 0 % imaginary part positiveradians = pi/2;else % imaginary part negativeradians = 3*pi/2;end;end;% recalculating the argument in degdegrees = radians*180/pi;

This program contains many nested if constructs so it is somewhat tortuous. Of the various alternatives, the switch construct, which we shall discuss below, is better.

This program illustrates the handling of if constructs quite extensively, along with an example of elseif. The latter makes it possible to distinguish the quadrant of the vector, including the special case in which the vector lies on the imaginary axis.

For-loops – calculating averages. A simple example of loop programming with a for construct is the calculation of the average of a sequence of numbers. The numbers to be averaged are, in typical MATLAB fashion, naturally organized (or to be organized) as a vector. Obviously, MATLAB has a prepared function for calculating averages, the function mean, but the following self-written function averageValue, should solve this problem with the aid of for-loop constructs. A for-loop is always

105

Page 105: Informatics. Study Guide. Mathcad. Matlab. VC++

employed when a certain previously specified number of operations must be repeated. In this example, the number of the components of the vector (the number of numbers to be averaged) is known. The following function sums these numbers one after another and then divides the sum by the number of numbers.function [avgval] = averageValue(nums)% This example calculates the average value% of the components of the vector Nums.N = length(nums);% the variable avgval, the average, is% initialized to 0avgval = 0;% adding the components to avgval, one after the otherfor k=1:N % do this from the 1st to the Nth componentavgval = avgval + nums(k);end% Divide avgval by the number of numbers (N)avgval= avgval/N;

As can be seen in this example, the word for must be followed by the condition under which the instructions are to be repeated until the end of the loop (indicated by the word end). This condition must cover a finite number of cases. In most cases, as in the example, this will be the upper and lower limits of an integral variable. The loop operation can, moreover, take place in larger steps.

Thus, for example, the instruction for k=1:2:N in the above example would cause the calculation to be done only on the odd components.

In conclusion, it should be noted that the above program for MATLAB is not at all typical. Many loops, including this one, can be performed more easily and more elegantly with vectorial constructions in MATLAB. Of course, there are other situations in which a classical loop construct cannot be avoided.

For-loops – maximum value search. Another simple example of the use of a for -loop is the determination of the maximum of a sequence of numbers (for which, of course, there is again a MATLAB command, namely the command max. A similar command (min) exists for the minimum.).

Here, we have the number of cases to work through already determined. This makes it a typical task for a for-loop.

The following function solves this problem:function [mval] = maxValue(nums)% This example calculates the maximum value% of the components of the vector Nums.N = length(nums);

106

Page 106: Informatics. Study Guide. Mathcad. Matlab. VC++

% the variable mval, the maximum value, is% initialized to the first value of the variablemval = nums(1);% search the components, one after the otherfor k=2:N % do this from 2nd to the Nth componentif nums(k) > mval % Compare the current componentmval = nums(k); % with the previous maximum: if it isend % greater, assign this number to mvalend

While-loop – input function. In the preceding examples the number of operations to be repeated was known in advance, so that the running condition could be executed in a for-loop. In the above examples this was done concretely by specifying a numerical vector (e.g., 1:2:N).

In many cases, however, the number of the operations to be carried through identically is not known beforehand. A simple example of this is the reading in of data until a datum satisfies a particular end criterion.

The following simple function FInput prompts the user to input data and saves these data in an output vector until an input number is negative.

The program uses the existing MATLAB function input as an input prompt, together with a so-called while-loop for reading in the data.function [InVector] = FInput()% This example prompts the user to% input data and saves these data in a% vector [InVector]. This procedure is repeated% until a NEGATIVE number is read in.% input parameter: nonedat = input('Input a number! (End if negative):');InVector = dat; % Initialize InVector with this% Checking and reading in further data, until% the end criterion is satisfiedwhile dat >= 0 % as long as the datum is positive:% read in the next numberdat = input('Input a number! (End if negative):');% append to InVectorInVector= [InVector; dat];end;

With the while-loop employed here, this program will run up to the end-instruction belonging to the construction as long as the condition specified after while is true. In this case the condition is dat>=0. Before the first run the condition must be evaluable, which in this case means that at least one value must be read in and evaluated. In other programming languages a do-while construction exists for these cases; in it the loops

107

Page 107: Informatics. Study Guide. Mathcad. Matlab. VC++

will run at least once in every case. In MATLAB this kind of behavior has to be imitated by specially evaluating the loop instructions in advance.

By the way, the above example can very easily mislead the beginner into only writing functions for which the parameters are not input from the parameter list but are read in interactively via the input-function to the function. Use of this function is, however, rather untypical and for the most part is just for test purposes; it creates a sense that, in general, a function of this sort naturally would not be used within other programs. Thus, you would be better off to put your energy into understanding the parameter-input mechanism of MATLAB.

Switch-construct – characteristics of a vector. When dealing with many cases which are to be distinguished, an if ...elseif construction is usually very obscure. In these situations it is better to use a switch ... case construction.

The following program uses this type of construction in order to calculate various characteristics of a vector depending on an input parameter (here a string):function [result] = multiFnVector(vector, operation)% This example calculates different characteristics% of a vector, such as its norm or length, etc, depending% on the string input under the parameter "operation".switch operationcase 'l2norm' % calculate the euclidean normdim = size(vector); % determine the dimension of theif dim(2)<dim(1) % vector when there is no rowvector = vector'; % vector, then create oneend;result= sqrt(vector*vector');case 'max' % maximum of the values of the componentsresult = max(vector);case 'min' % minimum of the values of the componentsresult = min(vector);case 'l1norm' % sum of the contributions of the componentsresult = sum(abs(vector));case 'maxnorm' % largest magnitude of the componentsresult = max(abs(vector));case 'average' % average value of the componentsresult = mean(vector);case 'length' % length of the vectorresult = length(vector);otherwisedisp('Please enter "help multiFnVector"');error('The input parameter is not allowed!');

108

Page 108: Informatics. Study Guide. Mathcad. Matlab. VC++

end;Admittedly, this function is not particularly meaningful, since in the

above case independent functions would surely be more appropriate, but here we are more concerned with demonstrating the switch....case construct than with the problem as such.

It can be seen that, after switch, a condition must be entered according to which the cases are to be distinguished. As in this example, it can be a string, but it can also be a number or, in general, an expression. Next, instructions are given for what is to be done in the different cases. These are distinguished by evaluating the expression after the keyword case. If the expression shows up in the cases specified under switch, then the instructions following it will be executed, otherwise the instruction following otherwise will be executed, which in the present case consists of an appropriate error message with the aid of the error function. Unlike in C++, no break is necessary after each case instruction.

VariantsTask1. For all variants.1. Change the function fnExample3 so that access to the result of the squaring of the vector ..... is possible.2. Change the function fnExample2 so that the colors for the graphical plots can be given through the function and the signal can then also be plotted accordingly.3. Change the function fnExample2 so that the parameters of the function can be passed on in the form of a parameter structure fctparams. The structure fields should then contain the original parameters of the function fnExample2.4. Write a function using a loop construction, which selects the positive values in a vector input to the function and returns these values assembled into an output vector.5. Write a function that calculates the standard scalar product of two vectors using a for-loop. This solution is not very elegant and is not typical of MATLAB. How would a MATLAB programmer solve this problem?6. Write the function FInput so that the negative number required to end the input is not read into the output vector.7. Write a function that plots sin (x) between 0 and 2π in a specified color. The color should be read as a parameter in the form 'red', 'blue', 'green', and 'magenta'. The different cases for the color are to be distinguished using a switch...case construct.

Task 2 should be taken from the laboratory work of the number 4 on the instructions of the teacher.

109

Page 109: Informatics. Study Guide. Mathcad. Matlab. VC++

Laboratory work 10

M-FILE IN MATLAB

Objective – get to know using of m-file in MatLab; learn the basics of programming with using m-file.

Problem statement – find the solution of a problem by defining function in m-file.

Theoretical information

The MATLAB software provides a full programming language that enables you to write a series of MATLAB statements into a file and then execute them with a single command.

You write your program in an ordinary text file, giving the file a name of filename.m. The term you use for filename becomes the new command that MATLAB associates with the program. The file extension of .m makes this a MATLAB M-file.

Types of m-Files. M-files can be scripts that simply execute a series of MATLAB statements, or they can be functions that also accept input arguments and produce output.MATLAB scripts:

Are useful for automating a series of steps you need to perform many times.

Do not accept input arguments or return output arguments. Store variables in a workspace that is shared with other scripts and

with the MATLAB command line interface.MATLAB functions:

Are useful for extending the MATLAB language for your application. Can accept input arguments and return output arguments. Store variables in a workspace internal to the function.

Basic parts of an m-file. This simple function shows the basic parts of an M-file. Note that any line that begins with % is not executable:function f = fact(n) Function definition line% Compute a factorial value. H1 line% FACT(N) returns the factorial of N, Help text% usually denoted by N!% Put simply, FACT(N) is PROD(1:N). Commentf = prod(1:n); Function body

The table below briefly describes each of these M-file parts. Both functions and scripts can have all of these parts, except for the function

110

Page 110: Informatics. Study Guide. Mathcad. Matlab. VC++

definition line which applies to functions only. These parts are described in greater detail following the table.

M-file element DescriptionFunction definition line (functions only)

Defines the function name, and the number and order of input and output arguments

H1 line A one line summary description of the program, displayed when you request help on an entire directory, or when you use lookfor

Help text A more detailed description of the program, displayed together with the H1 line when you request help on a specific function

Function or script body

Program code that performs the actual computations and assigns values to any output arguments

Comments Text in the body of the program that explains the internal workings of the program

Function definition line. The function definition line informs MATLAB that the M-file contains a function, and specifies the argument calling sequence of the function. This line contains the function keyword and must always be the first line of a function M-file, with the exception of lines that are nonexecutable comments. The function definition line for the fact

function is

All MATLAB functions have a function definition line that follows this pattern.

Syntax function [out1, out2, ...] = funname(in1, in2, ...)

defines function funname that accepts inputs in1, in2, etc. and returns outputs out1, out2, etc.

You add new functions to the MATLAB vocabulary by expressing them in terms of existing functions. The existing commands and functions that compose the new function reside in a text file called an M-file.

M-files can be either scripts or functions. Scripts are simply files containing a sequence of MATLAB statements. Functions make use of their own local variables and accept input arguments.

111

Page 111: Informatics. Study Guide. Mathcad. Matlab. VC++

The name of an M-file begins with an alphabetic character and has a filename extension of .m. The M-file name, less its extension, is what MATLAB searches for when you try to use the script or function.

A line at the top of a function M-file contains the syntax definition. The name of a function, as defined in the first line of the M-file, should be the same as the name of the file without the .m extension.

The variables within the body of the function are all local variables.A subfunction, visible only to the other functions in the same file, is

created by defining a new function with the function keyword after the body of the preceding function or subfunction. Subfunctions are not visible outside the file where they are defined.

You can terminate any function with an end statement but, in most cases, this is optional. end statements are required only in M-files that employ one or more nested functions. Within such an M-file, every function (including primary, nested, private, and subfunctions) must be terminated with an end statement.

You can terminate any function type with end, but doing so is not required unless the M-file contains a nested function.

Functions normally return when the end of the function is reached. Use a return statement to force an early return.

When you call an M-file function from the command line or from within another M-file, MATLAB parses the function and stores it in memory. The parsed function remains in memory until cleared with the clear command or you quit MATLAB. The pcode command performs the parsing step and stores the result on the disk as a P-file to be loaded later.

Example 1. Create a function M-file for the function f (x) = x2 − 1.function y = f(x)y = x^2-1;

Example 2. The existence of a file on disk called stat.m containing this code defines a new function called stat that calculates the mean and standard deviation of a vector:function [mean,stdev] = stat(x)n = length(x);mean = sum(x)/n;stdev = sqrt(sum((x-mean).^2/n));

Example 3. avg is a subfunction within the file stat.m:function [mean,stdev] = stat(x)n = length(x);mean = avg(x,n);stdev = sqrt(sum((x-avg(x,n)).^2)/n);function mean = avg(x,n)mean = sum(x)/n;

112

Page 112: Informatics. Study Guide. Mathcad. Matlab. VC++

Variants

Find the solution of problem by the craft a function M-file for the solution. After insuring that your function M-file is correct, use the function to plot the solution of the initial value problem on the given interval.1. f(y,t) = −t/y, where t is constant, on [0, 4].2. f(y,t) = −2ty2, , where t is constant, on [0, 5].3. f(y,t) = cos(ty) , where t is constant, on [0, 5π].4. f(y,t) = sin(2ty), where t is constant, on [0, 4π].5. f(y,t) = (1 − t)y, where t is constant, on [0, 4].6. f(y,t) = y sin(2ty), where t is constant, on [0, 2π].7. f(y,t) = = y/t + t , where t is constant, on [0, 3].8. f(y,t) = t2y – 3, where t is constant, on [0, 5].9. f(y,t) = 2ty − e−2t , where t is constant, on [0, 2].10. f(y,t) = y/t − t sin (2ty) , where t is constant, on [0, 2π].11. f(y,t) = 1 + 2y/t, where t is constant, on [1, 4].12. f(y,t) = y – t2, where t is constant, on [0, 2].13. f(y,t) = y – t2 cos(ty), where t is constant, on [0, 2π].14. y = (1/4)t2 − (1/8)t + 1/32 + Ce−4t , C = 1, 2, 3, 4, 5, on [0, 2].15. y = Cte−2t , C = −3, −2, −1, 0, 1, 2, 3, on [−2, 2].16. y = (t/2)(cos(t) + sin(t)) − (1/2) sin(t) + Ce−t , C = −3, −2, −1, 0, 1, 2,

3, on [0, 10].17. y = −1 + cos(t) + (C + t/2) sin(t), C = 0, 1, 2, 3, 4, 5, on [0, 6π].18. y = (1/10) sin(t) + (1/5) cos(t) + e−t(C sin(2t) − (1/5) cos(2t)), C = −3,

−2, −1, 0, 1, 2, 3, on [0, 2π].19. y = sin(t) + (C + t2/2)cos(t), C = 0, 1, 2, 3, 4, 5, on [0, 6π].20. y = Ct2e−t , C = −3, −2, −1, 0, 1, 2, 3, on [−2, 2].21. f(y,t) = t/(y-t), where t is constant, on [0, 4].22. f(y,t) = t−2ty2, , where t is constant, on [0, 5].23. f(y,t) = cos(ty)/t , where t is constant, on [0, 5π].24. f(y,t) = 1/sin(2ty), where t is constant, on [0, 4π].25. f(y,t) = (1 + t2)y, where t is constant, on [0, 4].26. f(y,t) = y- sin(2ty), where t is constant, on [0, 2π].27. f(y,t) = = y-1/t + t , where t is constant, on [0, 3].28. f(y,t) = t2-ty – 3, where t is constant, on [0, 5].29. f(y,t) = 2ty − e−2-t , where t is constant, on [0, 2].30. f(y,t) = y/t + t sin (2-ty) , where t is constant, on [0, 2π].

Laboratory work 12

INTRODUCTION TO VC++.STRUCTURE OF A PROGRAM.

113

Page 113: Informatics. Study Guide. Mathcad. Matlab. VC++

Objective – get to know with Microsoft Visual Studio; learn the basics of working with VC++ and data types that you can use during programming.

Problem statement – creat a program that defines different data types of variables according to student’s variant; learn to do calculations and display result in the view of values of all variables.

Theoretical information

How to start. Press on your window desktop, choose All Programs from the popup menu, then choose Developments and then Microsoft Visual Studio, and Microsoft Visual Studio 2005.

To get started on your first program, you must create a "project" that will keep track of all the parts of your program, including the C++ source code, the header files, etc. Therefore, click the "Create Project" link. A "New Project" dialogue box similar to the one below will appear.

Follow these steps: 1. For a “Name:” you can type any project name 2. “Location:”, you can leave it in default location3. “Creat directory for solution”, you can check or leave it

unchecked

114

Page 114: Informatics. Study Guide. Mathcad. Matlab. VC++

4. Click on "OK" The “Win32 Application Wizard” will appear. As demonstrated

below, click on “Application Settings” and select “Empty Project”. As shown in Fig.12.1.

After this, click on “Finish”. You will notice that it doesn't appear like anything has changed (you still see the "Start Page"). However, look at the “Solution Explorer” on the left-hand side you will see “Solution 'hello' (1 project)”.

You want to add C++ source code to this project. Select Project --> Add New Item... from the main menu, and select C++ File (.cpp) from the "Templates" section on the right-hand side. Type in the file name: “hello.cpp” in the Name: box. Click on “Add”. This file will be added to the hello work space that we have just created, and a blank document will be opened for editing.

Fig.12.1. Example of installation-specific settings

A C++ program begins with a function, a collection of commands that do something. The function that begins a C++ program is called main. From main, we can call other functions whether they be written by us or by

115

Page 115: Informatics. Study Guide. Mathcad. Matlab. VC++

others. To access a standard function that comes with the compiler, you include a header with the #include directive. What this does is take everything in the header and paste it into your program. Let's look at a working program:

// my first program in C++#include <iostream>using namespace std;int main(){ cout<<"2 + 2 = 4 not 5 \n"; cin.get();}

You may have noticed that not all the lines of this program perform actions when the code is executed. There were lines containing only comments (those beginning by //). To create a comment use either //, which tells the compiler that the rest of the line is a comment, or /* and then */ to block off everything between as a comment. Certain compiler environments will change the color of a commented area.

There were lines with directives for the compiler's preprocessor (those beginning by #). Then there were lines that began the declaration of a function (in this case, the main function) and, finally lines with statements (like the insertion into cout), which were all included within the block delimited by the braces ({}) of the main function.

#include is a preprocessor directive that tells the compiler to put code from the header called iostream into our program. By including header files, you an gain access to many different functions. For example, the cout function requires iostream.

using namespace std; All the elements of the standard C++ library are declared within what is called a namespace, the namespace with the name std. So in order to access its functionality we declare with this expression that we will be using these entities. This line is very frequent in C++ programs that use the standard library, and in fact it will be included in most of the source codes included in these tutorials.

int main(). This line tells the compiler that there is a function named main, and that function returns an integer, hence int. The braces ({ and }) signal the beginning and end of functions and other code blocks.

cout function is used to display text. It uses the << symbols, known as insertion operators. The quotes tell the compiler that you want to output the literal string as-is.

\n is actually one character that stands for a newline. It moves the cursor on your screen to the next line. The semicolon is added onto the end of all function calls in C++.

116

Page 116: Informatics. Study Guide. Mathcad. Matlab. VC++

cin.get(). This is another function call that expects the user to hit the return key. Many compiler environments will open a new console window, run the program, and then close the window. This command keeps that window from closing because the program is not done yet. It gives you time to see the program run.

A return value of 0 means success and is returned automatically (but only for main, other functions require you to manually return a value), but if we wanted to return something else, such as 1, we would have to do it with a return statement.

The final brace closes off the function. It is also possible for your program to accept input. The function you use is known as cin, and is followed by the insertion operator >>.

Fundamental data types. Before you try to receive input, you must have a place to store that input. In programming, input and data are stored in variables. There are several different types of variables; when you tell the compiler you are declaring a variable, you must include the data type along with the name of the variable.

The memory in our computers is organized in bytes. A byte is the minimum amount of memory that we can manage in C++. A byte can store a relatively small amount of data: one single character or a small integer. In addition, the computer can manipulate more complex data types that come from grouping several bytes, such as long numbers or non-integer numbers.

Next you have a summary of the basic fundamental data types as well as the range of values that can be represented with each one:

Name Description Size Range

charCharacter or small integer.

1bytesigned: -128 to 127unsigned: 0 to 255

short int (short)

Short Integer. 2bytessigned: -32768 to 32767unsigned: 0 to 65535

int Integer. 4bytessigned: -2147483648 to 2147483647unsigned: 0 to 4294967295

long int Long integer. 4bytessigned: -2147483648 to 2147483647unsigned: 0 to 4294967295

bool

Boolean value. It can take one of two values: true or false.

1byte true or false

floatFloating point number.

4bytes +/- 3.4e +/- 38 (~7 digits)

doubleDouble precision floating point number.

8bytes +/- 1.7e +/- 308 (~15 digits)

long Long double 8bytes +/- 1.7e +/- 308 (~15 digits)

117

Page 117: Informatics. Study Guide. Mathcad. Matlab. VC++

doubleprecision floating point number.

wchar_t Wide character.2 or 4 bytes

1 wide character

To declare a variable you use the syntax type <name>. It is permissible to declare multiple variables of the same type on the same line; each one should be separated by a comma. The declaration of a variable or set of variables should be followed by a semicolon (Note that this is the same procedure used when you call a function). If you attempt to use an undefined variable, your program will not run, and you will receive an error message informing you that you have made a mistake.

Declaration of variables. In order to use a variable in C++, we must first declare it specifying which data type we want it to be. The syntax to declare a new variable is to write the specifier of the desired data type followed by a valid variable identifier. For example:

int x; //declares a variable of type int with the identifier xint a, b, c, d; //has exactly the same meaning as: int a; int b; int c;char letter;float mynumber; //declares a variable of type float with the identifier

mynumberSeveral operators used with variables include the following: *, -,

+, /, =, ==, >, <. Here are a few examples: a = 4 * 6; // (Note use of comments and of semicolon) a is 24a = a + 5; // a equals the original value of a with five added to ita == 5 // it checks to see if a equals 5.For example: a < 5 // Checks to see if a is less than fivea > 5 // Checks to see if a is greater than fivea == 5 // Checks to see if a equals five, for good measureInitialization of variables. When declaring a regular local variable,

its value is by default undetermined. But you may want a variable to store a concrete value at the same moment that it is declared. In order to do that, you can initialize the variable. There are two ways to do this in C++, For example, if we want to declare an int variable called a initialized with a value of 0 at the moment in which it is declared, we could write: int a = 0;

Introduction to strings. Variables that can store non-numerical values that are longer than one single character are known as strings. The C++ language library provides support for strings through the standard string class.

A first difference with fundamental data types is that in order to declare and use objects (variables) of this type we need to include an additional header file in our source code: <string> and have access to the std namespace.

int main ()

118

Page 118: Informatics. Study Guide. Mathcad. Matlab. VC++

{ string mystring = "This is a string"; //string mystring ("This is a string"); cout << mystring;

return 0;}

Boolean literals. There are only two valid Boolean values: true and false. These can be expressed in C++ as values of type bool by using the Boolean literals true and false.

Constants. Constants are expressions with a fixed value.Literals. Literals are used to express particular values within the

source code of a program. We have already used these previously to give concrete values to variables or to express messages we wanted our programs to print out, for example, when we wrote: a = 5; the 5 in this piece of code was a literal constant. Literal constants can be divided in Integer Numerals, Floating-Point Numerals, Characters, Strings and Boolean Values. Integer Numerals can be: 189, 234, 1, 2 and so on.

They are numerical constants that identify integer decimal values. Notice that to express a numerical constant we do not have to write quotes (") nor any special character.

Literal constants, like variables, are considered to have a specific data type. By default, integer literals are of type int. However, we can force them to either be unsigned by appending the u character to it, or long by appending l:

75 // int75u // unsigned int75l // long75ul // unsigned long

In both cases, the suffix can be specified using either upper or lowercase letters.

Floating Point Numbers. They express numbers with decimals and/or exponents. They can include either a decimal point, an e character (that expresses "by ten at the Xth height", where X is an integer value that follows the e character), or both a decimal point and an e character:

3.14159 // 3.141596.02e23 // 6.02 x 10^231.6e-19 // 1.6 x 10^-193.0 // 3.0

These are four valid numbers with decimals expressed in C++. The first number is PI, the second one is the number of Avogadro, the third is the electric charge of an electron (an extremely small number) -all of them approximated- and the last one is the number three expressed as a floating-point numeric literal.

119

Page 119: Informatics. Study Guide. Mathcad. Matlab. VC++

Character and string literals. There also exist non-numerical constants, like:

'z' 'p' "Hello world" "How are you?" The first two expressions represent single character constants, and

the following two represent string literals composed of several characters. Notice that to represent a single character we enclose it between single quotes (') and to express a string (which generally consists of more than one character) we enclose it between double quotes (").

When writing both single character and string literals, it is necessary to put the quotation marks surrounding them to distinguish them from possible variable identifiers or reserved keywords. Notice the difference between these two expressions: x and 'x'; x alone would refer to a variable whose identifier is x, whereas 'x' (enclosed within single quotation marks) would refer to the character constant 'x'.

Character and string literals have certain peculiarities, like the escape codes. These are special characters that are difficult or impossible to express otherwise in the source code of a program, like newline (\n) or tab (\t). All of them are preceded by a backslash (\). Here you have a list of some of such escape codes:

\n newline\r carriage return\t tab\v vertical tab\b backspace\f form feed (page feed)\a alert (beep)\' single quote (')\" double quote (")\? question mark (?)\\ backslash (\)

Additionally, you can express any character by its numerical ASCII code by writing a backslash character (\) followed by the ASCII code expressed as an octal (base-8) or hexadecimal (base-16) number. In the first case (octal) the digits must immediately follow the backslash (for example \23 or \40), in the second case (hexadecimal), an x character must be written before the digits themselves (for example \x20 or \x4A).

String literals can extend to more than a single line of code by putting a backslash sign (\) at the end of each unfinished line.

"string expressed in \two lines"

120

Page 120: Informatics. Study Guide. Mathcad. Matlab. VC++

You can also concatenate several string constants separating them by one or several blank spaces, tabulators, newline or any other valid blank character:

"this forms" "a single" "string" "of characters"Finally, if you want the string literal to be explicitly made of wide

characters (wchar_t), instead of narrow characters (char), we can precede the constant with the L prefix:

L"This is a wide character string"Wide characters are used mainly to represent non-English or exotic

character sets.Defined constants (#define). Constants are expressions with a

fixed value. You can define your own names for constants that you use very often without having to resort to memory-consuming variables, simply by using the #define preprocessor directive. Its format is:

#define PI 3.14159#define NEWLINE '\n'

This defines two new constants: PI and NEWLINE. Once they are defined, you can use them in the rest of the code as if they were any other regular constant.

The #define directive is not a C++ statement but a directive for the preprocessor; therefore it assumes the entire line as the directive and does not require a semicolon (;) at its end. If you append a semicolon character (;) at the end, it will also be appended in all occurrences within the body of the program that the preprocessor replaces.

Declared constants (const). With the const prefix you can declare constants with a specific type in the same way as you would do with a variable:

const int pathwidth = 100;const char tabulator = '\t';

Here, pathwidth and tabulator are two typed constants. They are treated just like regular variables except that their values cannot be modified after their definition.

Operators. Assignment (=). The assignment operator assigns a value to a variable. a = 5; This statement assigns the integer value 5 to the variable a. Consider also that we are only assigning the value of b to a at the moment of the assignment operation. Therefore a later change of b will not affect the new value of a.For example:

a = 2 + (b = 5); is equivalent to: b = 5; a = 2 + b;that means: first assign 5 to variable b and then assign to a the value 2 plus the result of the previous assignment of b (i.e. 5), leaving a with a final value of 7.

121

Page 121: Informatics. Study Guide. Mathcad. Matlab. VC++

The following expression is also valid in C++: a = b = c = 5; It assigns 5 to the all the three variables: a, b and c.

Arithmetic operators ( +, -, *, /, % ). The five arithmetical operations supported by the C++ language are:

+ addition / division- subtraction % modulo* multiplication

Operations of addition, subtraction, multiplication and division literally correspond with their respective mathematical operators. The only one that you might not be so used to see is modulo; whose operator is the percentage sign (%). Modulo is the operation that gives the remainder of a division of two values.

For example, if we write: a = 11 % 3, the variable a will contain the value 2, since 2 is the remainder from dividing 11 between 3.

Example of defining of some basic fundamental data types is shown below:

#include "stdafx.h"#include <iostream>using namespace std;

int main () { double real_Var = 150.67; cout << "real number = " << real_Var << endl; int int_Var = 26; cout << "integer number = " << int_Var << endl; double Calc_Var; Calc_Var = (int_Var * 3.0) / 4.0; //Calc_Var = (double)(int_Var * 3) / 4; cout << "calculated value = " << Calc_Var << endl; cin.get(); return 0;}

The value after the line Calc_Var = (int_Var * 3.0) / 4.0; will be Calc_Var = 19.5. 3.0 and 4.0 presented as floating point number to get real result. If you want to use Calc_Var = (int_Var * 3) / 4; the result will be Calc_Var = 19 because division (/) gives you a value without its reminder.

Next example shows a program that prints out your name, number of the student card, and date of birth.

#include "stdafx.h"#include <iostream>#include <string>

122

Page 122: Informatics. Study Guide. Mathcad. Matlab. VC++

using namespace std;

int main () { int student_card_number = 100451208; string name="Elena Orlenko"; int day = 22; string month = "May"; int year = 1976;cout<<"\n";cout<<" ------------------------------------------------------\n";cout<<"| NAME |"<<" STUDENT'S CARD |"<<" DATE OF BIRTH |"<<"\n";cout<<"| |"<<" |"<<" |"<<"\n";cout<<"| "<<name<<" |"<<" "<<student_card_number<<" | "<<day<<" of "<<month<<year<<" |\n";cout<<" ------------------------------------------------------\n";cin.get();}

Variants1) Write a program that creates a table of Olympic competition running distances in meters, kilometers, yards, and miles. Use the pattern exhibited in these distances to write your program: 1m = 0.001 km = 1.094 yd = 0.0006215 mi. All distance are real number. Print the result to the screen in the following manner:

Table of Olympic running distancesMeters Kilometers Yards Miles

100200300400

________________

________________

________________

2) Write a program that computes the length of the fypotenuse of four right triangles based on the lengths of the two legs. The lengths are:

Triangle 1 5.4 8.7Triangle 2 3.1 12.6Triangle 3 23.7 5.8Triangle 4 1.56e + 8 2.37e + 6

Print the result to the screen in the following manner:Hypotenuse lengths of four triangles

Triangle number

Leg 1length

Leg 2length

Hypotenuselength

1 ____ ____ ____

123

Page 123: Informatics. Study Guide. Mathcad. Matlab. VC++

234

____________

____________

____________

Right-justify the the numbers in the table.

3) Write a program that computes the values of the two acute angles of a right triangle given the lengths of the two legs. Use the input data given in the problem 2. The output result should be in degrees, not radians, make sure that you convert from radians to degrees. Print the result to the screen in the following manner:

Acute angles of four trianglesTriangle number

Acute angle 1

Acute angle 2

1234

________________

________________

4) Write a program to calculate these unknown values: Alpha

(degree)Alpha

(radian)2*Alpha

30.045.060.0

???

???

5) The distance that a car (undergoing constant acceleration) will travel is diven by the expression , where = distanse traveled, = initial velocity, = time of travel, = acceleration. Print the result to the screen in the following manner:

Car under constant acceleration

Initial velocity Time Acceleration Distanse

10 5 3 4 5 6

????

10 10 3 4 5 6

????

6) The general gas law for an ideal gas is given by constant, where

P = pressure, V = volume, T = temperature, which leads to the equation

124

Page 124: Informatics. Study Guide. Mathcad. Matlab. VC++

, for a given mass of gas. Write a program that computes

the temperature of a gas that is originarry at atmospheres, liters, degrees Kelvin. The below-listed pressure, volume, and temperature conditions can occur for a given mass of an ideal gas which is originally at P= 5 atm, V=30 liters, and T=273 K.Print the result to the screen in the following manner:

Case P (atm) V (l) T (K)

1234

2361

40805015

????

7) Ohm’s law for a steady electrical current can be written as , where V = potential difference across a conductor, I= current in the conductor, R= resistance of the conductor. Write a program capable of filling in the blanks in the following table:

Case V (volts) I (Amps)R

(Ohms)123

10------

3

25

-----

----74

Print the complited table to the screen.

8) Write a program that is capable of displaying the distances from the sun to the four planets closest to the sun in centimeters and inches. The kilometer distances can be initialized in the source code. Print the result to the screen in the form of the following table:

Distance from the sunPlanet (million km) (cm) (inches)MercuryVenusEarthMars

58.0108.2149.5227.8

????

????

9) Write a program that prints out your course schedule for a single week. Here is an example of the output for one day:

MondayMondayMonday

9:0011:00

2:00

Computer science 101Physics 201Dance 153

Use named string constants whenever possible to avoid retyping any word or numbers. Be sure to include appropriate comments in your code.

125

Page 125: Informatics. Study Guide. Mathcad. Matlab. VC++

10) Write a program that prints out all six permutations of the ordering of the following three lines. Declare a named constant for each line and write an output statement for each permutation. Be sure to include appropriate comments in your code.I have not brought my golden ballI have not come to set you free,I have come to see you cry

11) Write a program that displays a checkerboard pattern made of stars and blanks, as shown.

A checkerboard is eight squares by eight squares. You should declare two named string constans representing the two different row patterns. Be sure to include appropriate comments in your code.

12) Write a program that prints out business card for yourself. A card should include your name, street

address, phone number(s), and email address. You also can make up a company name and put that on the card if you wish. Print the complited card to the screen.

13) The moon’s gravity is about 17 percent that of Earth’s. Write a program that displays a table that shows Earth pounds and their equivalent moon weight. Have the table run from 1, 25, 50 and 100 pounds.

14) A year on Jupiter (the time it takes for Jupiter to make one full circuit around the Sun) takes about 12 Earth years. Write a program that converts Jovian years to Earth years. Have the user specify the number of Jovian years. Allow fractional years.

15) Write a program that takes an integer as the number of minutes and outputs the total hours and minutes.

Time in minutesTime in hours and minutes

123min345min

1350min

???

16) Write a program that takes three double values x0, v0, and t and prints the value of x0 + v0*t + 1/2 gt^2, where g is the constant 9.800722 m/s^2.

Input values

* * * ** * * *

* * * ** * * *

* * * ** * * *

126

Page 126: Informatics. Study Guide. Mathcad. Matlab. VC++

x0v0t

1523

145

17) Write a program to print "HELLO" in big block letters where each letter is 7 characters high and 5 characters wide.

18) Write a program to calculate the volume of a sphere . Print

the result to the screen in the following manner:The volume of a sphere

r V2

3.51.07

???

19) Write a program that converts Celsius to Fahrenheit. The formula is

. Print the result to the screen in the following manner:

Celsius to Fahrenheit

Celsius Fahrenheit-17.8-1010

???

20) Write a program to print out the perimeter of a rectangle given its height and width. The formula is perimeter = 2 · (width + height). Print the result to the screen in the following manner:

The perimeter of a rectangle

Width Height Perimeter

3.042.911

107.63.4

???

21) Write a program that takes hours and minutes as input and outputs the total number of minutes.Print the result to the screen in the following manner:

Time in hours and minutes

Time in minutes

1h 35min5h 2min

12h 0min

???

127

Page 127: Informatics. Study Guide. Mathcad. Matlab. VC++

22) In many countries using the metric system, car fuel consumptions are measured in liters of fuel required to travel 100 kilometers. Write a program to evaluate the fuel consumption of a car. The mileage at the start and end of the journey should be defined, and also the fuel level in the tank at the start and end of the journey. Calculate fuel used, miles traveled, and hence the overall fuel consumption in miles traveled per gallon of fuel.

23) Write a program that converts Fahrenheit to Celsius. Use formula from the variant 19. Print the result to the screen in the following manner:

Fahrenheit to Celsius

Fahrenheit Celsius107.8

0-67

???

24) Write a program to calculate the expression . Print the result to the screen in the following manner:

x z Y32512.6

-2.3e-434.2f

-2476e+2

212

????

25) Write a program that displays a checkerboard pattern made of stars and blanks, as shown. *

* * ** * * * *

* * * * * * *You should declare several named string constans representing the different row patterns. Be sure to include appropriate comments in your code.

26) Write a program that displays a matrix, as shown.A1 B1 C1A2 B2 C2A3 B3 C3

For each row you should use named string constans.

27) Write a program that displays a matrix, as shown.a1 ……….. b1 ……….. c1.

128

Page 128: Informatics. Study Guide. Mathcad. Matlab. VC++

.a2 b2 c2..a3 b3 c3

28) Write a program to print "WORLD" in big block letters where each letter is 6 characters high and 4 characters wide.

29) Write a program to calculate the diagonal of a rectangular parallelepiped . Print the result to the screen in the following manner:

The diagonal of a rectangular parallelepipeda b c d

3.51.8

23.8

23.5

1.07

4.03

12.1

???

30) Write a program to calculate the altitudes of a right triangle .

Print the result to the screen in the view of complited table. (Use example of the table from the variant 29)

Laboratory work 13

Basic Input/Output.

Objective – to learn how to use the standard input and output library and interact with the user by printing messages on the screen and getting the user's input from the keyboard.

Problem statement – create a C++ project that uses abstraction called streams to perform input and output operations.

Theoretical information

Using the standard input and output library, user will be able to interact with another user by printing messages on the screen and getting the user's input from the keyboard.

In some languages (FORTRAN, Pascal, etc), the input and output routines are fixed in the language definition. C and C++ are more flexible. These languages assume only that the operating system can provide

129

Page 129: Informatics. Study Guide. Mathcad. Matlab. VC++

some primitive 'read' and 'write' functions that may be used to get bytes of data into or out from a program. More useful sets of i/o routines are then provided by libraries. Routines in these libraries will call the 'read' and 'write' routines but they will do a lot of additional work (e.g. converting sequences of digits into the appropriate bit pattern to represent a number).

Most C programs use an i/o library called stdio (for standard i/o). This library can be used in C++; but more often, C++ programs make use of an alternative library called iostream (i/o stream library).

The i/o stream library (iostream) makes use of some of the "object oriented" features of C++.

It uses "stream objects" to handle i/o. Now in general an object is something that "owns a resource and provides services related to that resource". A "stream object" owns a "stream", either an output stream or an input stream. An output stream is something that takes character data and gets them to an output device. An input stream gets data bytes from some input device and routes them to a program.

An ostream object owns an output stream. The "services" an ostream object provides include the following: an ostream object will take data from an integer variable and convert

it to digits (and ± sign if needed) and send these through its output stream to an output device;

similarly, an ostream object can take data from a "real number" variable and convert to a character sequence with sign character, digits, and decimal point (e.g. 3.142, -999.9, or it may use scientific notation and produce a character sequence like 1.70245E+43);

an ostream object can take a message string (some character data) and copy these characters to the output stream;

an ostream object can accept directions saying how many digits to show for a real number, how much space on a line to use, etc.

Istream objects. An istream object owns an input stream. The "services" an istream object provides include the following: an istream object can be asked to find a value for an integer

variable, it will check the input stream, miss out any blank space, read in a series of digits and work out the value of the number which it will then put into the variable specified;

similarly, an istream object can be asked to get a "real number" variable, in this case it will look for input patterns like 2.5, -7.9, or 0.6E-20 and sort them out to get the value for the number;

an istream object can be asked to read in a single character or a complete multicharacter message.

Error handling with input and output. It is unusual for an ostream object not to be able to deal with a request from a program. Something serious would have had to have gone wrong (e.g. the output is supposed

130

Page 130: Informatics. Study Guide. Mathcad. Matlab. VC++

to be being saved on a floppy disk and the disk is full). It is fairly common for an istream object to encounter problems. For example, the program might have asked for an integer value to be input, but when the istream object looks in the input stream it might not find any digits, instead finding some silly input entered by the user.

"end of file" condition. Another problem that an istream object might encounter is "end of file". Your program might be reading data from a file, and have some loop that says something like "istream object get the next integer from the file". But there may not be any more data in the file! In this case, the istream object would again put the value 0 in the variable, and record that it had failed because of end-of-file. A program can ask an istream object whether it has reached the end of its input file.

Standard streams. A program can use quite a large number of stream objects (the operating system may set a limit on the number of streams used simultaneously, 10, 16, 200 etc depends on the system). Streams can be attached to files so that you can read from a data file and write to an output file.

The iostream library sets up three standard streams: cin standard input stream (reads data typed at keyboard) cout prints results in an "output window" cerr prints error messages in an "output window" (often the

same window as used by cout); in principle, this allows the programmer to create error reports that are separate from the main output.

User does not have to 'declare' these streams, if its program says it wants to use the iostream library then the necessary declarations get included. User can create iostream objects that are attached to data files. Initially though, User will be using just the standard iostream objects: cout for output and cin for input.

Standard output. By default, the standard output of a program is the screen, and the C++ stream object defined to access it is cout, which is used in conjunction with the insertion operator, which is written as << (two “less than” signs).

cout << "Output sentence"; // prints Output sentence on screencout << 120; // prints number 120 on screencout << x; // prints the content of x on screen

The << operator inserts the data that follows it into the stream preceding it. In the examples above it inserted the constant string Output sentence, the numerical constant 120 and variable x into the standard output stream cout. Take note:

the sentence in the first instruction is enclosed between double quotes (") because it is a constant string of characters;

131

Page 131: Informatics. Study Guide. Mathcad. Matlab. VC++

whenever we want to use constant strings of characters we must enclose them between double quotes (") so that they can be clearly distinguished from variable names.

For example, these two sentences have very different results:cout << "Hello"; // prints Hellocout << Hello; // prints the content of Hello variable

The insertion operator (<<) may be used more than once in a single statement:

cout << "Hello, " << "I am " << "a C++ statement";This last statement would print the message Hello, I am a C++

statement on the screen. The utility of repeating the insertion operator (<<) is demonstrated when we want to print out a combination of variables and constants or more than one variable:cout << "Hello, I am " << age << " years old and my name is " << name;

It is important to notice that cout does not add a line break after its output unless we explicitly indicate it, therefore, the following statements:

cout << "This is a sentence.";cout << "This is another sentence.";

will be shown on the screen one following the other without any line break between them. Even though we had written them in two different insertions into cout. In order to perform a line break on the output we must explicitly insert a new-line character into cout. In C++ a new-line character can be specified as \n (backslash, n):

cout << "First sentence.\n ";cout << "Second sentence.\nThird sentence.";

To add a new-line, you may also use the endl manipulator. It produces a newline character, exactly as the insertion of '\n' does, but it also has an additional behavior when it is used with buffered streams: the buffer is flushed. Anyway, cout will be an unbuffered stream in most cases, so you can generally use both the \n escape character and the endl manipulator in order to specify a new line without any difference in its behavior.

Standard Input (cin). The standard input device is usually the keyboard. Handling the standard input in C++ is done by applying the overloaded operator of extraction (>>) on the cin stream. The operator must be followed by the variable that will store the data that is going to be extracted from the stream. For example:

int age;cin >> age;

The first statement declares a variable of type int called age, 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 RETURN key has been pressed. Therefore, even if you request

132

Page 132: Informatics. Study Guide. Mathcad. Matlab. VC++

a single character, the extraction from cin will not process the input until the user presses RETURN after the character has been introduced.

#include <iostream>using namespace std;int main(){int thisisanumber;cout<<"Please enter a number: ";cin>>thisisanumber;cin.ignore();cout<<"You entered: "<<thisisanumber <<"\n";cin.get();}

The keyword int declares thisisanumber to be an integer. The function cin>> reads a value into thisisanumber; the user must press enter before the number is read by the program. cin.ignore() is another function that reads and discards a character.

The lack of quotation marks informs the compiler that there is a variable, and therefore that the program should check the value of the variable in order to replace the variable name with the variable when executing the output function. Including multiple insertion operators on one line is acceptable as long as each insertion operator outputs a different piece of information; you must separate string literals (strings enclosed in quotation marks) and variables by giving each its own insertion operators (<<). Trying to put two variables together with only one << will give you an error message.

You must always consider the type of the variable that you are using as a container with cin extractions. If you request an integer you will get an integer, if you request a character you will get a character and if you request a string of characters you will get a string of characters.

#include <iostream>using namespace std;int main (){ int i; cout << "Please enter an integer value: "; cin >> i; cout << "The value you entered is " << i; cout << " and its double is " << i*2 << ".\n"; return 0;}

You can also use cin to request more than one datum input from the user: cin >> a >> b; is equivalent to: cin >> a; cin >> b;

133

Page 133: Informatics. Study Guide. Mathcad. Matlab. VC++

In both cases the user must give two data, one for variable a and another one for variable b that may be separated by any valid blank separator: a space, a tab character or a newline.

Cin and strings. We can use cin to get strings with the extraction operator (>>) as we do with fundamental data type variables:

cin >> mystring;cin extraction stops reading as soon as if finds any blank space character, so in this case we will be able to get just one word for each extraction. This behavior may or may not be what we want; for example if we want to get a sentence from the user, this extraction operation would not be useful.

In order to get entire lines, we can use the function getline, which is the more recommendable way to get user input with cin:

#include <iostream>#include <string>using namespace std;int main (){ string mystr; cout << "What's your name? "; getline (cin, mystr); cout << "Hello " << mystr << ".\n"; cout << "What is your favorite team? "; getline (cin, mystr); cout << "I like " << mystr << " too!\n"; return 0;}

What's your name? Anton BurkeHello Anton Burke.What is your favorite team? DolphinsI like Dolphins too!

Notice how in both calls to getline we used the same string identifier (mystr). What the program does in the second call is simply to replace the previous content by the new one that is introduced.

Choice of variable names. The C/C++ languages do not have any particular naming conventions. It canc be found useful to adopt some conventions. The use of consistent naming conventions will not make much difference until user get to write larger programs. Some suggestions: local variables and arguments for routines should have names like

aNum, or theQuotient; shared ("global") variables should have names that start with 'g', e.g.

gZeroPt; functions should have names that summarize what they do, use

multiple words (run together or separated by underscore characters _).Variable "definitions" and "declarations". There is a difference

between variable "definition" and "declaration". Basically, in C++ a

134

Page 134: Informatics. Study Guide. Mathcad. Matlab. VC++

declaration states that a variable or function exists, and will be defined somewhere (but not necessarily in the file where the declaration appears).

A definition of a function is its code; a definition of a variable identifies what storage it will be allocated (and may specify an initial value). Those were definitions because they also specified implicitly the storage that would be used for the variables (they were to be 'automatic' variables that would be stored in main's stack frame).

Sketch of code. The code consists mainly of i/o operations:int main(){long aNum1, aNum2, aQuotient, aRemainder;cout << "Enter two numbers" << endl;cin >> aNum1 >> aNum2;aQuotient = aNum1 / aNum2;aRemainder = aNum1 % aNum2;cout << "The quotient of " << aNum1 << " and "<< aNum2 << " is " << aQuotient << endl;cout << "and the remainder is " << aRemainder << endl;return 0;}

The next table explains the previous code.A part of the program’s code Explanation of code fragment.

int main(){…}

The definition of the main() routine starts with int main and ends with the final "}". The { } brackets are delimiters for a block of code.

long aNum1, aNum2, aQuotient, aRemainder;

Here the variables are defined; we want four long integers (long so that we can deal with numbers in the range ±2000million).

cout << "Enter two numbers" << endl;

This is the first request to the cout object, asking it to arrange the display of the prompt message.

cin >> aNum1 >> aNum2;This is a request to the cin object, asking it to read values for two long integers.

aQuotient = aNum1 / aNum2;aRemainder = aNum1 % aNum2;

These are the statements that do the calculations. In C/C++ the "/ operator" calculates the quotient, the "% operator" calculates the remainder for an integer division.

135

Page 135: Informatics. Study Guide. Mathcad. Matlab. VC++

cout << "The quotient of " << aNum1 << " and " << aNum2 << " is " << aQuotient << endl;cout << "and the remainder is " << aRemainder << endl;

These are the requests to cout asking it to get the results printed.

You should always complete a sketch of the code of an assignment before you come to the laboratory and start working on the computer!

Header file math.h. Contains function declarations for all the floating-point math functions. Next table shows basic math functions:

Function Usage Purposeacos double acos(double x); Compute arc cosine of x.asin double asin(double x); Compute arc sine of xatan double atan(double x); Compute arc tangent of x.atan2 double atan2(double y,

double x);Compute arc tangent of y/x, using the signs of both arguments to determine the quadrant of the return value.

ceil double ceil(double x); Get smallest integral value that exceeds x.

cos double cos(double x); Compute cosine of angle in radians.cosh double cosh(double x); Compute the hyperbolic cosine of x.exp double exp(double x); Compute exponential of xfabs double fabs (double x ); Compute absolute value of x.floor double floor(double x); Get largest integral value less than x.fmod double fmod(double x,

double y);Divide x by y with integral quotient and return remainder

log double log(double x); Compute log(x).log10 double log10 (double x ); Compute log to the base 10 of xpow double pow (double x,

double y);Compute x raised to the power y.

sin double sin(double x); Compute sine of angle in radianssinh double sinh(double x); Compute the hyperbolic sine of x.sqrt double sqrt(double x); Compute the square root of x.tan double tan(double x); Compute tangent of angle in radianstanh double tanh(double x); Compute the hyperbolic tangent of x.pow10 double pow10(int x); calculates 10 to the power of x

Next example shows how to calculate common arithmetic functions which are not directly supported by the language C++. For example the task is to calculate next expression :

#include "stdafx.h"#include <iostream>#include <math.h>using namespace std;

136

Page 136: Informatics. Study Guide. Mathcad. Matlab. VC++

int main () { double Y, x; cout<<"Enter value for input variable \n"; cin>>x; cin.get(); Y=abs(pow(sin(log10(x)),1/3))+3.2*pow(10.0,-2.3); cout<<"The result is "<<Y; cin.get();}

VariantsNote: All input values must be entered from the keyboard by the

user and a sensible input prompt and informative output should be included.

1) Write a program which reads values for two floats and outputs their sum, product and quotient.

2) Write a program that changes an integer number of centimetres into the equivalent in kilometres, metres and centimetres. For example 164375 centimetres is 1 kilometre, 643 metres and 75 centimetres. Include declarations of suitable variables.

3) Write a program to read in characters of different type (char, int, float, double, bool, string) and to print them out, each one on a separate line, enclosed in single quotation marks.

4) Write a program that converts a sum of money given as an integer number of pence into a floating point value representing the equivalent number of pounds. For example 365 pence would be 3.65 pounds.

5) Write a program which prompts the user to enter two integer values, a float value and two values of bool type and then prints out all five values that are entered with a suitable message.

6) Write a program which asks user to enter needed values and calculates the expression for the following mathematical formula:

Y= .

7) Write a program to evaluate the fuel consumption of a car. The mileage at the start and end of the journey should be read, and also the fuel level

137

Page 137: Informatics. Study Guide. Mathcad. Matlab. VC++

in the tank at the start and end of the journey. Calculate fuel used, miles traveled, and hence the overall fuel consumption in miles traveled per gallon of fuel.

8) Write a C++ program which asks user to enter needed values and calculates the expression for the following mathematical formula:

Y=

9) Write a program to convert currency from pounds sterling to deutsch marks. Read the quantity of money in pounds and pence, and output the resulting foreign currency in marks and pfennigs. (There are 100 pfennigs in a mark). Use a const to represent the conversion rate, which is 2.31DM to £1 at the time of writing. Be sure to print suitable headings and or labels for the values to be output.

10) Write a C++ program which will compute the area of a square () and a triangle ( ).

11) A customer's gas bill is calculated by adding a standard charge of 9.02 pence per day to the charge for gas, calculated as 1.433 pence per cubic meter. The whole bill is then liable for VAT at 8%. Write a program that reads the number of days, and the initial and final meter readings, and calculates and prints the bill. Use const for the various rates of charging.

12) Write a C++ program which will ask user to enter double figure and which will output:

– number of ten's place;– amount of digits in it;– summation of its digits.

Example: input: 123, output: 1) 12; 2) 3; 3) 6

13) Write a C++ program which will calculate Surface area (S= 4 Pi2Rr) and Volume (V= 2 Pi2Rr2) of the Circular (Ring Torus).

14) Write a C++ program which will ask user to enter rectangle with m and n sides and compute how many squares with side m can be placed in it.

15) Write a C++ program which will ask user to enter three figure and which will output:

– amount of digits in it– summation of its digits– product of its digits

138

Page 138: Informatics. Study Guide. Mathcad. Matlab. VC++

Example: input:123, output: 1) 3; 2) 6; 3) 6;

16) Write a C++ program which will ask user to enter three figures and which will output a number in which the first figure will be put after the third figure. Example: input: 123, output: 231.

17) Write a C++ program with a function which will ask user to enter four figures and which will output a number in which figures will be transposed. Example: input: 1234, output: 2143 or input: 7086, output: 768.

18) Write a C++ program which will ask user to enter natural number (n>9) and which will output an amount of ten's places. Example: input: 123456789, output: 9.

19) Write a program that computes the length of the fypotenuse of four right triangles based on the lengths of the two legs. (Use the thask 2 from the laboratory work 1).

20) Read in three integers of data type int from the keyboard. Then add the three numbers and devide received summation by the fourth number that was entered by the user.

21) Write a program that is capable of displaying the distances from the sun to the four planets closest to the sun in centimeters and inches. (Use the thask 8 from the laboratory work 1).

22) Write a program that prints out all six permutations of the three lines type into the screen. Declare a named constant for each line and write an output statement for each permutation. (Use the thask 10 from the laboratory work 1).

23) Write a program that prints out business card for yourself. A card should include your name, street address, phone number(s), and email address. Also make up a company name and put that on the card. Print the complited card to the screen.

24) Write a program that takes an integer as the number of minutes and outputs the total hours and minutes. (Use the thask 15 from the laboratory work 1).

25) Write a program with using the thask 18 from the laboratory work 1.

26) Write a program with using the thask 19 from the laboratory work 1.

139

Page 139: Informatics. Study Guide. Mathcad. Matlab. VC++

27) Write a program with using the thask 20 from the laboratory work 1.

28) Write a program which asks user to enter needed values and calculates the expression for the following mathematical formula:

Y=

29) Write a program that does the next: given as input three integers representing a date as day, month, year, print out the number day, month and year for the following day's date. Typical input: 28 2 1992 Typical output: Date following 28:02:1992 is 29:02:1992.

30) Write a program that creates a table of Olympic competition running distances in meters, kilometers, yards, and miles. The resul must be a table. (Use the task 1 from the laboratory work 1).

Laboratory work 14

Else-If conditional structure

Objective – understand how to program a single, dual alternative structures and nested conditional structures; to learn to rely on well-formed data for programs and be able to make one or two-way decisions with an if statement.

Problem statement – solve problem with using the conditional structure.

Theoretical information

A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose, C++ provides control structures that serve to specify what has to be done by our program, when and under which circumstances.

With the introduction of control structures we are going to have to introduce a new concept: the compound-statement or block. A block is a group of statements which are separated by semicolons (;) like all C++ statements, but grouped together in a block enclosed in braces: { }:

{ statement1; statement2; statement3; }

Most of the control structures that we will see in this section require a generic statement as part of its syntax. A statement can be either a

140

Page 140: Informatics. Study Guide. Mathcad. Matlab. VC++

simple statement (a simple instruction ending with a semicolon) or a compound statement (several instructions grouped in a block), like the one just described. In the case that we want the statement to be a simple statement, we do not need to enclose it in braces ({}). But in the case that we want the statement to be a compound statement it must be enclosed between braces ({}), forming a block.

Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=). When we want to modify the value of a variable by performing an operation on the value currently stored in that variable we can use compound assignment operators:

expression is equivalent tovalue += increase; value = value + increase;a -= 5; a = a - 5;a /= b; a = a / b;price *= units + 1; price = price * (units + 1);

and the same for all other operators. For example:

int main (){ int a, b=3; a = b; a+=2; // equivalent to a=a+2 cout << a; return 0;}Increase and decrease (++, --). Shortening even more some expressions, the

increase operator (++) and the decrease operator (--) increase or reduce by one the value stored in a variable. They are equivalent to +=1 and to -=1, respectively. Thus:

c++; c+=1; c=c+1;are all equivalent in its functionality: the three of them increase by one the value of c.

A characteristic of this operator is that it can be used both as a prefix and as a suffix. That means that it can be written either before the variable identifier (++a) or after it (a++). Although in simple expressions like a++ or ++a both have exactly the same meaning, in other expressions in which the result of the increase or decrease operation is evaluated as a value in an outer expression they may have an important difference in their meaning: In the case that the increase operator is used as a prefix (++a) the value is increased before the result of the expression is evaluated and therefore the increased value is considered in the outer expression; in case that it is used as a suffix (a++) the value stored in a is increased after being evaluated and therefore the value stored before the increase operation is evaluated in the outer expression. Notice the difference:

141

Page 141: Informatics. Study Guide. Mathcad. Matlab. VC++

Example 1 Example 2B=3;A=++B;// A contains 4, B contains 4

B=3;A=B++;// A contains 3, B contains 4

In Example 1, B is increased before its value is copied to A. While in Example 2, the value of B is copied to A and then B is increased.

Relational and equality operators ( ==, !=, >, <, >=, <= ). In order to evaluate a comparison between two expressions we can use the relational and equality operators. The result of a relational operation is a Boolean value that can only be true or false, according to its Boolean result. If user wants to compare two expressions, for example, to know if they are equal or if one is greater than the other is. Here is a list of the relational and equality operators that can be used in C++, suppose that a=2, b=3 and c=6:

== Equal to ((b=2) == a) // evaluates to true

!= Not equal to (3 != 2) // evaluates to true.

> Greater than(b+4 > a*c) // evaluates to false since (3+4 > 2*6) is false

< Less than (5 < 5) // evaluates to false.

>= Greater than or equal to (6 >= 6) // evaluates to true.

<= Less than or equal to(a*b <= c) // evaluates to true since (2*3 <= 6) is true

In the last expression ((b=2) == a), we first assigned the value 2 to b and then we compared it to a, that also stores the value 2, so the result of the operation is true.

Conditional structure: if and else. The if keyword is used to execute a statement or block only if a condition is fulfilled. Its form is:

if (condition) statement;

where condition is the expression that is being evaluated. If this condition is true, statement is executed. If it is false, statement is ignored (not executed) and the program continues right after this conditional structure.

For example, the following code fragment prints x is 100 only if the value stored in the x variable is indeed 100:

if (x == 100) cout << "x is 100";

If we want more than a single statement to be executed in case that the condition is true we can specify a block using braces { }:

if (x == 100){

142

Page 142: Informatics. Study Guide. Mathcad. Matlab. VC++

cout << "x is "; cout << x;}

We can additionally specify what we want to happen if the condition is not fulfilled by using the keyword else. Its form used in conjunction with if is:

if (condition) statement1; else statement2;

For example:if (x == 100) cout << "x is 100";else cout << "x is not 100";

prints on the screen x is 100 if indeed x has a value of 100, but if it has not -and only if not- it prints out x is not 100.

The if + else structures can be concatenated with the intention of verifying a range of values. The following example shows its use telling if the value currently stored in x is positive, negative or none of them (i.e. zero):

if (x > 0) cout << "x is positive";else if (x < 0) cout << "x is negative";else cout << "x is 0";

Remember: in case that user wants more than a single statement to be executed, he must group them in a block by enclosing them in braces { }.

The following example of a program is to find the roots of a quadratic equation.#include "stdafx.h"#include <iostream>#include <math.h>using namespace std;

int main(){

double a,b,c,discriminant;float x1,x2;cout<<"Enter the values of a,b,c:\n";cin>>a>>b>>c;discriminant=((b*b)-4*a*c);if(discriminant>0)

143

Page 143: Informatics. Study Guide. Mathcad. Matlab. VC++

{x1=(-1*b+sqrt(discriminant))/(2*a);x2=(-1*b-sqrt(discriminant))/(2*a);

}else if(discriminant==0)

{x1=x2=(-1*b)/(2*a);

}else{discriminant=-1*discriminant;cout<<"x1="<<"("<<(-1*b)<<"+

i"<<sqrt(discriminant)<<")/"<<2*a<<"\n";cout<<"x1="<<"("<<(-1*b)<<"+

i"<<sqrt(discriminant)<<")/"<<2*a;}

cout<<"x1 = "<<x1<<"\n";cout<<"x2 = "<<x2<<"\n";

cin.get();return 0;}

Program produces output as follows:Enter the values of a,b,c:9 4 -16x1 = 1.1295x2 = -1.57395

The following program demonstrates the if by playing a simple version of the “guess the magic number” game. The program generates a random number, prompts for your guess, and prints the message **Right** if you guess the magic number. This program also introduces another C++ library function, called rand( ), which returns a randomly selected integer value. It requires the <cstdlib> header.

#include <iostream>#include <cstdlib>using namespace std;

int main(){

int magic; // magic numberint guess; // user’s guessmagic = rand();cout<< “Enter your guess: ”;cin>> guess;

144

Page 144: Informatics. Study Guide. Mathcad. Matlab. VC++

if (guess == magic) cout << “** Right **”;return 0;

}This program uses the if statement to determine whether the user’s

guess matches the magic number. If it does, the message is printed on the screen. Taking the Magic Number program further, the next version uses the else to print a message when the wrong number is picked:

int main(){ ……..……..

if (guess == magic) cout << “** Right **”;else cout << “Sorry, you are wrong.”;

}Logical Expressions. It is possible to specify more complex

conditions than those which can be written using only the relational operators described above. Since the value of a condition has a numerical interpretation it could be operated on by the usual arithmetic operators, this is not to be recommended. There are explicit logical operators for combining the logical values true and false.

The simplest logical operator is not which is represented in C++ by !. It operates on a single operand, and returns false if its operand is true and true if its operand is false.

The operator and, represented by &&, takes two operands and is true only if both of the operands are true. If either operand is false, the resulting value is false.

or is the final logical operator and is represented by ||. It results in true if either of its operands is true. It returns false only if both its operands are false.

The logical operators can be defined by truth tables as follows. Note that F is used for false and T is used for true in these tables.

Not ! And && Or ||A !A A B A && B A B A || BF T F F F F F FT F F T F F T T

T F F T F TT T T T T T

These table shows that not reverses the truth value of the operand, that the and of two operands is only true if both operands are true and that the or of two operands is true if either or both of its operands are true. Using these logical operators more complex conditions can now be written.

If i has the value 15, and j has the value 10, then the expression (i > 10) && (j > 0) is evaluated by evaluating the relation i > 10 (which is true), then evaluating the relation j > 0 (which is also true), to give true. If j has

145

Page 145: Informatics. Study Guide. Mathcad. Matlab. VC++

the value -1 then the second relation would be false, so the overall expression would be false. If i has the value 5, then the first relation would be false and the expression will be false irrespective of the value of the second relation. C++ does not even evaluate the second relation in this situation. Similarly, if the first relation is true in an or (||) expression then the second relation will not be evaluated.

The following example program asks the user to enter coordinates and define whether this coordinate belong to the shaded area or not.

#include "stdafx.h"#include <iostream>#include <math.h>using namespace std;

void main(){ double x,y; cout<<"Enter a coordinate: "; cin>>x>>y; cin.get(); if((x*x+y*y<2*2)&&((y<1)&&(y>-1)&&(x<3)&&(x>-3))) cout<<"You are in the area.";

else cout<<"Sorry! Try again."; cin.get();}

Program produces output as follows:Enter a coordinate: 0 0 You are in the area.

Sometimes newcomers to C++ are confused by the fact that any valid C++ expression can be used to control the if. That is, the conditional expression need not be restricted to only those involving the relational and logical operators, or to operands of type bool. All that is required is that the controlling expression evaluate to either a true or false result. As you should recall from the previous module, a value of 0 is automatically converted into false, and all non-zero values are converted to true. Thus, any expression that results in a 0 or non-zero value can be used to control the if. For example, this program reads two integers from the keyboard and displays the quotient. To avoid a divide-by-zero error, an if statement, controlled by the second.

#include <iostream>using namespace std;

146

Page 146: Informatics. Study Guide. Mathcad. Matlab. VC++

int main(){

int a, b;cout<< “Enter numerator: ”;cin>> a;cout<< “Enter denominator: ”;cin>> b;if (b) cout << “Result : ” <<a / b << ‘\n’;else cout << “Cannot divide by zero. \n”;

return 0;}Here are two sample runs:Enter numerator: 12Enter denominator: 2Result: 6

Enter numerator: 12Enter denominator: 0Cannot divide by zero.

Notice that b (the divisor) is tested for zero using if(b). This approach works because when b is zero, the condition controlling the if is false and the else executes. Otherwise, the condition is true (non-zero) and the division takes place. It is not necessary to write this if as shown here:

if(b == 0) cout << a/Artifact << '\n'; This form of the statement is redundant and potentially inefficient.

Nested ifs. A nested if is an if statement that is the target of another if or else. Nested ifs are very common in programming. The main thing to remember about nested ifs in C++ is that an else statement always refers to the nearest if statement that is within the same block as the else and not already associated with an else. Here is an example:

if(i) { if(j) result = 1; if(k) result = 2; else result = 3; // this else is associated with if(k)}else result = 4; // this else is associated with if(i)As the comments indicate, the final else is not associated with if(j)

(even though it is the closest if without an else), because it is not in the same block. Rather, the final else is associated with if(i). The inner else is associated with if(k) because that is the nearest if. You can use a nested if to add a further improvement to the Magic Number program. This addition provides the player with feedback about a wrong guess. ……………………..int main(){

147

Page 147: Informatics. Study Guide. Mathcad. Matlab. VC++

………………….

if (guess == magic) {cout << “** Right **\n”;cout<< magic << “ is the magic number. \n”;

}else {

cout << “… Sorry, you are wrong.”;if (guess > magic) cout << “Your guess is too high. \n”;else cout << “Your guess is too low. \n”;

}

return 0;}

Variants

1) Write a program that reads characters from the keyboard until a $ is typed. Have the program count the number of periods. Report the total at the end of the program.

2) Write a C++ program which asks user to enter needed values and calculates the expression for the following mathematical formula:

Y= ;

Add a condition to the program: if are less then 0.

3) Write a C++ program which asks user to enter needed values and calculates the expression for the following mathematical formula:

Y= ;

Add a condition to the program: if are less then 0

4) A student is given a grade from `A' to `F' in a test. So averages can be calculated it is required to assign marks to these grades as follows, `A' is 10, `B' is 8, `C' is 6, `D' is 4, `E' is 2 and `F' is 0. In C++ what two methods are there of doing this? Which of these two methods would be better in this case? Write C++ program for the method you have chosen.

5) A student is given a grade from `A' to `F' in a test. It is required to assign marks to these grades as follows, `A' is 10, `B' is 8, `C' is 6, `D' is 4, `E' is 2 and `F' is 0.

148

Page 148: Informatics. Study Guide. Mathcad. Matlab. VC++

6) Write a complete program which reads floating point numbers from cin and computes two averages: the average of the negative numbers it reads and the average of the positive numbers it reads. For example, for input 9 -1 -1 -4 1 the positive average would be 5 (the sum of the positive numbers (9+1) divided by the number of positive numbers (2).

7) Write a program that asks the user to type strictly positive integer. When the user types a negative value the program write ERROR and ask for typing other value. When the user types 0 that means that the last value has been typed and the program must write the average of the strictly positive integers. If the number of typed values is zero the program writes 'NO AVERAGE'.

8) Request the user to type numbers, each time printing its triple, until the user enters -999.

9) Write a C++ program which asks user to enter needed values and calculates the expression for the following mathematical formula:

Y=

Add a condition to the program: if are less then 0.

10) Write a program that prints true if the double variables x and y are both strictly between 0 and 1 and false otherwise.

11) Write a program that asks the user to type an integer and writes "YOU WIN" if the value is between 56 and 78 (both included). In the other case it writes "YOU LOSE".

12) Write a complete working program that will ask for a person’s name and his/her game score. Then it will ask for a second person’s name and score. The program will print the winner’s name and also print by how many points that person won.

13) Write a program that will read in three integers: a, b and c. The output will always be the three numbers printed in order. For example, input is : 40, 20, 60 into a, b and c respectively, then output should be: b, a and c in that order, an output of 20, 40 and 60.

14) Percentage marks attained by a student in three exams are to be entered to a computer. An indication of Pass or Fail is given out after the three marks are entered. The criteria for passing are as follows: A student passes if all three examinations are passed. Additionally a student may

149

Page 149: Informatics. Study Guide. Mathcad. Matlab. VC++

pass if only one subject is failed and the overall average is greater than or equal to 50. The pass mark for an individual subject is 40. Write a C++ program to implement this task.

15) Write a C++ program which asks user to enter x and y numbers. Then user should enter one of the symbols: +, -, *, / and output should be the result of that operation.

16) Write a program that asks the user to type an integer between 0 and 20 (both included) and writes N+17. If someone types a wrong value, the program writes ERROR and he must type another value.

17) Write a program that will read a float and a character. The character could be d for deposit or w for withdrawal. Starting with a balance of zero, add the deposits and subtract the withdrawals until the balance becomes negative. Then print by how much the balance went negative. The sample input and output are given below.

18) Write a program that asks the user to type an integer N and that indicates if N is a prime number or not.

19) – 26) Write a program that asks the user to enter coordinates and define whether this coordinate belong to the shaded area or not.

19 20 21 22

23 24 25 26

27) – 30) Write a C++ program which will ask user to enter needed values and calculate y:

27 28

150

Page 150: Informatics. Study Guide. Mathcad. Matlab. VC++

29 30

Laboratory work 15

Iteration structures.

Objective – to learn to use loops for programs and be able to repeat statement while the condition set in expression is true.

Problem statement – solve problem with using the while loop, do-while loop and the for loop.

Theoretical information

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, to make a program to countdown using a while-loop user may use the next code:

#include <iostream>using namespace std;int main (){ int n; cout << "Enter the starting number: "; cin >> n; while (n>0) { cout << n << ", "; --n; } cout << "The End. \n"; return 0;}

151

Page 151: Informatics. Study Guide. Mathcad. Matlab. VC++

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.

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.

The next program illustrates the while in a short but sometimes fascinating program. Virtually all computers support an extended character set beyond that defined by ASCII. The extended characters, if they exist, often include special characters such as foreign language symbols and scientific notations. The ASCII characters use values that are less than 128. The extended character set begins at 128 and continues to 255. This program prints all characters between 32 (which is a space) and 255.

#include <iostream>using namespace std;int main (){unsigned char ch;ch = 32;while (ch) {

cout << ch;ch++;

} return 0;}

Examine the loop expression in the preceding program. Since ch is an unsigned character, it can only hold the values 0 through 255. When it holds the value 255 and is then incremented, its value will “wrap around” to zero. Therefore, the test for ch being zero serves as a convenient stopping condition.

As with the for loop, the while checks the conditional expression at the top of the loop, which means that the loop code may not execute at all. This eliminates the need to perform a separate test before the loop. The following program illustrates this characteristic of the while loop. It displays a line of periods. The number of periods displayed is equal to the value entered by the user. The program does not allow lines longer than 80

152

Page 152: Informatics. Study Guide. Mathcad. Matlab. VC++

characters. The test for a permissible number of periods is performed inside the loop’s conditional expression, not outside of it.

#include <iostream>using namespace std;int main (){ int len;

cout << “Enter length (1 to 79): ”; cin >> len;

while (len > 0 && len < 80) {cout << ‘ . ’;len – –;

}return 0;

}If len is out of range, then the while loop will not execute even once.

Otherwise, the loop executes until len reaches zero. There need not be any statements at all in the body of the while loop. Here is an example:

while(rand() != 100) ; This loop iterates until the random number generated by rand( ) equals 100.

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.

#include <iostream>using namespace std;int main (){ unsigned long n; do { cout << "Enter number (0 to end): "; cin >> n; cout << "You entered: " << n << "\n"; } 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 determined within the loop statement

153

Page 153: Informatics. Study Guide. Mathcad. Matlab. VC++

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.

Using a do-while loop, we can further improve the Magic Number program. This time, the program loops until you guess the number.

#include <iostream>#include <cstdlib>using namespace std;

int main(){

int magic; // magic numberint guess; // user’s guess

magic = rand(); // get a random numberdo {

cout << “Enter your guess: ”;cin >> guess;if (guess == magic) {

cout << “** Right **”;cout<< magic << “ is the magic number. \n”;

}else { cout << “… Sorry, you are wrong.”; if (guess > magic)

cout << “Your guess is too high. \n”; else cout << “Your guess is too low. \n”;}

} while (guess != magic); return 0;

}Here is a sample run:

Enter your guess: 10… Sorry, you are wrong. Your guess is too low.Enter your guess: 100… Sorry, you are wrong. Your guess is too high.Enter your guess: 50… Sorry, you are wrong. Your guess is too high.Enter your guess: 41“** Right ** 41 is the magic number.

The for loop. Its format is:

154

Page 154: Informatics. Study Guide. Mathcad. Matlab. VC++

for (initialization; condition; increase) statement;

its main function is to repeat statement while condition remains true, like the while loop. But in addition, the for 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:1. initialization is executed. Generally it is an initial value setting for a

counter variable. This is executed only once.2. condition is checked. If it is true the loop continues, otherwise the

loop ends and statement is skipped (not executed).3. statement is executed. As usual, it can be either a single statement

or a block enclosed in braces { }.4. 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:

#include <iostream>using namespace std;int main (){ for (int n=10; n>0; n--) { cout << n << ", "; } cout << "The End! \n"; return 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 a for 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:

for ( n=0, i=100 ; n!=i ; n++, i-- ){ // whatever here...}

155

Page 155: Informatics. Study Guide. Mathcad. Matlab. VC++

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.

Write a program that asks the user to enter m numbers and outputs the maximum value, and his index number.#include "stdafx.h"#include <iostream>using namespace std;

int main(){

int m, n, i=1, max=0, j=1;cout<<"How many numders do u need?: ";cin>>m;cout<<i<<": ";cin>>n; max=n;for(i=2;i<=m;i++){ cout<<i<<": ";

cin>>n;if (n>max) {max=n;j=i;}

}cout<<max<<" "<<j;cin.get();return 0;

}Program produces output as follows:

How many numders do u need?: 31: 342: 03: 5656 3

The following example program calculates values of the sin function. The for statement, which will be covered, repeats the statements after it. In this case, it takes values 0, 1, 2, ... 16.

#include "stdafx.h"

156

Page 156: Informatics. Study Guide. Mathcad. Matlab. VC++

#include <iostream>#include <math.h>using namespace std;

void main(){ double x; int i; for (i = 0; i <= 16; i++ ) { x = 0.1 * i; cout<<"if x = "<< x<<" then sin("<<x<<") = "<<sin(x); cout<< endl; cin.get(); }}

Program produces output as follows:if x = 0 then sin(0) = 0if x = 0.1 then sin(0.1) = 0.0998334…….if x = 1.6 then sin(1.6) = 0.999574

Loops with No Body. In C++, the body associated with a for loop can be empty. This is because the null statement is syntactically valid. Bodiless loops are often useful. For example, the following program uses one to sum the numbers from 1 to 10:

#include <iostream>#include <cstdlib>using namespace std;

int main(){

int i; int sum = 0;

for(i=1; i <= 10; sun += i++) ;cout<< “Sum is: ” << sum;return 0;}

The output from the program is shown here:Sum is 55

Notice that the summation process is handled entirely within the for statement and no body is needed. Pay special attention to the increment expression: sum += i++.

157

Page 157: Informatics. Study Guide. Mathcad. Matlab. VC++

Don’t be intimidated by statements like this. They are common in professionally written C++ programs and are easy to understand if you break them down into their parts. In words, this statement says, “add to sum the value of sum plus i, then increment i.” Thus, it is the same as this sequence of statements: sum = sum + i; i++.

Variants

1) The moon’s gravity is about 17 percent that of Earth’s. Write a program that displays a table that shows Earth pounds and their equivalent moon weight. Have the table run from 1 to 100 pounds. Output a newline every 25 pounds.

2) The increment expression in a for loop need not always alter the loop control variable by a fixed amount. Instead, the loop control variable can change in any arbitrary way. Using this concept, write a program that uses a for loop to generate and display the progression 1, 2, 4, 8, 16, 32, and so on.

3) Write a program that reads characters from the keyboard until a $ is typed. Have the program count the number of periods. Report the total at the end of the program.

4) Write C++ statements using a while statement to print n asterisks at the beginning of a new line.

5) Write C++ statements using a while statement to evaluate n!, i.e. 1*2*3*...*n, 0! is 1

6) Write a program that will add up all the integers from 1 to the integer that was scanned into the variable j. Store the sum in the variable called sum and use i to increment the integers from 1 to j. Print only sum. For example, if 5 were read into j, then sum would be 1 + 2 + 3 + 4 + 5 or 15. A sample output is given below. ---------Output----------------

Give an integer: 6Sum of integers from 1 to 6 is 24.

7) Write a program that asks the user to type all the integers between 8 and 23 (both included) using a for loop.

8) Using the following for loop: for(i=1; i <= count; i = i + 1). Write a program that will first read the variable count as a data item, read in that many more data items and print their total. For example, if the data were

158

Page 158: Informatics. Study Guide. Mathcad. Matlab. VC++

3, 40, 20, 50, and 10; count would become 3 and the sum of the next 3 data items would be calculated as 110.

9) Write a program that asks the user to type all the integers between 8 and 23 (both included) using a while loop.

10) Write a program that asks the user to type the value of N and computes N! with using for loop.

11) Write a program that asks the user to type an integer N and computes the sum of the cubes from 53 to N3.

12) Write a program that asks the user to type 10 integers and write the number of occurrence of the biggest value.

13) Write a program to produce the sum of the series where n is entered by the user.

14) Write a program to produce the sum of the series where n is entered by the user.

15) Write a program that will ask the user to give three integers. Call these integers start, step_by and stop. After these three integers are scanned in, set up the for loop that will start i at the value of start, make it increase by the value given by step_by and make it stop at the value stored in stop. Print these values as shown in the following output sample. -----------Output---------------Enter three integers: 23 3 3223 26 29 32

16) Using the following for loop: for(int i=1; i <= count; i++).  Write a program that will first read the variable count as a data item, read in that many more data items and print their total. For example, if the data were 3, 40, 20, 50, and 10; count would become 3 and the sum of the next 3 data items would be calculated as 110.

17) Write a program that asks the user to enter value for n and finds value of expression 1*1+2*2+...+n*n.

159

Page 159: Informatics. Study Guide. Mathcad. Matlab. VC++

18) Write a program that asks the user to enter value for n and finds value of expression 1+2+...+n.

19) Write a program that asks the user to type n integers and prints out a number of negative numbers and all of the –ve no. on the next line.

20) Write a program to read in numbers until the number -999 is encountered. The sum of all number read until this point should be printed out.

21) Read a positive integer value, and compute the following sequence: If the number is even, halve it; if it's odd, multiply by 3 and add 1. Repeat this process until the value is 1, printing out each value. Finally print out how many of these operations you performed.

22) Write a program that prints out the multiplication table for a value n. -----------Output---------------Enter a value: 51*5 = 52*5 = 10……..9*5 = 45

23) Write a program that: 1) prints out the column for values from 20 to 35 (20 and 35 are included); 2) prints out the column for squares numbers of all integers from 10 to b ( ).

24) Write a program that: 1) prints out the column of theird power for values from a to 50 (a is printed from the keyboard, ); 2) prints out the column for all integers from c to b (c and b are entered from the keyboard).

25) Write a program that prints out the column of numbers as following:a) b)10 10.4 25 25.5 24.811 11.4 26 26.5 25.8.......… ………….25 25.4 35 35.5 34.8

26) Write a program that prints out the column of numbers as following:a) b)21 19.2 45 44.5 44.2

160

Page 160: Informatics. Study Guide. Mathcad. Matlab. VC++

20 18.2 44 43.5 43.2.......… ………….10 8.2 25 24.5 24.2

27) One item of a thing costs 30$. Write a program that prints out the cost’s column for 2, 3,…,20 items.

28) Write a program that converts a sum of money given as an integer number of pence into a floating point value representing the equivalent number of pounds. Print out the column of numbers for 4 to 20 (365 pence would be 3.65 pounds).

29) Write a program that prints out the column of converts a sum of money given as an integer number of dollars into grivnas. Currency converter must be entered from the keyboard.

30) Write a program that calculates y expression for x (x=4, 5,…,28):.

Laboratory work 16

Control Structures.

Objective – to learn to be able to make one or two-way decisions with through multiple possible paths by using a switch statement.

Problem statement – solve problem with using the multi-branching switch statement.

Theoretical information

The goto statement. goto allows to make an absolute jump to another point in the program. You should use this feature with caution since its execution causes an unconditional jump ignoring any type of nesting limitations.

In order to use the goto statement, insert a name on a particular section of your function so you can refer to that name. The name, also called a label, is made of one word and follows the rules we have learned about C++ names (the name can be anything), then followed by a colon. The following program uses a for loop to count from 0 to 12, but when it encounters 5, it jumps to a designated section of the program:

#include <iostream>

161

Page 161: Informatics. Study Guide. Mathcad. Matlab. VC++

using namespace std;

int main(){

for(int Count = 0; Count <= 12; ++Count){

cout << "Count " << Count << endl; if( Count == 5 )

goto MamaMia;}

MamaMia:cout << "Stopped at 5";return 0;

}The break statement. Using break we can leave a loop even if the

condition for its end is not fulfilled. It can be used to end an infinite loop, or to force it to end before its natural end. For example, we are going to stop the count down before its natural end:

int main (){ int n; for (n=10; n>0; n--) { cout << n << ", "; if (n==3) { cout << "countdown aborted!"; break; } } return 0;}

The following program would display the letter d continuously unless something or somebody stops it. A break statement is inserted to stop this ever looping process:#include <iostream>using namespace std;

int main(){

char Letter = 'd';while( Letter <= 'n' ){

162

Page 162: Informatics. Study Guide. Mathcad. Matlab. VC++

cout << "Letter " << Letter << endl;break;

}return 0;

}The continue statement. The continue statement causes the

program to skip the rest of the loop in the current iteration as if the end of the statement block had been reached, causing it to jump to the start of the following iteration. For example, we are going to skip the number 5 in our countdown:

int main (){ for (int n=10; n>0; n--) { if (n==5) continue; cout << n << ", "; } cout << "The End!\n"; return 0;}

The result will be: 10, 9, 8, 7, 6, 4, 3, 2, 1, The End!

The selective structure: switch. The syntax of the switch statement is a bit peculiar. Its objective is to check several possible constant values for an expression. Something similar to what we did at the beginning of this section with the concatenation of several if and else if instructions. Its form is the following:

switch (expression){ case constant1: group of statements 1; break; case constant2: group of statements 2; break; …………….. default: default group of statements}

It works in the following way: switch evaluates expression and checks if it is equivalent to constant1, if it is, it executes group of statements 1 until it finds the break statement. When it finds this break statement the program jumps to the end of the switch selective structure.

163

Page 163: Informatics. Study Guide. Mathcad. Matlab. VC++

If expression was not equal to constant1 it will be checked against constant2. If it is equal to this, it will execute group of statements 2 until a break keyword is found, and then will jump to the end of the switch selective structure.

Finally, if the value of expression did not match any of the previously specified constants (you can include as many case labels as values you want to check), the program will execute the statements included after the default: label, if it exists (since it is optional).

For example, if we did not include a break statement after the first group for case one, the program will not automatically jump to the end of the switch selective block and it would continue executing the rest of statements until it reaches either a break instruction or the end of the switch selective block. This makes unnecessary to include braces { } surrounding the statements for each of the cases, and it can also be useful to execute the same block of instructions for different possible values for the expression being evaluated. For example:

switch (x) { case 1: case 2: case 3: cout << "x is 1, 2 or 3"; break; default: cout << "x is not 1, 2 nor 3"; }

Notice that switch can only be used to compare an expression against constants. Therefore we cannot put variables as labels (for example case n: where n is a variable) or ranges (case (1..3):) because they are not valid C++ constants.

If you need to check ranges or values that are not constants, use a concatenation of if and else if statements.

Even when using the break statement, the switch allows many case to execute as one. To do this, type two cases together. This technique is useful when validating letters because the letters could be in uppercase or lowercase. This illustrated in the following program:

#include "stdafx.h"#include <iostream>using namespace std;

int main(){ char Letter;

164

Page 164: Informatics. Study Guide. Mathcad. Matlab. VC++

cout << "Type a letter: "; cin >> Letter; switch( Letter )

{case 'a':case 'A':case 'e':case 'E':case 'i':case 'I':case 'o':case 'O':case 'u':case 'U':

cout << "The letter you typed, " << Letter << ", is a vowel\n";break;

case 'b':case 'c':case 'd':case 'f':case 'g':case 'h':case 'j':case 'k':case 'l':case 'm':case 'n':case 'p':case 'q':case 'r':case 's':case 't':case 'v':case 'w':case 'x':case 'y':case 'z':

cout << Letter << " is a lowercase consonant\n";break;

case 'B':case 'C':case 'D':case 'F':case 'G':case 'H':case 'J':case 'K':case 'L':case 'M':case 'N':case 'P':case 'Q':case 'R':case 'S':case 'T':case 'V':case 'W':case 'X':case 'Y':case 'Z':

cout << Letter << " is a consonant in uppercase\n";break;

default:cout << "The symbol " << Letter << " is not an alphabetical letter\n";} cin.get();return 0;

}

Variants

1) A student has a percentage mark for an examination, these marks are to be converted to grades as follows: >=70 `A', 60-69 `B', 50-59 `C', 40-49 `D', 30-39 `E', <30 `F'Write a C++ program. Use a switch statement to directly assign the appropriate grade given a percentage mark.

165

Page 165: Informatics. Study Guide. Mathcad. Matlab. VC++

2) A student is given a grade from `A' to `F' in a test. It is required to assign marks to these grades as follows, `A' is 10, `B' is 8, `C' is 6, `D' is 4, `E' is 2 and `F' is 0.

3) Using operator case, write a C++ program. Input data should be typed from the keyboard. Find the reminder after division a by 3. Calculate y:

4) Write a program that is able to compute some operations on an integer. The program writes the value of the integer and writes the following menu :

1. Add 12. Multiply by 23. Subtract 44. Quit

The programs ask the user to type a value between 1 and 4. If the user types a value from 1 to 3 the operation is computed, the integer is written and the menu is displayed again. If the user types 4, the program quits.

5) Write a C++ program which asks user to enter x and y numbers. Then user should enter one of the symbols: +, -, *, / and output should be the result of that operation.

6) Read an integer value (m, ). Assume it is the number of a month of the year; print out the name of that month.

7) Read an integer value (w, ). Assume it is the number of a day of the week; print out the name of that month.

8) Read an integer value (s, ). Assume it is the number of a season of the year; print out the name of that season.

9) Using operator case, write a C++ program. Input data should be typed from the keyboard. Calculate total area of geometric figure.

10) Read an integer value (d, ). Assume it is the number of a month of the year; print out the number of days of that month.

11) Write a program that reads from the screen the first letter of the day of the week and prints out the name of that day.

166

Page 166: Informatics. Study Guide. Mathcad. Matlab. VC++

12) Write a program that reads from the screen the first letter of the month of the year and prints out the name of that month.

13) Write a program that performs the next: if the value of letter (that was printed be the user) is 'A', 'E', 'I', 'O' or 'U' then numberofvowels is incremented. If the value of letter is ' ' (a space) then numberofspaces is incremented. If none of these is true then the default condition is executed, that is numberofconstants is incremented.

14) Using operator case, write a C++ program. Input data should be typed from the keyboard. You have sequence of symbols: 'a', 'b', 'c', 'd', 'e', 'v', 'x', '.', ',', ':'. To classify this symbols as:

- vowels;- consonant;- punctuation marks.

Type a symbol from the keyboard. Display symbol and his group.

15) Write a C++ program which should classify symbol as:- Latin letter;- a number;- a bracket.

16) Write a C++ program where user should enter coordinates and as a result program will analyze a location on the plane and show a massage: “coordinate point is in 1st quarter (X and Y - positive)”, … 'coordinate point is in 4th quarter (X and Y - negative)', ' coordinate point is on X axis', etc.

17) Write a C++ program which will ask user to enter a number, for example ‘244’ and which will output a text ‘two four four’.

18) Write a program that asks the user to type a name and prints out person’s detail (cell number, address, and nickname). Provide the information about 5 different people.

19) Write a program that has your scheduale for a day. It should ask user for typing in the time of the day and prints out particular note. Prepare additional condition for time that is not in the list.

20) Write a program that asks user for typing in a name of a student and prints out the debts for particular one. Prepare additional condition for names that are not in the list.

167

Page 167: Informatics. Study Guide. Mathcad. Matlab. VC++

21) Using operator case, write a C++ program. Input data should be typed from the keyboard. Where ;

22) Write a program that prints the insurance fee to pay for a pet according to the following rules:

A dog that has been neutered costs $50. A dog that has not been neutered costs $80. A cat that has been neutered costs $40. A cat that has not been neutered costs $60. A bird or reptile costs nothing.Any other animal generates an error message. The program should prompt the user for the appropriate

information, using a code to determine the kind of animal (i.e. D or d represents a dog, C or c represents a cat, B or b represents a bird, R or r represents a reptile, and anything else represents some other kind of animal). After printing the insurance fee, the program should ask the user if (s)he wants to insure another animal. 23) Write a C++ program which will ask user to enter a text, for example ‘four two three’ and which will output a number ‘423’.

24) A company pays employees on different schedules. All employees are paid an annual salary. Type 0 employees get paid every week. Type 1 employees are paid twice a month. Type 2 employees are paid once a month.. Write a program that calculates the base pay for each employee.

25) Write a program that calculates how much money (tips) you may give for the service. 20% of the food cost for a good service; 15% of the food cost for a bad service.

26) Write a program that uses a switch statement to examine the number of days for months containing less than 31 days.

27) Write a program that asks the user to enter the number of a month of the year and the year. For example, if the user wants to enter June, 2005, he/she would enter 6 and then enter 2005. The program should then display the number of days in that month. Be sure to take leap years into account.

28) Write a program to help balance user’s money market checking account. The program should begin by asking the user for the month's opening account balance. Then the program should display a menu that

168

Page 168: Informatics. Study Guide. Mathcad. Matlab. VC++

lists the following choices: D for a deposit, C for a check, W for a withdrawal, and Q for quit. If the user selects D, ask the user to enter the amount of the deposit, and add the amount to the account balance. If the user enters C, ask the user for the amount of the check, and subtract the check amount from the balance. If the user enters W, ask the user for the amount of the withdrawal, and subtract the amount from the balance. When the user enters Q, the program should display the opening balance, the total amount deposited, the total amount withdrawn, the total amount of the checks, and the final balance. If the user enters something other than D, W, C, or Q, the program should issue an error message and redisplay the menu. Allow the user to enter either uppercase or lowercase letters.

29) A commodities broker requires a program to calculate brokerage commissions. Write a program that asks the user if the transaction was a sale or a purchase and then asks for the amount of the transaction. The program should then ask the user where the transaction was made. The user should enter E for the Commodity Exchange, C for the New York Cotton Exchange, or M for the Mercantile Exchange. If the amount was a sale, and was made at the Commodity Exchange, the commission rate is 5.0% of the amount. If a sale is made at the New York Cotton Exchange, the commission rate is 3.7% of the amount. If a sale is made at the Mercantile Exchange, the commission rate is 4.2% of the amount. If the transaction was a purchase at the Commodity Exchange, the rate commission is 6.3% of the amount. If a purchase is made at the Cotton Exchange, the commission rate is 4.3% of the amount. If a purchase is made at the Mercantile Exchange, the commission rate is 5.7% of the amount. The program should process any number of transactions.

30) Your city's Parking Violation Bureau wants you to write a program to compute fines for parking violations. There are four types of violation: type A carries a fine of $10, type B carries a fine of $20, type C carries a fine of $30, and type D carries a fine of $50. The program should ask for the number of type A violations, the number of type B violations, and so on. If the number of type A, B, or C violations exceeds 10, impose an additional fine of $50 for each category that exceeds 10. If the total number of type A, B, or C exceeds 20 but none of types A, B, or C individually exceeds 10, impose an additional fine of $75. If the number of type D violations exceeds three, impose an additional fine of $20 for each type D violation over three. The program should display the total fine for the person. The program should process any number of persons.

Laboratory work 17

169

Page 169: Informatics. Study Guide. Mathcad. Matlab. VC++

User-defined functions in C++

Objective – to decrease the complexity of a piece of code, and allow the programmer to reuse specific functions, rather than constantly repeating the same block of code performing a specific operation.

Problem statement – to learn how to devide a program into functions and build structured programs.

Theoretical information

The general form of a function definition in C++ is as follows:

function-type function-name( parameter-list ) { local-definitions; function-implementation; }

If the function returns a value then the type of that value must be specified in function-type. For the moment this could be int, float or char. If the function does not return a value then the function-type must be void.

The parameter-list lists the formal parameters of the function together with their types.

The local-definitions are definitions of variables that are used in the function-implementation. These variables have no meaning outside the function.

The function-implementation consists of C++ executable statements that implement the effect of the function.С++ allows programmers to define their own functions. The first function example:

#include <iostream>using namespace std;int addition (int a, int b){ int r; r=a+b; return (r);}

int main (){ int z;

170

Page 170: Informatics. Study Guide. Mathcad. Matlab. VC++

z = addition (5,3); cout << "The result is " << z; return 0;}

The main function begins by declaring the variable z of type int. Right after that, goes a call to a function called addition. Paying attention you 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 addition passing 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 function addition. 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 r the 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 it 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;

171

Page 171: Informatics. Study Guide. Mathcad. Matlab. VC++

That, as you may already expect, produces the printing of the result on the screen.

Scope of variables. The scope of variables declared within a function or any other inner block is only their own function or their own block and cannot be used outside of them. For example, in the previous example it would have been impossible to use the variables a, b or r directly in function main since they were variables local to function addition. Also, it would have been impossible to use the variable z directly within function addition, since this was a variable local to the function main.

Therefore, the scope of local variables is limited to the same block level in which they are declared. Nevertheless, we also have the possibility to declare global variables; These are visible from any point of the code, inside and outside all functions. In order to declare global variables you simply have to declare the variable outside any function or block; that means, directly in the body of the program.

Functions with no parameters. Functions with no parameters are of limited use. Usually they will not return a value but carry out some operation. For example consider the following function which skips three lines on output.

#include <iostream>using namespace std;

void skipthree(void); // Function prototypes

172

Page 172: Informatics. Study Guide. Mathcad. Matlab. VC++

void main(){ // Test function skipthree() cout << "Testing function skipthree()"<< endl; skipthree(); cout << "Tested" << endl;} // End of main// Function Definitionsvoid skipthree(void) // skips three lines on output { cout << endl << endl << endl; }

Note that the function-type has been given as void, this tells the compiler that this function does not return any value. Because the function does not take any parameters the parameter-list is empty, this is indicated by the void parameter-list. No local variables are required by this function and the function implementation only requires the sending of three successive end of line characters to the output stream cout.

Functions with parameters and no return value. Function should have an input parameter which indicates how many lines should be skipped. The function skipthree() is now changed to the function skip which has a parameter n indicating how many lines have to be skipped as follows:

void skip(int n) // Function skips n lines on output { int i; // a local variable to this function for (i = 0; i < n; i++) // loop n times cout << endl; }

Now function takes an integer parameter n which indicates the number of lines to be skipped. The parameter list then consists of a type and a name for this formal parameter. Inside the body of the function (enclosed in {}) a loop control variable i is declared. This variable is a local variable to the function. A local variable defined within the body of the function has no meaning, or value, except within the body of the function. It can use an identifier name that is used elsewhere in the program without there being any confusion with that variable. The function is called in the same manner as skipthree() above, but a value must be given for the parameter n.

In writing the function prototype for a function with parameters it is not necessary to detail the formal names given to the parameters of the function, only their types. Thus a suitable function prototype for the

173

Page 173: Informatics. Study Guide. Mathcad. Matlab. VC++

parameterised version of skip would be: void skip(int); // function prototype.

Functions that return values. One of the most useful forms of function is one that returns a value that is a function of its parameters. In this case the type given to the function is that of the value to be returned. Thus consider the function, which given the co-ordinates of a point (x,y) will return its distance from the origin:#include <iostream>#include <math.h>using namespace std;

float distance(float,float); // Function prototypes

void main(){ float x,y,dist;

// Test function distance(x,y) cout << "Testing function distance(x,y)"<< endl; cout << "Enter values for x and y: "; cin >> x >> y; dist = distance(x,y); cout << "Distance of (" << x << ',' << y << ") from origin is " << dist << endl << "Tested"<< endl;} // End of main function

// Function Definitionsfloat distance(float x, float y) // Returns the distance of (x, y) from origin { float dist; //local variable dist = sqrt(x * x + y * y); return dist; }

The distance function has two input parameters, real values x and y, and returns the distance of the point (x,y) from the origin. In the function a local variable dist is used to temporarily hold the calculated value inside the function.

The function prototype for this function is: float distance(float, float); – function prototype. This function introduces several new features. Note the following:

The function has been given the type float because it is going to return a float value.

174

Page 174: Informatics. Study Guide. Mathcad. Matlab. VC++

The parameter-list now has two parameters, namely, x and y. Each parameter is declared by giving its type and name and successive parameter declarations are separated by a comma.

A local variable dist has been declared to temporarily hold the calculated distance.

Because this function returns a value it includes a return statement which returns the value. In a statement return value the value may be a constant, a variable or an expression. The use of the local variable dist was not essential since the return statement could have been written: return sqrt(x*x + y*y);

When the function is called the formal parameters x and y are replaced by actual parameters of type float and in the same order, i.e. the x co-ordinate first. Since the function returns a value it can only be used in an expression.

The following examples of the use of the above function in a program in which it is declared:

float a, b, c, d, x, y;a = 3.0;b = 4.4;c = 5.1;d = 2.6;

x = distance(a, b);y = distance(c, d);

if (distance(4.1, 6.7) > distance(x, y)) cout << "Message 1" << endl;

A function may have several return statements. This is illustrated in the following function which implements the algorithm for evaluating the square root previously considered. Function returns square root of x. If x is negative it returns zero.

float mysqrt(float x){ const float tol = 1.0e-7; // 7 significant figures float xold, xnew; // local variables if (x <= 0.0) return 0.0; // covers -ve and zero case else { xold = x; // x as first approx xnew = 0.5 * (xold + x / xold); // better approx while (fabs((xold-xnew)/xnew) > tol) { xold = xnew; xnew = 0.5 * (xold + x / xold); } return xnew; // must return float value

175

Page 175: Informatics. Study Guide. Mathcad. Matlab. VC++

} } // end mysqrt

If the function has type void then it must not return a value. If a void function does return a value then most compilers will issue some form of warning message that a return value is not expected.

Next function raises a number to the power. The function returns the value of its first parameter raised to the power of its second parameter. The second parameter is an integer, but may be 0 or negative.

#include <iostream.h>float power(float,int); // Function prototype

void main(){ int n; float x, y; // Testing function power(x,n) cout << "Testing function power(n)" << endl; cout << "Enter values for x and n: "; cin >> x >> n; y = power(x,n); cout << x << " to the power " << n<< " is " << y<< endl; y = power(x,-n); cout << x << " to the power " << -n<< " is " << y<< endl; cout << "Tested"<< endl;} // End of main

// Function Definitionfloat power(float x, int n){ float product = 1.0; int absn, i; if ( n == 0) return 1.0; else { absn = int(fabs(n)); for (i = 1; i <= absn; i++)

product *= x; if (n < 0) return 1.0 / product; else return product; }} // end of power

176

Page 176: Informatics. Study Guide. Mathcad. Matlab. VC++

Variants

Task 1. Use the task from the laboratory work №2 (from the VC++ section). Write a function according to your task.

Task 2. Execute the problem given in the next task.

1) Write a function max3() that takes three int values as arguments and returns the value of the largest one. Add an overloaded function that does the same thing with three double values.

2) Write a driver program which uses the function to output an m x n block of asterisks, m and n entered by the user. 3) Write a program that asks the user to type the value of N and computes N! . It’s needed to use function prototype.

4) Write a C++ program with a function int equals(int,int) which checks whether two integer numbers are the same. In this case the return value should be 1 otherwise 0.

5) Write a program for a function that takes two parameters of type float and returns true (1) if the first parameter is greater than the second and otherwise returns false (0).

6) Write a program MaxMin.cpp that reads in integers (as many as the user enters) from standard input and prints out the maximum and minimum values read in.

7) Write a program with GeometricMean function that reads in positive real numbers from standard input and prints out their geometric mean. The geometric mean of N positive numbers x1, x2, ..., xN is (x1 * x2 * ... * xN)1/N

8) Write a C++ program with using function prototype. Input data should be typed from the keyboard.

9) Write a program with Pnorm function that takes a command-line argument p, reads in real numbers from standard input, and prints out their p-norm. The p-norm norm of a vector (x1, ..., xN) is defined to be the pth root of (|x1|p + |x2|p + ... + |xN|p).

177

Page 177: Informatics. Study Guide. Mathcad. Matlab. VC++

10) Write a program with HarmonicMean function that reads in positive real numbers from standard input and prints out their harmonic mean. The harmonic mean of N positive numbers x1, x2, ..., xN is (1/x1 + 1/x2 + ... + 1/xN) / (1 / N).

11) Write a program that calculates the mileage you get on your car. The program should ask the user for the number of miles traveled and the number of gallons consumed. Use the function Mileage() to calculate the mileage. Mileage() should take two argumentsthe number of miles traveled and the number of gallons consumed. The function should return the mileage. The program should then display the mileage.

12) Write a program that computes the cost of a taxi cab ride. A taxi charges a fixed charge of $2.50 plus an additional charge of $5.50 per mile. The program should ask the user to enter the length of the trip in miles. The program should use the function Taxi_Charge() to calculate the fare. Taxi_Charge() should have one argument, the length of the trip, and should return the total fare for the ride. The program should display the total fare.

13) Write a program that asks the user to input a grade that he or she received on an exam. The grade is an integer from 0 to 100 inclusive. The program should convert the numeric grade into the equivalent letter grade. Do the conversion by using a function Letter_Grade() that converts a numeric grade in the range 0100 to the equivalent letter grade. The function should have one parameter, the integer grade. The return value of the function should be A if the grade is 90 to 100; B if the grade is 80 to 89; C if the grade is 70 to 79; D if the grade is 65 to 69; and F if the grade is 64 or lower. After converting the grade, the program should display the numeric grade and the equivalent letter grade.

14) – 16) Write a C++ program with AREA function which will ask user to enter coordinates and define whether this coordinate belong to the shaded area or not.

14 15 16

178

Page 178: Informatics. Study Guide. Mathcad. Matlab. VC++

17) You have a,b,c numbers. Write a program with TRIANGLE function which will define whether you can build a triangle with a,b,c sides or not.

18) The factorial n! of a positive integer n is defined as n! = 1*2*3 . . . * (n-1) * n,

Where 0! = 1. Write a function to calculate the factorial of a number.

19) Write a function power(double base, int exp) to calculate integral powers of floating-point numbers. The power x0 is defined as 1.0 for a

given number x. The power is defined as for a negative exponent

n.The power where n > 0 will always yield 0.0 .

20) Write a program that repeatedly asks the user to enter pairs of numbers until at least one of the pair is 0. For each pair, the program should use a function to calculate the harmonic mean of the numbers. The function should return the answer to main(), which should report the result. The harmonic mean of the numbers is the inverse of the average of the inverses and can be calculated as follows:

harmonic mean = 2.0 . x . y / (x + y)

21) The trigonometry functions (sin(), cos(), and tan()) in the standard <math.h> library take arguments in radians. Write three equivalent functions, called sind(), cosd(), and tand(), which take arguments in degrees. All arguments and return values should be type double.

22) Write a program that reads a number (an integer) and a name (less than 15 characters) from the keyboard. Design the program so that the data entry is done in one function, and the output in another. Keep the data in the main program. The program should end when zero is entered for the number.

23) Write a family of overloaded functions called equal(), which take two arguments of the same type, returning 1 if the arguments are equal, and 0 otherwise. Provide versions having char, int and double.

24) Write a program that calculates expression , where – the maximum number between x and y. Solve this problem with using function prototype.

179

Page 179: Informatics. Study Guide. Mathcad. Matlab. VC++

25) Write a C++ program with using function prototype that identifies whether the entered number is odd or even. Provide versions checking also if the entered number is a total square.

26) Date of a day consist of three numbers: y (year), m (month) and d (day). Write a program that prints out the date of the previous day and out the date of the next day.

27) Write a program that displays the following on the screen.

180

Page 180: Informatics. Study Guide. Mathcad. Matlab. VC++

*************************** ** I can write functions!** ***************************

The program should use three functions to accomplish its task. The function Stars() should display a line of 26 asterisks. The function Bar() should display an asterisk, 24 blanks, and an asterisk. The function Message() should display the middle line. None of the functions should return a value.

28) Write a program that draws a rectangle of Xs. Ask the user to enter the dimensions of the rectangle. Then use the function Rectangle() to draw a rectangle of the requested size consisting of Xs. Rectangle() should have two argumentsthe length and width of the rectangle, which must be integers. The function should not return a value.

29) A manufacturer needs a program to display a table of costs of manufacturing certain numbers of her product. She wants to input the cost of producing one unit, the smallest number of products produced, and the largest number of products produced, each in hundreds. For example, she might input 3.46 for the unit cost, and 300 and 700 as the range of numbers. The resulting table should look like the following. Product Cost Table----------------------------------------------------Number Produced Cost-------------------------------------------------------------------------------------------------------- 300 1038.00 400 1384.00 500 1730.00 600 2076.00 700 2422.00

Use a function Heading() to display the table heading lines. Heading() should receive no arguments and return no value. Use another function, Table(), to produce the table. Table() should have three argumentsthe unit cost, the smallest number produced, and the largest number produced. Table() should not return a value.

181

Page 181: Informatics. Study Guide. Mathcad. Matlab. VC++

30) Write a program that asks the user to enter two decimal numbers. The program should calculate and display the product and quotient of the two numbers. Use a function Product() to calculate the product. The function should have two arguments, which are the two numbers that the user inputs. The function should return the product of the numbers. Use a function Quotient() that has two arguments, which are the numbers input by the user. The function should return the quotient of the first number divided by the second. If the second number is zero (recall that division by zero is not allowed), display an error message and exit the program.

31) Write a program that calculates expression , where – the maximum number between x and y. Solve this problem with using function prototype.

Laboratory work 18

Arrays

Objective – to broaden the application of the basic programming techniques that were learned in the previous works, from using single items of data to working with whole collections of data items.

Problem statement – write a program with using arrays, provide declaration and initialization of an array of different types, put to use part with multidimensional arrays.

Theoretical information

An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier.

That means, for example, we can store 5 values of type int in an array without having to declare 5 different variables, each one with a different identifier. Instead of that, using an array we can store 5 different values of the same type, int for example, with a unique identifier.

An array to contain 5 integer values of type int called billy could be represented like this:

where each blank panel represents an element of the array, that in this case are integer values of type int. These elements are numbered from 0 to 4 since in arrays the first index is always 0, independently of its length.

182

Page 182: Informatics. Study Guide. Mathcad. Matlab. VC++

Like a regular variable, an array must be declared before it is used. A typical declaration for an array in C++ is:

type name [elements];where type is a valid type (like int, float...), name is a valid identifier and the elements field (which is always enclosed in square brackets []), specifies how many of these elements the array has to contain.

Therefore, in order to declare an array called billy as the one shown in the above diagram it is as simple as:

int billy [5];NOTE: The elements field within brackets [] which represents the

number of elements the array is going to hold, must be a constant value, since arrays are blocks of non-dynamic memory whose size must be determined before execution. In order to create arrays with a variable length dynamic memory is needed.

Initializing arrays. When declaring a regular array of local scope (within a function, for example), if we do not specify otherwise, its elements will not be initialized to any value by default, so their content will be undetermined until we store some value in them. The elements of global and static arrays, on the other hand, are automatically initialized with their default values, which for all fundamental types this means they are filled with zeros.

In both cases, local and global, when we declare an array, we have the possibility to assign initial values to each one of its elements by enclosing the values in braces { }. For example:

int billy [5] = { 16, 2, 77, 40, 12071 }; This declaration would have created an array like this:

The amount of values between braces { } must not be larger than the number of elements that we declare for the array between square brackets [ ]. For example, in the case with array billy it has been declared that it has 5 elements and in the list of initial values within braces { } we have specified 5 values, one for each element.

When an initialization of values is provided for an array, C++ allows the possibility of leaving the square brackets empty [ ]. In this case, the compiler will assume a size for the array that matches the number of values included between braces { }:

int billy [] = { 16, 2, 77, 40, 12071 };After this declaration, array billy would be 5 ints long, since we have

provided 5 initialization values. Accessing the values of an array. In any point of a program in

which an array is visible, we can access the value of any of its elements individually as if it was a normal variable, thus being able to both read and modify its value. The format is as simple as:

183

Page 183: Informatics. Study Guide. Mathcad. Matlab. VC++

name[index].Following the previous examples in which billy had 5 elements and

each of those elements was of type int, the name which we can use to refer to each element is the following:

For example, to store the value 75 in the third element of billy, we could write the following statement:

billy[2] = 75;and, for example, to pass the value of the third element of billy to a variable called a, we could write:

a = billy[2];Therefore, the expression billy[2] is for all purposes like a variable of

type int.Notice that the third element of billy is specified billy[2], since the first

one is billy[0], the second one is billy[1], and therefore, the third one is billy[2]. By this same reason, its last element is billy[4]. Therefore, if we write billy[5], we would be accessing the sixth element of billy and therefore exceeding the size of the array.

In C++ it is syntactically correct to exceed the valid range of indexes for an array. This can create problems, since accessing out-of-range elements do not cause compilation errors but can cause runtime errors.

At this point it is important to be able to clearly distinguish between the two uses that brackets [ ] have related to arrays. They perform two different tasks: one is to specify the size of arrays when they are declared; and the second one is to specify indices for concrete array elements. Do not confuse these two possible uses of brackets [ ] with arrays.

int billy[5]; // declaration of a new arraybilly[2] = 75; // access to an element of the array.

Some other valid operations with arrays:billy[0] = a;billy[a] = 75;b = billy [a+2];billy[billy[a]] = billy[2] + 5;

The following example calculates the summation of all elements of defined array.

#include <iostream>using namespace std;

int billy [] = {16, 2, 77, 40, 12071};int n, result=0;int main (){ for ( n=0 ; n<5 ; n++ )

184

Page 184: Informatics. Study Guide. Mathcad. Matlab. VC++

{ result += billy[n]; } cout << result; return 0;}

Multidimensional arrays. Multidimensional arrays can be described as "arrays of arrays". For example, a bidimensional array can be imagined as a bidimensional table made of elements, all of them of a same uniform data type. For example, array jimmy represents a bidimensional array of 3 per 5 elements of type int.

The way to declare this array in C++ would be:int jimmy [3][5];

and, for example, the way to reference the second element vertically and fourth horizontally in an expression would be:

jimmy[1][3]

Multidimensional arrays are not limited to two indices (i.e., two dimensions). They can contain as many indices as needed. But the amount of memory needed for an array rapidly increases with each dimension. For example:

char century [100][365][24][60][60];declares an array with a char element for each second in a century, that is more than 3 billion chars. So this declaration would consume more than 3 gigabytes of memory.

Multidimensional arrays are just an abstraction for programmers, since we can obtain the same results with a simple array just by putting a factor between its indices:

int jimmy [3][5]; // is equivalent toint jimmy [15]; // (3 * 5 = 15)

With the only difference that with multidimensional arrays the compiler remembers the depth of each imaginary dimension for us. Take as example these two pieces of code, with both exactly the same result. One uses a bidimensional array and the other one uses a simple array:

multidimensional array pseudo-multidimensional array#define WIDTH 5#define HEIGHT 3

#define WIDTH 5#define HEIGHT 3

185

Page 185: Informatics. Study Guide. Mathcad. Matlab. VC++

int jimmy [HEIGHT][WIDTH];int n,m;

int main (){ for (n=0;n<HEIGHT;n++) for (m=0;m<WIDTH;m++) { jimmy[n][m]=(n+1)*(m+1); } return 0;}

int jimmy [HEIGHT * WIDTH];int n,m;

int main (){ for (n=0;n<HEIGHT;n++) for (m=0;m<WIDTH;m++) { jimmy[n*WIDTH+m]=(n+1)*(m+1); } return 0;}

None of the two source codes above produce any output on the screen, but both assign values to the memory block called jimmy in the following way:

We have used "defined constants" (#define) to simplify possible future modifications of the program. For example, in case that we decided to enlarge the array to a height of 4 instead of 3 it could be done simply by changing the line with no need to make any other modifications to the program.

Arrays as parameters. At some moment we may need to pass an array to a function as a parameter. In C++ it is not possible to pass a complete block of memory by value as a parameter to a function, but we are allowed to pass its address. In practice this has almost the same effect and it is a much faster and more efficient operation.

In order to accept arrays as parameters the only thing that we have to do when declaring the function is to specify in its parameters the element type of the array, an identifier and a pair of void brackets []. For example, the following function:

void procedure (int arg[])accepts a parameter of type "array of int" called arg. In order to pass to this function an array declared as:

int myarray [40];it would be enough to write a call like this:

procedure (myarray);Here is a complete example:

#include <iostream>using namespace std;

void printarray (int arg[], int length) {

186

Page 186: Informatics. Study Guide. Mathcad. Matlab. VC++

for (int n=0; n<length; n++) cout << arg[n] << " "; cout << "\n";}int main (){ int firstarray[] = {5, 10, 15}; int secondarray[] = {2, 4, 6, 8, 10}; printarray (firstarray,3); printarray (secondarray,5); return 0;}

Program produces output as follows:5 10 152 4 6 8 10

As you can see, the first parameter (int arg[]) accepts any array whose elements are of type int, whatever its length. For that reason we have included a second parameter that tells the function the length of each array that we pass to it as its first parameter. This allows the for loop that prints out the array to know the range to iterate in the passed array without going out of range.

In a function declaration it is also possible to include multidimensional arrays. The format for a tridimensional array parameter is:

base_type[][depth][depth]for example, a function with a multidimensional array as argument could be:

void procedure (int myarray[][3][4])Notice that the first brackets [] are left blank while the following

ones are not. This is so because the compiler must be able to determine within the function which is the depth of each additional dimension.

Processing an Array: for Loops. A for loop is the ideal control structure to use to process an array. The array subscript acts as the loop counter. Each time through the loop, the loop body processes the array element that the subscript specifies. Consider a simple example of processing student grades, a teacher wants to enter the five quiz grades that a student receives during the semester. The program is to display the student's average to the nearest fifth. The teacher decides to store the grades in the five-element array grade[]. To verify that the grades are entered correctly, the teacher wants to display the five grades on one line before the program displays the average grade.

Next we discuss the for loop that displays the grades first because it is simpler than the for loop that inputs the grades. Suppose the five grades have already been loaded into the array grade[]. The following loop displays the elements of the array on one line.

187

Page 187: Informatics. Study Guide. Mathcad. Matlab. VC++

for (quiz = 0; quiz < 5; ++quiz) cout << grade[quiz];

There are several things to note about this for statement. First, the beginning value for quiz is zero because the first element in the array is element number zero. Second, the loop test is quiz < 5. Thus the program stays in the loop for the following values of quiz: 0,1,2,3,4, which are the valid offsets for the array. We use the test quiz < 5 instead of quiz <= 4 because 5 is the size of the array. Third, the subscript quiz is incremented by one each time through the loop so the loop processes every array element. Finally, the loop body processes the element determined by the value of quiz. Thus, in the loop body we refer to the array element as grade[quiz].

To input the array elements into the array grade[], we can use the following for loop.

for (quiz = 0; quiz < 5; ++quiz){ cout << "\nEnter grade for quiz " << quiz + 1 << ": "; cin << grade[quiz];}

The for loop prompts the user for the five quiz values and enters the values into the array grade[].

Next example shows how to find the average of the elements in an array.

#include "stdafx.h"#include <iostream>using namespace std;

int main(){ const int NUM_QUIZZES = 5; int grade[NUM_QUIZZES]; // The array to store the quiz grades int quiz, // The array subscript grade_sum = 0; double grade_avg;

cout<<"Please enter "<<NUM_QUIZZES<<" integer quiz grades.\n\n";

for (quiz = 0; quiz < NUM_QUIZZES; ++quiz) { cout << "\nEnter grade for quiz " << quiz + 1 << ": "; cin >> grade[quiz]; }

188

Page 188: Informatics. Study Guide. Mathcad. Matlab. VC++

cout << "\nThe grades you entered are:"; for (quiz = 0; quiz < NUM_QUIZZES; ++quiz) cout << " " << grade[quiz];

for (quiz = 0; quiz < NUM_QUIZZES; ++quiz) grade_sum += grade[quiz];

grade_avg = double(grade_sum) / NUM_QUIZZES; cout << "\n\nThe average quiz grade is " << grade_avg << endl; cin.get(); return 0;}

Program Output

Please enter 5 integer quiz grades.Enter grade for quiz 1: 12Enter grade for quiz 2: 7Enter grade for quiz 3: 3Enter grade for quiz 4: 8Enter grade for quiz 5: 4The grades you entered are: 12 7 3 8 4The average quiz grade is 6.8

The number of quizzes is defined as a symbolic constant, NUM_QUIZZES. It is used in the cout that labels the output to reflect the number of quizzes that the program processes.

It is good programming practice to define the size of an array as a symbolic constant. The program declares the accumulator grade_sum, which is initialized to zero, to hold the sum of the grades that the user enters into the array grade[]. The double variable grade_avg will store the average of the five grades.

The program inputs the five quiz grades. The second for loop adds each grade in the array to the accumulator grade_sum. Then, the assignment statement computes the grade average. A type cast converts the value of the integer variable grade_sum to the equivalent double. Finally, the cout statement displays the value of grade_avg.

Searching an Array. Suppose that our teacher wants to display the quiz number and corresponding grade of the first quiz, if any, on which the student achieved a grade of 85 or better. This is an example of an array search to find a particular array element. To do this, the program will test each array element beginning with the first. If the grade that the program is testing satisfies the condition (the grade is 85 or greater), it displays the grade and the quiz number and ends the program. If there is no grade equal to or greater than 85, the program should display a

189

Page 189: Informatics. Study Guide. Mathcad. Matlab. VC++

message to that effect. This method of searching, namely beginning at the first array element and proceeding through the entire array one element at a time, testing as we go along, is called a linear, or sequential, search.

This program shows how to find the first element in an array that satisfies a condition. The condition tested in this program is that the quiz grade is greater than or equal to 85.

#include "stdafx.h"#include <iostream>using namespace std;

int main(){ const int NUM_QUIZZES = 5; const int MIN_GRADE = 85; int grade[NUM_QUIZZES]; int quiz; cout << "Please enter " << NUM_QUIZZES<< " integer quiz grades.\n\n"; for (quiz = 0; quiz < NUM_QUIZZES; ++quiz) { cout << endl; cout << "Enter grade for quiz " << quiz + 1 << ": "; cin >> grade[quiz]; }for (quiz = 0; quiz < NUM_QUIZZES; ++quiz) if (grade[quiz] >= MIN_GRADE) { cout << "\nThe first grade of at least " << MIN_GRADE << " is:\n\n"; cout << "Quiz #" << quiz + 1 << " Grade: "<< grade[quiz] << endl; break; }if (quiz >= NUM_QUIZZES) { cout << endl; cout << "No grade greater than " << MIN_GRADE<< " was found.\n"; } cin.get(); return 0;}

Program Output

Please enter 5 integer quiz grades.

190

Page 190: Informatics. Study Guide. Mathcad. Matlab. VC++

Program Output

Enter grade for quiz 1: 35Enter grade for quiz 2: 67Enter grade for quiz 3: 89Enter grade for quiz 4: 87Enter grade for quiz 5: 49The first grade of at least 85 is:Quiz #3 Grade: 89

First, note that we define a symbolic constant MIN_GRADE with a value of 85. This makes it easier to change this minimum grade later.A for loop prompts the user to enter the five quiz grades. The for loop that does the linear search is next. The body of this loop consists of a single if statement. If the grade on the quiz being processed is greater than or equal to MIN_GRADE, the search is successful. Then, the program displays a message that shows the quiz number and the grade on that quiz. In this case, the break statement executes, which causes the program to exit the loop.

When the program exits the second for loop, it does so for one of two reasons. If the search is successful, as described in the previous paragraph, the break statement causes the program to exit the loop before the loop condition (quiz < 5) is false. If the search is unsuccessful, the program exits the loop because the loop condition is false, not because of the break statement. The if statement that follows the second for loop decides which condition caused the program to exit the loop. If the search was unsuccessful, the value of quiz must be greater than or equal to 5 because the loop condition must be false. Therefore, if quiz >= 5, the program displays a message that no grade was found that satisfies the condition. If quiz is not greater than or equal to 5, then it must be less than 5. In this case, the program exited the loop because the search was successful. Thus, if the condition in the if statement is false, the program does nothing.

Sorting an Array. Suppose that after inputting the five grades for a student, our teacher wants to display the grades in increasing order. To do this, the program must arrange the numbers that it stores in the array grade[] into increasing order. We call this process sorting the array. Among the techniques for sorting an array is the bubble sort, which programmers frequently use for sorting small arrays. There are several variations of the bubble sort. The one that we shall describe here is not the most efficient bubble sort, but it works and illustrates the basic technique.

The key idea of the bubble sort is to compare adjacent elements in the array. Begin by comparing the first two array elements. We assume

191

Page 191: Informatics. Study Guide. Mathcad. Matlab. VC++

that we want the array in nondecreasing order. If the elements are in order (that is, the first element is less than or equal to the second), leave them alone. If the elements are not in order (that is, the first is greater than the second), interchange them in the array. Then, compare the second and third array elements. Again, if they are out of order, interchange them; otherwise, leave them alone. Continue this process until you compare the last pair of array elements. This completes the first pass over the array.

To illustrate, suppose we start with the following array of five integers.

7 3 4 8 6

The first pass does the following. Because 7 and 3 are not in order, interchange them.

3 7 4 8 6Compare 7 and 4. They are not in order, so interchange them.

3 4 7 8 6

Compare 7 and 8. They are in order, so leave them alone and go on to the next pair.

Compare 8 and 6. They are not in order, so interchange them.

3 4 7 6 8

This completes the first pass. What does the first pass accomplish? The first pass moves the largest number in the array into the right-most position, which is where we want it when the array is completely sorted. This is why we call this sort the bubble sort. The largest array element "bubbles" up to the top of the array.

Now we make a second pass over the array. This time, however, we do not have to go to the end of the array because the first pass moved the largest array element into the right-most position. The second pass moves the second largest array element into the next-to-last position. Following is a trace of pass two.

Start with: 3 4 7 6 8  

Begin: 3 4 7 6 8 Leave 3 and 4 alone

  3 4 7 6 8 Leave 4 and 7 alone

  3 4 6 7 8 Interchange 7 and 6

Likewise for pass three and pass four.

Trace of Pass Three:            

Start with: 3 4 6 7 8  

Begin: 3 4 6 7 8 Leave 3 and 4 alone

  3 4 6 7 8 Leave 4 and 6 alone

192

Page 192: Informatics. Study Guide. Mathcad. Matlab. VC++

Trace of Pass Three:            

End of Pass Three.            

Trace of Pass Four:            

Start with: 3 4 6 7 8  

Begin: 3 4 6 7 8 Leave 3 and 4 alone

End of Pass Four. The array is sorted. After the fourth pass, the array is sorted. Note that the array is sorted at the end of pass two, but the procedure keeps going. It would be more efficient if the procedure recognizes at some point that the array is sorted and ends.

An important part of the bubble sort is interchanging two array elements. To interchange the values of two variables requires the use of a third variable. For example, consider the following declarations.int i = 5, j = 7, temp;

The following assignments interchange the values of i and j.temp = i; // Places 5 into tempi = j; // Places 7 into i, destroying its contentsj = temp; // Places 5 into j

The following program prompts the user to enter a five-element array and displays the array. Then, the program uses the bubble sort to sort the array in increasing order. Finally, the program displays the sorted array.#include <iostream>using namespace std;int main(){ const int NUM_QUIZZES = 5; int grade[NUM_QUIZZES]; //The array to store the quiz grades int quiz, // Subscript for the array grade[] temp, // For swapping array elements pass, // The number of the pass limit; // Keeps track of how far to go on a pass // Get the grades cout << "Please enter " << NUM_QUIZZES << " integer quiz grades.\n"; for (quiz = 0; quiz < NUM_QUIZZES; ++quiz) { cout << "\nEnter grade for quiz " << quiz + 1 << ": "; cin >> grade[quiz]; } // Display the quiz grades cout << "\n\nThe grades you entered are as follows:\n"; for (quiz = 0; quiz < NUM_QUIZZES; ++quiz)

193

Page 193: Informatics. Study Guide. Mathcad. Matlab. VC++

cout <<" "<< grade[quiz] << endl; // Do the bubble sort limit = NUM_QUIZZES - 2; for (pass = 1; pass <= NUM_QUIZZES - 1; ++pass) { for (quiz = 0; quiz <= limit; ++quiz) if (grade[quiz] > grade[quiz + 1]) { temp = grade[quiz]; grade[quiz] = grade[quiz + 1]; grade[quiz + 1] = temp; } limit; } // Display the sorted quiz grades cout << "\n\nThe grades in increasing order are as follows:\n"; for (quiz = 0; quiz < NUM_QUIZZES; ++quiz) cout <<" "<< grade[quiz]; cout << endl; return 0;}

The program needs the integer array grade[] to store the student grades. The variable quiz is the array subscript. The program uses the variable temp for swapping array elements, the variable pass to count the number of passes that the bubble sort makes, and the variable limit to keep track of how far to go on a pass.

The program obtains the five quiz grades from the user in a for loop and stores them in the array grade[]. Then, a for loop displays the grades in the order in which the user entered them. Now the program uses the bubble sort to arrange the elements of the array into increasing order.

The variable limit keeps track of how far to go on a pass. Recall, from our discussion, that the first pass of the bubble sort compares pairs of adjacent elements up to the last pair. Therefore, in an array with NUM_QUIZZES elements, it compares elements 0 and 1, elements 1 and 2, elements 2 and 3, ..., elements NUM_QUIZZES 2 and NUM_QUIZZES 1. Therefore, because the sort always compares an element to the next element, we initialize limit to NUM_QUIZZES 2. At the end of a pass, limit is decreased by one, so that the next pass considers one less element. Remember that a pass places the next highest element at the right of the array so the sort does not have to consider this element again.

The bubble sort is done in a nested for loop. The outer for loop initializes the value of pass to one. The sort makes a total of NUM_QUIZZES 1 passes over the array, which is reflected in the loop

194

Page 194: Informatics. Study Guide. Mathcad. Matlab. VC++

test. The if statement in the inner loop's body tests to see if the pair of adjacent array elements is out of order. If they are out of order, the elements are interchanged. If they are in order, nothing is done to the pair.

When the bubble sort finishes sorting the array, the elements of grade[] are in increasing order. Then, the program uses a for loop to display the elements of the array grade[], which are now in increasing order.

Multidimensional Arrays. Multidimensional arrays are a way of organizing data that you can classify according to two or more categories.

An array can be used to store a collection of related data. Data are related if you categorize them into a common class. For example, the grades that a student receives on a set of five quizzes forms a category. You can consider the five grades as belonging to a common class of data.Sometimes, you can classify data according to two or more categorie.

Suppose that our teacher now wants to find the average quiz grade of the five students in her class. We now have five quiz grades for five students a total of 25 integers. We can classify each grade according to two categories: the student to whom the grade belongs and the quiz on which the grade was achieved. You can arrange such data in a two-dimensional array, or matrix.

The data are arranged into rows and columns. The five rows represent the five students in the class. The five columns represent the five quiz grades. The array size is 5 x 5, meaning that the array has five rows and five columns. In keeping with the way in which C++ refers to array elements, we number the rows from 0 to 4 and the columns from 0 to 4.

Referring to a specific element in the two-dimensional array requires two subscripts. The first subscript specifies the row (that is, the student). The second subscript specifies the column (that is, the quiz). We enclose each subscript in brackets. Thus, class_grades[2][3] refers to the grade of student 2 (the third student) on quiz 3 (the fourth quiz).

To declare a two-dimensional array, specify the array type and the size of the array. Place the number of rows and the number of columns each in its own brackets. For example, the following declares a two-dimensional array of integers of size 5 x 5.int class_grades[5][5];

It is possible to initialize a two-dimensional array in the array declaration. The following initializes the elements of class_grades[][].int class_grades[5][5] = { {50, 56, 87, 67, 98}, {70, 68, 64, 78, 97}, {64, 76, 87, 67, 95}, {76, 65, 84, 47, 86}, {76, 57, 65, 45, 90}};

195

Page 195: Informatics. Study Guide. Mathcad. Matlab. VC++

We enclose the entire set of values in braces. We also enclose the values in each row in another set of braces. Note the comma after each set of inner braces. The final set of inner braces is not followed by a comma. This technique of organizing the initial values in a two-dimensional array mirrors the logical row-by-column structure of the array. The inner braces help to distinguish one row from the next row. In addition, if too few numbers are enclosed in the inner braces, the compiler automatically sets the remaining row elements to zero. If there are too many elements in the inner braces, the compiler ignores the extra elements in the row.

The C++ language does not require this bracing technique to initialize a two-dimensional array. The important thing is that the elements appear in the initialization in the order in which C++ stores them, that is, in row major order.

Processing a Two-Dimensional Array. The major tool for processing a two-dimensional array is the nested for loop. Assume the following declaration.int array[NUMBER_ROWS][NUMBER_COLUMNS];

To process each element in this two-dimensional array, we use a nested for loop structured as follows.for (row = 0; row < NUMBER_ROWS; ++row) for (column = 0; column < NUMBER_COLUMNS; ++column) {process the array element array[row][column]}

The outer for loop steps through the rows of the array one at a time. When the subscript row equals zero, the nested loop processes row number zero; when the subscript row equals one, the nested loop processes row number one, and so on. The inner loop processes each element in the row determined by the subscript row. Thus, the nested loop processes the elements of the array in row major order. When row equals zero, the for loop runs the subscript column from zero to one less than NUMBER_COLUMNS. Thus, the following displays all the grades in the 5 x 5 array class_grades[][] that we declared and initialized earlier.

int student, quiz;

for (student = 0; student < 5; ++student) for (quiz = 0; quiz < 5; ++quiz) cout << "The grade of student " << student + 1<< " on quiz " << quiz + 1 << " is " << class_grades[student][quiz] << endl;

196

Page 196: Informatics. Study Guide. Mathcad. Matlab. VC++

Following is the code for a program that uses a two-dimensional array to store the quiz grades of students in several classes. The program then calculates the average quiz grade of each student.

#include <iostream>using namespace std;

int main(){ const int NUM_QUIZZES = 5; const int NUM_STUDENTS = 5;

int class_grades[NUM_STUDENTS][NUM_QUIZZES]; int student, quiz, quiz_sum; double quiz_average; // Obtain and store the quiz grades for each student cout << "Enter exactly " << NUM_QUIZZES<< " quiz grades for each student." << endl; cout << "Separate the grades by one or more spaces." << endl;

for (student = 0; student < NUM_STUDENTS; ++student) { cout << endl << endl; cout << "Grades for Student " << student + 1 << ": "; for (quiz = 0; quiz < NUM_QUIZZES; ++quiz) cin >> class_grades[student][quiz]; } // Calculate and display the average quiz grade for each student for (student = 0; student < NUM_STUDENTS; ++student) { quiz_sum = 0; for (quiz = 0; quiz < NUM_QUIZZES; ++quiz) quiz_sum += class_grades[student][quiz]; quiz_average = (double) quiz_sum / NUM_QUIZZES; cout << "\n\nStudent: " << student + 1 << " Quiz Average: " << quiz_average; } cout << endl; return 0;}

197

Page 197: Informatics. Study Guide. Mathcad. Matlab. VC++

The program defines the number of quizzes and the number of students as symbolic constants. In main(), we declare the two-dimensional array class_grades[][] as described earlier, the subscripts student and quiz, the accumulator quiz_sum, and the double variable quiz_average.

Because this program must obtain 25 grades, it does not prompt for each grade individually. Instead, the program asks the user to enter all ten grades for each student at once. First, the program tells the user how many grades to enter for each student and how to separate the grades. Then, the outer for loop prompts for the ten grades of one student. The inner for loop obtains the ten grades for the student and stores them in the array.

The next for loop calculates and displays the average of each student. To calculate the average of the student currently being processed, the body of the loop first initializes the accumulator quiz_sum to zero. Next, a for loop sums the quiz grades for the student being processed. After exiting the for loop, an assignment statement calculates the quiz average. To obtain the quiz average to the nearest tenth, it is necessary to type cast the variable quiz_sum to the type double. Failure to do so would cause the computer to do integer arithmetic when evaluating the right side of the assignment, which would result in the loss of the decimal part of the division. The last statement in the loop body displays the student number and the student's quiz average.

VariantsTask 1. One-dimensional array

1) Write a program that fills in an array of 8 elements with numbers in decreasing order.

2) Write a program that a program that fills in an array of 8 elements with numbers in ascending order.

3) Write a program that asks user to type in elements of an array and deletes from the array all numbers that are equal to 0.

4) Write a program which will ask user to enter numbers for A array and which will output all negative numbers and numbers that are less then 50.

5) Write a program which will ask user to enter numbers for B array and which will output all even numbers and numbers that ends with 0.

6) Write a program that asks the user to type 10 integers and write the number of occurrence of the biggest value.

198

Page 198: Informatics. Study Guide. Mathcad. Matlab. VC++

7) Write a program that asks the user to type n integers and prints out a number of negative numbers and all of the negative nombers on the next line.

8) Write a program that shows the output array of 10 numbers. Then program will ask which numbers do you want to delete and then prints out a new array.

9) Write a program that asks the user to type n integers and prints out a number of positive numbers and all of the positive numbers on the same line in brackets.

10) Write a program that asks the user to enter two arrays A and B and output should A∩B.

11) Write a program that asks the user to enter two arrays A and B and output should AUB.

12) Write a program that searches an array of ten integers for duplicate values. Have the program display each duplicate found.

13) Aerosvit Airline has flights from Kyiv to six other cities in Ukraine. The cities are referred to by number, 1 to 6. The price for a round-trip ticket to each of the cities is shown here.

City 1 2 3 4 5 6

Price 56.79 105.69 93.49 155.99 87.49 73.99

Write a program that computes the total price of tickets that a customer orders. The program should prompt the user for the number of the destination city and the number of tickets desired. If the user enters an invalid city number, the program should display an error message and terminate. The program should display the total price of the ticket order. Use an array to store the ticket price table.

14) Write a program that prompts the user to enter a ten-element array and displays the array. Then, the program uses the bubble sort to sort the array in increasing order. Finally, the program displays the sorted array.

199

Page 199: Informatics. Study Guide. Mathcad. Matlab. VC++

15) Write a program that finds roots of the equation Ax + Bsin = 0, where = 1.3, A = {1.1, 2.5, 3.9, 8.1, 4.5, 12.1, 11.9, 15.5}.

;10

;10

;105.4

;5.03

i

i

i

ii A

A

A

AB

(i = 1..8).

16) Write a program that calculates the next array: , where – positive roots of equation Ax + Bcos = 0, with А = 0.75, B = 4.5, = -1.5 .. 2.5, .

17) Write a program that finds summation of all positive elements of an array A = {-1.2, 3.5, 4.1, 8.5, 5.3, -6.1, 3.4, 2.7}.

18) Write a program that finds product of elements of an array A = {1, 3.5, 4, -0.8, 1.9, 5, 13}, which satisfies the next condition , if С = 2, D = 10.

19) . Write a program that calculates

with Y = -5.5, X = {-1.8, -1.6, ... , 1.2}. The result should be presented in the view of an array.

20) Write a program that finds numbers of the first odd and the last even numbers of an array N = {10, 8, 4, 3, 6, 15, 2}.

21) Write a program that prompts the user to enter a ten-element array and displays the array. Then, the program uses the bubble sort to sort the array in decreasing order. Finally, the program displays the sorted array.

22) Write a program that finds the difference between maximum and K-th element of an array А = {-1.1, 2.5, -2.9, 8.8, 14.5, 2.2, -1.3, 5.9} if К = 4.

23) Write a program that calculates the element of an array

where x – the roots of a series of equations Аx + sin(i) = 0, , А = 5.5.

24) Write a program that finds summation of the first К positive elements of an array А = (2.8, -3.5, -2.1, 4, 6, 8.1, 6.2, 9.5, 1.1) when К = 5.

200

Page 200: Informatics. Study Guide. Mathcad. Matlab. VC++

25) Write a program that finds a product of the last N negative elements of an array А = (-5, 6.1, -9.2, 4, 5, -2, 7, -1, 5, 4, 1.9, -3, 5); N = 3.

26) Create an array , even elements of the array are equal to elements of an array А = (-5.1, 2.3, 4.6, 5.8, -2.9), odd – to elements of an array В = (2.8, 3, 5.4, -1.9, -4.1).

27) Find amount of positive, negative elements and elements equal to 0 of an array М = (-5, 0.1, 2.8, 0.64, 3, -5.1, 0, -7.5, 4.6, 10).

28) Calculate where х = , an array, its elements are remainder of dividing the entire array of components of an array N = (156, 18, 72, 10, 95, 100) to an integer number К = 9.

29) Calculate , where and – maximum and minimum

elements respectively of an array А = (5.5, -6, 8, 9.1, -3.5, 4.1, 10, -1, 2.5); – arithmetic mean of and .

30) A survey organization telephones 20 homes and records the household income of each family surveyed. Write a program that inputs the 20 incomes into an array and then sorts the array into decreasing order. The program should display the following statistics: the maximum income, the minimum income, the average income, and the median income. The median of a set of sorted numbers is the middle number, if there is an odd number of numbers. If there is an even number of numbers, the median is the average of the two middle numbers.

Task 2. Multidimensional array

1) Write a program that reads through real matrix, 10x10 dimensioned and finds the smallest element in main diagonal and smallest element in secondary diagonal.

2) Write your own C program that transposes matrix. Program stores given matrix dimensions and every single matrix element must be given. Transposed matrix is the one with rows and columns switched.

3) Write your own C program that stores real matrix whose dimensions are 10x10, and finds the sum of elements from every column and product of elements from every row. Program prints the smallest sum (including

201

Page 201: Informatics. Study Guide. Mathcad. Matlab. VC++

parent column’s index), and biggest product (including parent row’s index). Sums and products should be stored in one-dimensional arrays.

4) Maximal number of rows and columns matrix can have is predefined. Write your own main program which reads given number of matrix’s rows and columns, and additionally reads matrix’s given elements. Main program prints:Matrix’s elements sum (calls upon a function that calculates elements sum)

5) Maximal number of rows and columns matrix can have is predefined. Write your own main program which reads given number of matrix’s rows and columns, and additionally reads matrix’s given elements. Main program prints: Maximal value in every row of a matrix (calls upon a function that finds the biggest element in a flow)

6) Write a program that adds together two matrices whose dimensions and elements are input by the user, and then prints out the result.

7) An array A(m,n) is given. Write a program that creats array В of the smallest elements of each row of the array.

8) An array В(m,n) is given. Write a program that creats array C(n) of the sum of elements of each column of the array B.

9) An array E(m,n) is given. Write a program that will be able to change places of elements of i-th and k-th rows:

10) Write a program that devides all elements of an array Р(m,n) by the maximum number of k-th column:

11) An array A(m,n) is given. Creat an array С of elements of even columns and an array В of elements of odd rows of the array А:

202

Page 202: Informatics. Study Guide. Mathcad. Matlab. VC++

12) An array A(m,n) is given. Creat one-dimentional arrays В and С that contain odd and even elements of the array A, respectively:

13) Create an array В of product of elements of the columns of an array Z:

14) Create an array Т of elements’ summation situated in rows with negative elements on the main diagonal of the original array Z:

15) Create an array NS of rows’ numbers of an array R, where repited values are:

16) An array Q(m,n) is given. Replace negative elements of the array by the number of the column where they are situated:

17) Creat an one-dimensional array B of elements of an array A that are less then Е:

18) Creat an one-dimensional array B of elements that are below the main diagonal of an original array К:

19) An array V(n,n) is given. Replace the greatest element of each row by s:

203

Page 203: Informatics. Study Guide. Mathcad. Matlab. VC++

20) An array H(n,n) is given. Convert the array by dividing of all elements by the maximum element of K-th row:

21) Find the difference R between the maximum and minimum elements of an array W:

22) An array A(m,n) is given. Creat an array B of positive elements of an array A:

, m = 2, n = 3.

23) An array G(m,n) is given. Convert the array by replacing elements of K-th and (К+1)-th columns:

24) An array D(m,n) is given. Add the value S to negative elements of the array and subtract value X out of positive elements:

25) Replace all positive elements in an array F(n,m) by their squares and all negative – by their cubes.

26) Creat an array R of numbers of rows of an array Y(m,n) (those rows which have maximum element):

27) Creat an array K of positive proportions of elements of n-th and s-th columns of the array:

204

Page 204: Informatics. Study Guide. Mathcad. Matlab. VC++

28) Creat one-dimensional array B of elements of А(n,n) array that are greater then C:

29) An integer array of size NxN has to be defined. Determine whether this matrix are given as a magic square or not (magic square can be when sum of elements in the rows, columns and main diagonals are equal).

30) Your teacher wants a program to store the ten quiz grades of each of the five students in her four classes in a 4 x 5 x 10 three-dimensional array. Write a program that prompts the user to enter the grades on a class-by-class basis. Within each class, the program should prompt the user for the grades of each student. After all the grades are entered, the program should display the following: the average grade of each student on a class-by-class basis and the average grade of the entire class on the ten quizzes.

Laboratory work 19

Character sequences

Objective – get to know the C++ Standard Library of a powerful string class; to be able handle and manipulate strings of characters.

Problem statement – write a program according to your variant. Use theoretical information from the work.

Theoretical information

By far the most common use for one-dimensional arrays is to create character strings. C++ supports two types of strings.

The first, and most commonly used, is the null-terminated string, which is a null-terminated character array. A null is zero. Thus, a null-terminated string contains the characters that make up the string followed by a null. Null-terminated strings are widely used because they offer a high level of efficiency and give the programmer detailed control over

205

Page 205: Informatics. Study Guide. Mathcad. Matlab. VC++

string operations. When a C++ programmer uses the term string, he or she is usually referring to a null-terminated string.

The second type of string defined by C++ is the string class, which is part of the C++ class library. Thus, string is not a built-in type. It provides an object-oriented approach to string handling but is not as widely used as the null-terminated string. Here, null-terminated strings are examined.

When declaring a character array that will hold a null-terminated string, you need to declare it one character longer than the largest string that it will hold. For example, if you want to declare an array str that could hold a 10-character string, here is what you would write: char str[11]; Specifying the size as 11 makes room for the null at the end of the string. As you learned earlier in this book, C++ allows you to define string constants. A string constant is a list of characters enclosed in double quotes. Here are some examples: “hello there” “I like C++” “Mars” ““ It is not necessary to manually add the null terminator onto the end of string constants; the C++ compiler does this for you automatically. Therefore, the string “Mars” will appear in memory like this:

M a r s 0The last string shown is "". This is called a null string. It contains only

the null terminator and no other characters. Null strings are useful because they represent the empty string. Reading a String from the Keyboard The easiest way to read a string entered from the keyboard is to use a char array in a cin statement. For example, the following program reads a string entered by the user:

int main (){char str [80];cout <<”Enter a string: ”;cin>>str;cout<<”Here is your string: ”;cout<<str;return 0;}Here is a sample run: Enter a string: testing Here is your string: testing

Although this program is technically correct, it will not always work the way that you expect. To see why, run the program and try entering the string “This is a test”. Here is what you will see:

Enter a string: This is a test Here is your string: This

206

Page 206: Informatics. Study Guide. Mathcad. Matlab. VC++

When the program redisplays your string, it shows only the word “This”, not the entire sentence. The reason for this is that the C++ I/O system stops reading a string when the first whitespace character is encountered. Whitespace characters include spaces, tabs, and newlines. One way to solve the whitespace problem is to use another of C++’s library functions, gets( ). The general form of a call to gets( ) is gets(array-name);

To read a string, call gets( ) with the name of the array, without any index, as its argument. Upon return from gets( ), the array will hold the string input from the keyboard. The gets( ) function will continue to read characters, including whitespace, until you enter a carriage return. The header used by gets( ) is <cstdio>. This version of the preceding program uses gets( ) to allow the entry of strings containing spaces:

int main (){char str [80];cout <<”Enter a string: ”;gets(str);cout<<”Here is your string: ”;cout<<str;return 0;}Here is a sample run: Enter a string: This is a test Here is your string: This is a test

Now, spaces are read and included in the string. Notice that in a cout statement, str can be used directly. In general, the name of a character array that holds a string can be used any place that a string constant can be used. Keep in mind that neither cin nor gets( ) performs any bounds checking on the array that receives input. Therefore, if the user enters a string longer than the size of the array, the array will be overwritten. Later, you will learn an alternative to gets( ) that avoids this problem.

C++ supports a wide range of string manipulation functions. The most common are strcpy( ), strcat( ), strcmp( ), strlen( ).The string functions all use the same header, <cstring>. Let’s take a look at these functions now.

Strcpy. A call to strcpy( ) takes this general form:

strcpy(char destination[], const char source[]);

Function strcpy() takes two arguments, the first is the destination array that gets changed, the second is the source array. Note that the function

207

Page 207: Informatics. Study Guide. Mathcad. Matlab. VC++

prototype uses the const qualifier to distinguish between these roles; destination[] is modified so it is not const, source[] is treated as read only so it is const. Function strcpy() copies all the characters from the source to the destination, and adds a '\0' null character so that the string left in the destination is properly terminated. (Of course, there are no checks! What did you expect? It is your responsibility to make certain that the destination array is sufficient to hold the string that is copied.)

Strncpy. A call to strncpy( ) takes this general form:

strncpy(char destination[], const char source[], int numchars);

Functions strncpy() copies a specified number of characters from the source to the destination. It fills in elements destination[0] to destination[numchars-1]. If the source string is greater than or equal to the specified length, strncpy() does not place a '\0' null character after the characters it copied. (If the source string is shorter than the specified length, it is copied along with its terminating null character.) You can use strncpy() as a "safe" version of strcpy(). If your destination array is of size N, you call strncpy() specifying that it should copy N-1 characters and then you place a null character in the last element:

Strcat. A call to strcat( ) takes this form:

strcat(char target[], const char source[]);

The strcat() function appends ("catenates") the source string onto any existing string in the destination character array. Once again it is your responsibility to make sure that the destination array is large enough to hold the resulting string. An example use of strcat() is:char order[40] = "pizza with ";…strcat(order,"ham and pineapple");changes the content of character array order from:pizza with \0............................to:pizza with ham and pineapple\0...........

Strncat. A call to strncat( ) takes this form:

strncat(char target[], const char source[], int numchars);

Function strncat() works similarly but like strncpy() it transfers at most the specified number of characters.

Strcmp and Strncmp. Calls to strcmp( ) and strncmp( ) take these general forms:

int strcmp(const char firststring[], const char secondstring);int strncmp(const char firststring[], const char secondstring,int

num_chars_to_check);

208

Page 208: Informatics. Study Guide. Mathcad. Matlab. VC++

These functions compare complete strings (strcmp()) or a specified number of characters within strings (strncmp()). These functions return 1 if the first string (or first few characters) are "greater" than the second string, 0 if the strings are equal, or -1 if the second string is greater than the first.

Strlen. The general form of a call to strlen( ) is

int strlen(const char string[]);

Function strlen() counts the number of characters in the string given as anargument (the terminating '\0' null character is not included in this count).

The comparison uses the "collating" sequence of the characters, normally this is just their integer values according to the ASCII coding rules:

32: ' ' 33: '!' 34: '"' 35: '#' 36: '$' 37: '%'38: '&' 39: ''' 40: '(' 41: ')' 42: '*' 43: '+'44: ',' 45: '-' 46: '.' 47: '/' 48: '0' 49: '1'50: '2' 51: '3' 52: '4' 53: '5' 54: '6' 55: '7'56: '8' 57: '9' 58: ':' 59: ';' 60: '<' 61: '='62: '>' 63: '?' 64: '@' 65: 'A' 66: 'B' 67: 'C'…86: 'V' 87: 'W' 88: 'X' 89: 'Y' 90: 'Z' 91: '['92: '\' 93: ']' 94: '^' 95: '_' 96: '`' 97: 'a'……

For example, the code:char msg1[] = "Hello World";char msg2[] = "Hi Mom";cout << strcmp(msg1, msg2) << endl;

should print -1, i.e. msg1 is less than msg2. The H's at position 0 are equal, but the strings differ at position 1 where msg2 has i (value 105) while msg1 has e (value 101).

The following program illustrates the use of some string functions:

#include <iostream> #include <cstdio> #include <cstring> using namespace std; int main() { char s1[80], s2[80]; strcpy(s1, "C++"); strcpy(s2, " is power programming."); cout << "lengths: " << strlen(s1);

209

Page 209: Informatics. Study Guide. Mathcad. Matlab. VC++

cout << ' ' << strlen(s2) << '\n'; if(!strcmp(s1, s2)) cout << "The strings are equal\n"; else cout << "not equal\n"; strcat(s1, s2); cout << s1 << '\n'; strcpy(s2, s1); cout << s1 << " and " << s2 << "\n"; if(!strcmp(s1, s2)) cout << "s1 and s2 are now the same.\n"; return 0; } Here is the output: lengths: 3 22 not equal C++ is power programming. C++ is power programming. and C++ is power programming. s1 and s2 are now the same.

The fact that strings are null-terminated can often be used to simplify various operations. For example, the following program converts a string to uppercase:

int main (){char str [80]; int I;strcpy(str, “this is a test”);for(i=0; str[i]; i++)str[i]=toupper(str[i]);cout<<str;return 0;}The output from this program is shown here: THIS IS A TEST This program uses the library function toupper( ), which returns the

uppercase equivalent of its character argument, to convert each character in the string. The toupper( ) function uses the header <cctype>. Notice that the test condition of the for loop is simply the array indexed by the control variable. The reason this works is that a true value is any non-zero value. Remember, all character values are non-zero, but the null terminating the string is zero. Therefore, the loop runs until it encounters the null terminator, which causes str[i] to become zero. Because the null terminator marks the end of the string, the loop stops precisely where it is supposed to. You will see many examples that use the null terminator in a similar fashion in professionally written C++ code.The C++ standard library contains several other character-manipulation functions. For example, the complement to toupper( ) is tolower( ), which returns the lowercase equivalent of its character argument. You can

210

Page 210: Informatics. Study Guide. Mathcad. Matlab. VC++

determine the case of a letter by using isupper( ), which returns true if the letter is uppercase, and islower( ), which returns true if the letter is lowercase. Other character functions determine the category of that argument. For example, isalpha( ) returns true if its argument is a letter of the alphabet. include isalpha( ), isdigit( ), isspace( ), and ispunct( ). These functions each take a character argument and determine the category of that argument. Function isalnum( ) // checks whether the variable is a letter or digit. For example, isalpha( ) returns true if its argument is a letter of the alphabet.

Array Initialization. C++ allows arrays to be initialized. The general form of array initialization is similar to that of other variables, as shown here:

type-specifier array_name[size] = {value-list};The value-list is a comma-separated list of values that are type

compatible with the base type of the array. The first value will be placed in the first position of the array, the second value in the second position, and so on. Notice that a semicolon follows the }.

In the following example, a ten-element integer array is initialized with the numbers 1 through 10.

int i[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};This means that i[0] will have the value 1, and i[9] will have the value

10. Character arrays that will hold strings allow a shorthand initialization that takes this form: char array_name[size] = “string”; For example, the following code fragment initializes str to the string “C++”:

char str[4] = "C++"; This is the same as writing char str[4] = {'C', '+', '+', '\0'}; Because strings in C++ must end with a null, you must make sure

that the array you declare is long enough to include it. This is why str is four characters long in these examples, even though “C++” is only three. When a string constant is used, the compiler automatically supplies the null terminator. Multidimensional arrays are initialized in the same way as one-dimensional arrays. For example, the following program initializes an array called sqrs with the numbers 1 through 10 and their squares:

int sqrs[10][2] ={ 1,1,2,4,3,9,4,16,5,25,6,36,7,49,8,64,9,81,10,100 };Arrays of Strings. A special form of a two-dimensional array is an

array of strings. It is not uncommon in programming to use an array of strings. The input processor to a database, for instance, may verify user commands against a string array of valid commands. To create an array of strings, a two-dimensional character array is used, with the size of the left index determining the number of strings and the size of the right index specifying the maximum length of each string, including the null

211

Page 211: Informatics. Study Guide. Mathcad. Matlab. VC++

terminator. For example, the following declares an array of 30 strings, each having a maximum length of 79 characters plus the null terminator.

char str_array[30][80];Accessing an individual string is quite easy: you simply specify only

the left index. For example, the following statement calls gets( ) with the third string in str_array: gets(str_array[2]); To access an individual character within the third string, you will use a statement like this: cout << str_array[2][3]; This displays the fourth character of the third string. The following program demonstrates a string array by implementing a very simple computerized telephone directory. The two-dimensional array numbers holds pairs of names and numbers. To find a number, you enter the name. The number is displayed.

#include <iostream>#include <cstdio>using namespace std;int main(){int i; char str[80]; char numbers[10][80]={“Tom”, “707-4589”, “Mary”, “707-1278”, “Jon”, “707-9034”, “Tim”, “707-9965”, “Katya”, “707-7732”,};cout<<“Enter name: ”; cin>>str; for (i=0; i<10; i+=2)

if (!strcmp(str,numbers[i])) { cout<<“Number is ”<<numbers[i+1]<< “\n”; break;

}if(i==10) cout <<“Not found. \n”; return 0;

}Here is a sample run: Enter name: Tom Number is 707-4589

Notice how the for loop increments its loop control variable, i, by 2 each time through the loop. This is necessary because names and numbers alternate in the array.

212

Page 212: Informatics. Study Guide. Mathcad. Matlab. VC++

Variants

1) Write a program that prompts the user for two strings and then compares the strings for equality, but ignores case differences. Thus, “ok” and “OK” will compare as equal.

2) Read a file of English text, and print it out one word per line, all punctuation and non-alpha characters being omitted. For end-of-data, the program loop should read until "getchar" delivers a value <= 0. When typing input, end the data by typing the end-of-file character, usually control-D. When reading from a file, "getchar" will deliver a negative value when it encounters the end of the file. Typical output might be: ReadafileofEnglishtext.

3) Write a program to count the vowels and letters in free text given as standard input. Read text a character at a time until you encounter end-of-data. Then print out the number of occurrences of each of the vowels a, e, i, o and u in the text, the total number of letters, and each of the vowels as an integer percentage of the letter total. Suggested output format is: Numbers of characters: a 3 ; e 2 ; i 0 ; o 1 ; u 0 ; rest 17 Percentages of total: a 13%; e 8%; i 0%; o 4%; u 0%; rest 73%Read characters to end of data using a construct such as char ch; while( ( ch = getchar() ) >= 0 ) { /* ch is the next character */ .... }to read characters one at a time using getchar() until a negative value is returned.

4) Write a program to read a file INPUT.txt to end-of-data. The output must be a file OUTPUT.txt with words that don’t have repeated letters.

213

Page 213: Informatics. Study Guide. Mathcad. Matlab. VC++

5) Write a program that prompts the user to type text and then deletes all repeated words. Display obtained text, all repeated words and their number.

6) Write a program to read English text to end-of-data (type control-D to indicate end of data at a terminal, see below for detecting it), and print a count of word lengths, i.e. the total number of words of length 1 which occurred, the number of length 2, and so on. Define a word to be a sequence of alphabetic characters. You should allow for word lengths up to 25 letters. Typical output should be like this:

length 1 : 10 occurrences length 2 : 19 occurrences length 3 : 127 occurrences length 4 : 0 occurrences length 5 : 18 occurrences

7) Read ordinary text a character at a time from the program's standard input, and print it with each line reversed from left to right. Read until you encounter end-of-data (see below). You may wish to test the program by typing:

prog5rev | prog5revto see if an exact copy of the original input is recreated. To read characters to end of data, use a loop such as either char ch; while( ch = getchar(), ch >= 0 ) /* ch < 0 indicates end-of-data */or char ch; while( scanf( "%c", &ch ) == 1 ) /* one character read */

8) Words in the sentence are divided by the spaces. The sentence ends with "." "!" "?" Write a program that defines a word with a maximum number of "а" letters and the number of them.

9) Write a program to calculate all numbers and letters occurred in the given sentence and display these numbers.

10) Write a program that counts all words which end with "ed".

11) Given sentence ends with a dot. Delete letter "y" from all words of the sentence. Display the result.

12) Write a program to print the value of the last word in the sentence.

214

Page 214: Informatics. Study Guide. Mathcad. Matlab. VC++

13) Write a program to delete all words "cat" from the given sentence.

14) Write a program that prompts the user to enter a sentence, then counts number of letters in every word and the output in increasing order of numbers of letters in the words.

15) Write a program to replace given letter with three dots.

16) Write a program that prompts the user to enter a word and a letter and then displays a number of occurrences of the letter in the word.

17) Encode a word by replacing a letter with her number in the alphabet.

18) Write a program to output all words that start with a particular letter.

19) Write a program that prompts the user to enter a sentence and defines all words that ends with "ng". Display those words and their number of occurrence.

20) Write a program that prompts the user to enter several sentences and defines all words "she". Display their number of occurrence.

21) Write a program to define the number of words in the given sentence. The sentence must be read from the file INPUT.txt

22) Write a program to define the number of vowels in the given sentence.

23) Write a program that prompts the user to type text and defines how many sentences are there.

24) Write a program that prompts the user to type text and then defines how many spaces are there.

25) Write a program that will ask user to enter sequence of letters and numbers. The output must be the number of letters and numbers.For example: alex12set45The output: 7 and 4

26) Write a program that will ask user to enter several sentences that should end with a dot. The out put should be the same sentence but instead of dots will be other signs, like !,?,#.

215

Page 215: Informatics. Study Guide. Mathcad. Matlab. VC++

27) Write a C++ program which will ask user to enter two words and the output must be the word that has the biggest number of letter ‘e’.

28) Write a C++ program which will ask user to enter a sentence and the output must be the number of letter ‘a’ in the sentence.

29) Write a C++ program which will ask user to enter a word and will change a letter that was chosen by a user. A word must be typed from the keyboard; then user should type 2 letters: 1st – a letter that he wants to replace and 2nd – by which he wants to change. Example:Word: beautiful1st u2nd kResult: beaktifkl

30) Write a program that asks the user to enter his Name and outputs it in reverse way. For example Katya – aytaK.

Laboratory work 21

Input/output with files

Objective – get to know with data files and how to access them; acquirement simple input-output variables of different types; introduction to I / O-indexed variables, arrays, application formatting output.

Problem statement – present initial values in the form of an external text file, enter them from a file and display it in format. Enter the source array from a text file. Display him in its natural form. Implement the task. Results display in another text file.

Theoretical information

C++ provides the following classes to perform output and input of characters to/from files:

ofstream: Stream class to write on files ifstream: Stream class to read from files fstream: Stream class to both read and write from/to files.

These classes are derived directly or indirectly from the classes istream, and ostream. We have already used objects whose types were these classes: cin is an object of class istream and cout is an object of class ostream. Therfore, we have already been using classes that are related to our file streams. And in fact, we can use our file streams the

216

Page 216: Informatics. Study Guide. Mathcad. Matlab. VC++

same way we are already used to use cin and cout, with the only difference that we have to associate these streams with physical files. For example:

#include <iostream>#include <fstream>using namespace std;

int main () { ofstream myfile; myfile.open ("example.txt"); myfile << "Writing this to a file.\n"; myfile.close(); return 0;}

[file example.txt]Writing this to a file

This code creates a file called example.txt and inserts a sentence into it in the same way we are used to do with cout, but using the file stream myfile instead. Basic steps:

Open a file. The first operation generally performed on an object of one of these classes is to associate it to a real file. This procedure is known as to open a file. An open file is represented within a program by a stream object (an instantiation of one of these classes, in the previous example this was myfile) and any input or output operation performed on this stream object will be applied to the physical file associated to it.

In order to open a file with a stream object we use its member function open():

open (filename, mode);Where filename is a null-terminated character sequence of type const char * (the same

type that string literals have) representing the name of the file to be opened, and mode is an optional parameter with a combination of the following flags:ios::in Open for input operations.ios::out Open for output operations.ios::binary Open in binary mode.

ios::ateSet the initial position at the end of the file.If this flag is not set to any value, the initial position is the beginning of the file.

ios::appAll output operations are performed at the end of the file, appending the content to the current content of the file. This flag can only be used in streams open for output-only operations.

ios::truncIf the file opened for output operations already existed before, its previous content is deleted and replaced by the new one.

217

Page 217: Informatics. Study Guide. Mathcad. Matlab. VC++

All these flags can be combined using the bitwise operator OR (|). For example, if we want to open the file example.bin in binary mode to add data we could do it by the following call to member function open():ofstream myfile;myfile.open ("example.bin", ios::out | ios::app | ios::binary); class default mode parameterofstream ios::outifstream ios::infstream ios::in | ios::out

ofstream myfile ("example.bin", ios::out | ios::app | ios::binary);

218

Page 218: Informatics. Study Guide. Mathcad. Matlab. VC++

Combining object construction and stream opening in a single statement. Both forms to open a file are valid and equivalent.

To check if a file stream was successful opening a file, you can do it by calling to member is_open() with no arguments. This member function returns a bool value of true in the case that indeed the stream object is associated with an open file, or false otherwise:

if (myfile.is_open()) { /* ok, proceed with output */ }Closing a file. When we are finished with our input and output

operations on a file we shall close it so that its resources become available again. In order to do that we have to call the stream's member function close(). This member function takes no parameters, and what it does is to flush the associated buffers and close the file:

myfile.close();Once this member function is called, the stream object can be used

to open another file, and the file is available again to be opened by other processes.

In case that an object is destructed while still associated with an open file, the destructor automatically calls the member function close().

Text files. Text file streams are those where we do not include the ios::binary flag in their opening mode. These files are designed to store text and thus all values that we input or output from/to them can suffer some formatting transformations, which do not necessarily correspond to their literal binary value.

Data output operations on text files are performed in the same way we operated with cout:

// writing on a text file#include <iostream>#include <fstream>using namespace std;

int main () { ofstream myfile ("example.txt"); if (myfile.is_open()) { myfile << "This is a line.\n"; myfile << "This is another line.\n"; myfile.close(); } else cout << "Unable to open file"; return 0;}

[file example.txt]This is a line.This is another line.

219

Page 219: Informatics. Study Guide. Mathcad. Matlab. VC++

Data input from a file can also be performed in the same way that we did with cin:// reading a text file#include <iostream>#include <fstream>#include <string>using namespace std;

int main () { string line; ifstream myfile ("example.txt"); if (myfile.is_open()) { while (! myfile.eof() ) { getline (myfile,line); cout << line << endl; } myfile.close(); }

else cout << "Unable to open file";

return 0;}

This is a line.This is another line.

This last example reads a text file and prints out its content on the screen. Notice how we have used a new member function, called eof() that returns true in the case that the end of the file has been reached. We have created a while loop that finishes when indeed myfile.eof() becomes true (i.e., the end of the file has been reached).

Checking state flags. In addition to eof(), which checks if the end of file has been reached, other member functions exist to check the state of a stream (all of them return a bool value):

bad() – returns true if a reading or writing operation fails. For example in the case that we try to write to a file that is not open for writing or if the device where we try to write has no space left.

fail() – returns true in the same cases as bad(), but also in the case that a format error happens, like when an alphabetical character is extracted when we are trying to read an integer number.

eof() – returns true if a file open for reading has reached the end.

220

Page 220: Informatics. Study Guide. Mathcad. Matlab. VC++

good() – is the most generic state flag: it returns false in the same cases in which calling any of the previous functions would return true.

In order to reset the state flags checked by any of these member functions we have just seen we can use the member function clear(), which takes no parameters.

get and put stream pointers. All i/o streams objects have, at least, one internal stream pointer: ifstream, like istream, has a pointer known as the get pointer that points to the element to be read in the next input operation.

ofstream, like ostream, has a pointer known as the put pointer that points to the location where the next element has to be written.

Finally, fstream, inherits both, the get and the put pointers, from iostream (which is itself derived from both istream and ostream).

These internal stream pointers that point to the reading or writing locations within a stream can be manipulated using the following member functions:

tellg() and tellp(): these two member functions have no parameters and return a value of the member type pos_type, which is an integer data type representing the current position of the get stream pointer (in the case of tellg) or the put stream pointer (in the case of tellp).

seekg() and seekp(): these functions allow us to change the position of the get and put stream pointers. Both functions are overloaded with two different prototypes. The first prototype is: seekg ( position ); seekp ( position );

221

Page 221: Informatics. Study Guide. Mathcad. Matlab. VC++

Using this prototype the stream pointer is changed to the absolute position position (counting from the beginning of the file). The type for this parameter is the same as the one returned by functions tellg and tellp: the member type pos_type, which is an integer value.

The other prototype for these functions is: seekg ( offset, direction ); seekp ( offset, direction );

Using this prototype, the position of the get or put pointer is set to an offset value relative to some specific point determined by the parameter direction. offset is of the member type off_type, which is also an integer type. And direction is of type seekdir, which is an enumerated type (enum) that determines the point from where offset is counted from, and that can take any of the following values:

ios::beg offset counted from the beginning of the streamios::cur offset counted from the current position of the stream pointerios::end offset counted from the end of the stream

The following example uses the member functions we have just seen to obtain the size of a file:

// obtaining file size#include <iostream>#include <fstream>using namespace std;

int main () { long begin,end; ifstream myfile ("example.txt"); begin = myfile.tellg(); myfile.seekg (0, ios::end); end = myfile.tellg(); myfile.close(); cout << "size is: " << (end-begin) << " bytes.\n"; return 0;}

size is: 40 bytes.Buffers and Synchronization. When we operate with file streams,

these are associated to an internal buffer of type streambuf. This buffer is a memory block that acts as an intermediary between the stream and the physical file. For example, with an ofstream, each time the member function put (which writes a single character) is called, the character is not written directly to the physical file with which the stream is associated. Instead of that, the character is inserted in that stream's intermediate buffer.

When the buffer is flushed, all the data contained in it is written to the physical medium (if it is an output stream) or simply freed (if it is an

222

Page 222: Informatics. Study Guide. Mathcad. Matlab. VC++

input stream). This process is called synchronization and takes place under any of the following circumstances:

When the file is closed: before closing a file all buffers that have not yet been flushed are synchronized and all pending data is written or read to the physical medium.

When the buffer is full: Buffers have a certain size. When the buffer is full it is automatically synchronized.

Explicitly, with manipulators: When certain manipulators are used on streams, an explicit synchronization takes place. These manipulators are: flush and endl.

Explicitly, with member function sync(): Calling stream's member function sync(), which takes no parameters, causes an immediate synchronization. This function returns an int value equal to -1 if the stream has no associated buffer or in case of failure. Otherwise (if the stream buffer was successfully synchronized) it returns 0.

Variants should be taken from the laboratory works of the number 2 and number 7 on the instructions of the teacher.

223

Page 223: Informatics. Study Guide. Mathcad. Matlab. VC++

List of literature

1. Brent Maxfield. Engineering With Mathcad. – Elsevier, 2006. – 494p.

2. Beucher O., Weeks M. Introduction to MATLAB & Simulink: A Project Approach, Third Edition.– Pearson Studium, 2006. – 386p.

3. Otto S.R., Denier J.P. An introduction to programming and numerical methods in MATLAB. – Springer-Verlag London Limited, 2005. – 463p.

4. Jesse Liberty, Bradley Jones.Teach Yourself C++ in 21 Days. – Sams Publishing, 2005. – 911p.

5. Ivor Horton. Beginning Visual C++. – Wiley Publishing, Inc., 2008. – 1356p.

6. John C. Molluzzo. C++ for Business Programming. – Prentice Hall, 2005. – 848p.

7. Deitel H. M. C++ How to Program. – Prentice Hall, 2005. – 1536p.

8. http://www.mathworks.com/access/helpdesk/help/techdoc/index.html?/access/helpdesk/help/techdoc/matlab_prog/f7-41453.html

9. http://www.mathworks.com/access/helpdesk/help/techdoc/index.html?/access/helpdesk/help/techdoc/ref/function.html

10. http://www.owlnet.rice.edu/~math211/

224

Page 224: Informatics. Study Guide. Mathcad. Matlab. VC++

CONTENT:Laboratory work 1. Introduction to Mathcad……………………………. 3Laboratory work 2. Matrix operations in Mathcad……………………… 15Laboratory work 3. Plotting in Mathcad…………………………………. 28Laboratory work 4. Simple logic programming in Mathcad…………… 50Laboratory work 5. Advanced programming in Mathcad……………… 62Laboratory work 6. Elementary Matlab constructs…………………….. 75Laboratory work 7. Mathematical operations…………………………… 85Laboratory work 8. Graphical functions…………………………………. 105Laboratory work 9. More complicated data structures………………… 118Laboratory work 10. Matlab programming……………………………… 130Laboratory work 11. M-file in Matlab……………………………………. 144Laboratory work 12. Introduction to VC++. Structure of a program….. 148Laboratory work 13. Basic Input/Output………………………………… 166Laboratory work 14. Else-If conditional structure……………………… 178Laboratory work 15. Iteration structures………………………………… 189Laboratory work 16. Control Structures…………………………………. 200Laboratory work 17. User-defined functions in VC++…….…………… 209Laboratory work 18. Arrays………………………………………………. 221Laboratory work 19. Character sequences……………………………... 245Laboratory work 20. Input/output with files……………………………... 256

225