0% found this document useful (0 votes)
19 views

Chapter 3

Uploaded by

abebemako302
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Chapter 3

Uploaded by

abebemako302
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

ü Conditional Statements

ØIF Statement
ØSwitch Statement
ü Looping Statements
Ø The ‘While’ Statement
Ø The ‘for’ Statement
Ø The ‘do….While’ Statement
ü Other Statements
ØThe ‘Continue’ Statement
ØThe ‘break’ Statement
ØThe ‘goto’ Statement
ØThe ‘Return’ Statement
ü The following example demonstrates that correctly specifying the
order in which the actions execute is important.
ü Consider the "rise-and-shine algorithm" followed by one executive
for getting out of bed and going to work:
1) get out of bed; 4) get dressed;
2) take off pyjamas; 5) eat breakfast;
3) take a shower; 6) go to work.
ü Like many other procedural languages, C++ provides different forms of
statements for different purposes.
ØDeclaration statements are used for defining variables.
ØAssignment statements are used for simple, algebraic computations.
ØBranching statements are used for specifying alternate paths of execution,
depending on the outcome of a logical condition.
ØLoop statements are used for specifying computations, which need to be
repeated until a certain logical condition is satisfied.
ØFlow control statements are used to divert the execution path to another
part of the program.
ü Specifying the order in which statements (actions) execute in a
program is called program control.
ü Program control or control statement can be :
ØConditional (Selection) Statement (if, if…else, switch)
ØLooping (Repetition )Statement(while, do…while, for-loop)
ØBranching Statement(break, continue, return)
ü If Statement:
Ø It is sometimes desirable to make the execution of a statement
dependent upon a condition being satisfied.
Ø Syntax:
if (expression)
statement;

Ø For example:
if (count != 0)
average = sum / count;
ØTo make multiple statements dependent on the same condition,
we can use a compound statement:
Ø For Example :
if (balance > 0)
{
interest = balance * creditRate;
balance += interest;
}
ü The if-else statement
ØSyntax:
if (expression)
statement1;
else
statement2;

ØFirst expression is evaluated. If the outcome is nonzero (true)


then statement1 is executed. Otherwise, statement2 is executed.
ØFor example:
if (balance > 0) {
interest = balance * creditRate;
balance += interest;
}
else {
interest = balance * debitRate;
balance += interest;
}
ØIf statements may be nested by having an if statement appear
inside another if statement. For example:
if (callHour > 6) {
if (callDuration <= 5)
charge = callDuration * tarrif1;
else
charge = 5 * tarrif1 + (callDuration - 5) * tarrif2;
} else
charge = flatFee;
ü Switch Statement:
ØThe switch statement provides a way of choosing between a set of alternatives,
based on the value of an expression.
ØSyntax:
switch (expression) {
case constant1:
statements;
...
default:
statements;
}
ü Switch Statement:
Ø For example, suppose we have parsed a binary arithmetic operation into its
three components and stored these in variables operator, operand1, and
operand2.
ØThe following switch statement performs the operation and stores the result
in result.
Ø Switch Statement:
switch (operator) {
case '+': result = operand1 + operand2;
break;
case '-': result = operand1 - operand2;
break;
case '*': result = operand1 * operand2;
break;
case '/': result = operand1 / operand2; break;
default: cout << "unknown operator: " << ch << '\n'; break;
}
1. Write an if-else statement that outputs the word High if the value of the
variable score is greater than 100 and Low if the value of score is less
than100. The variable score is of type int.
2. Write an if-else statement that outputs the word Passed provided the value
of the variable exam is greater than or equal to 60 and also the value of the
variable programsDone is greater than or equal to 10. Otherwise, the if-else
statement outputs the word Failed. The variables exam and programsDone
are both of type int.
3. Write a program to display the month name as the user enters a number
from 1 to 12 .Hint use switch statement…(1-september,2-october,…..)
ü The ‘while’ Statement:
Ø The while statement (also called while loop) provides a way
of repeating a statement while a condition holds. It is one of
the three flavours of iteration in C++.
Ø The general form is:
while (expression) or while (expression){
statement; Statement1
Statement2
}
ü The while’ Statement:
Ø For example, suppose we wish to calculate the sum of all
numbers from 1 to 10.
Ø This can be expressed as:
i = 1;
sum = 0;
while (i <= 10)
sum += i;
ü The ‘for’ Statement:
ØThe for statement (also called for loop) is similar to the while
statement, but has two additional components: an expression
which is evaluated only once before everything
else(initialization ), and an expression which is evaluated once
at the end of each iteration(incremental/decremental).
Ø The general form is:
for (exp1;exp2; exp3) or for (exp1;exp2; exp3){
statement; statements’
}
Ø The general for loop is equivalent to the following while loop:
expression1;
while (expression2) {
statement;
expression3; }

