Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

[Week 4] Programming Basics 3

The document provides an overview of program control structures in C, including sequential execution, transfer of control, and control flow. It details three types of control structures: sequence, selection, and iteration, with a focus on iteration statements such as while, do...while, and for. Additionally, it discusses the concepts of definite, indefinite, and infinite repetition, along with the use of break and continue statements for managing loop execution.

Uploaded by

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

[Week 4] Programming Basics 3

The document provides an overview of program control structures in C, including sequential execution, transfer of control, and control flow. It details three types of control structures: sequence, selection, and iteration, with a focus on iteration statements such as while, do...while, and for. Additionally, it discusses the concepts of definite, indefinite, and infinite repetition, along with the use of break and continue statements for managing loop execution.

Uploaded by

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

while

▪ Program control
Specifying the order of statements for program execution

▪ Sequential execution
Line-by-line execution
Order of statements in a code is equal to the execution order.

▪ Transfer of program control


Execution order is different from what you can see in the code.

▪ Control flow
The order in which individual statements are executed or evaluated.
▪ Three types of control structures
Sequence structure

Selection structure
if, if…else, switch

Iteration structure
while, do…while, for

C has only seven control statements.


▪ Iteration statement
makes an action to be repeated when a certain condition is true.
Loop condition: A loop is a group of instructions that the computer executes
repeatedly while its loop condition remains true.

▪ Three means of repetition (iteration)


Definite repetition: Exact number of iterations is known.
Indefinite repetition: Number of iterations is determined on runtime.
Infinite repetition: The number of iteration is infinite.
Intentionally? A bug?

▪ Three statements for iterations


while, do…while, for
while / do-while

▪ Syntax
while Loop Conditions

while(logical_expression_1) {
/* When logical_expression_1 is true */
(statements to be repeated)
}

do-while

do {
/* Loop exits when logical_expression_1 is false */
(statements to be repeated)
} while(logical_expression_1)
while

▪ Execution order of while statement


The loop-continuation condition is tested at the beginning of the loop before the body of
the loop is performed.

while(logical_expression_1) {
/* When logical_expression_1 is true */
(statements to be repeated)
}

logical_expression_1 is evaluated first.


If it is true, the body of the while statement is executed.
After each iteration, logical_expression_1 is checked for true. The body is repeatedly
executed under the true condition of logical_expression_1.
When it becomes false, the program control escapes the loop and the next statement in
order is executed.
while

▪ Example: finding the first power of 3 larger than 100

product = 3;
while ( product <= 100 ) {
product = 3 * product;
} // end while

The loop starts with the product variable as 3.


The loop condition is true for that value and the body of while is executed.
The value of product increases as 9, 27 and 81.
When product becomes 243, the loop condition becomes false, which terminates the
iteration. (Check that this value is what we are looking for.)
Program execution continues with the next statement after the while.
while

▪ Easiest example with while


Variations with different loop conditions and strides

#include <stdio.h>
1
int main() {
2
int num = 1; 3
4
while (num <= 10) {
5
printf("%d\n", num); 6
7
num = num + 1;
8
} 9
return 0; 10

}
while

▪ Example: finding the first power of 3 larger than 100


#include <stdio.h>

int main() {

int product = 3;

while ( product <= 100 ) {

product = 3 * product;

} // end while

printf("%d\n", product);

return 0;
243
}
do…while

▪ Execution order of do…while statement


The do...while statement tests the loop-continuation condition after the loop body is
performed. (Very similar to the execution order of while statement, so not written here.)

do {
/* Loop exits when logical_expression_1 is false */
(statements to be repeated)
} while(logical_expression_1);

▪ Difference against the while statement


while: the loop condition is tested first. The body might never be executed.
do…while: the loop condition is checked after the body is performed.
The body has at least one chance to be executed.
do…while

▪ Transition from while to do…while


In most cases, converting while statements to do…while statements can be done easily.
However, you need to be very cautious of the first execution of the body.

product = 3;
while ( product <= 100 ) {
product = 3 * product;
With do…while
} // end while
product = 3;
With while
do {
product = 3 * product;
} while( product <= 100 ) // end do…while
do…while

▪ Example: finding the first power of 3 larger than 100

