Download as pdf or txt
Download as pdf or txt
You are on page 1of 43

C Programming

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)

() Parentheses Evaluated first. If the parentheses are nested, the


expression in the innermost pair is evaluated first. If
there are several pairs of parentheses “on the same level”
(i.e., not nested), they are evaluated left to right.
*, /, or % Multiplication Division Evaluated second. If there are several, they re
Modulus evaluated left to right.
+ or - Addition Evaluated last. If there are several, they are
Subtraction evaluated left to right.
Decision Making: Equality and
Relational Operators
• Executable statements
– Perform actions (calculations, input/output of data)
– Perform decisions
• May want to print "pass" or "fail" given the value of a test
grade
• if control structure
– Simple version in this section, more detail later
– If a condition is true, then the body of the if statement
executed
• 0 is false, non-zero is true
– Control always resumes after the if structure
• Keywords
– Special words reserved for C
– Cannot be used as identifiers or variable names
Decision Making: Equality and
Relational Operators

• 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

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
• Using if statements, relational Example 1
2 #include <stdio.h>
3
4 int main()
5 {
6 int num1, num2;
7
8 printf( "Enter two integers, and I will tell you\n" );
9 printf( "the relationships they satisfy: " );
10 scanf( "%d%d", &num1, &num2 ); /* read two integers */
11
12 if ( num1 == num2 )
13 printf( "%d is equal to %d\n", num1, num2 );
14
15 if ( num1 != num2 )
16 printf( "%d is not equal to %d\n", num1, num2 );
17
18 if ( num1 < num2 )
19 printf( "%d is less than %d\n", num1, num2 );
20
21 if ( num1 > num2 )
22 printf( "%d is greater than %d\n", num1, num2 );
23
24 if ( num1 <= num2 )
25 printf( "%d is less than or equal to %d\n",
26 num1, num2 );
27
28 if ( num1 >= num2 )
29 printf( "%d is greater than or equal to %d\n",
30 num1, num2 );
31
32 return 0; /* indicate program ended successfully */
33 }

Enter two integers, and I will tell you


the relationships they satisfy: 3 7
3 is not equal to 7
3 is less than 7
3 is less than or equal to 7

Enter two integers, and I will tell you


the relationships they satisfy: 22 12
22 is not equal to 12
22 is greater than 12
22 is greater than or equal to 12
Expression and Operations
• Logical Operators
– AND && (a > 0)
&& (b > 0)
– OR || (a <= 0)
|| (b <= 0)
– Negation ! !(a && c)
Expression and Operations
• Bitwise Operators
– Bitwise AND &
– Bitwise OR (Inclusive OR) |
– Bitwise XOR (Exclusive OR) ^
– Left shift <<
– Right shift >>
– One's complement ~
• Example
– x = 01001011 y = 00101100
~x = 10110100
– x & y = 00001000 x | y = 01101111
– x ^ y = 01100111 x << 2 = 00101100
Expression and Operations

• Assignment Operators and Expressions


– op is + - * / % << >> & ^ |
– If expr1 and expr2 are expressions, then
expr1 op= expr2
– Equivalent to
expr1 = (expr1) op (expr2)

• Example
– X += 1;
Equivalent
– X = X + 1;
Expression and Operations

• Conditional Expressions

expr1 ? expr2 : expr3

– If expr1 is true do expr2


– If expr1 is false do expr3
• Example
– a = 5;
b = 10;
min = a < b ? a : b;
Exercise for K54
Write a program asking for 3
integers then:
- display the maximum number
(do not use if else structure)
- if the average value of these 3
number > 10, display the sum of
2 first numbers. In other case
display the difference of the 2
last numbers.
• max = a>b? a:b;
• max = max >c ? max:c;

• (float)(a+b+c)/3>10? printf(“sum of
etc.. %4d”,a+b) : printf(“sum of
etc.. %4d”,b-c)
Expression and Operations

• Increment and Decrement Operators


– Pre-increment operation ++variable
– Post-increment operation variable++
– Pre-decrement operation --variable
– Post-decrement operation variable--
• Example
–x = 4;
y = x++ + 5; // x = 5, y = 9
–x = 4;
y = ++x + 5; // x = 5, y = 10
Expression and Operations

