Structures for Statements - Computing in Engineering and Science - Exercise, Exercises of Computer Science

Basic exercise from Computing in Engineering and Science course. Keywords in this course are: Structures for Statements, Algorithm, Basic If Statement, Boolean Expressions, Code Review and Errors, Data Validation with Boolean Variables, Significant Figures

Typology: Exercises

2013/2014

Uploaded on 02/01/2014

savitri_122
savitri_122 🇮🇳

4.6

(14)

184 documents

1 / 6

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Fifth Programming Exercise
Objective
This exercise should give you the ability to write code using the various structures for if
statements in C++. You will also see the results of two common errors in if statements:
(1) placing an extra semicolon at the end of the if statement and (2) using a single equal sign
instead of a double equal sign for the relational operator that tests for equality. Next you will look
at Boolean variables used for data validation. Finally, you will have the opportunity to write some
code that uses if statements, starting from a verbal description of an algorithm.
Background for Exercise
During class, we have seen various formats for C++ if statements as shown below.
The basic if statement
if (
<condition>
)
{
< true statement block >
}
<next statement executed if
condition is false>
The if-elseif statement
if (
<condition1>
)
{
< block executed if
condition1 is true>
}
else if (
<condition2>
)
{
< block executed if
condition2 is true>
}
else if (
<conditionN>
)
{
< block executed if
conditionN is true --- can
have many elseif blocks>
}
else
{
< executed is no conditions
are true block >
}
<transfer control here when
statements after first true
condition are completed>
The if-else statement
if (
<condition>
)
{
< true statement block >
}
else
{
< flase statement block >
}
<next statement executed after
true or false block>
The
<condition>
in the structures above is a Boolean expression that is evaluated as true or
false. Boolean expressions are created by a combination of relational operators (<, > <=, >=, ==,
and !=) and logical operators (!, &&, ||). The relational operators allow us to determine the truth or
falsity about relations between variables. E. g., hours < 40 will be true is the variable hours is
greater than 40; it will be false otherwise. We also saw that we could define Boolean variables
with the C++ type bool. An example of this is shown below.
bool goodData = x >= xMin && x <= xMax;
We can use either of the following approaches to do an if test for good data.
bool goodData = x >= xMin && x <= xMax;
if ( goodData)
docsity.com
pf3
pf4
pf5

Partial preview of the text

Download Structures for Statements - Computing in Engineering and Science - Exercise and more Exercises Computer Science in PDF only on Docsity!

Fifth Programming Exercise

Objective

This exercise should give you the ability to write code using the various structures for if

statements in C++. You will also see the results of two common errors in if statements: (1) placing an extra semicolon at the end of the if statement and (2) using a single equal sign

instead of a double equal sign for the relational operator that tests for equality. Next you will look at Boolean variables used for data validation. Finally, you will have the opportunity to write some

code that uses if statements, starting from a verbal description of an algorithm.

Background for Exercise

During class, we have seen various formats for C++ if statements as shown below.

The basic if statement

if ( )

< true statement block >

<next statement executed if

condition is false>

The if-elseif statement

if ( )

< block executed if

condition1 is true>

else if ( )

< block executed if

condition2 is true>

else if ( )

< block executed if

conditionN is true --- can

have many elseif blocks>

