0% found this document useful (0 votes)
31 views20 pages

4 Branching and Iteration V2

Uploaded by

kenneth tamatcho
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views20 pages

4 Branching and Iteration V2

Uploaded by

kenneth tamatcho
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Republic of Cameroon

Ministry of Higher Education


--------------------------------------
PKFokam Institute of Excellence
Department of Computing and Software Engineering

Introduction to C Programming
4. Branching and Iteration
Course code:
1 CS 1003
FRESHMAN 1 - ENGINEERING

Severin Kakeu, PhD Candidate


Fall 2024
Content

1. Introduction
2. If/Else
3. ?: Conditional expression
4. Switch
5. While loop
6. Do-While loop
7. For loop
8. Break and Continue
9. Exercices
2
Introduction

• The C language provides three types of decision-making constructs:


o if-else,
o the conditional expression ?:,
o and the switch statement.

• It also provides three looping constructs:


o while,
o do-while,
o and for.

3
3.1 If/Else

• The basic if statement tests a conditional expression and, if it is non-zero (i.e.,


TRUE), executes the subsequent statement.

• For example, in this code segment if (a < b) b = a;


c the assignment b = a will only occur if a is less-than b.

• The else statement deals with the alternative case where the conditional expression is
0 (i.e., FALSE)
if (a < b)
b = a;
else
b += 7;
4
3.1 If/Else

• The if-else statement can also command multiple statements by wrapping them in
braces. Statements so grouped are called a compound statement, or block, and they
are syntactically equivalent to a single statement. Example:
• if (a < b) { if (expression)
b = a;
statement;
a *= 2;
} else if (expression)
else { statement;
b += 7; else if (expression)
--a; statement;
} else
• It is possible to chain if-else statements if the following form statement;

• This chain is evaluated from the top and, if a particular if-conditional is TRUE, then
its statement is executed and the chain is terminated. On the other hand, if the
conditional is FALSE, the next if-conditional is tested. If all the conditionals are
evaluated to FALSE, then the final else statement is executed as a default. 5
3.1 If/Else

• Note. A common mistake with if-else blocks is the “dangling else problem”. For
example, consider the following nested-if statement.
if (a < b)
if (m != 0)
b = a;
else
a = m;
• The intention of the programmer, as indicated by the indentation, is that the else
corresponds to the outer if statement. However, it actually belongs to the inner if
statement. Desired association can be enforced by brackets.
if (a < b) {
if (m != 0)
b = a;
}
else
6
a = m;
3.2 ?: Conditional Expression
• The conditional expression is a ternary operator; that is, it takes three operands. It
has the following form:

(expression 1) ? (expression 2) : (expression 3)

If the first expression is TRUE (i.e., non-zero), the second expression is evaluated, otherwise the third
is evaluated. Thus, the result of the ternary expression will be the result of either the second or third
expressions, respectively.

• For example, to calculate the maximum of two values.


c = (a > b) ? a : b; /* c = max(a,b) */

• As a branching construct, the ?: operator appears far less frequently than the if-
else and switch constructs.
7
3.3 Switch
• The switch statement is a multi-way decision that tests whether an expression
matches one of a number of constant integer values, and branches accordingly.
• The general form of the switch statement is as follows.
switch (expression) {
case const-int-expr: statements
case const-int-expr: statements
default: statements}
• On evaluating the expression, if it matches one of the set of constant integer
expressions, the switch branches to the matching case label and executes the
statements following that point. Otherwise it jumps to the default label and
executes its statements.
• The default label is optional, and if it does not exist, and none of the case labels
match, the switch simply performs no action.
• Note. The default label is typically the last label in the block. While this is good
practice in general, it is not mandatory, and case labels may appear below default.
8
3.3 Switch
The following rules apply to a switch statement: • Flow diagram
• The expression used in a switch statement must have an integral or
enumerated type, or be of a class type in which the class has a single
conversion function to an integral or enumerated type.
• You can have any number of case statements within a switch. Each
case is followed by the value to be compared to and a colon.
• The constant-expression for a case must be the same data type as the
variable in the switch, and it must be a constant or a literal.
• When the variable being switched on is equal to a case, the statements
following that case will execute until a break statement is reached.
• When a break statement is reached, the switch terminates, and the flow
of control jumps to the next line following the switch statement.
• Not every case needs to contain a break. If no break appears, the flow
of control will fall through to subsequent cases until a break is
reached.
• A switch statement can have an optional default case, which must
appear at the end of the switch. The default case can be used for
performing a task when none of the cases is true. No break is needed
in the default case.
9
3.3 Switch
• Example
#include <stdio.h> printf("Well done\n" );
int main () break;
{ case 'D' :
/* local variable definition printf("You passed\n" );
*/ break;
char grade = 'B'; case 'F' :
switch(grade) printf("Better try again\n" );
{ break;
case 'A' : default :
printf("Excellent!\n" ); printf("Invalid grade\n" );
break; }
case 'B' : printf("Your grade is %c\n",grade);
printf("Well done\n" ); return 0;
break; }
case 'C' :

