Binary World

Download Report

Transcript Binary World

C programming Language
Chapter 2:
Control Flow
04 ‫ספטמבר‬
Copyright Meir Kalech
1
Statements and Blocks


An expression becomes a statement when it’s
followed by a semicolon (as a terminator).
Examples:





i++;
n = 0;
printf (…);
Braces { and } (also called curly brackets) are
used to group declarations and statements
together into a compound statement, or block.
A block is syntactically equivalent to a single
statement (but no semicolon after right brace).
04 ‫ספטמבר‬
Copyright Meir Kalech
2
What is Control Flow?


Sometimes we want a statement to be
executed only under certain conditions or
be done a few times (not just once).
C supplies a set of commands which
control the flow of the program:





if-else
switch-case
for
while
do-while
04 ‫ספטמבר‬
Copyright Meir Kalech
3
if Statement –
Flow Diagram
• if statement:
F
logic
expression
T
statement(s)
• if-else statement:
F
logic
expression
statement(s)
04 ‫ספטמבר‬
Copyright Meir Kalech
T
statement(s)
4
if Statement

“if” syntax:
if (expression)
statement;

If there are multiple statements, then
add a block (using braces):
if (expression)
{
statements;
}
04 ‫ספטמבר‬
Copyright Meir Kalech
5
if-else Statement

“if…else” Syntax:
if (expression)
statement;
else
statement;

If there are multiple statements, then add block:
if (expression)
{
statements;
}
else
{
statements;
}
04 ‫ספטמבר‬
Copyright Meir Kalech
6
Examples (1)

The program gets a character from user.
If the character is a digit or ‘y’, the user
gets a correct message:
char num; scanf(“%c”, &num);
if (num >= ‘0’ && num <= ‘9’ || num == ‘x’+1)
printf(“good choice\n”);
comment: ‘x’+1 is equal to ‘y’
(according to ASCII table).
04 ‫ספטמבר‬
Copyright Meir Kalech
7
Examples (2)

The program gets a character from user. If the
character is a digit or ‘y’, the user gets a correct
message and increments the character, else the user
gets an error message:
char num;
scanf(“%c”, &num);
if (num >= ‘0’ && num <= ‘9’ || num == ‘x’+1)
{
printf(“good choice\n”);
num++;
}
else
printf(“bad choice\n”);
04 ‫ספטמבר‬
Copyright Meir Kalech
8
Nested if Statement


“Nested if” is a condition in the scope of another condition.
If the first condition is true then the second condition is active.
Example syntax:
if (expression1)
{
if (expression2)
statement1;
statement2;
}
else if (expression3)
{
statements3;
}
else
statement4;
04 ‫ספטמבר‬
F
expression1
expression3
statement4
statements3
T
expression2
statement1
statement2
Copyright Meir Kalech
9
switch-case Statement
When few constant alternatives exist, we can select the correct one by
using if-else, or even better by switch-case:
switch(expression)
{
case constant1:
[break;]
case constant2:
statement(s);
[break;]
case constant3:
statement(s);
[break;]
default:
//
//
//
//
//
The value of the statement will be
looked for in the existing cases.
The matched case will be executed
up to the end of the switch block
or a break.
// The default statement is optional.
// If no matching case was found, the
// statements in default will be executed.
}
04 ‫ספטמבר‬
Copyright Meir Kalech
10
switch-case Statement



switch-case is useful for constructing menus.
A menu is composed of two parts: 1. Menu 2. Selection
Example:
Menu:
Selection:
int selection;
printf(“choose an option:\n”
“1 – addition\n”
“2 – subtraction\n”
“3 – multiplication\n”);
scanf(“%d”, &selection);
If we remove ‘break’
from case 1 and
selection is 1, then both
case1 and case2 will be
executed!!
04 ‫ספטמבר‬
switch(selection)
{
case 1:
case 2:
case 3:
default:
}
Copyright Meir Kalech
printf(“%d”, x+y);
break;
printf(“%d”, x-y);
break;
printf(“%d”, x*y);
break;
printf(“wrong”);
break;
11
Loops


When we want to execute
statement(s) multiple times,
we can use a loop statement.
Two categories of loops:
1. Counter loop: the number of
iterations is known in advance.
2.
Conditional loop: the number of
iterations depends on a condition.
04 ‫ספטמבר‬
Copyright Meir Kalech
12
for – Flow Diagram

for is a kind of counter loop.
expression
+
F
logic
expression
T
loop body
continue program
04 ‫ספטמבר‬
Copyright Meir Kalech
13
for - Syntax
for(counter initialization; condition; counter increment)
statement;
for(initialization; condition; increment)
For multiple
{
statements:
use a block
statements;
}



Initialization: initialization of the counter. Initialization is
applied only once at the start.
Condition: for each iteration, the condition is checked.
If the condition is true, the statement(s) are executed,
else the program continues after the ‘for’ block. Usually
the condition checks the counter.
Increment: Increment (or decrement) the counter.
After incrementing the counter, the condition is checked.
04 ‫ספטמבר‬
Copyright Meir Kalech
14
for - Examples

Printing numbered “hello world” 3 times:
int i;
for(i=0; i<3; i++)
printf(“no. %d hello world\n”, i+1);

Explanation:
Condition is true when i=0,1,2. In these cases, “hello world”
will be printed. When i=3, the “for” loop will be exited.

