SlideShare a Scribd company logo
CS F111
Lab 4:
Input/Output
Arithmetic Expressions
2
Advanced Output Formatting
• A few of many other things you can do:
– Control number of decimals
• 3.1 vs 3.100000
– Exponential (scientific) or decimal notation
• 3.1 vs 3.1E0
– Control total width (including spaces)
• _______3.1 vs __3.1
3
Output Format Examples
• %10.2f _ _ _ _ 1 2 3 . 5 5 float
• %10.4f _ _ 1 2 3 . 5 5 0 0
• %.2f 1 2 3 . 5 5
• %10d _ _ _ _ _ _ _ 4 7 5 int
• %-10d 4 7 5 _ _ _ _ _ _ _
• %10c _ _ _ _ _ _ _ _ _ a char
4
Output Expressions
•Basic rule:
–% placeholders in the format must match variables
in the input list
– MUST! match on for-one in number, order, and
type.
int studentID ;
double grade ;
scanf (“%d %lf”, &studentID , &grade ) ;
5
Multiple Inputs
What happens if types don’t match?
printf -- garbled output
scanf -- unpredictable errors
and don’t forget the &
Exercise: print the values of a and b.
scanf(“%d %d”,a,b);
scanf(“ %d %d”,&a,&b);
scanf(“%d %d”,&a,&b);
scanf(“%d %d ”,&a,&b);
scanf(“%d %d ”,&a,&b);
scanf(“%d %d”,&a,&b,&c);
scanf(“%d %d”,&b);
scanf(“%d %d n”,&a,&b);
scanf(“hello %d %d”,&a,&b);
scanf(“%d%d”,&a,&b);
scanf(“%f %f”,&a,&b);
Exercise: to study formatted input
int a,b,d; char c;
scanf(“%2d %5d”,&a &b);
printf(“%d %dn”,a,b);
i/p 50 31426
o/p 50 31426
 i/p 31426 50