else {

< executed is no conditions

are true block >

<transfer control here when

statements after first true

condition are completed>

The if-else statement

if ( )

< true statement block >

else {

< flase statement block >

<next statement executed after

true or false block>

The in the structures above is a Boolean expression that is evaluated as true or

false. Boolean expressions are created by a combination of relational operators (<, > <=, >=, ==,

and !=) and logical operators (!, &&, ||). The relational operators allow us to determine the truth or falsity about relations between variables. E. g., hours < 40 will be true is the variable hours is

greater than 40; it will be false otherwise. We also saw that we could define Boolean variables with the C++ type bool. An example of this is shown below.

bool goodData = x >= xMin && x <= xMax;

We can use either of the following approaches to do an if test for good data.

bool goodData = x >= xMin && x <= xMax; if ( goodData)

or

if( x >= xMin && x <= xMax )

It is simpler to use the single statement immediately above. However, the use of the Boolean variable goodData clarifies what we are doing and can be used in later if tests to continue the

calculation if the data are good.

Overview of the exercise

This project has four tasks. The first two are copy and paste assignments; the third requires you to create a program from scratch for solving a quadratic equation, ax 2 + bx + c = 0, that will

account for all possible results depending on the input data. The fourth task is a simple follow up to task three to illustrate the possible roundoff error in solving the quadratic equation. The

instructions below discuss the items that you should place on the submission file, to which you will copy all your listings and the screen displays from the program execution. See the notes for

the second exercise for details preparing the submission file. Make sure that your name and your lab day are on the top of your submission file.

Specific tasks

Task one: Code review and errors – Copy the code below into Visual C++ then compile and

execute it without any changes, except for entering your name and today’s date in the initial

comments.

Programmer: Date: Comp 106 Exercise Five If Statements Task one */ #include using namespace std;

int main() { // Examine output from errors (incorrect semicolon and // incorrect relational operator for "is equal to" )

int x = 1; if ( x == 10); { cout << "First if block is executed only when x = 10.\n" << "Here x = " << x << endl << endl; }

if ( x = 7 ) { cout << "True block from second if is executed when x = 7.\n" << "Here x = " << x << endl << endl; } else { cout << "False block from second if is executed when x != 7.\n" << "Here x = " << x << endl << endl; } }

Note the errors in the two if statements and observe the output these errors cause when you run

the program. Make sure that you understand these errors so that you can avoid them in the future. Correct the errors and run the code a second time. For both runs, copy the code and the

screen output to the submission file

Make sure that you understand why the output values of the Boolean variables have the values

they do. Copy the code and the output from your three runs to the submission file.

Task three: Quadratic roots – Write a program to solve the general problem of finding the roots of

a quadratic equation, ax^2 +bx + c = 0. Recall the conventional equation for the two roots, x 1 and x 2 , of a quadratic equation as shown below.

a

b b ac x x 2

4 ,

2 1 2

   

Several problems may occur when trying to use this equation in a program including zero coefficients, complex roots, and roundoff error. The algorithm below is used to handle all

possible problems by specifying values for x 1 and x 2 for special cases instead of using the formulas above. Your program should prompt the user to input a, b, and c then use the algorithm

below to calculate and print the appropriate results.

(a) If a = 0 and b= 0, the program should print a message that there is no solution for this case.

(b) Otherwise, if a = 0 and b ≠ 0, there is only one solution x = -c/b. The program should print out a message that these inputs give a linear equation, not a quadratic equation, with only one solution; it should also print the value of that solution.

(c) Otherwise, if b 2 – 4ac ≈ 0 print a message that there are two quadratic roots, both of which

have the same value. Print the value of the common root which is a

b

2

. To make this test

that b 2 – 4ac ≈ 0, you should use an if statement like the following: if ( fabs( b * b – 4 * a * c ) < 1e-15*( b * b + fabs( 4 * a * c) ). This will account for cases where the b^2 – 4ac is different from zero only due to roundoff error.

(d) Otherwise, if b 2 – 4ac < 0, the roots are complex. Your program should print out the fact that

the roots are complex and then print the roots as the real part plus i times the imaginary part;^1 the real and imaginary parts are found by the equations below

a

b ac and a

b

2

4

2

2  Real part  Imaginarypart.

(e) Otherwise, the only case remaining is b 2 – 4ac > 0; in this case, print a message that there are two distinct real roots and print their values. Calculate the roots from the conventional

equations a

b b ac x 2

4 2 1

    and a

b b ac x 2

4 2 2

   .

Run your code for the seven different sets of input data shown in the table below. If you use keyboard input, you can write your code to handle repeated cases, using the structure below that

we have used in previous programs. (This code is not required, but it can simplify the handling of multiple input cases.)

(^1) Recall that i is the square root of -1; in electrical engineering j is used to represent the square root of -1 to

avoid confusion with the symbol i used for the current. For this exercise you may use whatever symbol you

are more comfortable with. Your output should note that whatever letter you are using is  1. Here are four examples of different ways to write your output for the complex case where the real part is 3.1 and the imaginary part is 6.2: (1) x1 = 3.1 + 6.2i and x2 = 3.1 - 6.2i, (2) x1 = 3.1 + 6.2j and x2 = 3.1 – 6.2j, (3) x1 = 3.1 + 6.2 * sqrt(-1) and x2 = 3.1 + 6.2 * sqrt(-1), or (4) the roots are complex; the real part is 3.1 and the imaginary part is 6.2.

char yesno; do { // Place entire program code, including input and output here

cout << "\n\nDo you want to run another case Y[es]/N[o]? "; cin >> yesno; } while ( (yesno == 'Y') || (yesno == 'y') );

Print all results to 14 significant figures to compare with the results from task four below. Copy

your code and the screen input and output from the seven cases to the submission file. (Remember the difference between 14 significant figures and 14 decimal places. Also remember that default output

does not print trailing zeros.)

Case: I II III IV V VI VII

a = 0 0 0 2 1 1 10 -

b = 0 0 1.5 0 2 4 1

c = 0 1 2.25 1 1 1 10 -

Task four: Roundoff error – Replace step (e) in the task-three algorithm by the following steps, designed to reduce potential round-off error when the two terms in the numerator of the equation

for quadratic roots are very nearly equal.

(e) If b 2 – 4ac > 0 print a message that there are two distinct real roots and print their values.

Continue to use 14 significant figures for the output. Depending on the sign of b, use different equations to calculate the first root, x 1 , as shown in step (e1) below. Regardless of the sign of b, use the equation in step (e2) to compute the second root, x 2.

(e1) If b > 0 then compute x 1 , =  b b 4 ac  / 2 a

2    ,

otherwise, compute x 1 =  b b 4 ac  / 2 a

2   

(e2) x 2 = ax 1

c

Run the task-four code only for the Case VII data in the input table. Copy both the code and the

screen output to the submission file. Compute the results from a series solution that is accurate to 14 significant figures for the Case VII data. 2 (You can write a program, use a spreadsheet, or

do hand calculations to get these results.) Write a brief discussion in the submission file that compares the results for case VII from the codes in task three and task four to the results from

the series solution. Do your results verify that the task-four code is more accurate?

Submit a copy of the submission file with all the elements asked for in the each task above.

(^2) You can use the series expansion that (1 + x)n (^) = 1 + nx + n(n – 1)x (^2) /2 + n(n – 1)( n – 2)x (^3) /6 + … to obtain

series solutions for the roots of the quadratic in the round-off-error case where 4ac/b^2 << 1:

 

 

   

  

   

  

  

  

 

 

   

  

   

  

  ^     

3

2

2

2 2

3

2

2 1 2 2 2 5 1 2 b

ac

b

ac

b

ac

a

b x b

ac

b

ac

b

ac

b

c x

Use these equations to compute the exact results to 14 significant figures for comparison with the computed results from tasks three and four.