Calculating the sum of the teens group (10-19):
int i, sum=0;
for(i=10; i<20; i++)
sum += i;

Explanation:
In this case, i is initialized to 10, and the condition is i<20.
04 ‫ספטמבר‬
Copyright Meir Kalech
15
for - Comments

Increment can be any mathematical operation:
int i;
for (i = 20;
i > 0; i /= 2)

The counter can be any number type:

Each of the 3 expressions can include more than one
expression:
char c;
for (c='a'; c<='z'; c++)
double i, j;
for (i=11.1, j=22.2; i<j && j>=15; i*=2, --j)

One or more expressions can be left blank:
int i = 10;
//instead of initialization
for ( ; i<20; )
{
printf(“hello world\n”);
i++;
//instead of increment
}
04 ‫ספטמבר‬
Copyright Meir Kalech
16
while – Flow Diagram
While is a kind of condition loop:
logic
statement
true
execute
loop body
false (expression equals zero)
skip loop body and
continue the serial execution
of the program
04 ‫ספטמבר‬
Copyright Meir Kalech
17
while – Syntax
while (condition)
statement;
while (condition)
{
statements;
}
For multiple
statements:
use a block
Condition: In each iteration, the condition is
checked. If the condition is true, the
statement(s) are executed, else the program
continues after the ‘while’ block. The value of
the condition must be changed through the
statement(s), otherwise it’s an infinite loop.
04 ‫ספטמבר‬
Copyright Meir Kalech
18
while – Examples

Printing numbered “hello world” 3 times:

int i=0;
while(i<3)
printf(“no. %d hello world\n”, ++i);
Explanation:
Condition is true when i=0,1,2. In these cases, “hello world” will
be printed. When i=3, the “while” loop will be exited.
Attention: this loop is a counter loop, which is implemented
within the while loop. Generally, prefer a “for loop” for a counter loop.

Sum digits:
int num=345, sum=0;
while(num)
//exactly as: while(num != 0)
{
sum += num%10;
num /= 10;
}
04 ‫ספטמבר‬
Copyright Meir Kalech
19
while – Examples

Getting a digit from the user:
char digit;
while(digit <‘0’ || digit >‘9’)
{
printf(“enter a digit”);
scanf(“%c”, &digit);
}

problem:
In this example, the initial digit’s value is garbage –
not good! Garbage could also be some character
between ‘0’ to ‘9’. In this case, the while loop will
not be applied at all, and the user is never asked
to enter a digit.
04 ‫ספטמבר‬
Copyright Meir Kalech
20
do-while Statement




We can solve this problem by using a do-while loop:
char digit;
do
{
printf(“enter a digit”);
scanf(“%c”, &digit);
} while(digit <‘0’ || digit >‘9’);
In do-while loop, the statements are executed before the
condition test.
This kind of loop is used mainly in case the statement(s) need to
be performed at least once.
Syntax:

Parenthesis after the while are mandatory (even if there is
only one statement).

Semicolon is mandatory at the end of do-while.
04 ‫ספטמבר‬
Copyright Meir Kalech
21
break Statement

“break” command is intended to break out of a loop
execution.


Example: Getting a digit from the user for up to 3 times:
int flag = 0;
int i;
char digit;
for(i=0; i<3; i++)
{
printf(“enter a digit”);
scanf(“%c”, &digit);
if(digit >=‘0’ && digit <=‘9’)
{
flag = 1;
break;
}
}
Flag is necessary to inform us if the digit has been gotten.
04 ‫ספטמבר‬
Copyright Meir Kalech
22
continue Statement



“continue” command is used to skip over the rest of the
statements in the body of the loop.
Example: Adding a sequence of numbers, except those
that are divisible by 4:
int i, sum=0;
for(i=0; i<20; i++)
{
if(!(i%4))
continue;
sum += i;
}
When i is divided by 4 without a remainder, the ‘continue’
command is applied, and the statement “sum += i;” is not
executed but skipped (to proceed with increment of i).
04 ‫ספטמבר‬
Copyright Meir Kalech
23
Nested Loop




A nested loop is a loop within a loop. In each external loop
iteration, the internal loop is executed. In other words, the
body of the external loop (statement) is an internal loop.
The external and internal loops are independent of each
other - they could be of different types (say for and while).
A nested loop is used when we want to execute a task
multiple times and the task itself executes another task
multiple times.
For instance: the teacher collects from some students their
grades in various subjects:
1. collecting from each student is the first task
(external loop).
2. collecting each grade of the student is the second task
(internal loop).
04 ‫ספטמבר‬
Copyright Meir Kalech
24
Nested Loop


Example: do you remember the multiplication
table??? (without using a calculator ):
for(i=1; i<=3; i++)
{
for(j=1; j<=3; j++)
First task
printf(“%d ”, i*j);
printf(“\n”);
Second task
}
In each external iteration, we have 2 tasks:
1. Calculate the row of i multiplier.
2. Move to a new line.
04 ‫ספטמבר‬
Copyright Meir Kalech
25
Nested Loop


Comment: j is initialized in the internal loop
whenever the internal loop is started.
Let’s view a table of the variable’s values:
i
1
1
1
2
2
2
3
3
3
j
1
2
3
1
2
3
1
2
3
first external loop
04 ‫ספטמבר‬
second external loop
Copyright Meir Kalech
third external loop
26