product = 3;
do {
product = 3 * product;
} while( product <= 100 ); // end do…while

The loop starts with the product variable as 3 and the body is executed.
The value of product increases as 9, 27 and 81.
When the loop condition becomes false, which terminates the iteration.

CHECK: What happens when the initial value of product is 243 instead of 3?
do…while

#include <stdio.h>

int main()

{ 1
int num = 1; 2
3
do { 4
printf("%d\n", num); 5
6
num = num + 1; 7
} while (num <= 10); 8
9
return 0; 10
}
do…while

#include <stdio.h>

int main() {

int product = 3;

do {

product = 3 * product;

} while( product <= 100 ); // end do…while

printf("%d\n", product);

return 0;

}
243
▪ Definite repetition
Exact number of iterations is known.
Counter-controlled iteration
Counter: Specifying the number of times a set of statements should execute

int counter = 1;
while ( counter <= 10 ) {
printf("%d\n", counter);
counter++;
}
▪ Indefinite repetition
Number of iterations is determined on runtime.
Sentinel-Controlled Iteration
Sentinel value: Indicating "end of data entry"
Other names: a signal value, a dummy value, a flag value
The sentinel value must be chosen so that it cannot be confused with an acceptable input value.

int num;
scanf("%d", &num);
while ( num != -1 ) { // sentinel value is -1
printf("%d\n", num);
scanf("%d", &num);
}
▪ Infinite repetition
The number of iteration is infinite.
When we use it in our program, we normally terminate the loop using break statement
under some specific conditions.

// An erroneous example
while ( 1 ) {
printf("while (1)");
}
break / continue

▪ break and continue are used for managing program control explicitly.

▪ break breaks loops.


break has two usages.
With loops: Exiting from innermost one
The program control resumes at the next statement following the loop
With switch: Termination of a case

▪ continue continues loops.


With continue, loop continues next iteration ignoring following code in the code block.
In while and do…while statements, the loop-continuation test is evaluated immediately
after the continue statement is executed.
break / continue

#include <stdio.h>
int main()
{
int num = 0, sum = 0;
while (num < 10) {
sum += num++;
printf("before if\n");
if (sum < 20) {
printf("num:%d sum:%d (continue)\n", num, sum);
continue;
} else {
printf("num:%d sum:%d (break)\n", num, sum);
break;
}
printf("after else\n"); CHECK1: What is the first value added to sum?
}
CHECK2: Is the loop escaped by the loop-continuation condition?
CHECK3: Find a line never being executed.
}
#include <stdio.h>

int main()
{
int num = 1;
while (num != 10) {
printf("Input a number(for exit, type 10): ");
scanf("%d", &num);
printf("You type %d.\n", num);
}
return 0;
}
▪ Fill in the blank to print the result on the right side.

#include <stdio.h>
1
int main() { 2
int num = 1; 3
4
while (num <= 10) { 5
printf("%d\n", [BLANK] ); 6
7
} 8
return 0; 9
10
}
▪ We have several candidate positions for ‘++’ increment operator. (On 5th
and 6th line, before and after num variable.) What will be the results for
each position?

#include <stdio.h>

