Chapter 3 control ow
content:
•
If statement
•
Switch
•
Loops(while, for, do-while)
3.1 statement and blocks
•
When add a “;” at the end of a expression, it turns out to be a st
atement. For example:
–
a=b=c; x=a==b;
–
i++; j--;
–
a+b; a==b; sin(x)+cos(x)
(statements on the last line are syntacti
cally right, but make no sense)
•
Attention:Every c statement ended with a semicolon,eg:
–
int a=1,b=2; char c=‘a’ ; float d=3.
14;
–
printf(“%d %d”,a,b);
–
if (a>b) max=a; else max=b;
–
for (i=1;i<10;i++) sum=sum+i;
Compound statement (blocks)
•
{ } are used to group declarations and statements t
ogether into a block, so that they are syntactically
equivalent to a single statement.
•
Eg:
1. if
(a>b)
{ t=a;
a=b;
b=t;}
2. while (n!
=0)
{r=m%n;
m=n;
n=r;}
3. int max(int a,
int b)
{ int m;
m=a>b?a:b;
return m;}
3.2 if- else
•
Format:
if (expression)
statement1
else
statement2
Notes:
1.The else part is optional.
2.statement1~2 should be a single
statement or a block.
3.Do not forget the ( ) .
4.Pay attention to the indent format
Frist, the expression is evaluated; if it’s true (n
on-zero), statement1 is executed, if it is false (zer
o), and if there is an else part,statement2 is execu
ted.
the expression is often a relational or logical ex
pression, but it can be a arithmetic too. In this con
dition, you can regard non-zero value as true and
zero as false.
Nested and Ambiguity
•
Eg1:To find the maxi
mum of a,b,c
If (a>b)
if (a>c) max=a;
else max=c;
Else
if (b>c) max=b;
else max=c;
•
Eg2:Given the 3 sides of a t
riangle a,b,c, calculate the a
rea .
If (a>0&&b>0&&c>0)
if (a+b>c&&a+c>b&&b+c>a)
{ s=(a+b+c)/2;
area=sqrt(s*(s-a)*(s-b)*(s-c));
printf(“\narea=%.2f ”,area);}
else
printf(“\nNot a triangle.”);
Eg2 have a logical error. You
can read our textbook P56 for
help.