o/p 31 426
scanf(“%d ”,&d); /*What if there is this line: second input*/
scanf(“%d”,&c); /* c is char variable */
printf(“%dn”,c);
i/p 25
o/p 50
Exercise: to study formatted input
scanf(“%d %*d %d”,&a, &b);
printf(“%d %d”,a,b);
i/p 123 456 789
o/p 123 789
printf(“%11.4e”,-a); /* “%w.p e” what should
be the minimum difference
w-p ?
*/
9
• space (‘ ’), tab (‘t’), newline (‘n’) are
“whitespace”
• Whitespace is skipped by scanf for int (“%d”),
and double (“%lf”)
– This means the user can type spaces before
a number and they are ignored
• Not skipped for char input “%c”
– each character typed, including spaces, is
used
Whitespace
Reading single characters
• Another important pair of functions for keyboard
input/output is getchar/putchar
• getchar reads a single character
• putchar writes a single character
#include <ctype.h>
char c;
c = getchar(); /* blocks until data is entered
if more than one char is entered only
first is read */
putchar(c); /* prints value of c to screen */
11
• Arithmetic expressions
• Integer and floating-point (double)
types
• Unary and binary operators
• Precedence
• Associativity
• Conversions and casts
• Symbolic constants
We need precise rules that define exactly what an
expression means:
What is the value of 4 - 4 * 4 + 4?
Arithmetic on a computer may differ from everyday
arithmetic or math:
(1.0 / 9.0) * 9.0 could be 0.99999998213
2 / 3 is zero in C, not .667 (!)
Why Study Expressions?
double area, radius;
area = 3.14 * radius * radius;
assignment statement expression
Execution of an assignment statement:
Evaluate the expression on the right hand side
Store the value of the expression into the variable
named on the left hand side
Assignment Statement: Review
14
Expressions are things that have values
A variable by itself is an expression: radius
A constant by itself is an expression: 3.14
Often expressions are combinations of variables,
constants, and operators.
area = 3.14 * radius * radius;
Expressions
15
Expression Evaluation
Some terminology:
– Data or operand means the integer or
floating-point constants and/or variables in
the expression.
– Operators are things like addition,
multiplication, etc.
• The value of an expression will depend on the
data types and values and on the operators
used
– Additionally, the final result of an
assignment statement will depend on the
type of the assignment variable.
16
Arithmetic Types: Review
C provides two different kinds of numeric values
• Integers (0, 12, -17, 142)
Type int
Values are exact
Constants have no decimal point or exponent
• Floating-point numbers (3.14, -6.023e23)
Type float, double
Values are approximate (12-14 digits precision typical)
Constants must have decimal point and/or exponent
17
Operator Jargon
• Binary: operates on two operands
• 3.0 * b
• zebra + giraffe
• Unary: operates on one operand
• -23.4
• C operators are unary or binary
• Puzzle: what about expressions like a+b+c?
– Answer: this is two binary ops, in sequence
18
•Constants of type double:
–0.0, 3.14, -2.1, 5.0, 6.02e23, 1.0 3
–not 0 or 17
•Operators on doubles:
–unary: -
–binary: +, -, *, /
–Note: no exponentiation operator in C
Expressions with doubles
19
•Declarations
• double height, base, radius, x, c1, c2;
•Sample expressions (not statements):
• 0.5 * height * base
• ( 4.0 / 3.0 ) * 3.14 * radius * radius * radius
• - 3.0 + c1 * x - c2 * x * x
Example Expressions with doubles
20
•Constants of type int:
–0, 1, -17, 42
–not 0.0 or 1e3
•Operators on ints:
–unary: -
–binary: +, -, *, /, %
Expressions with ints
21
•Integer operators include integer division and
integer remainder:
• symbols / and %
•Caution: division looks like an old friend, but
there is a new wrinkle!
int Division and Remainder
2 rem 1
100 )299
200
99
2 rem 99
100 )299
200
99
22
/ is integer division: no remainder, no rounding
299 / 100
6 / 4
5 / 6
int Division and Remainder
% is mod or remainder:
299 % 100 99
6 % 4 2
5 % 6 5
2
1
0
23
•Given: total_minutes 359
•Find: hours 5
• minutes 59
•Solution in C:
Expressions with ints:
Time Example
hours = total_minutes / 60 ;
minutes = total_minutes % 60 ;
24
•int radius;
•double volume;
•double pi = 3.141596;
•volume = ( 4/3 ) * pi * radius *radius * radius;
A Cautionary Example
25
Sometimes only ints make sense
the 15th spreadsheet cell, not the 14.997th cell
Doubles may be inaccurate representing “ints”
In mathematics 3 • 15 • (1/3) = 15
But, 3.0 * 15.0 * (1.0 / 3.0) might be 14.9999997
Last, and least
operations with doubles is slower on some
computers
doubles often require more memory
Why Use ints? Why
Not doubles Always?
Resolving Complex Expressions
• C has precedence, associativity rules it uses to
determine the order operators are evaluated
• Precedence: some operators are executed
before others
• Associativity: when more than one operator in
an expression has the same precedence then
associativity rules are used to order
27
•Precedence determines the order of evaluation
of operators.
•Is a + b * a - b equal to ( a + b ) * ( a - b ) or
a + ( b * a ) - b ??
And does it matter?
•Try this:
• 4 + 3 * 2 - 1
•
Order of Evaluation
7
9
(4 + 3) * (2 - 1) =
4 + (3 * 2) - 1 =
28
Precedence rules:
–1. do ( )’s first, starting with innermost
–2. then do unary minus (negation): -
–3. then do “multiplicative” ops: *, /, %
–4. lastly do “additive” ops: binary +, -
Operator Precedence Rules
29
•Precedence doesn’t help if all the operators have
the same precedence
•Is a / b * c equal to
• a / ( b * c ) or ( a / b ) * c ??
•Associativity determines the order among
consecutive operators of equal precedence
•Does it matter? Try this: 15 / 4 * 2
Precedence Isn’t Enough
30
•Associativity determines the order among
consecutive operators of equal precedence
•Does it matter? Try this: 15 / 4 * 2
• (15 / 4) * 2 = 3 * 2 = 6
• 15 / (4 * 2) = 15 / 8 = 1
Associativity Matters
31
•Most C arithmetic operators are “left
associative”, within the same precedence
level
• a / b * c equals (a / b) * c
• a + b - c + d equals ( ( a + b ) - c ) + d
•C also has a few operators that are right
associative.
•HW- Which are they?
Associativity Rules
32
The Full Story...
• C has about 50 operators & 18 precedence
levels…
• A "Precedence Table" shows all the operators,
their precedence and associativity.
– Look in any C reference manual
• When in doubt: check the table
• When faced with an unknown operator: check
the table
Precedence Table
33
Highest on top
++ -- (Postfix)
++ -- (Prefix)
* / %
+ -
<< >>
< >
&
|
&&
||
34
•Mathematical formula:
________
- b +  b2 - 4 a c
----------------------
2 a
#include <math.h>
(- b + sqrt ( b * b - 4.0 * a * c) ) / ( 2.0 * a )
Compiling requires
gcc squareroot.c -lm
Precedence and
Associativity: Example
35
b * b - 4.0 * a * c
Depicting Expressions
-
67.05
-1.0 15.2
*
-4.0
*
-60.8
2.5 2.5
*
6.25
36
•What is 2 * 3.14 ?
•Compiler will implicitly (automatically) convert int to double
when they occur together:
•int + double double + double (likewise -, *, /)
•2*3 * 3.14 (2*3) * 3.14 6 * 3.14 6.0 * 3.14 18.84
•2/3 * 3.14 (2/3) * 3.14 0 * 3.14 0.0 * 3.14 0.0
• Strongly recommend you avoid mixed types:
e.g., use 2.0 / 3.0 * 3.14 instead.
Mixed Type Expressions
Promotion Hierarchy
short
int
long int
float
double
char
• Operands of the lower type
can be implicitly converted to
the higher type
• Occurs when an operator
expects the higher type
(adding together two floats
when one is an int)
38
•int total, count, value;
•double avg;
•total = 97 ; count = 10;
•avg = total / count ; /*avg is 9.0!*/
•value = total*2.2; /*bad news*/
Conversions in Assignments
implicit
conversion to int
– drops fraction
with no warning
implicit
conversion to
double
39
Use a cast to explicitly convert the result of an
expression to a different type
Format: (type) expression
Examples (double) myage
(int) (balance + deposit)
This does not change the rules for evaluating the
expression itself (types, etc.)
Good style, because it shows the reader that the
conversion was intentional, not an accident
Explicit Conversions: cast
40
•int total, count ;
•double avg;
•total = 97 ; count = 10 ;
•
• /* explicit conversion to double (right way)*/
•avg = (double) total / (double) count); /*avg is 9.7 */
•
Using Casts
/* explicit conversion to double (wrong way)*/
avg = (double) (total / count) ;
/*avg is 9.0*/
41
•Named constants:
•#define PI 3.14159265
•#define HEIGHT 50
•#define WIDTH 80
•#define AREA (HEIGHT * WIDTH)
–...
•circle_area = PI * radius * radius ;
•volume = length * AREA;
#define - Symbolic Constants
Note: = and ; are not used for #define
() can be used in #define
42
Centralize changes
No "magic numbers" (unexplained constants)
use good names instead
Avoid typing errors
Avoid accidental assignments to constants
double pi ; vs.
pi = 3.14 ; #define PI 3.14
... ...
pi = 17.2 ; PI = 17.2 ; syntax error
Why #define?
43
•Every variable, value, and expression in C has a type
•Types matter - they control how things behave (results of
expressions, etc.)
•Lots of cases where types have to match up
•Start now: be constantly aware of the type of everything in
your programs!
Types are Important
44
• Write in the clearest way possible to help the reader
• Keep it simple; break very complex expressions into
multiple assignment statements
• Use parentheses to indicate your desired precedence
for operators when it is not clear
• Use explicit casts to avoid (hidden) implicit
conversions in mixed mode expressions and
assignments
• Be aware of types
Advice on Writing Expressions
Home Work
45
•Meaning of
– Syntax
– Semantics of a programming language
•Find the Output:
– value=value++ + value++;
– value=++value + ++value;
– value=value++ + ++value;
Does Terminology Matter?
Lots of new terminology today!
"variable", "reserved word", "initialization",
"declaration", “statement”, "assignment", etc.,
etc.
You can write a complicated program without using
these words
But you can't talk about your programs without
them!
Learn the exact terminology as you go, and get in the
habit of using it.
C-46