Ø for example, calculates the sum of all integers from 1 to n.


sum = 0;
for (i = 1; i <= n; ++i)
sum += i;
Ø Any of the three expressions in a for loop may be empty.
Ø For example, removing the first and the third expression gives us
something identical to a while loop:
for (; i != 0;) // is equivalent to: while (i != 0)
something; something;

Ø Removing all the expressions gives us an infinite loop.


Ø This loop's condition is assumed to be always true:
for (;;) // infinite loop
something;
Ø For loops with multiple loop variables are not unusual. In such
cases, the comma operator is used to separate their expressions:
for (i = 0, j = 0; i + j < n; ++i, ++j)
something;

Ø Because loops are statements, they can appear inside other loops. In
other words, loops can be nested. For example,
for (int i = 1; i <= 3; ++i)
for (int j = 1; j <= 3; ++j)
cout << ‘(' << i << ',' << j << ")\n“;
ü The ‘do…while’ Statement:
Ø The do statement (also called do loop) is similar to the while
statement, except that its body is executed first and then the
loop condition is examined.
ØSyntax:
do or do{
statement; statements;
while (expression); }while(expression);
Ø For example, suppose we wish to repeatedly read a value and
print its square, and stop when the value is zero.
Ø This can be expressed as the following loop:
do {
cin >> n;
cout << n * n << '\n';
} while (n != 0);
1. Write a program is to display 1 up to 10 horizontally(i.e
separated by tab ‘\t’ as well as vertically use the endline ‘\n’
or endl
2. Write a program is to find the factorial of 10!.
3. Write a program is to display the reverse of a given number
for example if a user inters 123 the program should display
321.
4. Write a program that print sum of the digits. For instance if a
user enters 123 the program should display 6 i.e 1+2+3=6
Branching Statements
ü The ‘continue’ Statement:
ØThe continue statement terminates the current iteration of a
loop and instead jumps to the next iteration.
ØIt applies to the loop immediately enclosing the continue
statement.
ØIt is an error to use the continue statement outside a loop.
Branching Statements
ü The ‘continue’ Statement:
ØFor example, a loop which repeatedly reads in a number,
processes it but ignores negative numbers, and terminates when
the number is zero, may be expressed as:
do {
cin >> num;
if (num < 0) continue;
// process num here...
} while (num != 0);
Branching Statements
ü The ‘break’ Statement:
ØA break statement may appear inside a loop (while, do, or for)
or a switch statement.
ØIt causes a jump out of these constructs, and hence terminates
them.
ØLike the continue statement, a break statement only applies to
the loop or switch immediately enclosing it.
ØIt is an error to use the break statement outside a loop or a
switch.
Branching Statements
ü The ‘break’ Statement:
ØFor example, suppose we wish to read in a user password, but
would like to allow the user a limited number of attempts:
for (i = 0; i < attempts; ++i) {
cout << "Please enter your password: ";
cin >> password;
if (password==123) // check password for correctness
break; // drop out of the loop
cout << "Incorrect!\n";
}
Branching Statements
ü The ‘goto’ Statement:
ØThe goto statement provides the lowest-level of jumping.
ØIt has the general form:
goto label;

where label is an identifier which marks the jump


destination of goto.
ØThe label should be followed by a colon and appear before a
statement within the same function as the goto statement itself.
Branching Statements
ØFor example, the role of the break statement in the for loop in
the previous section can be emulated by a goto:
for (i = 0; i < attempts; ++i) {
cout << "Please enter your password: ";
cin >> password;
if (Verify(password)) // check password for correctness
goto out; // drop out of the loop
cout << "Incorrect!\n";
}
out:
//etc...
Branching Statements
ü The ‘return’ Statement :
ØThe return statement enables a function to return a value to its
caller.
ØIt has the general form:
return expression; where expression denotes the value
returned by the function.
ØThe type of this value should match the return type of the
function.
Branching Statements
ü The ‘return’ Statement:
ØFor a function whose return type is void, expression should be
empty:
return;
ØThe only function we have discussed so far is main, whose
return type is always int.
ØThe return value of main is what the program returns to the
operating system when it completes its execution.
Branching Statements
ü The ‘return’ Statement:
ØUnder UNIX, for example, it its conventional to return 0 from
main when the program executes without errors. Otherwise, a
non-zero error code is returned. For example:
int main (void)
{
cout << "Hello World\n";
return 0;
}
Branching Statements
ü The ‘return’ Statement:
ØWhen a function has a non-void return value (as in the above
example), failing to return a value will result in a compiler
warning.
ØThe actual return value will be undefined in this case (i.e., it
will be whatever value which happens to be in its
corresponding memory location at the time).

You might also like