Download PROGRAMMING FUNDAMENTALS IN C++

Transcript
CHAPTER 2. LECTURE NOTES
108
else if (del <0)
cout "Both roots are imaginary.\n";
else
cout Both roots are equal to -b/(2*a) endl;
}
return 0;
}
2.4.10.4 Step 4: Test and Correct the Program
Test values should include values for a, b and c that result in two real roots, plus limiting values for a and
b that result in linear equation (a = 0, b != 0), a degenerate equation ( a = 0, b = 0), and a negative and 0
discriminant. Two such test runs of the above program follow:
This program calculates the roots of a
quadratic equation of the form
ax^2 + bx + c = 0
Please enter values for a, b and c: 1 2 -35
The two real roots are 5 and 7
and
This program calculates the roots of a
quadratic equation of the form
ax^2 + bx + c = 0
Please enter values for a, b and c: 0 0 16
This equation is degenerate and has no roots.
We leave it as an exercise to create test data for the other limiting cases checked for by the program.
2.5 Repetition Statements, Arrays and Structured Programming
5
2.5.1 Basic Loop Structures
The real power of a program is realized when the same type of operation must be made over and over.
Constructing a repetitive section of code requires that four elements be present.
The rst necessary
element is a repetition statement. This repetition statement denes the boundaries containing the repeating
section of code and also controls whether the code is executed or not. C++ provides three dierent forms
of repetition statements:
1.
2.
3.
while structure
for structure
do-while structure
Each of these statements requires a condition that must be evaluated, which is the second required element
for constructing repeating sections of code. Valid conditions are similar to those used in selection statements.
If the condition is true, the code is executed; otherwise, it is not.
The third required element is a statement that initially sets the condition. This statement must always
be placed before the condition is rst evaluated to ensure correct loop execution the rst time the condition
is evaluated.
Finally, there must be a statement within the repeating section of code that allows the condition to
become false. This is necessary to ensure that, at some point, the repetition stop.
The condition being tested can be evaluated at either (1) the beginning or (2) the end of the repeating
section of code.
5 This
content is available online at <http://cnx.org/content/m27289/1.1/>.