SlideShare a Scribd company logo
Chapter 2
Variables, Arithmetic Expressions and
Input/Output
C Programming
a Q & A Approach
by H.H. Tan, T.B. D’Orazio, S.H. Or & Marian M.Y. Choy
2
2.1 Variables: Naming, Declaring,
Assigning and Printing Values
Question:
Calculate the area of 10,000 triangles, all of different
sizes. Suppose you have the following information:
1. the length of each of the three sides
2. the size of each three angles
Solutions:
1. representing the information with variables
2. write down the correct formula to calculate the result



1
l
2
l
3
l
1 2
* *sin( ) / 2.0
S l l 

In Algebraic
3
2.1 Variables: Naming, Declaring,
Assigning and Printing Values
 For programming in C
 choose the variable names,
 consist of entire words rather than single
characters
 easier to understand your programs if given
very descriptive names to each variable
4
2.1 Variables: Naming, Declaring,
Assigning and Printing Values
 We may use variable names
 Lengths: length1, length2, length3
 Angles: angle1, angle2, angle3
 Much less ambiguous than their algebraic
counterparts
 Expressions look more cumbersome
 length of expression may span over 1 line
 Disadvantage which we simply must live with
 Try your best to make the name descriptive – or
make sense
5
2.1 Variables: Naming, Declaring,
Assigning and Printing Values
 What can be chosen for variable names in C?
first character must be non-digit characters a–z,
A–Z, or _
other characters must be non-digit characters
a–z, A–Z, _, or digit 0–9
 Valid examples
 apple1 interest_rate xfloat Income one_two
 Invalid
 1apple interest_rate% float In come one.two
6
2.1 Variables: Naming, Declaring,
Assigning and Printing Values
 Can we use void, int, printf as a variable names?
 List of key words in C
 auto break case char const continue default
 do double else enum extern float for
 goto if int long register return short
 signed sizeof static struct switch typedef union
 unsigned void volatile while
 You could choose key words as variable names, but are strongly
suggested not to do it.
NO
7
Table 2.1
Some Constraints on Identifiers
Topic
Use of standard identifiers such
as printf
Use of uppercase or mixed-case
Comment
Standard identifiers, such as
the function name printf, can
be used as variable names.
However, their use is not
recommended because it
leads to confusion.
Allowed; however, many
programmers use lowercase
characters for variable names
and uppercase for constant
names. Differentiate your
identifiers by using different
characters rather than
different cases
8
2.1 Variables: Naming, Declaring,
Assigning and Printing Values
 In C statement, we might have
 length1 = 3.0;
 length2 = 8.0;
 angle1 = 30.0;
 length1 = 30.0;
 length2 = 80.0;
 angle1 = 60.0;
1* 2*sin( 1)/2.0;
Area length length angle

length1 length2 angle1 Area
9
2.1 Variables: Naming, Declaring,
Assigning and Printing Values
 But,
 Variable names must be declared before
 To define a variable, the syntaxes are:
data_type variable_name;
data_type variable_name1, variable_name2, … ;
 e.g:
int iex;
float length;
float angle1, angle2;
double length1, length2;
In C, data type categorized as:
1. Primitive Types in ANSI C (C89)/ISO C (C90) -
char, short, int, float and double.
2. Primitive Types added to ISO C (C99) - long
long
3. User Defined Types – struct, union, enum
and typedef (will be discussed in separate session).
4. Derived Types – pointer, array (will be discussed in
separate session).
C BASIC DATA TYPES
2/31
DATA TYPES
11
Later
DATA TYPES
12
DATA TYPES
13
14
2.1 Variables: Naming, Declaring,
Assigning and Printing Values
 Assignment operator =
 the syntax is:
variabel_name1 = value;
variable_name2 = expression;
or
variable_name1 = value, variable_name2 = value2;
 e.g:
int iex;
float length;
float angle1, angle2;
iex= 12;
angle1 = 30.0;
angle2 = angle1+30.0;
2.1 Variables: Naming, Declaring,
Assigning and Printing Values
15
16
2.1 Variables: Naming, Declaring,
Assigning and Printing Values
 Notes on Assignment operator =
 put the value on the right hand size of
assignment operator to the variable name on
the left;
 the precedence of operation order is from right
to left;
 the left side of “=“ must be a variable
 expressions on the right hand has to be
evaluated before assignment
 Assignment can be done with declaration
 float income=20.5, expense=8.5;
 float saving= income - expense;
17
2.1 Variables: Naming, Declaring,
Assigning and Printing Values
How to print out variable area during execution?
18
2.1 Variables: Naming, Declaring,
Assigning and Printing Values
How to print out variable value during execution?
printf (format_string, argument_list)
format_string:
plane_character , conversion_specification
print out directly how to display
To display integer: %[field width]d e.g. %5d
To display float: %[field width][.precision]f e.g %9.2f
argument_list:
variables/constant to be fed
19
int month;
float expense, income;
month = 12;
expense = 111.1;
income = 100.;
printf ("Month=%2d, Expense=$%9.2fn",
month, expense);
Result
2.1 Variables: Naming, Declaring,
Assigning and Printing Values
2.1 Variables: Naming, Declaring,
Assigning and Printing Values
20
21
int month;
float expense, income;
month = 11;
expense = 82.1;
income = 100.;
printf ("For the %2dth month of the yearn"
"the expenses were $%5.2f n"
"and the income was $%6.2fnn",
month, expense, income);
Result?
2.1 Variables: Naming, Declaring,
Assigning and Printing Values
22
printf
 To display the value of a variable or constant on the screen
printf(format_string,argument_list);
 format_string
 plain characters – displayed directly unchanged on the screen, e.g. “This is C”
 conversion specification(s) – used to convert, format and display argument(s)
from the argument_list
 escape sequences – control the cursor, for example, the newline ‘n’
 Each argument must have a format specification. For example,