• Type Cast Operator (Casting)

(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 */

/* Get the distance in kilometers. */


printf("Enter the distance in kilometers > ");
scanf("%f", & kms);

/* Convert the distance to miles. */


miles = kms/ KM2MILE;

/* Display the distance in miles. */


printf("That equals %.3f miles.\n", miles);
return 0;
}
Extended version
• Know that the fuel consumption of
your motorbike for 1 mile is 0.08
liters. Enter the distance of your trip
in kilometers and calculate the fuel
amount and cost. The price of 1 liter
of fuel is 20000 VND
Exercise 5.2
• Run the exercise5_2.c program
below to illustrate the operation of
Logical operators and relational
operators.
• Replace b - a == b – c by a = b-c
and then explain the result.
exercise5_2.c
#include <stdio.h>

main()
{
int a = 5, b = 6, c = 7;
puts("int a = 5, b = 6, c = 7;\n");

printf("The value of a > b is \t%i\n\n", a > b);


printf("The value of b < c is \t%i\n\n", b < c);

printf("The value of a + b >= c is \t%i\n\n", a + b >= c);


printf("The value of a - b <= b-c is\t%i\n\n", a - b <=b- c);

printf("The value of b - a == b - c is\t%i\n\n",b- a==b- c);


printf("The value of a * b != c * c is\t%i\n\n",a * b<c * c);
}
Exercise 5.3
• Type and compile the exercise5_3.c
below, the program illustrates the
operation of conditional expressions.
• Alter the program by eliminating the
abs and max variables.
exercise5_3.c
#include <stdio.h>
main()
{
int n, m, abs, max;

printf("Enter a positive or negative integer: ");


scanf("%i", &n);

printf("\nYou entered %i.\n", n);


abs = n < 0 ? -n : n;
printf("Its absolute value is %i.\n", abs);

printf("\nEnter two integers (e.g. 1 2): ");


scanf("%i %i", &n, &m);

printf("\nYou entered %i and %i.\n", n, m);


max = n > m ? n : m;
printf("%i is the larger value.\n", max);
}
Exercise for K54
• Write a program that get the value of
a 2 real numbers a, b from user and
then display the value of the
following expression:
• (a+b)3 / (a2 - b2 ) – ab
• (a - b)(a+b) / (a2 - b2 ) (a2 +b2 )

Exercise 5.4
• This example illustrates the integer
overflow that occurs when an
arithmetic operation attempts to
create a numeric value that is larger
than can be represented.
• Type and compile the program to see
the result.
exercise5_4.c
#include <stdio.h>
#include <limits.h>

void main(void)
{
unsigned int x = UINT_MAX - 1;
signed int y = INT_MAX - 1;

printf("x is an unsigned int, occupying %i bytes.\n\n",


sizeof(x));

printf("The initial value of x is %u\n", x);


x++;
printf("Add 1; the new value of x is %u\n", x);
x++;
exercise5_4.c
printf("Add 1; the new value of x is %u\n", x);
x++;
printf("Add 1; the new value of x is %u\n", x);

printf("\ny is a signed int, occupying %i bytes.\n\n",


sizeof(y));

printf("The initial value of y is %i\n", y);


y++;
printf("Add 1; the new value of y is %i\n", y);
y++;
printf("Add 1; the new value of y is %i\n", y);
y++;
printf("Add 1; the new value of y is %i\n", y);

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;

printf( "Enter two doubles, and I will tell you\n" );


printf( "the relationships they satisfy: " );
scanf( "%f%f", &num1, &num2 ); /* read two integers */

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 );

if ( num1 > num2 )


printf( "%f is greater than %f\n", num1, num2 );

if ( num1 <= num2 )


printf( "%f is less than or equal to %f\n",
num1, num2 );

if ( num1 >= num2 )


printf( "%f is greater than or equal to %f\n",
num1, num2 );

