Vous êtes sur la page 1sur 35

Programming for Engineers EE057IU

Lecture 2

Variables, Data Types, and


Arithmetic Expressions
Instructor: Dr. Nguyen Ngoc Truong Minh
School of Electrical Engineering
Vietnamese German University, VGU

Ho Chi Minh City, Fall 2016


Programming for Engineers EE057IU

Lecture Content
Tokens in C
Basic Data Types
Constants/Variables
Global and Local Variables
Operators
Type Conversions
Precedence Order
Floating Point Arithmetic
Exercises
2
Programming for Engineers EE057IU

Tokens in C
Keywords
These are reserved words of the C language. For example int, float,
if, else, for, while, etc.

3
Programming for Engineers EE057IU

Tokens in C

Identifiers
An identifier is a sequence of letters and digits, but must start with a
letter. Underscore (_) is treated as a letter. Identifiers are case
sensitive. Identifiers are used to name variables, functions etc.
Valid: Root, _getchar, __sin, x1, x2, x3, x_1, If
Invalid: 324, short, price$, My Name

Constants
Constants like 13, a, 1.3e-5, etc.

4
Programming for Engineers EE057IU

Tokens in C

String Literals
A sequence of characters enclosed in double quotes as . For
example, 13 is a string literal and not number 13. a and a are
different.

Operators
Arithmetic operators like +, -, *, / ,%, etc.
Logical operators like ||, &&, !, etc. and so on.

White Spaces
Spaces, new lines, horizontal/vertical tabs, comments (A sequence of
characters enclosed in /* and */ or after //) etc. These are used to
separate the adjacent identifiers, keywords and constants.

5
Programming for Engineers EE057IU

Basic Data Types

Integral Types
Integers are stored in various sizes. They can be signed or unsigned.
Example
Suppose an integer is represented by a byte (8 bits).
Leftmost bit is the sign bit. If the sign bit is 0, the number is treated as
positive. Otherwise (sign bit is 1), the number is negative.
Bit pattern 01001011 = 75 (decimal).
The largest positive number is 01111111 = 27 1 = 127.
Negative numbers are stored as twos complement or as ones complement.
-75 = 10110100 (ones complement)
-75 = 10110101 (twos complement)

6
Programming for Engineers EE057IU

Basic Data Types


Integral Types

char Stored as a byte (8 bits).


Unsigned 0 to 255 (=28-1)
Signed -128 to 127

short int Stored as two bytes (16 bits).


Unsigned 0 to 65535 (=216-1)
Signed -32768 to 32767

int Same as either short or long int.

long int Stored as four bytes (32 bits).


Unsigned 0 to 4294967295 (=232-1)
Signed -2147483648 to 2147483647
7
Programming for Engineers EE057IU

Basic Data Types

Floating Point Numbers


Floating point numbers are rational numbers. Always signed numbers.
float Approximate precision of 6 decimal digits.
Typically stored in 4 bytes (32 bits) with 24 bits of signed mantissa and 8 bits
of signed exponent.

double Approximate precision of 14 decimal digits.


Typically stored in 8 bytes (64 bits) with 56 bits of signed mantissa and 8 bits
of signed exponent.

You could check the file limits.h to what is implemented on a particular


machine.
8
Programming for Engineers EE057IU

Constants
Numerical Constants
Constants like 12,253 are stored as int type. No decimal point.
12L or 12l are stored as long int.
12U or 12u are stored as unsigned int.
12UL or 12ul are stored as unsigned long int.
Numbers with a decimal point (12.34) are stored as double.
Numbers with exponent (12e-3 = 12x10-3) are stored as double.
12.34f or 1.234e1f are stored as float.
These are not valid constants:
25,000 7.1e 4 $200 2.3e-3.4 etc.
9
Programming for Engineers EE057IU

Constants

Character and string constants


c, a single character in single quotes are stored as char.
Some special character are represented as two characters in single quotes.
\n = newline, \t= tab, \\ = backlash, \ = double quotes.
Char constants also can be written in terms of their ASCII code.
\060 = 0 (Decimal code is 48).
A sequence of characters enclosed in double quotes is called a string
constant or string literal. For example:
Charu A 3/9 x = 5

10
Programming for Engineers EE057IU

Variables

Naming a variable
Must be a valid identifier.
Must not be a keyword.
Names are case sensitive.
Variables are identified by only first 32 characters.
Library commonly uses names beginning with _.
Naming Styles: Uppercase style and Underscore style
lowerLimit lower_limit
incomeTax income_tax

11
Programming for Engineers EE057IU

Declarations
Declaring a variable
Each variable used must be declared.
A form of a declaration statement is:
data-type var1, var2, ;
Declaration announces the data type of a variable and allocates
appropriate memory location. No initial value (like 0 for integers)
should be assumed.
It is possible to assign an initial value to a variable in the declaration
itself.
data-type var = expression;
Examples
int sum = 0;
char newLine = \n;
float epsilon = 1.0e-6;
12
Programming for Engineers EE057IU

Exercise 1
1. Null character needs a space of _____.
a. zero bytes
b. one byte
c. three bytes
d. four bytes
2. Which of the following is a string literal constant?
a. Visual C++
b. 137.45
c. A
d. 2,365
e. All of the above
3. Which of the followings is not a keyword?
a. int
b. double
c. root
d. while
13
Programming for Engineers EE057IU

Global and Local Variables


/* Compute area and perimeter of a circle */
#include <stdio.h>
Global Variables float pi = 3.14159; /* Global */

int main() {
float rad; /* Local */
These variables are declared
outside all functions. printf( Enter the radius );
scanf(%f, &rad);

if ( rad > 0.0 ) {


Lifetime of a global variable is the
float area = pi * rad * rad;
entire execution period of the float peri = 2 * pi * rad;
program.
printf( Area = %f\n, area );
printf( Peri = %f\n, peri );
}
Can be accessed by any function else
defined below the declaration, in a printf( Negative radius\n);
file. return 0;
}

14
Programming for Engineers EE057IU

Global and Local Variables


/* Compute area and perimeter of a circle */
#include <stdio.h>
Local Variables float pi = 3.14159; /* Global */

int main() {
These variables are declared inside float rad; /* Local */
some functions. printf( Enter the radius );
scanf(%f, &rad);
Life time of a local variable is the
entire execution period of the if ( rad > 0.0 ) {
function in which it is defined. float area = pi * rad * rad;
float peri = 2 * pi * rad;
Cannot be accessed by any other
printf( Area = %f\n, area );
function. printf( Peri = %f\n, peri );
}
In general, variables declared inside else
a block are accessible only in that printf( Negative radius\n);
block.
return 0;
}

15
Programming for Engineers EE057IU

Operators
Arithmetic Operators
+, , *, / and the modulus operator %
+ and have the same precedence and associate left to right
35+7=(35)+73(5+7)
3+75+2=((3+7)5)+2
*, /, % have the same precedence and associate left to right
The +, group has lower precedence than the *, /, % group
35*7/8+6/2
3 35 / 8 + 6 / 2
3 4.375 + 6 / 2
3 4.375 + 3
-1.375 + 3
1.625
16
Programming for Engineers EE057IU

Operators

Arithmetic Operators
% is a modulus operator. x%y results in the remainder when x is
divided by y and is zero when x is divisible by y.
Cannot be applied to float or double variables.
Example
if (num % 2 == 0)
printf(%d is an even number \n, num);

else
printf(%d is an odd number \n, num);

17
Programming for Engineers EE057IU

Operators

Relational Operators
<, <=, >, >=, ==, != are the relational operators. The expression
operand1 relational-operator operand2
takes a value of 1 (int) if the relationship is true and 0 (int) if relationship is
false.
Example
int a = 25, b = 30, c, d;
c = a < b;
d = a > b;
value of c will be 1 and that of d will be 0.

18
Programming for Engineers EE057IU

Operators

Logical Operators
&&, || and ! are the three logical operators
expr1 && expr2 has a value 1 if expr1 and expr2 both are nonzero
expr1 || expr2 has a value 1 if either expr1 or expr2 is nonzero
!expr1 has a value 1 if expr1 is zero else 0
Example
if (marks >= 40 && attendance >= 75) grade = P
if (marks < 40 || attendance < 75) grade = N

19
Programming for Engineers EE057IU

Operators
Assignment operators
The general form of an assignment operator is:
v op= exp
where v is a variable and op is a binary arithmetic operator. This
statement is equivalent to:
v = v op (exp)
a=a+b can be written as a += b
a=a*b can be written as a *= b
a=a/b can be written as a /= b
a=a-b can be written as a -= b

20
Programming for Engineers EE057IU

Operators
Increment and Decrement Operators
The operators ++ and -- are called increment and decrement operators.
Pre-increment ++a and post-increment a++ are equivalent to a += 1
Pre-decrement --a and post-decrement a-- are equivalent to a -= 1
++a op b is equivalent to a++; a op b;
a++ op b is equivalent to a op b; a++;
Example
Let b = 10 then:
(++b) + b + b = 33
b + (++b) + b = 33
b + b + (++b) = 31
b + b * (++b) = 132
21
Programming for Engineers EE057IU

Increment/decrement operators
main()
{
int c;
c = 5;
printf(%d\n, c); 5
printf(%d\n, c++); 5
printf(%d\n\n, c); 6

c = 5;
printf(%d\n, c); 5
printf(%d\n, ++c); 6
printf(%d\n, c); 6

return 0;
}
22
Programming for Engineers EE057IU

Exercise 2
1. Let b = 10 then (b++) + b + (--b) =
a. 32
b. 31
c. 30
d. 29
2. Consider the following section of C program, in which i and n are int variables.
What are the outputs ?
n = 7;
i = 4;
i = n++;
a. i = 7 n = 7
b. i = 7 n = 8
c. i = 8 n = 8
d. i = 4 n = 7

23
Programming for Engineers EE057IU

3. Consider the following section of C program, in which i and n are int variables.
What are the outputs ?
n = 5;
i = 9;
i = --n;
a. i=9 n=5
b. i=4 n=4
c. i=4 n=5
d. i=5 n=4
4. If y has the value 5, what will be the value of the variable y after the following
piece of C is executed?
if (y > 0)
y += 2;
else
y = 3;
a. 5
b. 7
c. 3
d. 2
24
Programming for Engineers EE057IU

5. The following statement where T is true and F is false, T || F && F || T


a. is true
b. is false
c. is syntax error
d. not applicable in C language

6. If a is 5, b is 10, c is 15 and d is 0.
What are the truth values of the following expressions?
a. c == a+b || c == d
b. a != 7 && c >= 6 || a+c<=20
c. !(b <= 12) && a%2 == 0
d. !(a>5) || c < a+b

25
Programming for Engineers EE057IU

Type Conversions
The operands of a binary operator must have the same type and the result is
also of the same type.
Integer division:
c = (9 / 5) * (f - 32)
The operands of the division are both int, and hence, the result also would be
int. For correct results, one may write:
c = (9.0 / 5.0) * (f - 32)
In case the two operands of a binary operator are different, but compatible,
then they are converted to the same type by the compiler. The mechanism (set of
rules) is called Automatic Type Casting.
c = (9.0 / 5) * (f - 32)
It is possible to force a conversion of an operand. This is called Explicit Type
casting.
c = ((float) 9 / 5) * (f - 32)
26
Programming for Engineers EE057IU

Automatic Type Casting

1. char and short operands are converted to int Hierarchy


2. Lower data types are converted to the higher data types and double
result is of higher type.
float
3. The conversions between unsigned and signed types may not
long
yield intuitive results.
int
4. Example
short and char
float f; double d; long l;
int i; short s;
d+f f will be converted to double; double result
i/s s will be converted to int; int result
l/i i is converted to long; long result

27
Programming for Engineers EE057IU

Explicit Type Casting

The general form of a type casting operator is:


(type-name) expression
It is generally a good practice to use explicit casts than to rely on
automatic type conversions.
Example
c = (float)9 / 5 * ( f 32 )
float to int conversion causes truncation of fractional part

double to float conversion causes rounding of digits

long int to int causes dropping of the higher order bits

28
Programming for Engineers EE057IU

Exercise 3
1. What is the right order of the data type hierarchy?
a. float, double, long, int, short, char
b. double, float, long, short, int, char
c. float, double, long, int, char, short
d. double, float, long, int, short, char
2. Which of the following type casts will convert an integer variable named
amount to a double type?
a. (double) amount
b. (int to double) amount
c. int to double(amount)
d. int (amount) to double
3. Define: int c = (f - 32) * ((float)8 / 5);
When f = 50, c = _____.
a. 18
b. 28.8
c. 10.8
d. 28
29
Programming for Engineers EE057IU

Precedence and Order of evaluation

30
Programming for Engineers EE057IU

Precedence and Order of evaluation

31
Programming for Engineers EE057IU

Floating Point Arithmetic

Representation
All floating-point numbers are stored as 0.d1d2...dp x Be such that:
d1 is nonzero

B is the base

p is the precision or number of significant digits

e is the exponent

All these put together have finite number of bits (usually 32 or 64 bits) of storage.
Example
Assume B = 10 and p = 3
23.7 = +0.237E2
23.74 = +0.237E2
37000 = +0.370E5
37028 = +0.370E5
-0.000124 = -0.124E-4

32
Programming for Engineers EE057IU

Floating Point Arithmetic

Representation
Sk={ x|Bk-1 x < Bk }. Number of elements in each Sk is same. In the
previous example, it is 900.
Gap between successive numbers of Sk is Bk-p.
B1-p is called machine epsilon. It is the gap between 1 and next
representable number.
Underflow and Overflow occur when number cannot be represented
because it is too small or too big.
Two floating points are added by aligning decimal points.
Floating point arithmetic is not associative and distributive.

33
Programming for Engineers EE057IU

Exercise 4
1. Write a simple C program to print the sentence This is a C Programming for Engineers
class ! on the screen.

2. Write a simple C program that reads and compares two integer numbers a and b. Print the
relative comparison between them (larger than, equal to or less than).

3. Write a simple C program that reads and finds the minimum of three floating values a, b
and c.

4. Write a C code that input and output your name, address and age to an appropriate
structure.

5. Write a C code that calculates the distance between two points whose coordinates in the
[X,Y] plane are read from the keyboard as float.

6. Given as input an integer number of seconds, print as output the equivalent time in hours,
minutes and seconds. Recommended output format is something like 7322 seconds is
equivalent to 2 hours 2 minutes 2 seconds.
34
Programming for Engineers EE057IU

35

Vous aimerez peut-être aussi