More Related Content

PPTX
Ch8 Arrays
PPTX
Error correction-and-type-of-error-in-c
PPTX
Unit 2. Elements of C
PPT
Basic concept of c++
PPT
Basic of c &c++
PPT
6 operators-in-c
PDF
Introduction
Ch8 Arrays
Error correction-and-type-of-error-in-c
Unit 2. Elements of C
Basic concept of c++
Basic of c &c++
6 operators-in-c
Introduction

What's hot (17)

PDF
Flag Waiving
PPT
c-programming
PPT
Basics of c++
ODP
(2) cpp imperative programming
PDF
Introduction to Excel, basic financial functions
PPTX
Ch6 Loops
PDF
Format string
PPT
Cbasic
PPTX
C Programming Unit-3
PPSX
Getting started with c++.pptx
PPT
C language programming
PPTX
Introduction to C Programming - R.D.Sivakumar
PPTX
C Programming Introduction
PDF
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
DOCX
C Programming
PPTX
C language basics
PPTX
Variables, Data Types, Operator & Expression in c in detail
Flag Waiving
c-programming
Basics of c++
(2) cpp imperative programming
Introduction to Excel, basic financial functions
Ch6 Loops
Format string
Cbasic
C Programming Unit-3
Getting started with c++.pptx
C language programming
Introduction to C Programming - R.D.Sivakumar
C Programming Introduction
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
C Programming
C language basics
Variables, Data Types, Operator & Expression in c in detail
Ad

