Lecture2 2 C Programming II
Lecture2 2 C Programming II
C PROGRAMMING II
March 17, 2016
Outline
• Assignment Operation
• Symbolic Constant
• Computational Form of Scientific Numbers
• Basic Arithmetic Operations
• Relational Operators and if-conditional
• Logical Operators
• switch-conditional
• ‘?’ conditionals
Assignment Operation
Assignment of a value (constant) to a variable
x=100;
y ax 2 bx c y = a*x*x + b*x +c
x yx
m m = (x + y + z) / 3
3
Note: How to represent power such as x3? There is no operator for the
power. It should be done like x*x*x, or a math-library function
‘pow(x,3)’ should be called.
Basic Arithmetic Operation
++x raise x-value by 1, and use x for other operation
x++ use x first, and raise its value by 1
--x Lower x-value by 1, and use x for other opera
x-- Use x first, and lower its value by 1
Basic Arithmetic Operation
x += y x=x+y
x -= y x=x-y
x *= y x=x*y
x /= y x=x/y
Example
x += 1 // x = x + 1
x *= 5 // x = x * 5
x -= y + 1 // x = x - (y + 1)
x *= y + 1 // x = x * (y + 1)
x += y / z // x = x + y / z
x %= x + y // x = x % (x + y)
Relational Operators and if-conditional
• If-conditional statements are used as follows
if(conditional) { …}
else if(conditional) { …}
else if(conditional) {…}
…
else { … }
A && B And operator: 1 (true) only when both A and B are true
Or operator: 1 (true) when either A and B is true. 0 (false) only when
A || B
both A and B are false
!A Not operator: 1(true) when A is 0 (false), vice versa
Examples
switch(integer)
{
case c1: yes
statement 1; Statement 1
break; no
yes
case c2:
statement 2; Statement 2
break; no
yes
…..
Statement 3
default: no
statement;
break;
}
‘?’ Conditionals
• When exp1 is true, return exp2, otherwise, return exp3
Exp1 is true
Exp1 is false
(5 > 2) ? 5 : 2 //Return 5
(1.2 < 1.1) ? 1 : 0 // Return 0
(x == 0) ? 1: 2 // when x== 0, return 1. Otherwise return 2
Exercise
Exercise 1
Make a C-program. Assign any value to a variable x. if x is the same as 2.5, then
print 2x on the screen. If not, print a sentence ‘Different!’ followed by the value of x.
Exercise 2
Make a C-program. Assign any values to variables x and y. Compare x with 1.3.
Compare y with 2.5. If both are the true, print the product of them on the screen.
If either x=1.3 OR y=2.5 is (are) true, then print the product of x2 and y2. If both are
false, print x-y.
Homework 2-2
Question 1
Make a C-program, which prints ‘Pass’ if an input value is larger than 60, and ‘Fail’ if
smaller than 60. For a C-program to get user’s input, you have to use scanf()
function. How to use scanf function can be easily found in many web sites.
Example.
#include “stdio.h”
#include “stdlib.h”
main()
{
float x,y;
int a;
scanf(“%g %g %d”,&x,&y,&a);