Arithmetic Operation in C
CptS 121 – Summer 2016 – Armen Abnousi
Lecture 3
General Form of a C Program
• Preprocessor Directives
• Main function heading
• {
• Declarations
• Executable statements
• }
General Form of a C Program
General form
• Preprocessor Directives
• Main function heading
• {
• Declarations
• Executable statements
• }
Example
• #include <stdio.h>
• Int main()
• {
• double len, width;
• printf(“Enter length and width”);
• scanf(“%lf%lf”, &len, &wid);
• printf(“area = %f”, len * wid);
• }
Data Type Matters
• What will happen in this scenario:
double real_num;
int integer_num;
real_num = 3.5;
integer_num = real_num;
• How about here:
int num = 3;
printf(“%f”, num);
• Now let’s look at arithmetic opertions
Arithmetic Operation in C
• All operators +, -, * and / work on both double and int
values.
printf(“%f”, 3.5 + 4.2)
printf(“%f”, 2.1 * 1.9)
printf(“%d”, 3 – 1)
• How about:
Printf(“%f”, 3 – 1);
Arithmetic Operation in C
• All operators +, -, * and / work on both double and int
values.
printf(“%f”, 3.5 + 4.2)
printf(“%f”, 2.1 * 1.9)
printf(“%d”, 3 – 1)
• How about:
printf(“%f”, 3 – 1);
• If both operands are integer, the result will be integer,
if either one or both of the operands are real, the result
will be real and needs to be treated as double!
Division ( / )
• However:
3 / 5 = 0 3.0 / 5 = 0.6
6 / 4 = 1 while 6 / 4.0 = 1.5
7 / 2 = 3 7.0 / 2.0 = 3.5
If both operands of “/” are integers, the result will be the
integer part of the division. (Beware of the loss in your
computations!)
If either nominator or denominator or both of them was
double, then the result will be the complete division result
(integer and fractional parts together).
• Division by zero is undefined!
Modulus Operator ( % )
• % works only on integers!
• % gives the remainder of integer division of two operands.
• 7 % 2 = 1 ( 7 = (2 * 3) + 1 )
• 9 % 3 = 0 ( 9 = (3 * 3) + 0 )
• 10 % 3 = 1 (10 = (3 * 3) + 1) (10 = (10
3*3) + 1)
Mixed Type Assignments
• Variable = expression;
double var;
var = 2 + 3;
• C computes the expression, after completing the
computation, puts the result in variable.
• First compute the right-hand-side, store the result in
left-hand-side!
• (sidenote: what happens in “var1 = var1 + 2”? The value
of var1 will be refreshed to whatever it was before plus
2).
Mixed Type Assignments
• What should be the data type for var2 here:
var2 = 2 + 3.5;
Remember: If both operands are integer, the result will be
integer, if either one or both of the operands are real, the
result will be real and needs to be treated as double!
Type Casts
• Let’s compute the average of 2 numbers a and b:
• int a, b;
• double average;
• a = 2; b = 3;
• average = (a + b) / 2;
• What will go wrong here?
Type Casts
• Let’s compute the average of 2 numbers a and b:
• int a, b;
• double average;
• a = 2; b = 3;
• average = (a + b) / 2;
• What will go wrong here?
• If both operands of “/” are integers, the result will be
the integer part of the division. (Beware of the loss in
your computations!)
a is int; b is int; => a+b is int;
a+b is int; 2 is int; => (a+b) / 2 is integer division!
• Solution:
Type Casts
• Let’s compute the average of 2 numbers a and b:
• int a, b;
• double average;
• a = 2; b = 3;
• average = (a + b) / 2;
• What will go wrong here?
• If both operands of “/” are integers, the result will be
the integer part of the division. (Beware of the loss in
your computations!)
a is int; b is int; => a+b is int;
a+b is int; 2 is int; => (a+b) / 2 is integer division!
• Solution:
• You can explicitly “cast” one of the operands to double to avoid
integer division!
• Average = (double) (a + b) / 2;
Type Casts
• Placing the desired data type in parenthesis before an
expression is called explicit type cast. It changes the
data type from what it should be to what you want it to
be!
int a = (int) (2 * 3.5);
double avg = (double) (2 + 3) / 2;
• You can even cast a char to int or vice versa!
char c = ‘A’;
int val_c = (int) c;
printf(“%d”, val_c); //will print 65
printf(“%c”, (char) (val_c + 1)); //will print B
These are ASCII values for characters!
Type Casts
• Sometimes type casts happen implicitly! Without you writing a
type name in front of the expression!
double d = 3.5;
int i = d; /* d casts from double to int automatically */
• Avoid implicit type casts to add to your code readability!
Unary vs. Binary Operation
• Unary operations have the form:
operator operand
• E.g. “-3”, “+a”, or “–first_var”
• Unary negation and unary plus
• You will learn more unary operators later.
• Binary operations have the form:
operand1 operator operand2
• E.g. “3 + 5” or “var1 / var2”
Operator Precedence
• What do these expressions evaluate to:
#1: 3 + 2 * 2
#2: 3 + 2 * 2 * 3 / 2.0
#3: 3 + 2 * 2 / 3.0 + 2
#4: 3 + 2 * 2 / (3.0 + 2)
Operator Precedence
• What do these expressions evaluate to:
#1: 3 + 2 * 2 = 12
#2: 3 + 2 * 2 * 3 / 2.0 = 9.0
#3: 3 + 2 * 2 / 3.0 + 2 = 6.3333
#4: 3 + 2 * 2 / (3.0 + 2) = 3.8
• Operator precedence in C is very similar to that in
math.
First all unary operations are computed
Then all parenthesis
Then *, / and %
Finally binary + and binary -.
If there are multiple binary operators in the same level, it’s
computed from left to right.
If there are multiple unary operators in the same level, they
are computed from right to left!
Operator Precedence
First all unary operations are computed
Then all parenthesis
Then *, / and %
Finally binary + and binary -.
If there are multiple binary operators in the same level, it’s
computed from left to right.
If there are multiple unary operators in the same level, they
are computed from right to left!
• 2 + 10 / 5 * 2 + 4 / 2
2 + (10 / 5) * 2 + 4 / 2
• 2 + ((10 / 5) * 2) + 4 / 2
• 2 + ((10 / 5) * 2) + (4/2)
• (2 + ((10 / 5) * 2)) + (4/2)
• ((2 + ((10 / 5) * 2)) + (4/2))
Evaluation Tree (page 80 from the textbook)
How would you write these formulas in C:
•𝑎 + 𝑏
2
•𝑛 𝑛−1 𝑥2
2
•𝑛 𝑛−1
2𝑥2
How would you write these formulas in C:
•𝑎 + 𝑏
2
• (double)(a+ b) / 2
•𝑛 𝑛−1 𝑥2
2
• (double) n * (n - 1) * x * x / 2
•𝑛 𝑛−1
2(𝑥+1)𝑥2
• (double) n * (n - 1) / (2 * (x + 1) * x * x)
Formatting the Output
• By default C doesn’t print blank spaces before or after
your numerical output
• You can tell C the least number of positions you want
your number to take when printed on the screen.
Use %n.mf or %.mf placeholder (instead of %f) for double…
And %nd placeholder (instead of %d) for int values…
Where n is the field width (the total positions you want the
number to be printed on including integer part, decimal
point and fractional part)
And m is the number of places on the right of the decimal
point you want to print
If your number needs more space to be printed, your
request will be overwritten automatically!
Use ‘-’ before the n.m or n to make it right aligned!
Formatting the Output
• double a = 3.005
• printf(“%9.2f”, a) => □□□□□3.00
• printf(“%9.3f”, a) => □□□□3.005
• printf(“%9.4f”, a) => □□□3.0050
• printf(“%-9.2f”, a) => 3.00□□□□□
Progamming Errors
• Syntax Errors:
You haven’t followed the rules that C asks for in composing
the code. Can have multiple reasons, including:
- misspelling variable/function names
- forgetting to declare a variable/function before using it
- forgetting ; at the end of a command
- forgetting { or } (mismatched braces)
Your code won’t compile while there are syntax errors
Programming Errors
• Runtime errors:
These are errors that occur while running the program
(compilation has passed).
- Division by zero is a common one.
- Invalid pointer (later)
- Stack overflow (later)
Programming Errors
• Undetected Errors:
What is happening here:
• Printf(“enter year:\n”);
• Scanf(“%d”, &year);
• Printf(“Enter your initials:\n”);
• Scanf(“%c%c”, &finit, &linit);
• Printf(“initials: %c and %c”, finit, linit);
Programming Errors
• Undetected Errors:
What is happening here:
• Printf(“enter year:\n”);
• Scanf(“%d”, &year);
• Printf(“Enter your initials:\n”);
• Scanf(“%c%c”, &finit, &linit);
• Printf(“initials: %c and %c”, finit, linit);
• Scanning for int or real skips whitespace inputs.
Scanning for char does not skip anything.
• New line character that you entered after typing the
year, is read as the first initial character!
• Your program still runs but gives incorrect results!
• Undetected errors are hard to locate and you need to be
careful while writing the program to avoid them!
Programming Errors
• Logic Errors:
Mistakes in your algorithm if not detected early, can result
in a program that runs but does not give you the correct
results.
Hard to detect.
Examine your algorithm for all possible cases that you have
missed before implementing it!
Interactive Mode vs Batch Mode
• Interactive mode asks the user for input does
computation and returns the result or asks for more
data
• Batch mode gets the data from a file that user has
provided previously
• Use > to redirect printf statements to file
• Use < to redirect user input data from file to the
program
• Instead of printing prompt messages before scanf, in
the batch mode we printf the data that was read right
after its scanf.
Numerical Inaccuracies (optional)
• Cancellation Error: 1/3
• Representation Error: 10000.0 + 0.00000000001
• Overflow: 2bln + 2bln (as integer)
• Underflow: (0.000000000001)^2
References
• J.R. Hanly & E.B. Koffman, Problem Solving and Program
Design in C (8thed.), Pearson, 2016
• Andy O’Fallon’s lecture notes for CptS121
(http://eecs.wsu.edu/~aofallon/cpts121)