Similar to Lab 4 reading material formatted io and arithmetic expressions (20)

PDF
02 - Data Types and Expressions using C.pdf
PPT
Token and operators
PPT
PPTX
Cs1123 4 variables_constants
PDF
lec1).pdfbjkbvvttytxtyvkuvvtryccjbvuvibu
PPTX
Lecture 2 variables
PPTX
Class05bnsjsnsnsnjsjsjsjsjjsnsnsjjjzmsmsnnsnsnjjzns
PPT
operators and arithmatic expression in C Language
PPTX
Chapter 2: Elementary Programming
PDF
Module 2_PPT_P1 POP Notes module 2 fdfd.pdf
PDF
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
PDF
ICP - Lecture 5
PPTX
C programming(Part 1)
PPTX
C Language Part 1
PPTX
Operators in C Programming
PPT
lecture-ON-C.ppt BASIC WITH DEPTH CONTENT
PPT
lecture2.ppt...............................................
PPT
basic of C programming (token, keywords)lecture2.ppt
PPT
lecture2.ppt FOR C PROGRAMMING AND DATA S TRUCT
02 - Data Types and Expressions using C.pdf
Token and operators
Cs1123 4 variables_constants
lec1).pdfbjkbvvttytxtyvkuvvtryccjbvuvibu
Lecture 2 variables
Class05bnsjsnsnsnjsjsjsjsjjsnsnsjjjzmsmsnnsnsnjjzns
operators and arithmatic expression in C Language
Chapter 2: Elementary Programming
Module 2_PPT_P1 POP Notes module 2 fdfd.pdf
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
ICP - Lecture 5
C programming(Part 1)
C Language Part 1
Operators in C Programming
lecture-ON-C.ppt BASIC WITH DEPTH CONTENT
lecture2.ppt...............................................
basic of C programming (token, keywords)lecture2.ppt
lecture2.ppt FOR C PROGRAMMING AND DATA S TRUCT
Ad

Recently uploaded (20)