return 0; /* indicate program ended successfully */


}
Exercise for K54 ICT
• Topcare supermarket gives the
promotion on the Apple product this
month.
– If you buy >= 3 Ipod (148USD/P) AND 2
IPAD (288USD/P)
– OR if your net payment is greater than 1020
USD
• you will get the 10% discount.
– Write a program that get from the users the
numbers of Ipod – and Ipad and print in detail
the bill they have to pay.
– if else statements are not allowed.
Expected Interface
• Ban muon mua bao nhieu IPOD? 7
• Ban muon mua bao nhieu IPAD ? 1
• SIEU THI TOPCARE - HOA DON THANH TOAN
• Ipod 7x 148 = 1036
• Ipad 1x 288 = 288
• Net 1324
• Discount 1324x10% = 132.4
• You pay: 1324 – 132.4 = …
Exercise for ICT K54
• You are chatting in the same time with 2 girls
and have to make decision what girl you should
make a dating. Ask the girls about
– Age:
• (<=16): -2 points
• 16 < age < 21: 5 points
• >= 21: 2 points
– Height:
• taller than or equal to you: decrease 1 point
• less than you 30 cm: decrease 2 point
• else: increse 3 point.
– The girl with higher point is choosen.
– In the case 2 girls get the same points – make dating
with them in Sartuday and Sunday.
Interface of Program
• Login – enter your height (cm): 170
• Hi Lan:
– How old are you? 25 (2)
– What’s your height? 160 (3)
• Hi Mai:
– How old are you? 18 (5)
– What’s your height? 172 (-1)
• Your decision:
– Lan, are you free on Saturday?
Exercise 5.6
• A group of n students is to be divided into 7
classes, as evenly as possible. (No class size
should differ by more than 1 student when
compared to all other class sizes.) Write a C
expression for:
– the number of students in the smallest class
– the number of students in the largest class
– the average number of students per class;
– the number of classes of above average size;
– the number of classes of at most average size;
– the number of students in classes of larger than average
size;
– the number of classes of exactly average size.
Solution
• 7(a) n/7
• 7(b) (n + 6) / 7 , NOT n / 7 + 1.
– Both expressions give the same result, except when n is
divisible by 7. In this case, n/7+1 gives the wrong
answer.
• 7(c) n / 7.0
• 7(d) n%7
• 7(e) 7-n%7
• 7(f) (n % 7) * ((n + 6) / 7)
• 7(g) (n % 7 == 0) * 7 or ! (n % 7) * 7
Exercise 5.8
• Write a simple program containing
the line:

• a -=a++;

• And see what happens to the


variable a.
Bai Tap Bo Sung
• Sieu thi VietLong ban cac mat hang dien tu voi
don gia nhu sau:
– Tu lanh Electrolux: 8trieu VND/chiec
– Tivi LCD Sony: 15 trieu VND/chiec
– Laptop HP: 12 trieu VND/chiec.

• Viet chuong trinh yeu cau nhap vao so luong


hang ban cho ba loai mat hang tren va in ra:
• Doanh so cho tung mat hang
• Tong Doanh So
• Mat hang ban chay nhat – ban e nhat
• Mat hang doanh so cao nhat – thap nhat.
• Khong dung cau truc lenh if.
Bai tap ve nha
• Viet chuong trinh in lich lam viec ca nhan
trong tuan. Chuong trinh yeu cau nguoi
dung nhap cac ngay trong tuan va khoang
thoi gian bat dau – ket thuc cong viec.
• Ngoai ra chuong trinh cung in ra nhac nho
neu mot ngay lam viec hon 8h cho nguoi
dung nhu sau: “Hay can bang giua lam
viec va nghi ngoi”.
Vi du giao dien chuong trinh
• Lich Lam viec ca nhan trong tuan
• cua Nguyen Van A
• Ngay trong tuan Thoi gian lam viec
• Thu hai 08-> 14h
• …….

• Thu sau 14->17h


Exercises Submission
• mail to: ict54hut@gmail.com
• Format (strictly respected)
– Name wno
The same for the file name.tar.gz
• Example : NguyenTranNam w6

• Week1-5: Make in one compressed


file.

You might also like