Well done
Your grade is B 10
3.3 Nested Switch Statements
• It is possible to have a switch as part of the statement sequence of an outer switch.
Even if the case constants of the inner and outer switch contain common values, no
conflicts will arise. #include <stdio.h>
• The syntax for a nested switch statement is as follows: int main ()
{
switch(ch1) { /* local variable definition */
case 'A': int a = 100;
printf("This A is part of outer switch" ); int b = 200;
switch(ch2) { switch(a) {
case 'A': case 100:
printf("This A is part of inner switch" ); printf("This is part of outer switch\n", a );
break; switch(b) {
case 'B': /* case code */ case 200:
} printf("This is part of inner switch\n", a );
break; }
case 'B': /* case code */ }
} printf("Exact value of a is : %d\n", a );
printf("Exact value of b is : %d\n", b );
return 0;
} 11
3.4 While loop
• The while loop has the general form
while (expression)
statement;
• If the conditional expression is TRUE, then the while will execute the following
statement, after which it will re-evaluate the conditional. It continues this iteration
while ever the conditional remains TRUE. As with the if-else statement, the while loop
can execute multiple statements as a block by enclosing them in braces.
• For example, the following code segment computes the greatest common divisor
(GCD) of two positive integers m and n (i.e., the maximum value that will divide both
m and n). The loop iterates until the value of n becomes 0, at which point the GCD is
the value of m.
while (n) {
int tmp = n;
n = m%n;
m = tmp;
}
12
3.4 While loop
• Break statement
The break statement in C programming language has the following two usages:
1. When the break statement is encountered inside a loop, the loop is immediately
terminated and program control resumes at the next statement following the
loop.
2. It can be used to terminate a case in the switch statement (covered in the next
chapter).
If you are using nested loops (i.e., one loop inside
another loop), the break statement will stop the execution
of the innermost loop and start executing the next line of
code after the block.
Syntax
The syntax for a break statement in C is as follows:
break;
13
3.4 While loop
• Continue statement
• The continue statement in C programming language works somewhat like the
break statement. Instead of forcing termination, however, continue forces the next
iteration of the loop to take place, skipping any code in between.
• For the for loop, continue statement causes the conditional test and increment
portions of the loop to execute. For the while and do...while loops, continue
statement causes the program control passes to the conditional tests.
int main ()
{ /* local variable definition */
int a = 10;
/* do loop execution */
do
{
if( a == 15)
{ /* skip the iteration */
a = a + 1;
continue;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 ); return 0;
} 14
3.5 Do While loop
• The general form:
do
statement;
while (expression);

• Its behaviour is virtually the same as the while loop except that it always executes the
statement at least once.

• The statement is executed first and then the conditional expression is evaluated to
decide upon further iteration. Thus, the body of a while loop is executed zero or more
times, and the body of a do-while loop is executed one or more times.

• Style note: It is good form to always put braces around the do-while body, even when
it consists of only one statement. This prevents the while part from being mistaken for
the beginning of a while.
15
3.5 Do While loop
• The following code example takes a non-negative integer val and prints it in reverse
order. The use of a do-while means that 0 can be printed without needing extra special
case code.
• Example:
do
{
printf("%d", val % 10);
val /= 10;
} while (val != 0);

Output:

16
3.5 For loop
• General form of for loop : Flow diagram
expr1 = init;
for (expr1; expr2; expr3) expr2 = condition;
statement; expr3 = increment;

• Its behaviour is equivalent to a while loop with the


following arrangement of expressions:

expr1;
while (expr2) {
statement;
expr3;
}

17
3.5 For loop
Here is the flow of control in a for loop:
1. The init step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. You are not required to put a statement here,
as long as a semicolon appears.
2. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it
is false, the body of the loop does not execute and flow of control jumps to the
next statement just after the for loop.
3. After the body of the for loop executes, the flow of control jumps back up to
the increment statement. This statement allows you to update any loop control
variables. This statement can be left blank, as long as a semicolon appears after the
condition.
4. The condition is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then increment step, and then again condition).

After the condition becomes false, the for loop terminates.


18
3.5 For loop
Example:
{
{ n[ i ] = i + 100; /* set element at
/* for loop execution */ location i to i + 100 */
for( int a = 10; a < 20; a = a + 1 ) }
{ /* output each array element's value */
printf("value of a: %d\n", a); for (j = 0; j < 10; j++ )
{
}
printf("Element[%d] = %d\n", j, n[j] );
return 0; }
} return 0;
For with Arrays: }

#include <stdio.h>
int main ()
For with multidimensionnal arrays:
{
int n[10]; /* n is an array of 10 integers */
int a[3][4] = {
int i,j; {0, 1, 2, 3} , /* initializers for row indexed by 0 */
/* initialize elements of array n to 0 */ {4, 5, 6, 7} , /* initializers for row indexed by 1 */
for ( i = 0; i < 10; i++ ) {8, 9, 10, 11} /* initializers for row indexed by 2 */
};

19
Exercises
Write the following programs:
1. Print the message according to the value of user
example: if the user types 1, the program prints « it’s Monday, day of work ». 2 =>
« it’s Tuesday, go to work », 3… 5=> « It’s Friday, a day before the weekend », 6=>
« Saturday, first day of weekend », 7=> « go to church »

2. Ask your age until you enter -1.

3. Illustrate the use of while and for on factorial formula.

4.Verify an integer value intered by user until he types 20. For example, say « enter the
magic number »
5. Initialize a matrix and list all the values with For and While loops

6. Give two examples of programs to illustrate the do While and While and what is your
best choice according to your example. 20

You might also like