beginning c for engineers fall 2005
DESCRIPTION
Beginning C For Engineers Fall 2005. Lecture 3: While loops, For loops, Nested loops, and Multiple Selection Section 2 – 9/14/05 Section 4 – 9/15/05 Bettina Schimanski. Homework. Read Chapter 4 HW 3 Don’t forget the classroom change next week: Section 2 (Wednesday): Sage 5101 - PowerPoint PPT PresentationTRANSCRIPT
Beginning C For EngineersFall 2005
Lecture 3:While loops, For loops, Nested loops, and Multiple Selection
Section 2 – 9/14/05Section 4 – 9/15/05
Bettina Schimanski
Homework Read Chapter 4 HW 3
Don’t forget the classroom change next week: Section 2 (Wednesday): Sage 5101 Section 4 (Thursday): Walker 5113
More C Operators
8
int age;
age = 8;
age = age + 1;
age
9
age
PREFIX FORMIncrement Operator
8
int age;
age = 8;
++age;
age
9
age
POSTFIX FORM Increment Operator
8
int age;
age = 8;
age++;
age
9
age
Decrement Operator
100
int dogs;
dogs = 100;
dogs--; --dogs;
dogs
98
dogs
When the increment (or decrement) operator is used in a “stand alone” statement solely to add one (or subtract one) from a variable’s value, it can be used in either prefix or postfix form
But… when the increment (or decrement) operator is used in a statement with other operators, the prefix and postfix forms can yield different results
Which Form to Use
dogs-- ; --dogs ;
USE EITHER
The += operator If you wish to add a value to a variable and
put the result back in the variable, use the += operator
ex:
int stuff = 4;stuff += 3; /* same as stuff = stuff + 3;
stuff is now 7 */
Adds the value on the right to the variable on the left.
Other similar operators
As you might expect, there are also operators for -=, *=, /=, and %=.
x += y; /* same as x = x + y; */
z *= 3; /* same as z = z * 3; */
y /= 2; /* same as y = y / 2; */
i %= 5; /* same as i = i % 5; */
A loop is a repetition control structure.
It causes a single statement or block to be executed repeatedly
What is a loop?
Loop constructs in C while
execute block of statements repeatedly as long as some condition is true
condition is tested before block of statements are executed
for an abbreviation for a collection of statements that use a
while loop for creating counting loops ideal when the number of iterations of the loop is “known”
beforehand
do – while similar to while condition is tested after block of statements are executed
While Statement
SYNTAX
while ( Expression ){ .
. // loop body .}
NOTE: Loop body can be a single statement, a null statement, or a block.
Event-controlled Loops
Keep processing data until a certain event happens, for example
a special value is entered (e.g. -1) to indicate that processing should stop
there is more data in the file
until the value of a flag changes
13
#include <stdio.h>
int main( ) /* Example from Lecture 2 */{
int total = 0, num;
printf( “Enter a number (-1 to stop ) ”);scanf(“%d”, &num);
/* Read until the user enters -1 */while (num != -1){
total = total + num;printf( “Enter a number (-1 to stop ) ”);scanf(“%d”, &num);
}printf( “Total = %d”, total);return 0;
}
#include <stdio.h>
int main( ){
int total = 0, num;
printf( “Enter a number (-1 to stop ) ”);scanf(“%d”, &num);
/* Read until the user enters -1 */while (num != -1){
total += num;printf( “Enter a number (-1 to stop ) ”);scanf(“%d”, &num);
}printf( “Total = %d”, total);return 0;
}
Flag-controlled Loops Initialize a flag to 1(true) or 0 (false) Use a meaningful name for the flag A condition in the loop body changes the
value of the flag Test for the flag in the loop test
expression
int numpos = 0;int isSafe = 1 /* initialize Boolean flag */
/*Loop while flag is true, i.e. while only positive numbers */
while (isSafe){
scanf(“%d”, &num);if ( num < 0 )
isSafe = 0; /* change flag value */
elsenumpos++;
}
printf(“%d positive numbers were entered\n”, numpos);
Count-controlled Loops contain: An initialization of the loop control
variable An expression to test for continuing the
loop An update of the loop control variable to
be executed with each iteration of the body
* Although count-controlled loops can be implemented using while loops, it is more common to use for loops for counting
Using For loops for Counting
SYNTAXfor ( initialization ; test expression ; update ) {
0 or more statements to repeat
}
initialization update
teststatementstatement. . .
done
true
false
Example of Repetition
int num;
for ( num = 1 ; num <= 3 ; num++ ) {
printf(“%d Potato\n”, num);}
initialization test update
21
Example of Repetition num
int num;
for ( num = 1 ; num <= 3 ; num++ ) { printf(“%d Potato\n”, num);}
OUTPUT
?
Example of Repetition num
OUTPUT
1
int num;
for ( num = 1 ; num <= 3 ; num++ ) { printf(“%d Potato\n”, num);}
Example of Repetition num
OUTPUT
1
int num;
for ( num = 1 ; num <= 3 ; num++ ) { printf(“%d Potato\n”, num);}
true
Example of Repetition num
OUTPUT
1
int num;
for ( num = 1 ; num <= 3 ; num++ ) { printf(“%d Potato\n”, num);}
1 Potato
Example of Repetition num
OUTPUT
2
int num;
for ( num = 1 ; num <= 3 ; num++ ) { printf(“%d Potato\n”, num);}
1 Potato
Example of Repetition num
OUTPUT
2
int num;
for ( num = 1 ; num <= 3 ; num++ ) { printf(“%d Potato\n”, num);}
1 Potato
true
Example of Repetition num
OUTPUT
2
int num;
for ( num = 1 ; num <= 3 ; num++ ) { printf(“%d Potato\n”, num);}
1 Potato
2 Potato
Example of Repetition num
OUTPUT
3
int num;
for ( num = 1 ; num <= 3 ; num++ ) { printf(“%d Potato\n”, num);}
1 Potato
2 Potato
Example of Repetition num
OUTPUT
3
int num;
for ( num = 1 ; num <= 3 ; num++ ) { printf(“%d Potato\n”, num);}
true
1 Potato
2 Potato
Example of Repetition num
OUTPUT
3
int num;
for ( num = 1 ; num <= 3 ; num++ ) { printf(“%d Potato\n”, num);}
1 Potato
2 Potato
3 Potato
Example of Repetition num
OUTPUT
4
int num;
for ( num = 1 ; num <= 3 ; num++ ) { printf(“%d Potato\n”, num);}
1 Potato
2 Potato
3 Potato
Example of Repetition num
OUTPUT
4
int num;
for ( num = 1 ; num <= 3 ; num++ ) { printf(“%d Potato\n”, num);}
1 Potato
2 Potato
3 Potato
false
Example of Repetition num 4
int num;
for ( num = 1 ; num <= 3 ; num++ ) { printf(“%d Potato\n”, num);}
false
When the loop control condition is evaluated and has value false, control passes to the statementfollowing the for statement.
int count ;
for ( count = 0 ; count < 4 ; count++ ){ printf(“%d \n”, count);}
printf( “Done\n”);
Count-controlled Loop
OUTPUT: 0123Done
int count ;
for ( count = 0 ; count <= 4 ; count++ ){ printf(“%d \n”, count);}
printf( “Done\n”);
Count-controlled Loop
OUTPUT: 01234Done
Equivalence with while loop
The following while loop is equivalent to the previous for loop (on the previous slide)
int count ;count = 0; /* initialization */
while (count <= 4) /* test expression */{ printf(“%d \n”, count);
count++; /* update loop variable*/}
printf( “Done\n”);
Summing Values in Loops
int num, count;int total = 0;
for ( count = 0; count < 10; count++ ){
printf(“nter a numer:”;scanf (“%d”, &num);total += num;
}
For Loop Variations The counter variable can be initialized to
anything. The test expression can be any logical
expression involving the counter variable. The increment can be any value, positive or
negative. Examples:
for (i = 0; i < 10; i += 2) for (k = 20; k > 0; k -= 1)for (j = 1; j != 6; j += 2)
Warning: What happens in the last example?
What Is Displayed By Each Program Segment?
for (i = 0; i < 10; i +=2){
printf(“%d\n”, i );}
for (j = 20; j >= 0; j -= 3){
printf(“%d\n”, j );}
02468
20171411852
Nested For Loops
for (j = 0; j <= 3; j ++) {
for (k = j; k < 5; k ++) {
printf(“%d %d\n”, j , k);}printf (“\n”);
}
What is printed to the screen?
0 00 10 20 30 4
1 11 21 31 4
2 22 3 2 4
3 33 4
Multiple Selection An algorithm may contain a series of
decisions in which a variable or expression is tested Many if…else if… else statements Switch statement
Switch Statement
case a
case b
case z
default
true
true
true
false
false
false
case a action(s)
case b action(s)
case z action(s)
break;
break;
break;
/* count the letter grades */
switch(grade) {case ‘A’:
aCount++; break;
case ‘B’:bCount++;break;
case ‘C’:cCount++;break;
case ‘D’:dCount++;break;
default:fCount++;
}
Place within a while loop to capture many grades:
Switch Statement Each case can have one or more actions Each break statement causes control to
immediately exit the switch statement What happens if you leave out a break?
Error: What is printed out for bCount and cCount?
/* count the letter grades */
switch(grade) {case ‘A’:
aCount++; break;
case ‘B’:bCount++;/* No break! */
case ‘C’:cCount++;break;
case ‘D’:dCount++;break;
default:fCount++;
}
More than one case can have the same action(s).
/* count the letter grades */
switch(grade) {case ‘A’:case ‘a’:
aCount++; break;
case ‘B’:case ‘b’:
bCount++;break;
case ‘C’:case ‘c’:
cCount++;break;
case ‘D’:case ‘d’:
dCount++;break;
default:fCount++;
}
The Lab Tracing code by hand Summing, Average Max/Min
In <limits.h> there is INT_MAX and INT_MIN These defined constants are useful for
initializing your min and max variables