Conditionals, Loops, and Other Kinds of Statements

advertisement
Conditionals, Loops, and
Other Kinds of Statements
CS-2301, System Programming
for Non-Majors
(Slides include materials from The C Programming Language, 2nd edition, by Kernighan and Ritchie and
from C: How to Program, 5th and 6th editions, by Deitel and Deitel)
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
1
Reading Assignment
• Chapter 3 of Kernighan and Ritchie
• Helpful to follow along in class
• Note on §3.8 :– we do not allow goto
statements in this course
• There is rarely, if any, situation at WPI
where a goto in C would be the right thing
• There is rarely a situation in any program
where a goto is the right thing!
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
2
Review
• Expression – a sequence of operators and
operands that return a value
• Assignment – expression with the side effect
of changing the value of the left operand
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
3
Definition – Side Effect
• The changing of the value of some data in the
course of evaluating or executing something else
• Sometimes unrelated data!
• Examples:–
– Explicit assignments
• x = y + 3; i++; --j;
– printf()
• Writes to internal buffer; flushes buffer to screen on '\n'
– scanf() – returns values from input
• Explicit – assigns data to arguments
• Implicit – keeps track of where it is in internal buffer
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
4
Definition – Statement
• Instruction to “do” something
• Specifies order of execution & evaluation
• §A.9 – a statement in C may be any of:–
•
•
•
•
•
•
labeled-statement
expression-statement
compound-statement
selection-statement
iteration-statement
jump-statement
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
5
Expression Statement
• expressionoptional ;
• Note: semicolon is terminator
• Exists primarily for its side effects
• E.g.,
• x = y + 3; i++; --j;
• printf(“string”, arg1, arg2, arg3);
• The following is perfectly legal in C:–
•
y + 3;
• Evaluates the expression, then throws the result away!
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
6
Compound Statement
• A sequence of statements surrounded by {}
• Example:–
{
x = 0;
i++;
printf("The value of x is %d\n", x);
}
• Reason:– so that we can group together
statements in loops, if-else, functions, etc.
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
7
Compound Statement (continued)
• Compound statements may be nested
{
...;
{ x = 0;
i++;
}
/* no semicolon needed here*/
printf("The value of x is %d\n", x);
...;
}
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
8
Compound Statement (continued)
• Compound statements may include declarations
inside
{
double angle;
angle = atan2(y, x) * 360/(2*pi);
printf("Angle is %f degrees\n", angle);
}
• Declarations inside of {} are not known outside of
{}
• Book says declarations must be at beginning of {}
• Later versions of C relax this rule
• Declaration must always precede first use of declared identifier
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
9
Questions?
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
10
If-else Statements
if (expr)
statement1
/*do this if expr is non-zero*/
else
statement2
/*do this if expr is zero*/
• The else clause is optional!
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
11
If-else Examples
if (j > limit)
return j;
else
j += stepValue;
...
if (++k >= 4)
k = 0;
CS-2301, B-Term 2009
/* note semicolon*/
/* note semicolon*/
/* increment k mod 4*/
Conditionals, Loops, and
Other Statements
12
If-else Examples (continued)
if (n < maxInput) {
scanf("string", &arg1, &arg2, …);
n++;
printf("string2", arg3, arg4, …);
} else {
/* note NO semicolon*/
printf("Summary\n", arg5, …);
return n;
}
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
13
Concatenated If-else Statements
if (expr1)
statement1
/*do this if expr1 is non-zero*/
else if (expr2)
statement2
/*i.e., expr1 == 0, expr2 != 0*/
else if (expr3)
statement3 /expr1 and expr2 are zero, expr3 != 0*/
else if (expr4)
statement4 /expr1, expr2 , expr3 all zero, expr4 != 0*/
else
statement5
CS-2301, B-Term 2009
/*i.e., all expr are zero*/
Conditionals, Loops, and
Other Statements
14
Concatenated If-else Statements
• Last else is always attached to last if
• If it should be attached to any other if, use
{} to control the flow of execution.
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
15
Switch Statement
• Somewhat like a concatenated if-else
• Occasionally easier to read
• Each arm is called a case
• Evaluate switch expression, select the
appropriate case (if any)
– default case is optional
• Difference from concatenated if-else
• Need break statement to exit switch after a case
• Otherwise, control falls through to next case
• See §3.4 and p. 59
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
16
Switch Statement Example
int month, daysInMonth, leapYear;
…
switch (month) {
case 0:
printf("January\n");
daysInMonth = 31;
break;
case 1:
printf("February\n");
daysInMonth = leapYear ? 29 : 28;
break;
case 2:
printf("March\n");
daysInMonth = 31;
break;
case 3:
printf("April\n");
daysInMonth = 30;
break;
…
} // switch
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
17
Switch Statement Example
int month, daysInMonth, leapYear;
…
switch (month) {
case 0:
printf("January\n");
daysInMonth = 31;
break;
case 1:
printf("February\n");
daysInMonth = leapYear ? 29 : 28;
break;
case 2:
printf("March\n");
daysInMonth = 31;
break;
case 3:
printf("April\n");
daysInMonth = 30;
break;
…
} // switch
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
18
Questions?
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
19
Iterative Statement
• while loop
• for loop
• do-while loop
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
20
while loops
while (expression)
statement
Often a compound statement
• Evaluate expression
• If true, execute statement and then repeat
• Repeat until expression becomes false
• statement may be executed zero or more
times!
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
21
while loop example
int sum = 0;
int count = 0;
int input;
while (scanf("%d", &input) != EOF){
sum += input;
count++;
printf("Input value of %f recorded.\n", input);
...
}
if (count > 0)
printf("Average is %f\n", (double)sum/count);
else
printf("No inputs recorded\n");
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
22
while loop examples (continued)
• Study example on p. 59 (§3.4)
• A program to count digits, white space
characters, and other characters.
• Includes a while loop with a switch
statement inside
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
23
do-while loop
• do
statement
while (expression);
• Similar to while loop, but guaranteed to
execute statement at least once
• See §3.6
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
24
Breaking out of a Loop
• When it becomes necessary to terminate a
loop prematurely
– break;
/*exits smallest containing
switch or loop*/
• When it becomes necessary to terminate the
current iteration and start the next one
– continue; /*terminates this iteration
only*/
• See p. 65, §3.7
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
25
Questions?
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
26
for loop
• A counting loop
for (expr1; expr2; expr3)
statement
• Evaluate expr1 to initialize
• Evaluate expr2 to test
• If true, execute statement
• If not true, exit for loop
• Evaluate expr3 to prepare for next iteration
• Repeat expr2 to test
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
27
for loops and while loops
• The for loop
for (expr1; expr2; expr3)
statement
• is exactly equivalent to the following
expr1;
while (expr2) {
statement
expr3;
}
• See p. 60
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
28
The most common kind of for-loop
int i;
for (i = 0; i < limit; i++) {
...;
/* do something with ith entity */
...;
}
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
29
The most common kind of for-loop
int i;
for (i = 0; i < limit; i++) {
...;
/* do something with ith entity */
...;
}
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
30
The most common kind of for-loop
int i;
for (i = 0; i < limit; i++) {
...;
/* do something with ith entity */
...;
}
• This loop iterates limit times.
– Iterations are numbered i = 0, 1, 2, …, limit-1
• Reason:– arrays are indexed this way!
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
31
Nested for-loops
int i, j;
for (i = 0; i < limit; i++) {
...;
/*prepare subgroup i*/
for (j=0; j < limit2; j++) {
...;
/* do something with item j of
subgroup i*/
...;
}
...;
}
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
32
An Extension in Modern C Compilers
• The following construct (not in book) is legal in C99:–
for (int i = 0; i < limit; i++){
expression involving i;
...;
printf(“Iteration %d completed.\n”, i);
...;
}
• The loop counter i is declared in for loop
• Not visible outside of loop!
• Common practice
• Good programming style
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
33
Notes on Loop Style
for (int i = 0; i < limit; i++) {
...;
/*prepare for subgroup i*/
for (int j=0; j < limit2; j++) {
...;
/* do something with item j of
subgroup i*/
...;
} /* end of loop j */
...;
}
/* end of loop i */
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
34
Notes on Loop Style
for (int i = 0; i < limit; i++) {
...;
/*prepare for subgroup i*/
for (int j=0; j < limit2; j++) {
...;
/* do something with item j of
subgroup i*/
...;
} /* end of loop j */
...;
}
/* end of loop i */
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
35
Questions?
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
36
Simple Example
• Read a series of numbers
• Add up the numbers and also the squares of
those numbers “on-the-fly”
• After all numbers are input, print out:–
– The mean
– The standard deviation
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
37
Simple Example (continued)
#include <stdio.h>
#include <math.h>
for (n = 0; ; n++) {
int rc;
double input;
int main(int argc, char
*argv[]) {
unsigned int n;
double mean;
double sum = 0;
double sumOfSquares = 0;
printf("Enter sequence“
" of numbers:- ");
rc = scanf("%lf", &input);
if (rc == EOF)
break;
else if (rc == 0)
continue;
sum += input;
sumOfSquares += input *
input;
} //for (n = 0 ...
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
38
Simple Example (concluded)
printf("The total number of input entries“
" was %u.\n", n);
if (n > 0 ) {
printf("The mean is %g.\n", mean = sum/n);
printf("The standard deviation is %g.\n",
sqrt(sumOfSquares/n - pow(mean, 2)));
}
// if (i > 0)
return 0;
} //main
Example can be found here
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
39
Questions?
CS-2301, B-Term 2009
Conditionals, Loops, and
Other Statements
40
Download