Chapter 3 - RLeach.com

Download Report

Transcript Chapter 3 - RLeach.com

Chapter 3
Arithmetic and Other Operations
in C
Chapter 3 slides
Slide 1
Integer Arithmetic
There are 5 commonly-used operations for
expressions of type int :
+
*
/
%
Chapter 3 slides
Slide 2
Integer Arithmetic
There are 5 commonly-used operations for
expressions of type int :
+ addition
subtraction
*
multiplication
/
division
% modulus
Results are always of type int
Chapter 3 slides
Slide 3
How do these operations behave?
For +, -, and * :
• the expected manner
• the values of the result are what you would
normally expect
• if two expressions both of type int are
added, subtracted, or multiplied, the result
is also of type int.
Chapter 3 slides
Slide 4
Division is different
Division of int expressions always produces
a result of type int
Example: 7/2 has the value 3, which is of
type int also.
Division fails if the divisor is 0.
Chapter 3 slides
Slide 5
Division is different
Division of int expressions always produces
a result of type int
• Example: 7/2 has the value 3, of type int
• Division fails if the divisor is 0.
• We can recover the dividend:
• 7 = 2 * 3 + 1 (1 is the remainder)
• The remainder is also called the modulus.
• The value of 7 % 2 is 1
Chapter 3 slides
Slide 6
More about the modulus operator
• 24 % 12 is 0
• 13 % 12 is 1
• 20 % 12 is 8
why?
why?
why?
Chapter 3 slides
Slide 7
More about the modulus operator
• 24 % 12 is 0 since 24/12 has remainder 0
• 13 % 12 is 1 since 13/12 has remainder 1
• 20 % 12 is 8 since 20/12 has remainder 8
Chapter 3 slides
Slide 8
More about the modulus operator
•
•
•
•
24 % 12 is 0 since 24/12 has remainder 0
13 % 12 is 1 since 13/12 has remainder 1
20 % 12 is 8 since 20/12 has remainder 8
This is really clock arithmetic
Chapter 3 slides
Slide 9
Divsion can always be reversed
For any two positive ints n and m
n is equal to n/m + n % m
What happens for negative ints? It’s tricky –
probably not necessary in most
applications.
Chapter 3 slides
Slide 10
C has some shorthand notations
The code in
variable = variable + 1;
can be done by the incrementation operator
i++;
++i;
The decrementation operator is used for
subtracting 1 from an expression.
i--;
--i;
Chapter 3 slides
Slide 11
Two ways to use incrementation
and decrementation
• The easy way: to increment or decrement
variables as in j++ or k– within, say, a forloop or while-loop
• The hard way, in the middle of other
statements
x = i++;
Which comes first: the ++ or the
assignment?
Chapter 3 slides
Slide 12
Precedence rules apply
Example 3.2
#include <stdio.h>
int main(void)
{
int i=4, x;
printf("Increment before the assignment: %d\n", x=++i);
i=4;
printf("Assignment before the increment: %d\n", x=i++);
}
Chapter 3 slides
Slide 13
The output is what is expected
•
•
Increment before the assignment: 5
Assignment before the increment: 4
Chapter 3 slides
Slide 14
Watch the order
• x = i++; the incrementation occurs before
the assignment
• x = ++i; the incrementation occurs after
the assignment
Chapter 3 slides
Slide 15
Try to avoid use of complex
precedence rules
• Use the ++ and – forms
• Be able to understand what you read in
other people’s programs.
Chapter 3 slides
Slide 16
• Example 3.3
#include <stdio.h>
/* Same as example 2.12 except for the ++
operator */
int main(void)
{
int i, number_of_students;
int number_of_A = 0, number_of_B = 0,
number_of_C = 0;
int number_of_D = 0, number_of_others = 0;
float average;
char grade;
puts("Enter the number of students in the class");
scanf("%d", &number_of_students);
Chapter 3 slides
Slide 17
if (number_of_students > 100)
puts("Remember to ask for raise");
for (i = 1; i < number_of_students; i ++)
{ /* code to compute the average and grade goes
here */
switch (grade)
{
case 'A' :
printf("Grade is A\n");
if (average >= 95.0)
printf("Outstanding job!!!\n");
number_of_A ++;
break;
Chapter 3 slides
Slide 18
case 'B' :
printf("Grade is B\n");
number_of_B ++;
break;
case 'C' :
printf("Grade is C\n");
number_of_C ++;
break;
case 'D' :
printf("Grade is D\n");
number_of_D ++;
break;
Chapter 3 slides
Slide 19
case 'W' :
printf("Grade is W\n");
number_of_other ++;
break;
case 'I' :
printf("Grade is I\n");
number_of_other ++;
break;
default:
printf("Sorry\n");
number_of_other ++;
} /* end of switch */
} /* end of for loop */
} /* end of main */
Chapter 3 slides
Slide 20
Other incrementation operators
variable += increment;
variable -= increment;
variable *= increment;
variable /= increment;
Chapter 3 slides
Slide 21
Watch for constants
• Can’t change a constant
const int x = 4;
x += 3; /* illegal - will not compile */
Chapter 3 slides
Slide 22
Usually try to avoid mixed mode
• Sometimes unavoidable, or even desirable
• n = c – ‘0’ changes the value of a
character (usually in range 0..9) to convert
to an int value named n
• Can force a type conversion in a
computation using a “cast operation”
• x = (float) n + 3.0
• Arithmetic is done on floats, then result is
converted to type of lhs
Chapter 3 slides
Slide 23
Life gets more complicated if operands
have mixed types – here’s why
•
•
•
•
•
If one of the operands is of type short, then it is
converted to type int.
If one operand is of type unsigned long int, then the
other is converted to unsigned long int.
Otherwise, if one operand is of type long int and the
other operand is of type unsigned int, then each of the
operands is converted to unsigned long int, and the
result is of type long int (not generally unsigned long
int).
Otherwise, if one operand is of type long int, then the
other is converted to long int.
Otherwise, if one operand is of type unsigned int, then
the other one is converted to type unsigned int.
Chapter 3 slides
Slide 24
SHORT
CHAR
INT
LONG
FLOAT
DOUBLE
A
B
C
D
E
F
G
H
I
A: SHORT + SHORT
B: SHORT + INT
C: CHAR + INT
D: INT + FLOAT
E: FLOAT + FLOAT
F: FLOAT + DOUBLE
G: INT + DOUBLE
H: CHAR + DOUBLE
I : SHORT + LONG
Chapter 3 slides
Slide 25
Operator Precedence
#include <stdio.h>
int main(void)
{ int i = 0; float x = 0.0;
printf("%d\n",2 + 3 * 5 );
printf("%d\n",i += 3);
printf("%d\n",i += 3 * 5);
printf("%d\n",i *= 3 * 5);
printf("%f\n",2.0 + 3.0 * 5.0);
printf("%f\n",x += 3.0);
printf("%f\n",x += 3.0 * 5.0);
printf("%f\n",x *= 3.0 * 5.0);
}
Chapter 3 slides
Slide 26
17
3
18
270
17.000000
3.000000
18.000000
270.000000
Chapter 3 slides
Slide 27
Part of precedence table
OPERATOR
()
COMMENTS ON USE
grouping
!
++
--
negation, right-associative
increment, right-associative
decrement, right-associative
unary minus, right-associative
*
/
%
multiplication
division
modulus
Chapter 3 slides
Slide 28
OPERATOR
COMMENTS ON USE
+
-
addition
subtraction
<
<=
>
>=
less than
less than or equal to
greater than
greater than or equal to
==
!=
equal to (comparison)
not equal to
Chapter 3 slides
Slide 29
• OPERATOR
&&
COMMENTS ON USE
logical AND
||
logical OR
?:
if-else, right-associative
=
+=
-=
*=
/=
assignment, right associative
assignment (with addition), right-associative
assignment (with subtraction), right-assoc.
assignment (with multiplication), right-assoc.
assignment (with division), right-associative
Chapter 3 slides
Slide 30
What if you forget the precedence
table?
• Use parentheses
• They have the highest precedence and
help keep ideas clear.
• What is the value of
++ x ++ ++ ++ - x++ - --x * x*=x +=x;
if x is equal to 3?
Chapter 3 slides
Slide 31
An unusual combination
Assignment statements in C have both
• lvalues, for the variable to which a value is
being assigned
and
• rvalues, for the value being assigned to
the variable.
x=5>3+(x=7)
Chapter 3 slides
Slide 32
What ‘s the value of this expression
Start with the inside of the parentheses
x=7
• This assignment gives the value 7 to the
variable x.
• The value of the expression x = 7 is the
lvalue, namely 7.
• (x = 7) has the same value
Chapter 3 slides
Slide 33
General principle for lvalues
• The lvalue of an assignment statement
is the value assigned to the variable on
the left-hand side of the assignment
operator.
Chapter 3 slides
Slide 34
Example, continued
• What’s the value of x = 5 > 3 + 7 ?
• Use the table again to see that > has lower
precedence than does +
• Perform the addition first.
• The expression simplifies to
x = 5 > 10
Chapter 3 slides
Slide 35
Example, continued
• What’s the value of x = 5 > 10 ?
• According to the precedence table, we now have
to determine the evaluation of the expression
5 > 10
• The lvalue of an inequality statement is 0 if the
statement is false and some nonzero value if it is
not false.
• In this case, the statement is false and so the
value 0 is assigned to x
• The last assignment of 0 to x has an lvalue of 0.
Chapter 3 slides
Slide 36
Reading from files
•
•
•
•
fopen( ) used to prepare the file for reading
fclose( ) used to close the file after we are finished
getc( ) similar to the function getchar( ) we have already seen
Follow the template of this example exactly to use files; change only the file
name and the name of the variable used to store the value read in.
#include <stdio.h>
int main(void) /* reads from a file named “file1” */
{
FILE *fp;
int c;
fp= fopen("file1","r");
while ((c = getc(fp) ) != EOF)
printf("%c",c);
fclose(fp);
}
Chapter 3 slides
Slide 37
What is a file?
• A collection of data.
• Files may be stored on a variety of
devices; hard disks, CDs, DVDs, flash
drives, other computers on a network, etc.
• C programs that use files usually don’t
distinguish between different types of
devices used to store files
Chapter 3 slides
Slide 38
Files on disks are stored in blocks
• Each block is on a track and sector
The disk spins
and different
data blocks are
under the
read/write
head which
moves in and
out
Chapter 3 slides
Slide 39
Data files on CDs may be stored in
contiguous blocks.
• Each block is on a track and sector
The disk spins
and different
data blocks are
under the
read/write
head which
moves in and
out
Chapter 3 slides
Slide 40
Data files on hard disks almost
never stored in contiguous blocks
• Each block is on a track and sector
The disk spins
and different
data blocks are
under the
read/write
head which
moves in and
out
Chapter 3 slides
Slide 41
Storage on flash drives is different
• Probably a contiguous set of bytes if the
data is written at once.
• If the data is written in chunks, such as
temp files from Microsoft Word, the data
might be stored anywhere on the flash
drive
Chapter 3 slides
Slide 42
Let’s look at the code again
#include <stdio.h>
int main(void) /* reads from a file named “file1” */
A FILE pointer is a data type defined in stdio.h
{
FILE *fp;
int c;
fp= fopen("file1","r");
while ((c = getc(fp) ) != EOF)
printf("%c",c);
fclose(fp);
}
Chapter 3 slides
Slide 43
Let’s look at the code again
#include <stdio.h>
int main(void) /* reads from a file named “file1” */
A FILE pointer is a data type defined in stdio.h
{
FILE *fp;
Open the file for reading
int c;
fp= fopen("file1","r");
while ((c = getc(fp) ) != EOF)
printf("%c",c);
fclose(fp);
}
Chapter 3 slides
Slide 44
Let’s look at the code again
#include <stdio.h>
int main(void) /* reads from a file named “file1” */
A FILE pointer is a data type defined in stdio.h
{
FILE *fp;
Open the file for reading
int c;
Uses getc(fp) to
read a character –
fp= fopen("file1","r");
like getchar()
while ((c = getc(fp) ) != EOF)
printf("%c",c);
fclose(fp);
}
Chapter 3 slides
Slide 45
Let’s look at the code again
#include <stdio.h>
int main(void) /* reads from a file named “file1” */
A FILE pointer is a data type defined in stdio.h
{
Open the file for reading
FILE *fp;
Uses getc(fp) to
int c;
read a character –
like getchar()
fp= fopen("file1","r");
while ((c = getc(fp) ) != EOF)
printf("%c",c);
EOF is the end of file
marker – defined in stdio.h
fclose(fp);}
Chapter 3 slides
Slide 46
Let’s look at the code again
#include <stdio.h>
int main(void) /* reads from a file named “file1” */
A FILE pointer is a data type defined in stdio.h
{
Open the file for reading
FILE *fp;
Uses getc(fp) to
int c;
read a character –
like getchar()
fp= fopen("file1","r");
while ((c = getc(fp) ) != EOF)
printf("%c",c);
EOF is the end of file
marker – defined in stdio.h
fclose(fp);}
Close the file after use
Chapter 3 slides
Slide 47
Why did we use a while-loop?
#include <stdio.h>
int main(void) /* reads from a file named “file1” */
{
FILE *fp;
int c;
fp= fopen("file1","r");
while ((c = getc(fp) ) != EOF)
printf("%c",c);
fclose(fp);
}
• Iteration through the file requires a loop
Chapter 3 slides
Slide 48
Why did we use a while-loop?
#include <stdio.h>
int main(void) /* reads from a file named “file1” */
{
FILE *fp;
int c;
fp= fopen("file1","r");
while ((c = getc(fp) ) != EOF)
printf("%c",c);
fclose(fp);
}
• Iteration through the file requires a loop
• File might be empty – can’t read from an empty file
Chapter 3 slides
Slide 49