Download notes

Document related concepts

Addition wikipedia , lookup

Mathematics of radio engineering wikipedia , lookup

Elementary mathematics wikipedia , lookup

Transcript
Lecture 3.1
Operators and Expressions
Structured Programming
Instructor: Prof. K. T. Tsang
1
Binary Arithmetic Operators (p.41)
Binary arithmetic operators: +, -, *, / (float, double, or mixed)
% modulus operator (for integer only)
int i1=9, i2=4, i3=6, i4, i5;
i4=i1/i2;
i5=(i1+i2)*i3/i4;
/*int division results int*/
printf( “The answer is %d\n”, i5);
float f1=4.5, f2=2.3;
float f3 = f1/f2;
/*float division results float*/
f3 = 15/10.0;
/*mixed mode results f3=1.5*/
f3 = 15/10;
/*int division first then cast into float
f3=1.0*/
f3 = 13 % 5;
/*answer: 3 remainder*/
2
Type Casting强制性类型转换
int i2 = 5;
float x2;
x2 = (float)i2 / 4.0;
In general, explicit type conversion can be
forced by a unary operator called a cast.
(type-name) expression
3
Unary Arithmetic Operators
++ -int i1=0, N1, N2;
i1++;
/*postfix—increment by 1 after value is used*/
++i1;
/*prefix—increment by 1 before value is used */
int i8=9;
i8--;
--i8;
i1 = 5;
N1 = i1++;
i1 = 5;
N2 = ++i1;
/*postfix—decrement by 1 after value is used */
/*prefix—decrement by 1 before value is used */
/i1=6, N1=5*/
/i1=6, N2=6*/
4
Examples of ++ and -/*Any difference between the following Expressions?*/
int i1=0, i8=9, N1, N2, N3, N4, N5;
N1 = i1++ + i8--;
/*i1=1, i8=8, N1=9*/
N2 = i1++ + --i8;
/*i1=2, i8=7, N2=8*/
N3 = ++i1 + i8--;
/*i1=3, i8=6, N3=10*/
N4 = ++i1 + --i8;
/*i1=4, i8=5, N4=9*/
/*What is this?? Never write code like this*/
i1 = 1;
N5 = i1++ * 3 + i1++ * 5; /*Result is compiler dependent*/
/*Do this instead*/
i2 = i1++;
/*i2=1, i1=2*/
i3 = i1++;
/*i3=2, i1=3*/
N5 = i2 * 3 + i3 * 5;
/*N5=13*/
Or
N5 = i3 * 3 + i2 * 5;
/*N5=11*/
5
Post-fixing & Pre-fixing ++/-Post-fixing ++/-- a variable in an expression,
the expression is evaluated first with the
original value of the variable before it is
incremented or decremented by 1.
Pre-fixing ++/-- a variable in an expression,
it is incremented or decremented by 1 first
before the expression is evaluated with the
new value of the variable.
6
Precedence and Associativity of
operators (p.53 K&R)
Precedence – which operation to be performed
first?
n1 + n2 * n3 - ++n4 / n5
Same as
n1 + (n2 * n3) – ((++n4) / n5)
Associativity – order of operations with same
precedence when there is no parenthesis
n1 * n2 / n3 means (n1 * n2) / n3 --left to right-To avoid confusion, always use parentheses.
7
Relational operators
To form relational Expression to be used in control
Actions. (p.41 K&R)
Larger than
>
Larger than or equal to
Less than
<
Less than or equal to
Equal to
==
Not equal to !=
>=
<=
8
Relational Expressions
Example:
a == b; i1 > 34; student_id < 100;
Relational Expressions have values: true or
false
10 > 6
true
1
3 >= 12
false
0
-22 == 9
false
0
‘A’ != ‘g’
true
1
‘M’ > ‘a’
false
0
9
Logical operators
&&
||
!
and
or
Not
Example:
(n1 < 10) && (n2>= 6)
(days > 4) || (months < 7)
!(n2 > n1)
10
Truth table
Logical Expressions have truth values.
e1
1
0
1
0
e2
1
1
0
0
e1&&e2
1
0
0
0
e1||e2
1
1
1
0
!e1
0
1
11
Equivalent Expressions
!(a > b)
!(a < b)
!(a == b)
a <= b
a >= b
a != b
a>b
a<b
a == b
!(a <= b)
!(a >= b)
!(a != b)
12
Assignment operators
Simple assignment:
var1 = 10; var2 = i1;
Shorthand assignment:
var1 (op)= exp means
var1 = var1 (op) exp
Examples:
a += 5;
/* a = a + 5 */
a -= n;
/* a = a – n */
x *= a + b;
/* x = x * (a + b) */
x /= 16;
/* x = x / 16 */
x %= 2;
/* x = x % 2 */
13
Bitwise operators (p. 48 K&R)
Six operators for bit manipulation, applied only to
char, short, int, long (signed or unsigned).
& bitwise AND
| bitwise inclusive OR
^ bitwise exclusive OR
<< left shift
>> right shift
~ complement (unary)
14
Bit-Operators: & | ^ ~
bit1
0
0
1
1
bit2
0
1
0
1
bit1 & bit2
0
0
0
1
bit1 | bit2
0
1
1
1
bit1 ^ bit2
0
1
1
0
~bit2
1
0
15
Left and right shift operators
n = 0x1C
00011100
n << 1 (= 0x38)
00111000
n >> 2 (= 0x07)
00000111
“<<“ moves data left fixed number of bits.
New bits come from right are zeros.
“>>” moves data right fixed number of bits.
New bits come from left are zeros
16
Examples
n = n & 0177; /*set all but lower 7 bits to 0*/
n = n & 0377; /*set all but lower 8 bits to 0*/
n = n | 070;
/*set to 1 the 6th to 4th bits from the right*/
n = n & ~077
/*set the lower 6 bits to 0*/
17
Conditional operator
exp1 ? exp2 : exp3
x = exp1 ? exp2 : exp3
equivalent to
if (exp1) x = exp2;
else x = exp3;
18
Lecture 3.2
Control structures and Loops
Structured Programming
Instructor: Prof. K. T. Tsang
19
Control structures
• Provide
– Ability to control whether an Action list is
executed
• Two constructs
– if statement
• if
• if-else
• if-else-if
– switch statement
20
Simple IF statement
Syntax
if(Expression) Action;
If the Expression is true (nonzero), the
action will be executed. Otherwise do
nothing.
Expression
true
Example:
if ( n1 > n2 ) printf( “%d is larger
than %d\n”, n1, n2);
false
Action
21
If…else statement
Example:
int n1 = 23;
int n2 = 35;
if ( n1 > n2 ) printf( “%d is larger than %d\n”, n1, n2);
else printf( “%d is not larger than %d\n”, n1, n2);
22
If…else
if (Expression) Action1 ;
else Action2 ;
If the Expression is true (nonzero),
the Action1 will be executed.
Otherwise Action2 will be
executed.
Expression
true
false
Action1
Action2
23
Example: if-else
#include<stdio.h>
int main()
{
int value1;
int value2;
int larger;
printf("Enter two characters:\n” );
if(value1 = getchar() == EOF ) return (0);
if(value2 = getchar() == EOF ) return (0);
if(value1 > value2)
larger = value1;
else
larger = value2;
printf( "Larger of the inputs in ASCII is: %c\n“, larger) ;
return (0);
}
24
The standard library provides several functions for reading
one character at a time from the keyboard, of which getchar
is the simplest.
int getchar ( void );
Get character from stdin
Returns the next character from the standard
input (stdin).
Use with
#include <stdio.h>
25
if-else-if statement
General form (p. 23):
if ( Expression_1 ) Action_1 ;
else if ( Expression_2 ) Action_2 ;
…
else if ( Expression_n ) Action_n ;
else Action_m ;
26
if-else-if flow-chart
Expression1
false
true
Expression2
Action1
true
Action2
false
Action3
27
Example: if-else-if
int score;
...
if(score >= 90)
printf( "Grade = A\n“
else if(score >= 80)
printf( "Grade = B\n“
else if(score >= 70)
printf( "Grade = C\n“
else if(score >= 60)
printf( "Grade = D\n“
else
printf( "Grade = E\n“
);
);
);
);
);
28
Switch statement –
When there are too many ‘else-if’s it is easier to use a switch block.
int score;
...
switch(score/10){
case 10:
printf( "Grade = A\n”);
break;
case 9:
printf( "Grade = A\n”);
break;
case 8:
printf( "Grade = B\n”);
break;
case 7:
printf( "Grade = C\n”);
break;
case 6:
printf( "Grade = D\n”);
break;
default:
printf( "Grade = E\n”);
}
29
Switch statement: effect of ‘break’
int score;
...
switch(score/10){
case 10:
/*no action, falls through*/
case 9:
printf( "Grade = A\n”);
break;
case 8:
printf( "Grade = B\n”);
break;
case 7:
printf( "Grade = C\n”);
break;
case 6:
printf( "Grade = D\n”);
break;
default:
printf( "Grade = E\n”);
}
30
More example: ‘switch’ statement
int left;
int right;
char oper;
printf( "Enter simple Expression: \n“);
cin >> left >> oper >> right;
cout << left << " " << oper << " " << right
<< " = ";
switch (oper) {
case '+' : cout << left + right << endl; break;
case '-' : cout << left - right << endl; break;
case '*' : cout << left * right << endl; break;
case '/' : cout << left / right << endl; break;
default: cout << "Illegal operation" << endl;
}
31
‘break’ statement –
cause the program action break out from the block
Loops or switch statement can be exited at any
point through the use of a break statement.
Example:
int c;
while (1) { /*infinite loop*/
if (c=getchar() == EOF) break;
printf(“you have enter %c\n”, c);
}
32
Nested if Statements
– Nested means that one complete statement is
inside another
– Example:
if (<it is Tuesday>) {
if (<it is time for class>)
<go to programming class>;
else <meet your friends>;
}
33
“Dangling Else” Problem
• Problem: Nested if statements can seem
ambiguous in their meaning.
• What is the value of c after the following is
executed?
int a=-1, b=1, c=1;
if(a>0)
if(b>0)
c = 2;
else
c = 3;
34
“Dangling Else” Problem
• C groups a dangling else with the most recent if.
• The following indentation shows how C/C++
would group this example (answer: c=1).
int a=-1, b=1, c=1;
if(a>0)
if(b>0)
c = 2;
else // dangling else grouped to nearest if
c = 3;
35
Use braces to clear up ambiguity
int a=-1, b=1, c=1;
if(a>0){
if(b>0)
c = 2;
}
else
c = 3;
Or
int a=-1, b=1, c=1;
if(a>0){
if(b>0) c = 2;
else c = 3;
}
36
Iterative Constructs
• Provide
– Ability to control how many times a statement
list is executed
• Three constructs
– while statement
– for statement
– do-while statement
37
while loop
Syntax:
while (condition) Action;
Or:
while (condition) {
Action1;
Action2;
Action3;
…
}
Condition
true
false
Action
Example: p. 9 & p.12 K&R ( What is
the difference?)
38
while loop to calculate 2N
int number, result, n;
result = 1;
n = 1;
number = 6;
while (n <= number) {
result *= 2;
n++;
}
printf("Two raised to the %d power is %d\n“, number, result);
39
while loop to calculate N!
int number, factorial, n;
number = 8;
factorial = 1;
n = 1;
while (n <= number) {
factorial *= n;
n++;
}
printf(" The factorial of %d is %d\n“, number, factorial);
40
‘break’ statement –
cause the program action break out from the block
Loops or switch statement can be exited at any
point through the use of a break statement.
Example:
int c;
while (1) {
/*infinite loop*/
if (c=getchar() == EOF) break;
printf(“you have enter %c\n”, c);
}
41
for loop
for (initial-Action; condition; iteration-Action)
body-Action;
Equivalent to:
initial-Action;
while (condition) {
body-Action;
iteration-Action;
)
Example: p.13 & p.15 K&R
42
for loop to calculate
N
2
int number, result, n;
result = 1;
n = 1;
/*iteration variable*/
number = 6;
/*or other ways to input number*/
if (number == 0) printf("Two raised to 0 power is %d\n“, result);
else {
for(n=1; n<=number; n++) result *= 2;
printf("Two raised to the %d power is %d\n“, number, result);
}
43
for loop to calculate N!
int number, result, n;
result = 1;
n = 1;
/*iteration variable*/
number = 6;
/*or other ways to input number*/
if (number == 0) printf(" The factorial of 0 is %d\n“, result);
else {
for(n=1; n<=number; n++) result *= n;
printf(" The factorial of %d is %d\n“, number, result);
}
44
45
Exercise/study examples
K&R
p. 9: print Fahrenheit – Celsius table
p. 19: line counting
p. 20: word counting
p. 22: number of occurrence (after we learn
‘arrays’)
46
K&R p.9
47
K&R p.15
48
The Do-While Statement
• Syntax
do Action
while (Expression)
• How it works:
– Execute Action
– if Expression is true then
execute Action again
– Repeat this process until
Expression evaluates to
false
• Action is either a single
statement or a group of
statements within braces
Action
true
Expression
false
49
“do-while” loop to calculate 2N
int number, result, n;
result = 1;
n = 1;
/*iteration variable*/
number = 6;
/*or other ways to input number*/
if (number == 0) printf("Two raised to 0 power is %d\n“, result);
else {
do {
result *= 2;
n++;
} while(n <= number);
printf("Two raised to the %d power is %d\n“, number, result);
}
50
Which Loop to Use?
• ‘for’ loop
– Usually best for sums, products, and counting.
• ‘while’ loop
– You want to repeat an action without knowing exactly
how many times it will be repeated.
– You are working with user input
– There are situations when the action should not be
executed.
• ‘do-while’ loop
– The action should always be executed at least once.
– Otherwise, the do-while loops and while loops are
used in similar situations.
51
Key Points of Iteration
– Make sure there is a statement that will eventually
stop the loop
– Make sure to initialize loop counters correctly
– Be sure to initialize to 0 a variable used for sums
– Be sure to initialize to 1 a variable used for products
– Have a clear purpose for the loop
52
“do-while” loop to calculate N!
int number, result, n;
result = 1;
n = 1;
/*iteration variable*/
number = 6;
/*or other ways to input number*/
if (number == 0) printf(" The factorial of 0 is %d\n“, result);
else {
do {
result *= n;
n++;
} while (n <= number);
printf(" The factorial of %d is %d\n“, number, result);
}
53
How to Stop a Loop
• Known number of iterations before
the loop stops (for)
• Carefully test for a user-controlled
condition before or after
each iteration (while, do-while)
54
55
“break” from a loop
double sum=0.0, product=1.0;
int j=0;
while (1) {
j++;
product = product/double(j);
sum= sum + product;
if(product < 1.0e-7) break;
}
56
Effect of the “continue” statement
double sum=0.0, prod=1.0;
int j, NN=900;
for (j=1; j<NN; j++) {
prod= prod/double(j);
sum= sum + prod;
if(prod < 1.0e-7) break;
if(j-j%3 != 0) continue;
sum = sum + prod;
}
57
The continue statement is related to break, but less
often used; it causes the next iteration of the enclosing for,
while, or do loop to begin. In the while and do, this means that
the test part is executed immediately; in the for, control
passes to the increment step. The continue statement applies
only to loops, not to switch.
A continue inside a switch inside a loop causes the next loop
iteration.
58
Common Loop Errors
float balance=100.0, amount=0.01;
while (balance != 0.0)
{
balance = balance - amount;
}
– This will lead to an infinite loop!
balance may not become equal zero due to numerical
inaccuracies.
int n, count = 10;
for (n=1; n<=count; n++);
{
printf( "hello\n“);
}
– "hello" only printed once! Why?
59
What’s wrong?
60
What’s wrong?
61
Assignment:
1. Write a C program to print all prime numbers
smaller than a given positive integer N.
2. Write a C program to find all prime numbers less
than 2^N. Choose any 2 of these prime numbers
and find their product. Print out your result. Run
the program with N=8.
3. Now suppose you are given this product of 2
prime numbers less than 2^N, write another
program to determine what these 2 prime
numbers are. Is the answer unique? Run the
program with N=8.
62
4. What are the values of i and j after the following
lines are executed?
int i = 0;
int j = 0;
int x = 0;
i = x++;
j = ++x;
63
5. Consider the following statement:
When state = BEGIN_STATE, what messages will you get?
64
6. Write a program to print the first 50 terms of the
Fibonacci Sequence.
The Fibonacci sequence is: 1 1 2 3 5 8 . . .
The terms are computed from the equations:
1
1
2=1+1
3=1+2
5=3+2
etc.
In general terms this is: f n = f n-1 + f n-2
65