You are on page 1of 19

Sheet 2

control structures

if condition
if (condition) statement

if (x == 100)
cout << "x is 100";

Relational and equality operators


( ==, !=, >, <, >=, <= )
==
!=
>
<

Equal to
Not equal to
Greater than
Less than

>=

Greater than or equal to

<=

Less than or equal to

Relational and equality operators


( ==, !=, >, <, >=, <= )
(7 == 5)
(5 > 4)
(3 != 2)
(6 >= 6)
(5 < 5)

// evaluates to false.
// evaluates to true.
// evaluates to true.
// evaluates to true.
// evaluates to false.

Logical operators ( !, &&, || )


!(5 == 5)
!(6 <= 4)
!true
!false

// evaluates to false
// evaluates to true
// evaluates to false
// evaluates to true.

Logical operators ( !, &&, || )


( (5 == 5) && (3 > 6) ) // evaluates to false
( (5 == 5) || (3 > 6) ) // evaluates to true

if condition
if (x == 100)
{
cout << "x is ";
cout << x;
}

if else
if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";

if else
if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative";
else
cout << "x is 0";

Question 6 (Sheet 1)
Write a program that reads in the values for a, b,
and c and find the roots of the polynomial:
2 + + = 0

Question 6 (Sheet 1)
Write a program that reads in the values for a, b,
and c and find the roots of the polynomial:
2 + + = 0

2 4
2

Question 6 (Sheet 1)
a. The first coefficient is zero: Program terminates with an
error message.
b. Complex roots: Program prints solutions including the
imaginary part.
c. One real solution: Program states that there is only one
solution and prints it.
d. Two different real solutions: Program prints both
normally.

Loops
Do I know the number of repetitions?
Yes (for loop)
for (initialization; condition; increase)
statement;

No (while and do-while)


while (expression)
statement;

for loop

Question 1
Write a program that prints the square of all
numbers from 1 to 20.

Question 2
Write a program that computes and displays the
sum of odd integers in the range 0 to 100,
inclusive.

Conditional operator ( ? )
X= (7==5) ? 4 : 3
X= (7==5+2) ? 4 : 3
X= 5>3 ? a : b

// returns 3
// returns 4
//X=a

Question 4
Write a program to read a collection of exam
scores ranging in values from 1 to 100. Your
program should find and print the average
score, the maximum and the minimum scores.
the program will terminate if the value -99 is
entered by the user.

Question 5
Write a program fragment that uses nested loops to produce
the following output:
1
12
123
1234
12345
123456
1234567
12345678
123456789

You might also like