Tin Hoc Co So 2 Week5 Hust
Tin Hoc Co So 2 Week5 Hust
Tin Hoc Co So 2 Week5 Hust
Introduction
Week 5:Expressions
Lecturers : Cao Tuan Dung
Dept of Software Engineering
Hanoi University of
Technology
For HEDSPI Project
Topic of this week
• Expressions
– Class Lecture Review
•mathematic operators
•boolean operators
•conditional expressions
– Programming Exercises
Expression and Operations
• Arithmetic Operators
– Addition +
– Subtraction -
– Multiplication *
– Division /
– Modulation %
• Example
– fag = x % y;
– c = a – (a/b)*b;
– sum = var1 + var2 + var3;
Expression and Operations
• Operator precedence
– Some arithmetic operators act before
others (i.e., multiplication before
addition)
• Use parenthesis when needed
– Example: Find the average of three
variables a, b and c
• Do not use: a + b + c / 3
• Use: (a + b + c ) / 3
Expression and Operations
• Rules of operator precedence:
Operator(s) Operation(s) Order of evaluation (precedence)
• Relational Operators
– Less than < a < 5
– Less than or equal <= a <= b
– More than > a > b+c
– More than or equal>= a >= b + 5
– Equal == a == -6
– Not equal != a != 0
Decision Making: Equality and
Relational Operators
Keyw o rd s
• Example
– X += 1;
Equivalent
– X = X + 1;
Expression and Operations
• Conditional Expressions
• (float)(a+b+c)/3>10? printf(“sum of
etc.. %4d”,a+b) : printf(“sum of
etc.. %4d”,b-c)
Expression and Operations
(type-specifier) expression;
• Example
– (double) date;
– float var1 = 2.7;
int var2 = (int) var1; //var2 = 2
– (char) x;
– (int) d1 + d2;
Exercise 5.1
• Write a program that converts
distances from kilometers to miles.
• Ask user to input the kilometers
value then output to screen the miles
value.
• 1 km ~= 0.621 mile
• 1 mile ~= 1.609344 km
Solution
#include <stdio.h>
#define KM2MILE 1.609344
int main()
{
double miles, /* distance in miles */
kms; /* equivalent distance in kilometers */
main()
{
int a = 5, b = 6, c = 7;
puts("int a = 5, b = 6, c = 7;\n");
void main(void)
{
unsigned int x = UINT_MAX - 1;
signed int y = INT_MAX - 1;
return;
}
Exercise 5.5
• Write a program that requires user
to input two double values stored in
two variables x,y.
• Use if control structure to examine
all the relation between x and y.
Solution
#include <stdio.h>
main()
{
double num1, num2;
if ( num1 == num2 )
printf( "%f is equal to %f\n", num1, num2 );
if ( num1 != num2 )
printf( " %f is not equal to %f\n ", num1, num2 );
Solution
if ( num1 < num2 )
printf( "%f is less than %f\n", num1, num2 );
• a -=a++;