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

Chapter 3-Control StatementsI

This document is a chapter on control statements in C++ programming, covering the flow control of programs, including conditional statements like if and switch, as well as looping statements such as while, for, and do-while. It explains the syntax and usage of these statements with examples, highlighting how they direct the execution path of a program. Additionally, it discusses other control statements like continue, break, goto, and return, providing insights into their applications within loops and functions.

Uploaded by

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

Chapter 3-Control StatementsI

This document is a chapter on control statements in C++ programming, covering the flow control of programs, including conditional statements like if and switch, as well as looping statements such as while, for, and do-while. It explains the syntax and usage of these statements with examples, highlighting how they direct the execution path of a program. Additionally, it discusses other control statements like continue, break, goto, and return, providing insights into their applications within loops and functions.

Uploaded by

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

Assosa University Department of Computer Science

Fundamentals of Programming I
Chapter III
Control Statements
________________________________________________________________________________

3.1. Introduction
A running program spends all of its time executing statements. The order in
which statements are executed is called flow control (or control flow). Flow
control in a program is sequential, from one statement to the next, but may be
diverted to other paths by branch statements.
There are different forms of C++ statements:
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.

3.2. Conditional Statements

3.2.1. The if Statement


General form:
if (expression)
statement;
First expression is evaluated. If the outcome is true then statement is executed.
Otherwise, nothing happens.
For example, when dividing two values, we may want to check that the
denominator is nonzero:
if (y!= 0) if(n<=0)
z = x/y; cout<<”Illegal Square Root!”;
To make multiple statements dependent on the same condition, we can use a
compound statement:
if (balance > 0) {
interest = balance * creditRate;
balance += interest;
}
3.2.1.1 if-else statement
General form:
if (expression)
statement1;
else
statement2;
First expression is evaluated. If the outcome is true then statement1 is
executed. Otherwise, statement2 is executed.

For example: if(score>=85)


{
if (balance > 0) cout<<”A Grade”;
{ }
interest = balance * creditRate; else if(score>=75){
cout<<”B Grade”;
balance += interest; }
else if(score>=65){
cout<<”C Grade”; 1|P a g e
}
else if(score>=50){
cout<<”D Grade”;
Assosa University Department of Computer Science

}
else {
interest = balance * debitRate;
balance += interest;
}
For example:
if(n!=0){
if(score>=50)
z = x/y; {
} cout<<”U Passed!”;
else { }
else{
cout<<”Illegal Division by 0!”;Cout<<”U Failed!”;
} Cout<<”U Must Take This Course
Again!”;
3.2.2. The switch Statement }

Multiple-choice, provides a way of choosing between a set of alternatives.


General form:
switch (expression) {
case constant1:
statements;
...
case constantn:
statements;
default:
statements;
}

First expression (called the switch tag) is evaluated, and the outcome is
compared to each of the numeric constants (called case labels), in the order
they appear, until a match is found. The final default case is optional and is
exercised if none of the earlier cases provide a match.
Example: Binary arithmetic operation into its three components and stored
these in variables operator, operand1, and operand2, switch performs the
operation and stores the result in result.
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;
}
The break terminates the switch statement by jumping to the very end of it.
For example, allowing x to be used as a multiplication operator
switch (operator) {
case 'x':
case '*': result = operand1 * operand2;
break;
default: cout << "unknown operator: " << ch << '\n';
break;
}
The above switch statement can be written as in if-else statement
if (operator == '+')

2|P a g e
Assosa University Department of Computer Science

result = operand1 + operand2;


else if (operator == '-')
result = operand1 - operand2;
else if (operator == 'x' || operator == '*')
result = operand1 * operand2;
else if (operator == '/')
result = operand1 / operand2;
else
cout << "unknown operator: " << ch << '\n';

3.3. Looping Statements

3.3.1. The ‘while’ Statement


The while loop provides a way of repeating a statement while a condition holds
or is true.
while (expression)
statement;

First expression (called the loop condition) is evaluated. If the outcome is


nonzero then statement (called the loop body) is executed and the whole
process is repeated. Otherwise, the loop is terminated.
Example: To calculate the sum of all numbers from 1 to integer n and 1-10

i = 1; int n, sum=0; while(age<=17 &&


age>=45)
sum = 0; while(n<=10) {
while (i <= n) sum+=n; cout<<”Invalid Age! Plz

While loop can have an empty body i.e., null statement).


Example: Setting n to its greatest odd factor.

while (n % 2 == 0 && n /= 2)