printf("month=%5d ",month);
23
printf
 Each argument must have a format specification. For example,
printf("month=%5d n",month);
 What will you get when:
int people = 456356;
printf(“people =%5dn",people);
printf(“people =%9dn”,people);
Question:
How is the case when we deal float numbers?
24
printf
Problem in Engineering:
float people= 0.000001;
 What will you get when:
printf(“people =%fn",people);
 Using scientific notation
printf(“people =%en", people);
printf
25
26
printf
Exercise
27
28
 We can instruct the computer to retrieve
data from various input devices
 the keyboard
 a mouse
 the hard disk drive
 Programs that have input from the keyboard
usually create a dialogue between the
program and the user during execution
2.2 Reading Data from The Keyboard
29
 This is done by printing out an hint
message,e.g.,
printf(“please input the current month (int): ”)
scanf(“%d”,&month);
2.2 Reading Data from The Keyboard
30
 Input data from keyboard can be done using scanf() function
 scanf(format_string, argument_list)
format_string : converts input characters into a specified type
argument_list: addresses of variables in which the input data are
stored;
 Example
float income;
double expense;
scanf(“%f %lf”,&income, &expense);
 & is required to get the address of variable
2.2 Reading Data from The Keyboard
31
 scanf() function
scanf("%f%lf", &income, &expense);
 &income stands for the address of the memory cell for income
 & : “address of” operator
 &income - pass the address of variable income to function scanf
 By giving scanf the address, the program knows where in memory to put
the value typed
2.2 Reading Data from The Keyboard
32
printf("what was your month salary in 2015?n");
scanf("%f", &salary);
printf("How many months have you worked?n");
scanf("%d",&work_month);
printf("what did you earn on vocation month?n");
scanf(" %f",&vocation_salary);
printf("what was month expense in 2015?n");
scanf("%f",&expense);
2.2Reading Data from The Keyboard
keyboard input
keyboard input
keyboard input
keyboard input
dialogue
33
2.2 Reading Data from The Keyboard
float income;
double expense;
int month, hour, minute;
printf ("What month is it?n");
scanf ("%d", &month);
printf ("You have entered month=%5dn",month);
34
 scanf() function
scanf (format_string, argument_list);
 format_string converts characters in the input into
values of a specific type
2.2 Reading Data from The Keyboard
2.2 Reading Data from The
Keyboard
 argument_list contains the address of the variable(s)
into which the input data are stored. e.g.
scanf("%f%lf",&income,&expense);
 1st
keyboard input data converted to float (%f) =>
income
 2nd
keyboard input converted to double (%lf) =>
expense
35
printf ("Please enter your income and expensesn");
scanf ("%f%lf", &income,&expense);
printf ("Please enter the time, e.g., ");
scanf ("%d : %d", &hour,&minute);
printf ("Entered Time=%d:%dn",hour,minute);
36
37
38
39
Input data for q2 in
homework3
40
41
2.3 Arithmetic Operators
and Expressions
 Consists of a sequence of operand(s) and
operator(s) that specify the computation of a
value
 Look much like algebraic expressions that you
write
d = x/y; // x divided by y
 Assigns the value of the arithmetic
expression(division) on the right to the variable
on the left
 Is correct to write
x/y =d ; ?
Wrong
42
2.3 Arithmetic Operators
and Expressions
 Calculate the time needed for a car to drive
from A to B with constant speed v
 Calculate the how many groups we have in
the class if each group has 4 students?
43
Output
44
Example 1
int i,j,k,p,m,n;
float a,b,c,d,e,f,g,h,x,y;
i=5; j=5;
k=11; p=3;
x=3.0; y=4.0;
printf("...... Initial values ......n");
printf("i=%4d, j=%4dnk=%4d, p=%4dnx=%4.2f, y=
%4.2fnn", i,j,k,p,x,y);
45
Example 1
a=x+y;
b=x-y;
c=x*y;
d=x/y;
e=d+3.0;
f=d+3;
i=i+1;
j=j+1;
printf("...... Section 1 output ......n");
printf("a=%5.2f, b=%5.2fnc=%5.2f, d=%5.2fn"
"e=%5.2f, f=%5.2fni=%5d, j=%5d nn",
a,b, c,d, e,f, i,j);
46
Example 1
m=k%p;
n=p%k;
i++;
++j;
e--;
--f;
printf("...... Section 2 output ......n");
printf("m=%4d, n=%4dni=%4d, j=%4dn"
"e=%4.2f, f=%4.2fn",m,n, i,j, e,f);
47
2.3 Arithmetic Operators and
Expressions
Operators ++, --, and %
 ++ increment operator, can be placed before or after a
variable
 increase the value of the variable by 1
 i++; or ++i;
equivalent to i=i+1;
 i--; or --i;
same as i=i-1;
 Only difference between i++ and ++i is in order of increment
(addressed later)
 % is a remainder operator
 must be placed between two integer variables or constants
 e.g. 11%3 return 2
48
2.3 Arithmetic Operators
and Expressions
 Depending on data types, division get can you
different answers
int i=3, j = 5, k;
float x = 3.0, y=5.0,z;
k = i/j;
z = x/y;
 remainder operator only accept integer
operands
k = i%j; right
z = x%y; wrong
49
2.3 Arithmetic Operators
and Expressions
 Cannot write
x/y = d;
i + 1 = i;
 Left side of assignment statement can have
only single variable
 Single variables are allowed to be lvalues
(allowed to be on the left side of assignment
)
 Expressions are rvalues (allowed on the
right side of assignment )
50
Conversion Specification
 If the precision specified for a real is
 less than actual, displays only the number of
digits in the specified precision (trailing digits are
not lost from memory, they simply are not
displayed)
 greater than actual, adds trailing zeros to make
the displayed precision equal to the precision
specified
 not specified, makes the precision equal to six
51
int DAYS_IN_YEAR = 365;
//One int value displayed in different field width
printf ("CONVERSION SPECIFICATIONS FOR INTEGERS n
n");
printf ("Days in year = n"
"[[%1d]] t(field width less than actual)n"
"[[%9d]] t(field width greater than actual)
n"
"[[%d]] t(no field width specified) nnn",
DAYS_IN_YEAR, DAYS_IN_YEAR, DAYS_IN_YEAR);
52
float PI=3.14159;
//One float value displayed in different field width
printf ("CONVERSION SPECIFICATIONS FOR REAL NUMBERSnn");
printf ("Cases for precision being specified correctly 
n");
printf ("PI = n"
"[[%1.5f]] tt(field width less than actual) n"
"[[%15.5f]] t(field width greater than actual)n"
"[[%.5f]] tt(no field width specified) nn",
PI,PI,PI);
53
float PI=3.14159;
//One float value displayed in different precision
printf ("Cases for field width being specified
correctly n");
printf ("PI = n"
"[[%7.2f]] tt(precision less than actual) n"
"[[%7.8f]] tt(precision greater than actual)n"
"[[%7.f]] tt(no precision specified) nn",
PI,PI,PI);
54
Conversion Specification
 Display int with %f or float with %d?
likely get nonsensical values or zeros
displayed
common error beginners make
 Why was so much attention given to the
printf statement?
will write printf statements very frequently
can substantially reduce your programming
errors
55
Constant
 constant can be done using constant macro
# define PI 3.1415926
 it is a preprocessing directive, it replace the occurrence of macro name (PI) by its value (3.1415926)
 it is not a C statement, no “;” at the end
 it is usually appear after preprocessing directives
E.g.:
# include <stdio.h>
# define DAY_OF_WEEK 7
void main(void)
{
printf(“total =%dn”,DAY_OF_WEEK);
}
56
Preprocessor
 To create a constant macro
 use a preprocessor directive
 begin with the symbol # (which must begin the line)
 semicolon must not be used at the end
 General form
#define symbolic_name replacement
 #define DAYS_IN_YEAR 365
 Draw equivalent of DAYS_IN_YEAR to 365
 Prior to translation into machine code, the preprocessor
replaces every symbolic_name in the program with the
given replacement
 printf("Days in year=%5d
n",DAYS_IN_YEAR);
after preprocessing becomes
printf("Days in year=%5dn",365);
57
2.4 Mixed Type Arithmetic,
 Giving variables their first numerical values is called
initializing them, e.g.
x = 5;
 Usually complicated expression is placed
 Order of performance of numerical operations can be
controlled
 Rules about the order of operation of +, -, *, / are
established by setting the precedence of the
operators
 Operators of higher precedence are executed first
while those of lower precedence are executed later
58
Operator Name No of operands Position Associativity Precedence
( parentheses unary prefix L to R 1
) parentheses unary postfix L to R 1
+ positive sign unary prefix R to L 2
- negative sign unary prefix R to L 2
++ post-increment unary postfix L to R 2
-- post-decrement unary postfix L to R 2
++ pre-increment unary prefix R to L 2
-- pre-decrement unary prefix R to L 2
+= addition and assignment binary infix R to L 2
-= subtraction and
assignment
binary infix R to L 2
*= multiplication and
assignment
binary infix R to L 2
/= division and assignment binary infix R to L 2
%= remainder and assignment binary infix R to L 2
% remainder binary infix L to R 3
* multiplication binary infix L to R 3
/ division binary infix L to R 3
+ addition binary infix L to R 4
- subtraction binary infix L to R 4
= assignment binary infix R to L 5
*=
Multiply the value of the first operand by the value of the second
operand; store the result in the object specified by the first operand.
A*=B; // A=A*B;
/=
Divide the value of the first operand by the value of the second
operand; store the result in the object specified by the first operand.
A/=B; // A=A/B;
%=
Take modulus of the first operand specified by the value of the
second operand; store the result in the object specified by the first
operand.
A%=B; // A=A%B;
+=
Add the value of the second operand to the value of the first
operand; store the result in the object specified by the first operand.
A+=B; // A=A+B;
–=
Subtract the value of the second operand from the value of the first
operand; store the result in the object specified by the first operand.
A-=B; // A=A-B;
59
Compound Assignment
60
Variable Initialization/Increment
Operator
 How do we initialize variables?
1. Uses an assignment statement, e.g.
int e ; e=3;
2. Initializes in a declaration statement, e.g.
float a=7, b=6;
– int i = 1, j =1;
int k = i++;
– int h = ++j ;
– For 1st
expression,
1. value of i is first assigned to k
2. i is then incremented (post-increment ++) from 1 to 2
– For 2nd
one,
1. value of j is first incremented (pre-increment operator ++) from
1 to 2.
2. Then the new j value, now equal to 2, is assigned to h
?i,j,k,h
61
Mixed Data Type
Calculation
 6.0/4.0 = 1.5
 6/4 = 1
 6/4.0 = 1.5
C converts integer to
real temporarily and
perform the operation
62
cast Operators
 Change the type of an expression
temporarily
 General form
(type) expression
 int aa=5, bb=2;
float xx;
xx = (float) aa / bb;
 xx = 2.5, otherwise xx = 2.0
Force a floating
Point division
63
Controlling Precedence
 Arithmetic operators located within the
parentheses() always have highest
precedence
 Example
z = ((a+b)*c/d);
 a+b evaluated first
64
Associativity
 Specifies the direction of evaluation of
the operators with the same
precedence
1+2 -3
First evaluated
Next evaluated
Direction of evaluation
65
Further Exploration
 Assign an integer value to a float variable
 convert the result to float and store to variable
 e.g.,
float p = 6 / 4;
 floating variable p will store 1.0
66
Summary
 #define symbolic_name replacement
 where symbolic_name occurred throughout the rest of
program will be replaced by replacement during compilation
by preprocessor
 Format specifications
 %[flag][field width][.precision]type
 where format string components enclosed by [ ] are optional
 Output of a float number to scientific notation is
 [sign]d.ddd e[sign]ddd
 where d represents a digit
67
Summary
 During mixed mode (different data types) arithmetic, C
will automatically convert one of the operands to facilitate
calculations
 Sometimes type casting can be used to explicitly change
data type during calculation
 (type) operand
 where type is the target type being converted into
operand is the data to be casted
68
Summary
 Basic structure of a program
# include<stdio.h>
void main()
{
statements;
}
 Constant with preprocessing
 using #define CONT_NAME value
 # define DAY_OF_YEAR 365
 Define variables
 data_type variable_name ;
 int number; float salary; double rate;
Indentation
69
Summary
 Output data on to screen
 printf(format_string, argument_lists)
 printf("You input %dn", month);
 Get data from keyboard
 scanf(format_string, address_variables)
 scanf("%d, %f", &month, &salary);
 Mathematical Operators
 +, -, *, /, %, ++, --, +=,-=, *=, …
 binary operators require its operands of same type
 % works on integers
 / depends on operands
70
Home work 4
 Calculate the average score of a students within
one semester. Suppose there are 3 courses in
total.
 Procedures
• Question description(not code in program):
• average_score = (score1+score2+score3)/3
• Steps of programming:
• define variables with right data type
• ask user to input 3 scores from keyboard
• convert the math expression into C code
• Output the results (keep 2 decimal places)

More Related Content

Similar to Variable< Arithmetic Expressions and Input (20)

Ch2 introduction to c
Ch2 introduction to cCh2 introduction to c
Ch2 introduction to c
Hattori Sidek
 
Chapter2
Chapter2Chapter2
Chapter2
Anees999
 
C++
C++C++
C++
Prakash Sharma
 
java or oops class not in kerala polytechnic 4rth semester nots j
java or oops class not in kerala polytechnic  4rth semester nots jjava or oops class not in kerala polytechnic  4rth semester nots j
java or oops class not in kerala polytechnic 4rth semester nots j
ishorishore
 
C_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptxC_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptx
Likhil181
 
Chapter3
Chapter3Chapter3
Chapter3
Kamran
 
Principals of Programming in CModule -5.pdfModule-3.pdf
Principals of Programming in CModule -5.pdfModule-3.pdfPrincipals of Programming in CModule -5.pdfModule-3.pdf
Principals of Programming in CModule -5.pdfModule-3.pdf
anilcsbs
 
Unit 2- Module 2.pptx
Unit 2- Module 2.pptxUnit 2- Module 2.pptx
Unit 2- Module 2.pptx
simranjotsingh2908
 
dinoC_ppt.pptx
dinoC_ppt.pptxdinoC_ppt.pptx
dinoC_ppt.pptx
DinobandhuThokdarCST
 
C++ for beginners
C++ for beginnersC++ for beginners
C++ for beginners
Salahaddin University-Erbil
 
Introduction%20C.pptx
Introduction%20C.pptxIntroduction%20C.pptx
Introduction%20C.pptx
20EUEE018DEEPAKM
 
Problem Solving Techniques
Problem Solving TechniquesProblem Solving Techniques
Problem Solving Techniques
valarpink
 
Unit i intro-operators
Unit   i intro-operatorsUnit   i intro-operators
Unit i intro-operators
HINAPARVEENAlXC
 
Python
PythonPython
Python
Sangita Panchal
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01
Wingston
 
C++ lecture 01
C++   lecture 01C++   lecture 01
C++ lecture 01
HNDE Labuduwa Galle
 
presentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptxpresentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptx
KrishanPalSingh39
 
basic C PROGRAMMING for first years .pptx
basic C  PROGRAMMING for first years  .pptxbasic C  PROGRAMMING for first years  .pptx
basic C PROGRAMMING for first years .pptx
divyasindhu040
 
introduction to python programming course 2
introduction to python programming course 2introduction to python programming course 2
introduction to python programming course 2
FarhadMohammadRezaHa
 
The best every notes on c language is here check it out
The best every notes on c language is here check it outThe best every notes on c language is here check it out
The best every notes on c language is here check it out
rajatryadav22
 
Ch2 introduction to c
Ch2 introduction to cCh2 introduction to c
Ch2 introduction to c
Hattori Sidek
 
java or oops class not in kerala polytechnic 4rth semester nots j
java or oops class not in kerala polytechnic  4rth semester nots jjava or oops class not in kerala polytechnic  4rth semester nots j
java or oops class not in kerala polytechnic 4rth semester nots j
ishorishore
 
C_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptxC_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptx
Likhil181
 
Chapter3
Chapter3Chapter3
Chapter3
Kamran
 
Principals of Programming in CModule -5.pdfModule-3.pdf
Principals of Programming in CModule -5.pdfModule-3.pdfPrincipals of Programming in CModule -5.pdfModule-3.pdf
Principals of Programming in CModule -5.pdfModule-3.pdf
anilcsbs
 
Problem Solving Techniques
Problem Solving TechniquesProblem Solving Techniques
Problem Solving Techniques
valarpink
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01
Wingston
 
presentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptxpresentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptx
KrishanPalSingh39
 
basic C PROGRAMMING for first years .pptx
basic C  PROGRAMMING for first years  .pptxbasic C  PROGRAMMING for first years  .pptx
basic C PROGRAMMING for first years .pptx
divyasindhu040
 
introduction to python programming course 2
introduction to python programming course 2introduction to python programming course 2
introduction to python programming course 2
FarhadMohammadRezaHa
 
The best every notes on c language is here check it out
The best every notes on c language is here check it outThe best every notes on c language is here check it out
The best every notes on c language is here check it out
rajatryadav22
 

Recently uploaded (20)

Grannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI ExperiencesGrannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI Experiences
Lauren Parr
 
The case for on-premises AI
The case for on-premises AIThe case for on-premises AI
The case for on-premises AI
Principled Technologies
 
Fortinet Certified Associate in Cybersecurity
Fortinet Certified Associate in CybersecurityFortinet Certified Associate in Cybersecurity
Fortinet Certified Associate in Cybersecurity
VICTOR MAESTRE RAMIREZ
 
Securiport - A Border Security Company
Securiport  -  A Border Security CompanySecuriport  -  A Border Security Company
Securiport - A Border Security Company
Securiport
 
Contributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptxContributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptx
Patrick Lumumba
 
UiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPath Community Berlin: Studio Tips & Tricks and UiPath InsightsUiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPathCommunity
 
Jeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software DeveloperJeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software Developer
Jeremy Millul
 
Evaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical ContentEvaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical Content
Paul Groth
 
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyesEnd-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
ThousandEyes
 
European Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility TestingEuropean Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility Testing
Julia Undeutsch
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
James Anderson
 
Measuring Microsoft 365 Copilot and Gen AI Success
Measuring Microsoft 365 Copilot and Gen AI SuccessMeasuring Microsoft 365 Copilot and Gen AI Success
Measuring Microsoft 365 Copilot and Gen AI Success
Nikki Chapple
 
Co-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using ProvenanceCo-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using Provenance
Paul Groth
 
6th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 20256th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 2025
DanBrown980551
 
Improving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevExImproving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevEx
Justin Reock
 
Supercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMsSupercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMs
Francesco Corti
 
Let’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack CommunityLet’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack Community
SanjeetMishra29
 
New Ways to Reduce Database Costs with ScyllaDB
New Ways to Reduce Database Costs with ScyllaDBNew Ways to Reduce Database Costs with ScyllaDB
New Ways to Reduce Database Costs with ScyllaDB
ScyllaDB
 
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Lorenzo Miniero
 
Grannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI ExperiencesGrannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI Experiences
Lauren Parr
 
Fortinet Certified Associate in Cybersecurity
Fortinet Certified Associate in CybersecurityFortinet Certified Associate in Cybersecurity
Fortinet Certified Associate in Cybersecurity
VICTOR MAESTRE RAMIREZ
 
Securiport - A Border Security Company
Securiport  -  A Border Security CompanySecuriport  -  A Border Security Company
Securiport - A Border Security Company
Securiport
 
Contributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptxContributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptx
Patrick Lumumba
 
UiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPath Community Berlin: Studio Tips & Tricks and UiPath InsightsUiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPathCommunity
 
Jeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software DeveloperJeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software Developer
Jeremy Millul
 
Evaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical ContentEvaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical Content
Paul Groth
 
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyesEnd-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
ThousandEyes
 
European Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility TestingEuropean Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility Testing
Julia Undeutsch
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
James Anderson
 
Measuring Microsoft 365 Copilot and Gen AI Success
Measuring Microsoft 365 Copilot and Gen AI SuccessMeasuring Microsoft 365 Copilot and Gen AI Success
Measuring Microsoft 365 Copilot and Gen AI Success
Nikki Chapple
 
Co-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using ProvenanceCo-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using Provenance
Paul Groth
 
6th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 20256th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 2025
DanBrown980551
 
Improving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevExImproving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevEx
Justin Reock
 
Supercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMsSupercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMs
Francesco Corti
 
Let’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack CommunityLet’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack Community
SanjeetMishra29
 
New Ways to Reduce Database Costs with ScyllaDB
New Ways to Reduce Database Costs with ScyllaDBNew Ways to Reduce Database Costs with ScyllaDB
New Ways to Reduce Database Costs with ScyllaDB
ScyllaDB
 
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Lorenzo Miniero
 
Ad

Variable< Arithmetic Expressions and Input

  • 1. Chapter 2 Variables, Arithmetic Expressions and Input/Output C Programming a Q & A Approach by H.H. Tan, T.B. D’Orazio, S.H. Or & Marian M.Y. Choy
  • 2. 2 2.1 Variables: Naming, Declaring, Assigning and Printing Values Question: Calculate the area of 10,000 triangles, all of different sizes. Suppose you have the following information: 1. the length of each of the three sides 2. the size of each three angles Solutions: 1. representing the information with variables 2. write down the correct formula to calculate the result    1 l 2 l 3 l 1 2 * *sin( ) / 2.0 S l l   In Algebraic
  • 3. 3 2.1 Variables: Naming, Declaring, Assigning and Printing Values  For programming in C  choose the variable names,  consist of entire words rather than single characters  easier to understand your programs if given very descriptive names to each variable
  • 4. 4 2.1 Variables: Naming, Declaring, Assigning and Printing Values  We may use variable names  Lengths: length1, length2, length3  Angles: angle1, angle2, angle3  Much less ambiguous than their algebraic counterparts  Expressions look more cumbersome  length of expression may span over 1 line  Disadvantage which we simply must live with  Try your best to make the name descriptive – or make sense
  • 5. 5 2.1 Variables: Naming, Declaring, Assigning and Printing Values  What can be chosen for variable names in C? first character must be non-digit characters a–z, A–Z, or _ other characters must be non-digit characters a–z, A–Z, _, or digit 0–9  Valid examples  apple1 interest_rate xfloat Income one_two  Invalid  1apple interest_rate% float In come one.two
  • 6. 6 2.1 Variables: Naming, Declaring, Assigning and Printing Values  Can we use void, int, printf as a variable names?  List of key words in C  auto break case char const continue default  do double else enum extern float for  goto if int long register return short  signed sizeof static struct switch typedef union  unsigned void volatile while  You could choose key words as variable names, but are strongly suggested not to do it. NO
  • 7. 7 Table 2.1 Some Constraints on Identifiers Topic Use of standard identifiers such as printf Use of uppercase or mixed-case Comment Standard identifiers, such as the function name printf, can be used as variable names. However, their use is not recommended because it leads to confusion. Allowed; however, many programmers use lowercase characters for variable names and uppercase for constant names. Differentiate your identifiers by using different characters rather than different cases
  • 8. 8 2.1 Variables: Naming, Declaring, Assigning and Printing Values  In C statement, we might have  length1 = 3.0;  length2 = 8.0;  angle1 = 30.0;  length1 = 30.0;  length2 = 80.0;  angle1 = 60.0; 1* 2*sin( 1)/2.0; Area length length angle  length1 length2 angle1 Area
  • 9. 9 2.1 Variables: Naming, Declaring, Assigning and Printing Values  But,  Variable names must be declared before  To define a variable, the syntaxes are: data_type variable_name; data_type variable_name1, variable_name2, … ;  e.g: int iex; float length; float angle1, angle2; double length1, length2;
  • 10. In C, data type categorized as: 1. Primitive Types in ANSI C (C89)/ISO C (C90) - char, short, int, float and double. 2. Primitive Types added to ISO C (C99) - long long 3. User Defined Types – struct, union, enum and typedef (will be discussed in separate session). 4. Derived Types – pointer, array (will be discussed in separate session). C BASIC DATA TYPES 2/31
  • 14. 14 2.1 Variables: Naming, Declaring, Assigning and Printing Values  Assignment operator =  the syntax is: variabel_name1 = value; variable_name2 = expression; or variable_name1 = value, variable_name2 = value2;  e.g: int iex; float length; float angle1, angle2; iex= 12; angle1 = 30.0; angle2 = angle1+30.0;
  • 15. 2.1 Variables: Naming, Declaring, Assigning and Printing Values 15
  • 16. 16 2.1 Variables: Naming, Declaring, Assigning and Printing Values  Notes on Assignment operator =  put the value on the right hand size of assignment operator to the variable name on the left;  the precedence of operation order is from right to left;  the left side of “=“ must be a variable  expressions on the right hand has to be evaluated before assignment  Assignment can be done with declaration  float income=20.5, expense=8.5;  float saving= income - expense;
  • 17. 17 2.1 Variables: Naming, Declaring, Assigning and Printing Values How to print out variable area during execution?
  • 18. 18 2.1 Variables: Naming, Declaring, Assigning and Printing Values How to print out variable value during execution? printf (format_string, argument_list) format_string: plane_character , conversion_specification print out directly how to display To display integer: %[field width]d e.g. %5d To display float: %[field width][.precision]f e.g %9.2f argument_list: variables/constant to be fed
  • 19. 19 int month; float expense, income; month = 12; expense = 111.1; income = 100.; printf ("Month=%2d, Expense=$%9.2fn", month, expense); Result 2.1 Variables: Naming, Declaring, Assigning and Printing Values
  • 20. 2.1 Variables: Naming, Declaring, Assigning and Printing Values 20
  • 21. 21 int month; float expense, income; month = 11; expense = 82.1; income = 100.; printf ("For the %2dth month of the yearn" "the expenses were $%5.2f n" "and the income was $%6.2fnn", month, expense, income); Result? 2.1 Variables: Naming, Declaring, Assigning and Printing Values
  • 22. 22 printf  To display the value of a variable or constant on the screen printf(format_string,argument_list);  format_string  plain characters – displayed directly unchanged on the screen, e.g. “This is C”  conversion specification(s) – used to convert, format and display argument(s) from the argument_list  escape sequences – control the cursor, for example, the newline ‘n’  Each argument must have a format specification. For example, printf("month=%5d ",month);
  • 23. 23 printf  Each argument must have a format specification. For example, printf("month=%5d n",month);  What will you get when: int people = 456356; printf(“people =%5dn",people); printf(“people =%9dn”,people); Question: How is the case when we deal float numbers?
  • 24. 24 printf Problem in Engineering: float people= 0.000001;  What will you get when: printf(“people =%fn",people);  Using scientific notation printf(“people =%en", people);
  • 28. 28  We can instruct the computer to retrieve data from various input devices  the keyboard  a mouse  the hard disk drive  Programs that have input from the keyboard usually create a dialogue between the program and the user during execution 2.2 Reading Data from The Keyboard
  • 29. 29  This is done by printing out an hint message,e.g., printf(“please input the current month (int): ”) scanf(“%d”,&month); 2.2 Reading Data from The Keyboard
  • 30. 30  Input data from keyboard can be done using scanf() function  scanf(format_string, argument_list) format_string : converts input characters into a specified type argument_list: addresses of variables in which the input data are stored;  Example float income; double expense; scanf(“%f %lf”,&income, &expense);  & is required to get the address of variable 2.2 Reading Data from The Keyboard
  • 31. 31  scanf() function scanf("%f%lf", &income, &expense);  &income stands for the address of the memory cell for income  & : “address of” operator  &income - pass the address of variable income to function scanf  By giving scanf the address, the program knows where in memory to put the value typed 2.2 Reading Data from The Keyboard
  • 32. 32 printf("what was your month salary in 2015?n"); scanf("%f", &salary); printf("How many months have you worked?n"); scanf("%d",&work_month); printf("what did you earn on vocation month?n"); scanf(" %f",&vocation_salary); printf("what was month expense in 2015?n"); scanf("%f",&expense); 2.2Reading Data from The Keyboard keyboard input keyboard input keyboard input keyboard input dialogue
  • 33. 33 2.2 Reading Data from The Keyboard float income; double expense; int month, hour, minute; printf ("What month is it?n"); scanf ("%d", &month); printf ("You have entered month=%5dn",month);
  • 34. 34  scanf() function scanf (format_string, argument_list);  format_string converts characters in the input into values of a specific type 2.2 Reading Data from The Keyboard
  • 35. 2.2 Reading Data from The Keyboard  argument_list contains the address of the variable(s) into which the input data are stored. e.g. scanf("%f%lf",&income,&expense);  1st keyboard input data converted to float (%f) => income  2nd keyboard input converted to double (%lf) => expense 35
  • 36. printf ("Please enter your income and expensesn"); scanf ("%f%lf", &income,&expense); printf ("Please enter the time, e.g., "); scanf ("%d : %d", &hour,&minute); printf ("Entered Time=%d:%dn",hour,minute); 36
  • 37. 37
  • 38. 38
  • 39. 39
  • 40. Input data for q2 in homework3 40
  • 41. 41 2.3 Arithmetic Operators and Expressions  Consists of a sequence of operand(s) and operator(s) that specify the computation of a value  Look much like algebraic expressions that you write d = x/y; // x divided by y  Assigns the value of the arithmetic expression(division) on the right to the variable on the left  Is correct to write x/y =d ; ? Wrong
  • 42. 42 2.3 Arithmetic Operators and Expressions  Calculate the time needed for a car to drive from A to B with constant speed v  Calculate the how many groups we have in the class if each group has 4 students?
  • 44. 44 Example 1 int i,j,k,p,m,n; float a,b,c,d,e,f,g,h,x,y; i=5; j=5; k=11; p=3; x=3.0; y=4.0; printf("...... Initial values ......n"); printf("i=%4d, j=%4dnk=%4d, p=%4dnx=%4.2f, y= %4.2fnn", i,j,k,p,x,y);
  • 45. 45 Example 1 a=x+y; b=x-y; c=x*y; d=x/y; e=d+3.0; f=d+3; i=i+1; j=j+1; printf("...... Section 1 output ......n"); printf("a=%5.2f, b=%5.2fnc=%5.2f, d=%5.2fn" "e=%5.2f, f=%5.2fni=%5d, j=%5d nn", a,b, c,d, e,f, i,j);
  • 46. 46 Example 1 m=k%p; n=p%k; i++; ++j; e--; --f; printf("...... Section 2 output ......n"); printf("m=%4d, n=%4dni=%4d, j=%4dn" "e=%4.2f, f=%4.2fn",m,n, i,j, e,f);
  • 47. 47 2.3 Arithmetic Operators and Expressions Operators ++, --, and %  ++ increment operator, can be placed before or after a variable  increase the value of the variable by 1  i++; or ++i; equivalent to i=i+1;  i--; or --i; same as i=i-1;  Only difference between i++ and ++i is in order of increment (addressed later)  % is a remainder operator  must be placed between two integer variables or constants  e.g. 11%3 return 2
  • 48. 48 2.3 Arithmetic Operators and Expressions  Depending on data types, division get can you different answers int i=3, j = 5, k; float x = 3.0, y=5.0,z; k = i/j; z = x/y;  remainder operator only accept integer operands k = i%j; right z = x%y; wrong
  • 49. 49 2.3 Arithmetic Operators and Expressions  Cannot write x/y = d; i + 1 = i;  Left side of assignment statement can have only single variable  Single variables are allowed to be lvalues (allowed to be on the left side of assignment )  Expressions are rvalues (allowed on the right side of assignment )
  • 50. 50 Conversion Specification  If the precision specified for a real is  less than actual, displays only the number of digits in the specified precision (trailing digits are not lost from memory, they simply are not displayed)  greater than actual, adds trailing zeros to make the displayed precision equal to the precision specified  not specified, makes the precision equal to six
  • 51. 51 int DAYS_IN_YEAR = 365; //One int value displayed in different field width printf ("CONVERSION SPECIFICATIONS FOR INTEGERS n n"); printf ("Days in year = n" "[[%1d]] t(field width less than actual)n" "[[%9d]] t(field width greater than actual) n" "[[%d]] t(no field width specified) nnn", DAYS_IN_YEAR, DAYS_IN_YEAR, DAYS_IN_YEAR);
  • 52. 52 float PI=3.14159; //One float value displayed in different field width printf ("CONVERSION SPECIFICATIONS FOR REAL NUMBERSnn"); printf ("Cases for precision being specified correctly n"); printf ("PI = n" "[[%1.5f]] tt(field width less than actual) n" "[[%15.5f]] t(field width greater than actual)n" "[[%.5f]] tt(no field width specified) nn", PI,PI,PI);
  • 53. 53 float PI=3.14159; //One float value displayed in different precision printf ("Cases for field width being specified correctly n"); printf ("PI = n" "[[%7.2f]] tt(precision less than actual) n" "[[%7.8f]] tt(precision greater than actual)n" "[[%7.f]] tt(no precision specified) nn", PI,PI,PI);
  • 54. 54 Conversion Specification  Display int with %f or float with %d? likely get nonsensical values or zeros displayed common error beginners make  Why was so much attention given to the printf statement? will write printf statements very frequently can substantially reduce your programming errors
  • 55. 55 Constant  constant can be done using constant macro # define PI 3.1415926  it is a preprocessing directive, it replace the occurrence of macro name (PI) by its value (3.1415926)  it is not a C statement, no “;” at the end  it is usually appear after preprocessing directives E.g.: # include <stdio.h> # define DAY_OF_WEEK 7 void main(void) { printf(“total =%dn”,DAY_OF_WEEK); }
  • 56. 56 Preprocessor  To create a constant macro  use a preprocessor directive  begin with the symbol # (which must begin the line)  semicolon must not be used at the end  General form #define symbolic_name replacement  #define DAYS_IN_YEAR 365  Draw equivalent of DAYS_IN_YEAR to 365  Prior to translation into machine code, the preprocessor replaces every symbolic_name in the program with the given replacement  printf("Days in year=%5d n",DAYS_IN_YEAR); after preprocessing becomes printf("Days in year=%5dn",365);
  • 57. 57 2.4 Mixed Type Arithmetic,  Giving variables their first numerical values is called initializing them, e.g. x = 5;  Usually complicated expression is placed  Order of performance of numerical operations can be controlled  Rules about the order of operation of +, -, *, / are established by setting the precedence of the operators  Operators of higher precedence are executed first while those of lower precedence are executed later
  • 58. 58 Operator Name No of operands Position Associativity Precedence ( parentheses unary prefix L to R 1 ) parentheses unary postfix L to R 1 + positive sign unary prefix R to L 2 - negative sign unary prefix R to L 2 ++ post-increment unary postfix L to R 2 -- post-decrement unary postfix L to R 2 ++ pre-increment unary prefix R to L 2 -- pre-decrement unary prefix R to L 2 += addition and assignment binary infix R to L 2 -= subtraction and assignment binary infix R to L 2 *= multiplication and assignment binary infix R to L 2 /= division and assignment binary infix R to L 2 %= remainder and assignment binary infix R to L 2 % remainder binary infix L to R 3 * multiplication binary infix L to R 3 / division binary infix L to R 3 + addition binary infix L to R 4 - subtraction binary infix L to R 4 = assignment binary infix R to L 5
  • 59. *= Multiply the value of the first operand by the value of the second operand; store the result in the object specified by the first operand. A*=B; // A=A*B; /= Divide the value of the first operand by the value of the second operand; store the result in the object specified by the first operand. A/=B; // A=A/B; %= Take modulus of the first operand specified by the value of the second operand; store the result in the object specified by the first operand. A%=B; // A=A%B; += Add the value of the second operand to the value of the first operand; store the result in the object specified by the first operand. A+=B; // A=A+B; –= Subtract the value of the second operand from the value of the first operand; store the result in the object specified by the first operand. A-=B; // A=A-B; 59 Compound Assignment
  • 60. 60 Variable Initialization/Increment Operator  How do we initialize variables? 1. Uses an assignment statement, e.g. int e ; e=3; 2. Initializes in a declaration statement, e.g. float a=7, b=6; – int i = 1, j =1; int k = i++; – int h = ++j ; – For 1st expression, 1. value of i is first assigned to k 2. i is then incremented (post-increment ++) from 1 to 2 – For 2nd one, 1. value of j is first incremented (pre-increment operator ++) from 1 to 2. 2. Then the new j value, now equal to 2, is assigned to h ?i,j,k,h
  • 61. 61 Mixed Data Type Calculation  6.0/4.0 = 1.5  6/4 = 1  6/4.0 = 1.5 C converts integer to real temporarily and perform the operation
  • 62. 62 cast Operators  Change the type of an expression temporarily  General form (type) expression  int aa=5, bb=2; float xx; xx = (float) aa / bb;  xx = 2.5, otherwise xx = 2.0 Force a floating Point division
  • 63. 63 Controlling Precedence  Arithmetic operators located within the parentheses() always have highest precedence  Example z = ((a+b)*c/d);  a+b evaluated first
  • 64. 64 Associativity  Specifies the direction of evaluation of the operators with the same precedence 1+2 -3 First evaluated Next evaluated Direction of evaluation
  • 65. 65 Further Exploration  Assign an integer value to a float variable  convert the result to float and store to variable  e.g., float p = 6 / 4;  floating variable p will store 1.0
  • 66. 66 Summary  #define symbolic_name replacement  where symbolic_name occurred throughout the rest of program will be replaced by replacement during compilation by preprocessor  Format specifications  %[flag][field width][.precision]type  where format string components enclosed by [ ] are optional  Output of a float number to scientific notation is  [sign]d.ddd e[sign]ddd  where d represents a digit
  • 67. 67 Summary  During mixed mode (different data types) arithmetic, C will automatically convert one of the operands to facilitate calculations  Sometimes type casting can be used to explicitly change data type during calculation  (type) operand  where type is the target type being converted into operand is the data to be casted
  • 68. 68 Summary  Basic structure of a program # include<stdio.h> void main() { statements; }  Constant with preprocessing  using #define CONT_NAME value  # define DAY_OF_YEAR 365  Define variables  data_type variable_name ;  int number; float salary; double rate; Indentation
  • 69. 69 Summary  Output data on to screen  printf(format_string, argument_lists)  printf("You input %dn", month);  Get data from keyboard  scanf(format_string, address_variables)  scanf("%d, %f", &month, &salary);  Mathematical Operators  +, -, *, /, %, ++, --, +=,-=, *=, …  binary operators require its operands of same type  % works on integers  / depends on operands
  • 70. 70 Home work 4  Calculate the average score of a students within one semester. Suppose there are 3 courses in total.  Procedures • Question description(not code in program): • average_score = (score1+score2+score3)/3 • Steps of programming: • define variables with right data type • ask user to input 3 scores from keyboard • convert the math expression into C code • Output the results (keep 2 decimal places)

Editor's Notes

  • #5: Identifiers Naming convention
  • #16: See example Chap2-1.c
  • #23: 输出方式为“%5d”表示按5位的固定位宽输出整型数值。如果不足5位,则在前面补空格;超过5位,则按实际位数输出
  • #24: 编译程序只是检查printf 函数的调用形式,不分析格式控制字符串,如果格式字符与输出项的类型不匹配,不进行类型转换。(输出的数为随机) printf("%f",a),用这样的格式输出就会自动保留六位小数
  • #56: 1.Readability 2.Maintenance