int main() {

int num = 1;

while (num <= 10) {

printf("%d\n", num++);

return 0;

}
▪ Basic concept for the while iteration statement
An iteration statement allows you to specify that an action is to be repeated while some
condition remains true. The pseudocode statement describes the iteration that occurs
during a shopping trip. The condition, "there are more items on my shopping list" may be
true or false. If it’s true, then the action, "Purchase next item and cross it off my list" is
performed. This action will be performed repeatedly while the condition remains true.

While there are more items on my shopping list


Purchase next item and cross it off my list

Eventually, the condition will become false (when the last item on the shopping list has
been purchased and crossed off the list). At this point, the iteration terminates, and the
first pseudocode statement after the iteration structure is executed.
▪ Example code and corresponding flowchart

product = 3;
while ( product <= 100 ) {
product = 3 * product;
} // end while
▪ do...while Iteration Statement
The do...while iteration statement is similar to the
while statement. In the while statement, the loop-
continuation condition is tested at the beginning of
the loop before the body of the loop is performed.
The do...while statement tests the loop-continuation
condition after the loop body is performed.
Therefore, the loop body will be executed at least
once. When a do...while terminates, execution
continues with the statement after the while clause.
for
▪ Counter-controlled iteration
Definite iteration (or definite repetition)
vs. indefinite iteration (sentinel-controlled iteration)
The exact number of loop execution is known in advance.

▪ Counter-controlled iteration requires:


The name of a control variable (or loop counter).
The initial value of the control variable.
The increment (or decrement) by which the control variable is modified
each time through the loop.
The condition that tests for the final value of the control variable
(i.e., whether looping should continue).
for

▪ The for iteration statement handles all the details of counter-controlled iteration.
▪ Syntax

for(initialization; condition; increment) {


/* When condition is true */
(code block)
}

initialization
executed first and once
a name of a control variable and its initial value
• Multiple control variables are acceptable.

Condition
loop condition
for

▪ The for iteration statement handles all the details of counter-controlled iteration.
▪ Syntax

for(initialization; condition; increment) {


/* When condition is true */
(code block)
}

Increment
update any loop control variables
Control variables are modified each time through the loop

Execution order:
initialization → condition → code block → increment → condition → code block → increment →
condition → code block → …
for

▪ Components of for statements are not mandatory.


Initialization can be omitted if we use already declared variables for the condition

Loop-continuation condition can be omitted in two or more cases. When it is omitted, C


assumes that the condition is always true.
The condition is checked inside of the body with break and/or continue.
The for statement intentionally runs infinitely.

Increment part can be omitted when the variables are updated inside of the body.

// an extreme case
for( ; ; ) {
(code block)
}
for

#include <stdio.h>
0
1
int main() 2
3
{ 4
for (int i = 0; i < 10; i++) { 5
6
printf("%d\n", i);
7
} 8
9
return 0;

Variations will come up with demo


for

▪ You can check methods of varying the control variable in a for statement.
CHECK: What are the semicolons for?

// Vary the control variable from 1 to 100 in increments of 1.


for (i = 1; i <= 100; i++);

// Vary the control variable from 100 to 1 in increments of -1 (decrements of 1).


for (i = 100; i >= 1; --i);

// Vary the control variable from 7 to 77 in steps of 7.


for (i = 7; i <= 77; i += 7);

// Vary the control variable from 20 to 2 in steps of -2.


for (i = 20; i >= 2; i -= 2);

// Vary the control variable over the following sequence of values: 2, 5, 8, 11, 14, 17.
for (j = 2; j <= 17; j += 3);

// Vary the control variable over the following sequence of values: 44, 33, 22, 11, 0.
for (j = 44; j >= 0; j -= 11);
continue for

▪ continue continues loops.


With continue, loop continues next iteration ignoring following code in the code block.
In for statements, the increment expression is executed, then the loop-continuation test
is evaluated.

#include <stdio.h>
int main()
{
int num = 0, sum = 0;
for(int i = 0; i < 10; i++) {
if( i % 3 == 0 )
continue;
printf("%d ", i);
}
printf("\nContinue is used to skip printing multiples of 3.\n");
}
▪ Summing the Even Integers from 2 to 100

(intentionally blank box)

2550
▪ Summing the Even Integers from 2 to 100

#include <stdio.h>

int main() {

int sum = 0;

for (int num = 2; num <= 100; num += 2) {

sum += num;

printf("Sum: %d\n", sum);

return 0; 2550
}
▪ Program control: order of statements for program execution

▪ Sequential execution
Line-by-line execution

▪ Transfer of program control


Execution order is different from what you can see in the code.
Selection structure: if, if else, switch
Iteration structure: while, do…while, for

▪ C has only seven control statements.


And we learned all of them.
▪ General Format of a for Statement
If the condition expression is omitted, C assumes that the condition is true, thus creating
an infinite loop. You may omit the initialization expression if the control variable is
initialized elsewhere in the program. The increment may be omitted if it’s calculated by
statements in the body of the for statement or if no increment is needed. This flowchart
makes it clear that the initialization occurs only once and that incrementing occurs after
the body statement is performed.

for (unsinged int counter = 1; counter <= 10; ++counter)


printf("%u", counter);

You might also like