PPTX
ai tools demonstartion for schools and inter college
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PPTX
Reimagine Home Health with the Power of Agentic AI​
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
System and Network Administraation Chapter 3
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PPTX
history of c programming in notes for students .pptx
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
Nekopoi APK 2025 free lastest update
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Digital Strategies for Manufacturing Companies
ai tools demonstartion for schools and inter college
Softaken Excel to vCard Converter Software.pdf
Upgrade and Innovation Strategies for SAP ERP Customers
Navsoft: AI-Powered Business Solutions & Custom Software Development
PTS Company Brochure 2025 (1).pdf.......
wealthsignaloriginal-com-DS-text-... (1).pdf
Reimagine Home Health with the Power of Agentic AI​
How to Choose the Right IT Partner for Your Business in Malaysia
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Design an Analysis of Algorithms II-SECS-1021-03
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
2025 Textile ERP Trends: SAP, Odoo & Oracle
Internet Downloader Manager (IDM) Crack 6.42 Build 41
System and Network Administraation Chapter 3
Wondershare Filmora 15 Crack With Activation Key [2025
history of c programming in notes for students .pptx
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Nekopoi APK 2025 free lastest update
VVF-Customer-Presentation2025-Ver1.9.pptx
Digital Strategies for Manufacturing Companies

Lab 4 reading material formatted io and arithmetic expressions

  • 2. 2 Advanced Output Formatting • A few of many other things you can do: – Control number of decimals • 3.1 vs 3.100000 – Exponential (scientific) or decimal notation • 3.1 vs 3.1E0 – Control total width (including spaces) • _______3.1 vs __3.1
  • 3. 3 Output Format Examples • %10.2f _ _ _ _ 1 2 3 . 5 5 float • %10.4f _ _ 1 2 3 . 5 5 0 0 • %.2f 1 2 3 . 5 5 • %10d _ _ _ _ _ _ _ 4 7 5 int • %-10d 4 7 5 _ _ _ _ _ _ _ • %10c _ _ _ _ _ _ _ _ _ a char
  • 4. 4 Output Expressions •Basic rule: –% placeholders in the format must match variables in the input list – MUST! match on for-one in number, order, and type. int studentID ; double grade ; scanf (“%d %lf”, &studentID , &grade ) ;
  • 5. 5 Multiple Inputs What happens if types don’t match? printf -- garbled output scanf -- unpredictable errors and don’t forget the &
  • 6. Exercise: print the values of a and b. scanf(“%d %d”,a,b); scanf(“ %d %d”,&a,&b); scanf(“%d %d”,&a,&b); scanf(“%d %d ”,&a,&b); scanf(“%d %d ”,&a,&b); scanf(“%d %d”,&a,&b,&c); scanf(“%d %d”,&b); scanf(“%d %d n”,&a,&b); scanf(“hello %d %d”,&a,&b); scanf(“%d%d”,&a,&b); scanf(“%f %f”,&a,&b);
  • 7. Exercise: to study formatted input int a,b,d; char c; scanf(“%2d %5d”,&a &b); printf(“%d %dn”,a,b); i/p 50 31426 o/p 50 31426  i/p 31426 50 o/p 31 426 scanf(“%d ”,&d); /*What if there is this line: second input*/ scanf(“%d”,&c); /* c is char variable */ printf(“%dn”,c); i/p 25 o/p 50
  • 8. Exercise: to study formatted input scanf(“%d %*d %d”,&a, &b); printf(“%d %d”,a,b); i/p 123 456 789 o/p 123 789 printf(“%11.4e”,-a); /* “%w.p e” what should be the minimum difference w-p ? */
  • 9. 9 • space (‘ ’), tab (‘t’), newline (‘n’) are “whitespace” • Whitespace is skipped by scanf for int (“%d”), and double (“%lf”) – This means the user can type spaces before a number and they are ignored • Not skipped for char input “%c” – each character typed, including spaces, is used Whitespace
  • 10. Reading single characters • Another important pair of functions for keyboard input/output is getchar/putchar • getchar reads a single character • putchar writes a single character #include <ctype.h> char c; c = getchar(); /* blocks until data is entered if more than one char is entered only first is read */ putchar(c); /* prints value of c to screen */
  • 11. 11 • Arithmetic expressions • Integer and floating-point (double) types • Unary and binary operators • Precedence • Associativity • Conversions and casts • Symbolic constants
  • 12. We need precise rules that define exactly what an expression means: What is the value of 4 - 4 * 4 + 4? Arithmetic on a computer may differ from everyday arithmetic or math: (1.0 / 9.0) * 9.0 could be 0.99999998213 2 / 3 is zero in C, not .667 (!) Why Study Expressions?
  • 13. double area, radius; area = 3.14 * radius * radius; assignment statement expression Execution of an assignment statement: Evaluate the expression on the right hand side Store the value of the expression into the variable named on the left hand side Assignment Statement: Review
  • 14. 14 Expressions are things that have values A variable by itself is an expression: radius A constant by itself is an expression: 3.14 Often expressions are combinations of variables, constants, and operators. area = 3.14 * radius * radius; Expressions
  • 15. 15 Expression Evaluation Some terminology: – Data or operand means the integer or floating-point constants and/or variables in the expression. – Operators are things like addition, multiplication, etc. • The value of an expression will depend on the data types and values and on the operators used – Additionally, the final result of an assignment statement will depend on the type of the assignment variable.
  • 16. 16 Arithmetic Types: Review C provides two different kinds of numeric values • Integers (0, 12, -17, 142) Type int Values are exact Constants have no decimal point or exponent • Floating-point numbers (3.14, -6.023e23) Type float, double Values are approximate (12-14 digits precision typical) Constants must have decimal point and/or exponent
  • 17. 17 Operator Jargon • Binary: operates on two operands • 3.0 * b • zebra + giraffe • Unary: operates on one operand • -23.4 • C operators are unary or binary • Puzzle: what about expressions like a+b+c? – Answer: this is two binary ops, in sequence
  • 18. 18 •Constants of type double: –0.0, 3.14, -2.1, 5.0, 6.02e23, 1.0 3 –not 0 or 17 •Operators on doubles: –unary: - –binary: +, -, *, / –Note: no exponentiation operator in C Expressions with doubles
  • 19. 19 •Declarations • double height, base, radius, x, c1, c2; •Sample expressions (not statements): • 0.5 * height * base • ( 4.0 / 3.0 ) * 3.14 * radius * radius * radius • - 3.0 + c1 * x - c2 * x * x Example Expressions with doubles
  • 20. 20 •Constants of type int: –0, 1, -17, 42 –not 0.0 or 1e3 •Operators on ints: –unary: - –binary: +, -, *, /, % Expressions with ints
  • 21. 21 •Integer operators include integer division and integer remainder: • symbols / and % •Caution: division looks like an old friend, but there is a new wrinkle! int Division and Remainder 2 rem 1 100 )299 200 99 2 rem 99 100 )299 200 99
  • 22. 22 / is integer division: no remainder, no rounding 299 / 100 6 / 4 5 / 6 int Division and Remainder % is mod or remainder: 299 % 100 99 6 % 4 2 5 % 6 5 2 1 0
  • 23. 23 •Given: total_minutes 359 •Find: hours 5 • minutes 59 •Solution in C: Expressions with ints: Time Example hours = total_minutes / 60 ; minutes = total_minutes % 60 ;
  • 24. 24 •int radius; •double volume; •double pi = 3.141596; •volume = ( 4/3 ) * pi * radius *radius * radius; A Cautionary Example
  • 25. 25 Sometimes only ints make sense the 15th spreadsheet cell, not the 14.997th cell Doubles may be inaccurate representing “ints” In mathematics 3 • 15 • (1/3) = 15 But, 3.0 * 15.0 * (1.0 / 3.0) might be 14.9999997 Last, and least operations with doubles is slower on some computers doubles often require more memory Why Use ints? Why Not doubles Always?
  • 26. Resolving Complex Expressions • C has precedence, associativity rules it uses to determine the order operators are evaluated • Precedence: some operators are executed before others • Associativity: when more than one operator in an expression has the same precedence then associativity rules are used to order
  • 27. 27 •Precedence determines the order of evaluation of operators. •Is a + b * a - b equal to ( a + b ) * ( a - b ) or a + ( b * a ) - b ?? And does it matter? •Try this: • 4 + 3 * 2 - 1 • Order of Evaluation 7 9 (4 + 3) * (2 - 1) = 4 + (3 * 2) - 1 =
  • 28. 28 Precedence rules: –1. do ( )’s first, starting with innermost –2. then do unary minus (negation): - –3. then do “multiplicative” ops: *, /, % –4. lastly do “additive” ops: binary +, - Operator Precedence Rules
  • 29. 29 •Precedence doesn’t help if all the operators have the same precedence •Is a / b * c equal to • a / ( b * c ) or ( a / b ) * c ?? •Associativity determines the order among consecutive operators of equal precedence •Does it matter? Try this: 15 / 4 * 2 Precedence Isn’t Enough
  • 30. 30 •Associativity determines the order among consecutive operators of equal precedence •Does it matter? Try this: 15 / 4 * 2 • (15 / 4) * 2 = 3 * 2 = 6 • 15 / (4 * 2) = 15 / 8 = 1 Associativity Matters
  • 31. 31 •Most C arithmetic operators are “left associative”, within the same precedence level • a / b * c equals (a / b) * c • a + b - c + d equals ( ( a + b ) - c ) + d •C also has a few operators that are right associative. •HW- Which are they? Associativity Rules
  • 32. 32 The Full Story... • C has about 50 operators & 18 precedence levels… • A "Precedence Table" shows all the operators, their precedence and associativity. – Look in any C reference manual • When in doubt: check the table • When faced with an unknown operator: check the table
  • 33. Precedence Table 33 Highest on top ++ -- (Postfix) ++ -- (Prefix) * / % + - << >> < > & | && ||
  • 34. 34 •Mathematical formula: ________ - b +  b2 - 4 a c ---------------------- 2 a #include <math.h> (- b + sqrt ( b * b - 4.0 * a * c) ) / ( 2.0 * a ) Compiling requires gcc squareroot.c -lm Precedence and Associativity: Example
  • 35. 35 b * b - 4.0 * a * c Depicting Expressions - 67.05 -1.0 15.2 * -4.0 * -60.8 2.5 2.5 * 6.25
  • 36. 36 •What is 2 * 3.14 ? •Compiler will implicitly (automatically) convert int to double when they occur together: •int + double double + double (likewise -, *, /) •2*3 * 3.14 (2*3) * 3.14 6 * 3.14 6.0 * 3.14 18.84 •2/3 * 3.14 (2/3) * 3.14 0 * 3.14 0.0 * 3.14 0.0 • Strongly recommend you avoid mixed types: e.g., use 2.0 / 3.0 * 3.14 instead. Mixed Type Expressions
  • 37. Promotion Hierarchy short int long int float double char • Operands of the lower type can be implicitly converted to the higher type • Occurs when an operator expects the higher type (adding together two floats when one is an int)
  • 38. 38 •int total, count, value; •double avg; •total = 97 ; count = 10; •avg = total / count ; /*avg is 9.0!*/ •value = total*2.2; /*bad news*/ Conversions in Assignments implicit conversion to int – drops fraction with no warning implicit conversion to double
  • 39. 39 Use a cast to explicitly convert the result of an expression to a different type Format: (type) expression Examples (double) myage (int) (balance + deposit) This does not change the rules for evaluating the expression itself (types, etc.) Good style, because it shows the reader that the conversion was intentional, not an accident Explicit Conversions: cast
  • 40. 40 •int total, count ; •double avg; •total = 97 ; count = 10 ; • • /* explicit conversion to double (right way)*/ •avg = (double) total / (double) count); /*avg is 9.7 */ • Using Casts /* explicit conversion to double (wrong way)*/ avg = (double) (total / count) ; /*avg is 9.0*/
  • 41. 41 •Named constants: •#define PI 3.14159265 •#define HEIGHT 50 •#define WIDTH 80 •#define AREA (HEIGHT * WIDTH) –... •circle_area = PI * radius * radius ; •volume = length * AREA; #define - Symbolic Constants Note: = and ; are not used for #define () can be used in #define
  • 42. 42 Centralize changes No "magic numbers" (unexplained constants) use good names instead Avoid typing errors Avoid accidental assignments to constants double pi ; vs. pi = 3.14 ; #define PI 3.14 ... ... pi = 17.2 ; PI = 17.2 ; syntax error Why #define?
  • 43. 43 •Every variable, value, and expression in C has a type •Types matter - they control how things behave (results of expressions, etc.) •Lots of cases where types have to match up •Start now: be constantly aware of the type of everything in your programs! Types are Important
  • 44. 44 • Write in the clearest way possible to help the reader • Keep it simple; break very complex expressions into multiple assignment statements • Use parentheses to indicate your desired precedence for operators when it is not clear • Use explicit casts to avoid (hidden) implicit conversions in mixed mode expressions and assignments • Be aware of types Advice on Writing Expressions
  • 45. Home Work 45 •Meaning of – Syntax – Semantics of a programming language •Find the Output: – value=value++ + value++; – value=++value + ++value; – value=value++ + ++value;
  • 46. Does Terminology Matter? Lots of new terminology today! "variable", "reserved word", "initialization", "declaration", “statement”, "assignment", etc., etc. You can write a complicated program without using these words But you can't talk about your programs without them! Learn the exact terminology as you go, and get in the habit of using it. C-46