Here the loop condition provides all the necessary computation including
division by 2, so there is no real need for a body.

3.3.2. The ‘for’ Statement


The for loop is similar to the while statement, but has two additional
components: an expression which is evaluated only once before everything else,
and an expression which is evaluated once at the end of each iteration.
The general form:

for(expression1;expression2;expression3) for(initialization; condition;


inc/decrement)
statements; statements;

First expression1 is evaluated. Each time round the loop, expression2 is


evaluated. If the condition is true then statement is executed and expression3 is
evaluated. Otherwise, the loop is terminated.

The general for loop is equivalent to the following while loop:


expression1;
while (expression2) {
3|P a g e
Assosa University Department of Computer Science

statement;
expression3;
}
For loop example to calculates the sum of all integers from 1 to n.
sum = 0;
for (i = 1; i <= n; ++i)
sum += i;
This is preferred to the while-loop version, i is usually called the loop variable.
Loop variable i can be defined inside the loop itself:

for (int i = 1; i <= n; ++i) Equivalent to: int i;


sum += i; for (i = 1; i <= n;
++i)
sum += i; //sum=sum+i;
For loop can be empty, removing the first and the third expression gives
identical to while loop:

for (; i != 0;) // is equivalent to: while (i != 0)


something; //something;
Removing all the expressions gives infinite loop. This loop's condition is
assumed to be always true:
for (;;) // infinite loop
something;
Example:
for(;;)
{
if(n<=0)
break;
else
{
sum+=i;
}
}
For loops with multiple loop variables are not unusual. In such cases, the
comma operator is used to separate their expressions:
Output:
(1,1)
for (i = 0, j = 0; i + j < n; ++i, ++j) (1,2)
something; (1,3)
Because loops are statements, they can appear inside other(2,1)
loops.
(2,2)
In other words, loops can be nested. (2,3)
For example, (3,1)
for (int i = 1; i <= 3; ++i) (3,2)
(3,3)
for (int j = 1; j <= 3; ++j)
cout << '(' << i << ',' << j << ")\n";
Produces the product of the set {1,2,3} with itself.

3.3.3. The ‘do…while’ Statement


The do loop is similar to the while statement, except that its body is executed
first and then the loop condition is examined.
The general form:
do
statement;
while (expression);

4|P a g e
Assosa University Department of Computer Science

First statement is executed and then expression is evaluated. If the outcome of


the latter is nonzero then the whole process is repeated. Otherwise, the loop is
terminated.
The do loop is less frequently used than the while loop. It is useful for situations
where we need the loop body to be executed at least once, regardless of the
loop condition. For example to repeatedly read a value and print its square, and
stop when the value is zero.
do {
cin >> n;
cout << n * n << '\n';
} while (n != 0);

Unlike the while loop, the do loop is never used in situations where it would
have a null body.

3.4. Other Statements

3.4.1. 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.
In while and do loops, the next iteration commences from the loop condition.
In for loop, the next iteration commences from the loop’s third expression.

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 is equivalent to: do
{ {
cin >> num; cin >> num;
if (num < 0) if (num >= 0) {
continue; // process num here...
// process num here... }
} }
while (num != 0); while (num != 0);

For loop that reads in a number exactly n times.


for (i = 0; i < n; ++i) {
cin >> num;
if (num < 0)
continue; // causes a jump to: ++i
// process num here...
}
When the continue statement appears inside nested loops, it applies to the loop
immediately enclosing it, and not to the outer loops. For example, in the
following set of nested loops, continues applies to for loop, and not the while
loop:
while (more) {
for (i = 0; i < n; ++i) {
cin >>num;
if (num < 0)
5|P a g e
Assosa University Department of Computer Science

continue; // causes a jump to: ++i


}
}

3.4.2. 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.

For example:
for(n=10; n>0; n--)
{
cout<<n << ", ";
if(n==3)
{
cout<< "Countdown Aborted!";
break; //drop out of the loop
}
}

3.4.3. The ‘goto’ Statement


The goto statement provides the lowest-level of jumping. 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.
For, example:
int n=10;
loop:
cout<<n<<",";
n--;
if(n>0)
goto loop;
cout<<"FIRE!";

3.4.4. The ‘return’ Statement


The return statement enables a function to return a value to its caller.
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. For a function whose return
type is void, expression should be empty:
return;
The main function may have return type int. The return value of main is what the
program returns to the operating system when it completes its execution. Under
UNIX, for example, it is 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;
}
6|P a g e
Assosa University Department of Computer Science

7|P a g e

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy