0% found this document useful (0 votes)
3 views

lecture 4

The document provides an introduction to computer programming in C, covering data types, operators, tokens, and variable declarations. It explains the importance of keywords, identifiers, constants, and the various data types such as integral and floating-point types. Additionally, it discusses operators including arithmetic, relational, logical, and assignment operators, as well as type casting and the nuances of variable scope.

Uploaded by

madin20232022
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

lecture 4

The document provides an introduction to computer programming in C, covering data types, operators, tokens, and variable declarations. It explains the importance of keywords, identifiers, constants, and the various data types such as integral and floating-point types. Additionally, it discusses operators including arithmetic, relational, logical, and assignment operators, as well as type casting and the nuances of variable scope.

Uploaded by

madin20232022
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

University of Hafr Al-Batin

Hafr Al-Batin Community College ( HBCC )

CST121 + CNT 234: Introduction to


Computer Programming
Data types and operators in C
language
Lecture-4
1
Tokens in C
• Keywords
– These are reserved words of the C language. For example
int, float, if, else, for, while , etc...
• Identifiers
– Identifiers are names given to variables and functions etc.
– 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..
– Valid: Root, _getchar, __sin, x1, x2, x3,
x_1, If
– Invalid: 324, short, price$, My Name, 1x
• Constants
– Constants are fixed values like 13, 3.1416, ‘a’, 1.3e-5 etc.
2
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…

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

3
Basic Data Types
• C is strongly typed. The variables and constants etc have a certain
data types.
• All variables could have been double type, but then multiplying double
numbers is very expensive. So the various data types have been
provided for the reason of efficiency and ease of handling.

– Numbers are stored in various sizes; can be signed or unsigned.


– Example
– Suppose an integer is represented by a byte (8 bits). Leftmost bit is sign bit. If
the sign bit is 0, the number is treated as positive.
Bit pattern 01001011 = 75 (decimal).
The largest positive number is 01111111 = 27 – 1 = 127.
– Negative numbers are stored as two’s complement or as one’s complement.
+75= 01001011
-75 = 10110100 (one’s complement)…….by inverting each bit
-75 = 10110101 (two’s complement)…….by adding 1 to 1’s compliment.
4
Basic Data Types
• Integral Types:
• Integers are whole numbers and are stored in various
sizes. They can be signed or unsigned.
– char Stored as 8 bits.
Unsigned 0 to 255.
Signed -128 to 127.
– short int Stored as 16 bits.
Unsigned 0 to 65535.
Signed -32768 to 32767.
– int Same as either short or long int.
– long int Stored as 32 bits.
Unsigned 0 to 4294967295.
Signed -2147483648 to 2147483647
▪ Range of Signed numbers with N bits : –2 N–1 …to… 2 N–1 – 1
▪ Range of Unsigned numbers with N bits : 0 …to… 2N – 1
Note: C guarantees only the following: sizeof(short) <= sizeof(int) <= sizeof(long). 5
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 with 24 bits of signed mantissa and 8
bits of signed exponent.
– double: Approximate precision of 14 decimal digits.
• Typically stored in 8 bytes with 56 bits of signed mantissa and 8
bits of signed exponent.

– One should check the file limits.h to what is


implemented on a particular machine.
6
Constants
• Numerical Constants
– Integer 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 (like 20.3) or
exponent ( like 12e-3 or 12 x 10-3 ) are stored as
double.
– Rational numbers ( like 12.34f or 1.234e1f ) are
stored as float.
– The following are not valid constants:
25,000 7.1e 4 $200 2.3e-3.4
7
Constants
• Character
– ‘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.
E.g., in octal‘\060’ = ‘0’ (Decimal code is 48).
(Please see http://www.ascii-code.com/ )

• string constants
– A sequence of characters enclosed in double quotes is called a
string constant or string literal. For example
“Hafr”,“KFUPM”, “A”, “3/9”, “x = 5”

8
Variables
• Naming a Variable
1. Can consist of alphabets (small or CAPS), digits (0 to 9), and
underscore ( _ ).
2. Must start with an alphabet or underscore.
3. Must not be a keyword, constant or literal.
4. Must not include any white spaces (space or tab etc.) or special
characters (only _ is allowed).
5. Is case sensitive.
6. Only first 32 characters are considered by compiler.
– Example:
– Valid: incomeTax, _getch, my_age, x9
– Invalid: price$, short, 512, 9x
– Library of C language commonly uses names beginning with _.
– Naming Styles:
– Uppercase style : lowerLimit , incomeTax
– Underscore style: lower_limit , income_tax 9
Declarations
• Declaring a Variable
– Each variable must be declared before use.
– A form of a declaration statement is
data-type var1, var2,…;
– Examples
int sum = 0;
char newLine = ‘\n’;
float epsilon = 1.0e-6;
– 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;
e,g., int x = 9+5;

10
Global and Local Variables
• Global Variables
/* Compute Area and Perimeter of a
circle */
#include <stdio.h>
– These variables are float pi = 3.14159; /* Global*/
declared outside all main() {
functions. float rad,area,peri; /* Local */
– Life time of a global printf( “Enter the radius “ );
variable is the entire scanf(“%f” , &rad);

execution period of if ( rad > 0.0 ) {


the program. area = pi * rad * rad;
peri = 2 * pi * rad;
– Can be accessed by any
function defined below printf( “Area = %f\n” , area );
printf( “Peri = %f\n” , peri );
the declaration, in a }
file. else
printf( “Negative radius\n”);
– For example, pi is
printf( “Area = %f\n” , area );
global variable in }
this program.

11
Global and Local Variables
• Local Variables /* Compute Area and Perimeter of a
circle */
#include <stdio.h>
– These variables are float pi = 3.14159; /* Global */
declared inside some
functions. main() {
– Life time of a local float rad,area,peri;/*Local*/
variable is the entire printf( “Enter the radius “ );
execution period of the scanf(“%f” , &rad);
function in which it is if ( rad > 0.0 ) {
defined. area = pi * rad * rad;
– Cannot be accessed by any peri = 2 * pi * rad;
other function.
printf( “Area = %f\n” , area );
– In general variables printf( “Peri = %f\n” , peri );
declared inside a block }
else
are accessible only in printf( “Negative radius\n”);
that block.
– For example, rad, area printf( “Area = %f\n” , area );
}
and peri are local
variables in this
program.

12
Operators
• Arithmetic Operators:
– +, - , *, / and %. (modulus).
– + and – have the same precedence and associate left to right.
3 – 5 + 7 = ( 3 – 5 ) + 7  3 – ( 5 + 7 )
3 + 7 – 5 + 2 = ( ( 3 + 7 ) – 5 ) + 2

– *, /, % have the same precedence and associate left to right.

– The +,- group has lower precedence than the *,/,% group.
E.g., the final value of expression 3–5*7/8+6/2 is 1.625 …
– 3 – 5 * 7 / 8 + 6 / 2
– 3 – 35 / 8 + 6 / 2
– 3 – 4.375 + 6 / 2
– 3 – 4.375 + 3
– -1.375 + 3
– 1.625

13
Operators
• Arithmetic Operators
– % is a modulus operator applied to integers only.
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);

14
Operators
• Relational Operators
– <, <=, >, >=, ==, != are the relational operators. The
expression
operand1 relational-operator operand2
takes integer value of 1 if the relationship is true and 0 if
the 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.
15
Operators
• Logical Operators
– &&, || and ! are the three logical operators.
– expr1 && expr2 has a value true (1) if expr1
and expr2 are both true.
– expr1 || expr2 has a value true (1) if either
expr1 or expr2 are true, or both are true.
– !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’

16
Operators
• Assignment operators
– =, -=, +=, *=, /=
– The general form of an assignment operator is
var op= exp
– Where var is a variable and op is a binary arithmetic
operator. This statement is equivalent to
var = var op (exp)
– Examples:
• 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

17
Operators
• Increment and Decrement Operators
– The operators ++ and –- are called increment and decrement
operators.
• a++ and ++a are equivalent to a += 1.
• a-- and --a are equivalent to a -= 1.

• ++a op b is equivalent to a ++; a op b;


• That is, a is incremented first and then used
• a++ op b is equivalent to a op b; a++;
• That is, a is used first and then incremented

– Example: Let b = 10 then


(++b)+b+b = 33
b+(++b)+b = 32
b+b+(b++) = 30
18
Precedence of operators

19
Associativity of operators

20
Type Casting / Conversions
– The operands of a binary operator must have the same
type and the result is also of the same type.
For example, 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.
For example, c = (9.0 / 5)*(f - 32)
– It is possible to force a conversion of an operand. This is
called Explicit Type casting.
For example, c = ((float) 9 / 5)*(f - 32)
21
Automatic Type Casting
1. char and short operands are converted to
int Hierarchy
2. Lower data types are converted to the double
higher data types and result is of higher float
type. long
3. The conversions between unsigned and int
signed types may not yield intuitive results.
Short, char

• For example:
float f; double d; long l; int i; short s;
d + f --- f will be converted to double
i / s --- s will be converted to int
l / i --- i is converted to long

22
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.
23
Floating Point Arithmetic
– All floating point numbers are stored as:
 0.d1d 2  d p  B e such that d1 is nonzero.
where B is base, p is precision or number of significant digits, and e is exponent.

– All these put together have – Example: let B=10, p = 3.


finite number of bits (usually 32 •23.7 = +0.237E2
or 64 bits ) of storage. •23.74 = +0.237E2
•37000 = +0.370E5
– Sk = { x | Bk-1 <= x < Bk }. •37028 = +0.370E5
Number of elements in each Sk is same. •-0.000124 = -0.124E-3
– 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. 24

You might also like