1. Objectives
UNIT-1
Introduction to the C Language
Dr L.Lakshmi
• Understand the basic structure of a program in C .
• Learn the commands used in UNIX/LINUX and MS-DOS for compiling and running a
program in C.
• Obtain a preliminary idea of the keywords in C.
• Learn the data types, variables, constants, operators, and expressions in C.
• Understand and grasp the precedence and associativity rules of operators in C.
• Get acquainted with the rules of type conversions in C. Get to know the input and output
streams that exist in C to carry out the input and output Tasks.
• Understand that C provides a set of input and output functions
• Learn to use the formatted input and output functions scanf() and printf() for handling
multiple input and output.
1
2. Basics of C
Dr L.Lakshmi
•Ken Thompson at Bell Labs, USA, wrote his own variant over Martin
Richards’s Basic Combined Programming Language and called it B .
•Dennis Ritchie, at Bell Labs, is credited for designing C in the early 1970s.
•Today C is a high-level language which also provides the capabilities that
enable the programmers to ‘get in close’ with the hardware and allows them to
interact with the computer on a much lower level.
2
3. WHY LEARN C?
Dr L.Lakshmi
There are a large number of programming languages in the world today even so,
there are several reasons to learn C, some of which are stated as follows:
a . C is quick.
b . C is a core language : In computing, C is a general purpose, cross-platform,
block structured procedural, imperative computer programming language.
c . C is a small language: C has only thirty-two keywords. This makes it relatively
easy to learn compared to bulkier languages.
d . C is portable.
3
4. WHY LEARN C?
Dr L.Lakshmi
Currently, the most commonly-used language for embedded systems
“High-level assembly”
Very portable: compilers exist for virtually every processor
Easy-to-understand compilation
Produces efficient code
Fairly concise
4
6. Definition of Algorithm:
Dr L.Lakshmi
An algorithm for solving a problem
“a finite sequence of unambiguous, executable
steps or instructions, which, if followed would
ultimately terminate and give the solution of the
problem”.
Note the keywords:
Finite set of steps;
Unambiguous;
Executable;
Terminates;
6
7. Characteristics of Algorithm
Dr L.Lakshmi
•Correctness
•Complexity --- time, space (memory), etc
•Ease of understanding
•Ease of coding
•Ease of maintenance
7
8. Ex:Average of two
Dr L.Lakshmi
Input: Two numbers
1. Add the two numbers
2. Divide the result by 2
3. Return the result by step 2
End
8
9. Ex:Adding two (n-digit) numbers
Dr L.Lakshmi
Input: Two positive m-digit decimal
numbers (a and b)
am, am-1, …., a1
bm, bm-1, …., b1
Output: The sum c = a + b
cm+1, cm, cm-1, …., c1
(Note: In the textbook, it was am-1,…,a1,a0 … )
9
10. Assignments
Dr L.Lakshmi
1. Write an Algorithm for how to prepare
Tea.(Real life Example..)
2. Write an Algorithm to check person is
eligible to vote or not
10
11. Pseudo Code
Dr L.Lakshmi
Mixture of computer language and English
• Somewhere in between
• precise enough to describe what is meant without being too
tediuos
Examples:
• Let c be 0;
• Sort the list of numbers in increasing order;
11
13. Simple Algorithms: Prime Numbers
Dr L.Lakshmi
• Algorithm to determine if n is prime
Given: A positive integer n
Question: Is n a prime number?
• What do we know?
“A number n is prime iff
n has no positive factors except 1 and n”
• Idea: Express it “algorithmically”
“n is not divisible by any positive number k
such that 1 < k < n.” or k=2,3,4,…,(n-1)
• What we already have:
– A module Divisible(m,n) to check divisibility
– We can use it as a primitive
13
14. Ex:Prime(in pseudo-code)
Dr L.Lakshmi
Prime(n)
(* To determine if n is prime *)
begin
for k 2 to (n-1) do
if Divisible(k,n)
then (Print “False” & exit)
else (* Do nothing *)
endfor
Print “True” & Stop
end;
Note: Prime uses the module Divisible(k,n)
Exercise it with:
Prime (5); Prime (4);
Prime (55); Prime (41);
14
15. Flowchart
Dr L.Lakshmi
(Dictionary) A schematic representation of a sequence of operations, as in a
manufacturing process or computer program.
(Technical) A graphical representation of the sequence of operations in an
information system or program. Information system flowcharts show how data
flows from source documents through the computer to final distribution to
users. Program flowcharts show the sequence of instructions in a single
program or subroutine. Different symbols are used to draw each type of
flowchart.
15
16. Flowchart
Dr L.Lakshmi
A Flowchart
•shows logic of an algorithm
•emphasizes individual steps and their interconnections
•e.g. control flow from one action to the next
16
17. Flowchart Symbols
Dr L.Lakshmi
Oval
Parallelogram
Rectangle
Diamond
Hybrid
Name Symbol Use in Flowchart
Denotes the beginning or end of the program
Denotes an input operation
Denotes an output operation
Denotes a decision (or branch) to be made.
The program should continue along one of
two routes. (e.g. IF/THEN/ELSE)
Denotes a process to be carried out
e.g. addition, subtraction, division etc.
Flow line Denotes the direction of logic flow in the program
17
19. Assignment 2
Dr L.Lakshmi
Write an algorithm and draw a flowchart to convert
the length in feet to centimeter.
Pseudocode:
Input the length in feet (Lft)
Calculate the length in cm (Lcm) by multiplying LFT
with 30
Print length in cm (LCM)
19
21. Assignment 3
Dr L.Lakshmi
Write an algorithm and draw a flowchart that will
read the two sides of a rectangle and calculate its
area.
Pseudocode
• Input the width (W) and Length (L) of a rectangle
• Calculate the area (A) by multiplying L with W
• Print A
21
23. Assignment 4
Dr L.Lakshmi
• Write an algorithm and draw a flowchart that will
calculate the roots of a quadratic equation
• Hint: d = sqrt ( ), and the roots are: x1 =
(–b + d)/2a and x2 = (–b – d)/2a
2
4b ac
23
24. Assignment 4
Dr L.Lakshmi
Pseudocode:
• Input the coefficients (a, b, c) of the quadratic
equation
• Calculate d
• Calculate x1
• Calculate x2
• Print x1 and x2
24
25. Assignment 4
Dr L.Lakshmi
• Algorithm:
• Step 1: Input a, b, c
• Step 2: d sqrt ( )
• Step 3: x1 (–b + d) / (2 x a)
• Step 4: x2 (–b – d) / (2 x a)
• Step 5: Print x1, x2
START
Input
a, b, c
d sqrt(b x b – 4 x a x c)
Print
x1 ,x2
STOP
x1 (–b + d) / (2 x a)
X2 (–b – d) / (2 x a)
25
26. BACKGROUND
Developed between 1969 and 1973 along with Unix
Due mostly to Dennis Ritchie
Designed for systems programming
Operating systems
Utility programs
Compilers
Filters
Evolved from B, which evolved from BCPL
26Dr L.Lakshmi
27. BACKGROUND
Taxonomy of the C Language
A much more significant update was made in 1999 known as C99.
The changes incorporated into the standard C99 are summarized
in the following list.
1. Extensions to the character type to support non-English characters.
2. A Boolean type
3. Extensions to the integer type.
4. Inclusion of type definitions in the for statement.
5. Addition of imaginary and complex types
6. Incorporation of c++ style line comment(//).
27Dr L.Lakshmi
28. C Programs (1 of 7)
It's time to write your first C program! This section will take you through all the basic parts of a
C program so that you will be able to write it.
Topics discussed in this section:
Structure of a C Program
Your First C Program
Comments
The Greeting Program
Structure of a C Program:
28Dr L.Lakshmi
29. C Programs (2 of 7)
1. Every C program is made of one or more preprocessor commands, a global declaration
section, and one or more functions.
2. The global declaration section comes at the beginning of the program. The basic idea of
global declarations is that they are visible to all parts of the program.
3. The work of the program is carried out by its functions, blocks of code that accomplish a task
within a program.
4. The function must be named is main. The main function is the starting point for the program.
5. All functions in a program, including main, are divided into 2 sections:
1) The declaration section 2) The statement section.
6. The declaration section is at the beginning of the function, it describes the data will be using
in the function. Declarations in a function are known as local declarations because they are
visible only to the function.
Structure of a C Program:
29Dr L.Lakshmi
30. C Programs (3 of 7)
Structure of a C Program:
7. The statement section contains the instructions to the computer that cause it to do
something, such as add 2 numbers .
8. The preprocessor directives are special instructions to the preprocessor that tell it how to
prepare the program for compilation.
9. One of the most important preprocessor command is include.
10. The include command tells the preprocessor that we need information from selected libraries
known as header files.
Our first C program is very
simple.
No preprocessor commands
No global declarations.
No local definitions.
It only prints simple message
Your First C Program:
30Dr L.Lakshmi
31. C Programs (4 of 7)
Preprocessor Commands:
1. Preprocessor commands comes at the beginning of the program. They can start in any column ,
usually start in column 1
2. All the preprocessor commands start with pound sign(#). They tell the compiler to include the
standard input/output library file in the program
3. The complete syntax is #include<stdio.h> stdio->standard input/output header file.
4. Executable part the program begins with the function main. Syntax is
int main(void)
Main starts with open brace({) and ends with close brace(})
Main contains two statements
1)to print message
2) to terminate the program.
31Dr L.Lakshmi
32. C Programs (5 of 7)
Comments:
Although it reasonable to expect that a good programmer should be able to read code,
sometimes the meaning of a section is not entirely clear. This is especially true in C. Thus it is
helpful if the person who writes the code places some comments in the to help the reader.
1. Comments are ignored by the compiler.
2. To identify the comments, C uses 2 different formats.
1. Line comments 2. Block comments.
3. A block comment is used when the comment will span several lines
block comment opening token is /* and closing token is */
Example of Block Comments:
32Dr L.Lakshmi
33. C Programs (6 of 7)
Comments:
4.The second format, the line comment, uses. two slashes (//) to identify the comment. This
format does not require an end of comment token. The line comment can start anywhere on
the line.
Example of Line Comments:
Note: comments can not be nested
Closing
token
Inner
comment not
allowed
Left on its
own
ignored
33Dr L.Lakshmi
34. C Programs (7 of 7)
The Greeting Program:
We have some
comments at the
beginning.
We have also shown
comments to identify
the declaration and
statements section of
our program
34Dr L.Lakshmi
35. Identifiers (1 of 3)
1. One feature present in all computer languages is the identifier.
2. Identifiers allow us to name data and other objects in the program. Each identified
object in the computer is stored at a unique address.
3. If we didn’t have identifiers, we would have to know and use object’s addresses. Instead,
we simply give data identifiers and let the compiler keep track of where they are physically
located.
4. The rules for identifiers are:
1. The first character must be alphabetic character(A-Z, a-z) or underscore.
2. Must contain only alphabetic characters(A-Z, a-z), digits(0-9) or underscore.
3. First 63 characters of an identifier are significant.
4. Cannot duplicate a keyword.
5. Usually the identifies in the C system libraries start with an underscore, not an
application programs.
35Dr L.Lakshmi
36. Identifiers (2 of 3)
auto _Comple
x
doube for int short switch volatile
_Bool const else goto long signed typedef while
break continue enum if register sizeof union
case default extern _imaginar
y
restrict static unsigned
char do float inline return struct void
6. The last rule says the name we create cannot be keywords. Keywords also known as reserved
words
7. C language contains 37 keywords that cannot be used ad identifies.
36Dr L.Lakshmi
37. Identifiers (3 of 3)
1. The underscore used in identifiers is to make it descriptive. When the names contain
multiple words, the underscore makes it easier to read .
2. An identifier must start with a letter or underscore: it may not have a space or a
hyphen.
3. C is a case-sensitive language.
Examples of Valid and Invalid Names:
37Dr L.Lakshmi
38. Types (1 of 7)
1. A type defines a set of values and a set of operations that can be applied on those values.
2. For example, a light switch can be compared to a computer type. It has a set of two values, on and
off. Only two operations can be applied to a light switch: turn-on and turn-off.
3. The C language has defined set of types that can divided into four general categories:
1. void
2. Integral
3. floating-point
4. Derived
Data Types:
38Dr L.Lakshmi
39. Types (2 of 7)
Void Type:
1. The void type designated by the keyword void, has values and no operations.
2. Which mainly used with functions and pointers.
Integral Type:
1. The C language has three integral types: Boolean ,character and integer.
2. Integral types cannot contain fractional part; they are whole numbers
Boolean:
1. With the release of C99, the C language incorporated a Boolean data type
named by French mathematician George Boole
2. A Boolean data type represent only two values: true and false
3. The Boolean type, referred to by the keyword bool, is stored in memory as
0(false) or 1(true)
character:
1. To a computer, a character is any value that can be represented in the
computer’s alphabet, or as it better known , its character set.
2. C standard provides two character types: char and wchar_t
39Dr L.Lakshmi
40. Types (3 of 7)
character:
3. Most computers use the American standard
code for Information Interchange (ASCII) .
4. Most computer uses 1 byte or 8-bits to store
char data types.
5. To support non-English languages, the c99
standard created wide character type(wchat_t).
Integer:
1. An integer type is a number without fractional part.
2. C supports four different sizes of integer data type: short int, int, long int and long long int.
3. C defines these data types so that they can be organized from the smallest to the largest .
4. The type also defines the size of the field in which data can be stored
5. To know the size of any data type, C provides an operator, sizeof, that will tell us the exact
size in bytes.
6. Each integer can be signed or unsigned. If the integer is signed , then one bit must be used
for a signed (0 is plus, 1 is minus). The unsigned integer can store a positive number that is
twice as large as the signed integr of same size.
7. C has a library, limits.h that contains information about integers.
8. Ex: minimum integer value is INT_MIN
maximum integer value is INT_MAX 40Dr L.Lakshmi
41. Types (4 of 7)
Integral Types:
Note: sizeof (short) ≤ sizeof (int) ≤ sizeof (long) ≤ sizeof (long long)
Typical integer sizes and range of values for signed Integers:
41Dr L.Lakshmi
42. Types (5 of 7)
Floating-Point Types:
1. The C language recognizes three floating-pint types: real, imaginary and complex.
2. There is a standard library, float.h, for the floating point values
3. The real type values are always signed.
Real:
1. The Real type holds values that consist of an integral and fractional part, such as 43.32.
2. The C language supports three different sizes of real types: float, double and long double.
3. C defines these data types so that they can be organized from the smallest to the largest.
Note: sizeof (float) ≤ sizeof (double) ≤ sizeof (long double)
42Dr L.Lakshmi
43. Types (6 of 7)
Imaginary Type:
1. An imaginary number is used extensively in mathematics and engineering.
2. An imaginary number is a real number multiplied by square root of -1.
3. The imaginary type is of three different sizes : float imaginary, double imaginary and
long double imaginary.
4. Most implementations do not support imaginary type.
Complex Type:
1. C defines a complex type, which is implemented by most compilers.
2. A complex number is a combination of a real and imaginary number.
3. The complex type is of three different sizes: float complex, double complex and long
double complex
4. The size needs to be same in both the real and imaginary part.
43Dr L.Lakshmi
45. Variables (1 of 2)
1. Variables are named memory locations that have a type, such as integer or character, which is
inherited from their type. The type determines the values that a variable may contain and the
operations that may be used with its values.
Variable Declaration:
1. Each variable in our program must be declared and defined.
2. In C, a declaration is used to name an object, such as a variable.
3. Definitions are used to create an object.
4. A variable is declared and defined at the same time.
5. Declaration gives them symbolic name and definition reserves memory for them.
6. Once defined, variables are used to hold the data that are reqired by the program for its
operation
7. A variable can be any data type, such as char, int or real but a variable cannot be void.
45Dr L.Lakshmi
46. Variables (2 of 2)
Variable Initialization:
1. We can initialize a variable at the same time that we declare it by including an initializer,
the initializer establishes the first value that the variable will contain.
2. To initialize a variable when it is define, the identifier is followed by assignment operator
and the initializer, which is the value the variable is to have when the function starts.
Example: int count=0;
int count=0,sum=0
Note: When a variable is defined, it is not initialized. We must initialize any variable
requiring prescribed data when the function starts.
When variables are defined ,they usually contain garbage(meaningless) values.
46Dr L.Lakshmi
47. Constants (1 of 7)
Constants are data values that cannot be changed during the execution of a program. Like variables,
constants have a type. Here, we discuss Boolean, character, integer, real, complex, and string constants.
Boolean constants:
1. A Boolean data type can take only two values, so only two symbols to represent a
Boolean data type. The values are true and false.
2. A Boolean value can have only two values: 1(true) and 0(false)
3. To use Boolean constants we have to include the Boolean library stdbool.h
Character constants:
1. The character constants are enclosed between two single quote. Ex: ‘a’ or ‘x’ or ‘2’
2. In addition to the character, we can also use a backslash() before the character.
3. The backslash() is known as the escape character. It is used when the character cannot
be printed or when it can be entered from the keyboard. Ex: n ->new line
4. Wide character constants are coded by prefixing the constant with an L. ex: L ‘X’
5. Most computers use ASCII character set
47Dr L.Lakshmi
48. Constants (2 of 7)
Symbolic names for control characters:
48Dr L.Lakshmi
49. Constants (3 of 7)
Integer Constants:
1. Integers are always stored in their binary form. They simply coded as we use them in
everyday life. Ex x=15.
49Dr L.Lakshmi
50. Constants (4 of 7)
Real Constants:
1. The default form of real constants is double.
2. If we want the resulting data type to be float or long double, we must use a code to
specify the desired data type.
3. You must anticipate f and F are used for float and l and L are used for long double.
50Dr L.Lakshmi
51. Constants (5 of 7)
Complex Constants:
1. Complex constants are coded as two parts, the real part and the imaginary part,
separated by a plus sign.
2. The real part is coded using the real format rules.
3. The imaginary part is coded as a areal number times(*) the imaginary
constant(_Complex_I).
4. Here we need to include the complex library complex.h
5. The default form of complex constants is double.
6. The two components of a complex constant must be of the same precision, that is, if
the real part is type double, then the imaginary part must also be type double.
51Dr L.Lakshmi
52. Constants (6 of 7)
String Constants:
1. A string constant is a sequence of zero or more characters enclosed in double quotes
2. It is important to understand the difference between the null character and an empty
string.
3. The null character represents no value. As a character it is eight zero bits.
4. An empty string is a string containing nothing.
5. Use single quotes for character constants.
Use double quotes for string constants.
52Dr L.Lakshmi
53. Constants (7 of 7)
Coding Constants:
There are 3 types of coding constants
1. Literal constants:
A literal is an unnamed constant used to specify data.
if we know that the data cannot be changed, then we can simply code the data value
itself in a statement.
Ex: the literal 5 is used in the following statement
a=b+5
2. Defined constants:
Another way to designate a constant is to use the preprocessor command define,
which is prefaced with pound sign(#), usually placed at beginning of the program.
Ex: #define SALES_TAX_RATE 0.0825
The preprocessor does not evaluate the code__ it just blindly makes the substitution.
3. memory constants :
The third way to use a constant is with memory constants. Memory constants use a C
type qualifier, const, to indicate that the data cannot be changed. Its format is:
Ex: const type identifier=value
Here the content of memory location are fixed.
53Dr L.Lakshmi
54. Input/output statements (1 of 11)
Although our programs have implicitly shown how to print messages, we have not formally
discussed how we use C facilities to input and output data.
Streams:
1. In C data is input to and output from a stream.
A stream is source of or destination for data.
2. It is Associated with physical device, such as a terminal, or with a file stored in auxiliary
memory. C uses two forms of streams : text and binary.
3. A text stream consists of sequence of characters divided into lines with line terminated by
a newline(n). A binary stream consists of sequence of data values such as integer, real, or
complex using their memory representation.
4. Here we assume that the source of data is the keyboard and destination of data is the
monitor. Keyboard is known as standard input and monitor is known as standard output
54Dr L.Lakshmi
55. Input/output statements (2 of 11)
Formatted Input/Output:
The C language provides two formatting functions: printf for output formatting and
scanf for input formatting.
Output formatting: printf
1. The printf function takes a set of data values, converts them to a text stream using
formatting instructions contained in a format control string, and sends the resulting text
stream to the standard output(monitor).
2. printf is data to text stream converter.
3. The syntax of printf function is
int printf(“ format control string”, argument list);
55Dr L.Lakshmi
56. Input/output statements (3 of 11)
Output formatting: printf
Format control string
• Input and output functions use a format control string.
• Format control string describes how data is to be formatted when read or write.
• Format control string may also contain the text to be printed, such as instructions to the user,
captions to make the output more readable.
• We can also print control characters, such as (t), (n), (a) by including them in format control
string.
56Dr L.Lakshmi
57. Input/output statements (4 of 11)
Output formatting: printf
Conversion specification
1. To insert data into the stream, we use a conversion specification that contain a start token
(%), a conversion code, and up to four optional modifiers as shown below.
2. The number, order and type of conversion specification must match the
number, order and type of the parameters in the list. Otherwise it causes
unpredictable results resulting in termination of input/output function.
3. The first element is a conversion specification token (%) and the last element is the
conversion code. Both of these elements are required, the other elements are optional
57Dr L.Lakshmi
58. Input/output statements (5 of 11)
Conversion codes
Type Size Code Example
char none c %c
short int h d %hd
int none d %d
long int l d %ld
long long int ll d %lld
float none f %f
double none f %f
long double l f %lf
Precision:
If a floating point number is being printed, then we may specify the number of decimal places
to be printed with precision modifier. The precision modifier has the format
.m ex: %.2f
Where m is the number of decimal digits. If no precision is specified printf prints six decimal
positions.
58Dr L.Lakshmi
59. Input/output statements (6 of 11)
Width modifier:
1. A width modifier may be used to specify the minimum number of position in the output.
2. It is very useful to align the output in columns, such as we need to print a column of
numbers.
3. It we don’t use a width modifier, each output value will take just enough room for the
data.
Ex: often width and precision are used
%2hd //short integer-2 print positions
%4d //integer -4 print positions
%8ld //long int-8 print positions
%7.2f //float-7 print positions. 2 decimal places
%10.3f //long double -10 print positions. 3 decimal places
Flag modifier:
• Flags allows the user to format the output in a desired fashion.
• Four output flags:
1) Justification
2) Padding
3) Sign
4) Alternate form
59Dr L.Lakshmi
60. Input/output statements (7 of 11)
The table defines the flag type, flag code and formatting
Program for printf statement with flags u1_ex16.c
60Dr L.Lakshmi
61. Input/output statements (8 of 11)
Input formatting: scanf
1. The standard input formatting function in C is scanf .
2. This function takes a text stream from keyboard, extracts and formats data from the stream
according to a format control string, and the stores the data in specified program variables.
3. scanf requires variable addresses in the address list.
4. Syntax of scanf statement is
int scanf (“format control string”, & argument list);
61Dr L.Lakshmi
62. Input/output statements (9 of 11)
Format control string
Like the format control string for prints, the control string for scanf is enclosed in a set of
quotation marks and contains one or more conversion specifications that describe the data
types.
62Dr L.Lakshmi
63. Input/output statements (10 of 11)
Conversion Specification
To format data from the input stream ,we use a conversion specification that contains a start
token (%), a conversion code, and up to three optional modifiers as shown below.
1. There is no precision in an input conversion specification.
2. There is only one flag for input formatting, the assignment suppression flag(*).
3. This flag tells scanf that the next input field is to be read but not stored. It is discarded.
Ex: scanf(%d%*c%f”, &a,&b)
It reads integer, character and real numbers but only stores integer and real.
4. The width modifier specifies the maximum number of characters to be read .With input
formatting width is maximum, not a minimum
63Dr L.Lakshmi
65. Operators (1 of 17)
An operator is a symbol which helps the user to give instruction to the
computer to do a certain mathematical or logical manipulations.
Operators are used in C language program to operate on data and variables.
C has a rich set of operators which can be classified as follows:
1. Arithmetic operators.
2. Relational Operators.
3. Logical Operators.
4. Assignment Operators.
5. Increments and Decrement Operators.
6. Conditional Operators.
7. Bitwise Operators.
8. Special Operators.
65Dr L.Lakshmi
66. Operators (2 of 17)
Arithmetic Operators
All the basic arithmetic operations can be carried out in C.
All the operators have almost the same meaning as in other languages.
Both unary and binary operations are available in C language.
Unary operations operate on a singe operand,
Therefore the number 5 when operated by unary – will have the value –5.
Operator Meaning
+ Addition or Unary Plus
- Subtraction or Unary Minus
* Multiplication
/ Division
% Modulus Operator
66Dr L.Lakshmi
67. Operators (3 of 17)
1.Arithmetic Operators
Examples of arithmetic operators are: x + y , x - y , x * y , x / y , x % y
The modulus operator is a special operator in C language which evaluates the remainder of the
operands after division.
Integer Arithmetic
When an arithmetic operation is performed on two integers than such an operation is called as
integer arithmetic. It always gives an integer as the result. Let x = 27 and y = 5 x + y = 32 , x – y
= 22 , x * y = 115 , x % y = 2 , x / y = 5
Floating point arithmetic
When an arithmetic operation is preformed on two real numbers such an operation is called
floating point arithmetic.
Let x = 14.0 and y = 4.0 then x + y = 18.0 , x – y = 10.0 , x * y = 56.0 , x / y = 3.50
Mixed mode arithmetic
When one of the operand is real and other is an integer and if the arithmetic
operation is carried out on these 2 operands then it is called as mixed mode
arithmetic. If any one operand is of real type then the result will always be real t
15/10.0 = 1.5 67Dr L.Lakshmi
68. Operators (4 of 17)
2.Relational Operators
Often it is required to compare the relationship between operands and bring out a decision and
program accordingly. This is when the relational operator come into picture. C supports the
following relational operators.
Ex: It is required to compare the marks of 2
students, salary of 2 persons, we can
compare them using relational operators.
(6.5 <= 25) , (-65 > 0) , (10 < 7 + 5)
which result in either TRUE OR FALSE
Relational expressions are used in decision
making statements of C language such as if,
while and for statements to decide the
course of action of a running program
Operator Meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
68Dr L.Lakshmi
69. 3. Logical Operators
Operators (5 of 17)
C has the following logical operators; they compare or evaluate logical and
relational expressions.
Logical AND (&&)
If both the expressions are true then the whole compound expression is true. Example:
a > b && x = = 10
Logical OR (||)
If any one of the 2 expressions is true.
Example: a < m || a < n
Logical NOT (!)
The logical not operator evaluates to true if the expression is false and evaluates to false if
the expression is true.
For example: ! (x >= y)
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Op1 Op2 Op1 & op2 Op1|| op2
Nonzero Nonzero 1 1
Nonzero 0 0 0
0 Nonzero 0 0
0 0 0 0
69Dr L.Lakshmi
70. 4. Assignment Operators
Operators (6 of 17)
The Assignment Operator evaluates an expression on
the right of the expression and substitutes it to the
value or variable on the left of the expression.
Example: x = a + b
In addition, C has a set of shorthand assignment
operators of the form.
var oper = exp;
Example: x + = 1 is same as x = x + 1
The commonly used shorthand assignment operators
are as follows
Shorthand assignment operators
Statement
with simple
assignment
operator
Statement
with
shorthand
operator
a = a + 1 a += 1
a = a – 1 a -= 1
a = a * (n+1) a *= (n+1)
a = a / (n+1) a /= (n+1)
a = a % b a %= b
70Dr L.Lakshmi
71. 5. Increment and Decrement Operators
Operators (7 of 17)
1. The increment and decrement operators are one of the unary operators which are very useful
in C language.
2. They are extensively used in for and while loops. The syntax of the operators is given below
1. ++ variable name 2. variable name++
3. – –variable name4. variable name– –
The increment operator ++ adds the value 1 to the current value of operand.
The decrement operator – – subtracts the value 1 from the current value of operand.
71Dr L.Lakshmi
72. 5. Increment and Decrement Operators
Operators (8 of 17)
1. ++variable name and variable name++ mean the same thing when they form statements
independently.
2. They behave differently when they are used in expression on the right hand side of an
assignment statement.
Consider the following
m = 5;
y = ++m; (prefix) In this case the value of y and m would be 6
Suppose if we rewrite the above statement as
m = 5;
y = m++; (post fix) Then the value of y will be 5 and that of m will be 6.
72Dr L.Lakshmi
73. 6. Conditional or Ternary Operator
Operators (9 of 17)
The conditional operator consists of 2 symbols the question mark (?) and the colon (:). The
syntax for a ternary operator is as follows:
exp1 ? exp2 : exp3
The ternary operator works as exp1 is evaluated first. If the expression is true then exp2 is
evaluated & its value becomes the value of the expression. If exp1 is false,exp3 is evaluated
and its value becomes the value of the expression. Note that only one of the expression is
evaluated.
For example:
a = 10;
b = 15;
x = (a > b) ? a : b
Here x will be assigned to the value of b.
The condition follows that the expression is false therefore b is assigned to x.
Output
Input 2 integers : 45 34
The largest of two numbers is 45
73Dr L.Lakshmi
74. 7. Bitwise Operators
Operators (10 of 17)
The C language is well suited to system programming because it
contains operators that can manipulate data at the bit level.
Those operators are used for testing, complementing or shifting bits
to the right on left.
C has two categories of bitwise operators that operate on data at the
bit level:
1. Logical bitwise operators and
2. Shift bitwise operators.
Logical bitwise operators: Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise
Exclusive OR
<< Shift left
>> Shift right
74Dr L.Lakshmi
75. 7. Bitwise Operators Truth table
Operators (11 of 17)
~aa^ba|ba&bba
100000
111010
011001
001111
75Dr L.Lakshmi
76. 7. Bitwise Shift Operators
Operators (12 of 17)
The shift operators moves bits to the right or left.
Bitwise shift-right operator:
The bitwise shift right (>>) is a binary operator that requires two integral operands .
The first operand is the value to be shifted.
The second operand specifies the number of bits to be shifted.
Ex: a >>= 5; /* shift right 5 bits */
For unsigned data type,
bits positions vacated
by shift are filled with
zeros.
76Dr L.Lakshmi
77. 7. Bitwise Right-Shift Operators
Operators (13 of 17)
When we shift a binary numbers, the right-shift operator divides by a
power of 2.
If we shift a binary number two places to the right, we are dividing by 4.
If we shift it three places , we are dividing by 8.
2 shift value Divide by Shift Operator
1 2 >>1
2 4 >>2
3 8 >>3
4 16 >>4
….. ……. ……
n 2n >>n
77Dr L.Lakshmi
78. 7. Bitwise Left-Shift Operators
Operators (14 of 17)
The bitwise shift right (<<) is a binary operator that requires two
integral operands .
The first operand is the value to be shifted.
The second operand specifies the number of bits to be shifted.
Ex: a <<=3; /* shift right 5 bits */
Bits positions
vacated by shift are
filled with zeros
78Dr L.Lakshmi
79. 7. Bitwise Left-Shift Operators
Operators (15 of 17)
When we shift a binary numbers, the Left-shift operator multiplies by a
power of 2.
If we shift a binary number two places to the left, we are multiplying by 4.
If we shift it three places , we are multiplying by 8.
2 shift value Multiplies by Shift Operator
1 2 <<1
2 4 <<2
3 8 <<3
4 16 <<4
…. …….. ……
n 2n <<n
79Dr L.Lakshmi
80. 8. Special Operators
Operators (16 of 17)
C supports some special operators of interest such as comma operator, size of
operator, pointer operators (& and *) and member selection operators (. and ->).
The size of and the comma operators are discussed here.
The Comma Operator
The comma operator can be used to link related expressions together. A comma linked list of
expressions are evaluated left to right and value of right most expression is the value of the
combined expression.
For example the statement
value = (x = 10, y = 5, x + y);
First assigns 10 to x and 5 to y and finally assigns 15 to value. Since comma has
the lowest precedence in operators the parenthesis is necessary. Some examples of comma
operator are In for loops:
for (n=1, m=10, n <=m; n++,m++)
In while loops While (c=getchar(), c != ‘10’)
Exchanging values t = x, x = y, y = t; . 80Dr L.Lakshmi
81. The size of Operator
The operator size of gives the size of the data type or variable in terms of bytes occupied in
the memory. The operand may be a variable, a constant or a data type qualifier.
Example
m = sizeof (sum);
n = sizeof (long int);
k = sizeof (235L);
The size of operator is normally used to determine the lengths of arrays and structures when
their sizes are not known to the programmer. It is also used to allocate memory space
dynamically to variables during the execution of the program
8. Special Operators
Operators (17 of 17)
81Dr L.Lakshmi
82. Expressions (1 of 9)
An expression is a sequence of operands and operators that reduce
to a single value.
Expressions can be simple or complex.
An operator is a syntactical token that requires an action be taken.
An operand is an object on which an operation is performed;
it receives an operator’s action .
A simple expression contains only one operator.
Ex: 2+5
A complex expression contains more than one operator.
Ex: 2+5*7
An expression always reduces to a single value.
We can divide simple expressions into six categories based on number of
operands, relative position of the operand and operator and the precedence
of operator.
82Dr L.Lakshmi
83. The most elementary type of expression is a primary expression.
A primary expression consists of only one operand with no operator.
In C, the operand in the primary expression can be a name, a constant,
or a parenthesized expression.
Names:
A name is any identifier for a variable, a function, or any other object in the language. Examples
of some names used as primary expressions.
Ex: a b12 price calc INT_MAX SIZE
Literal Constants:
The second type of primary expression is the literal constant. A literal is a piece of data whose
value cannot be changed during execution of the program.
Ex: 5 123.98 ‘A’ “Wel come”
Parenthetical expressions:
The third type of primary expression is the parenthetical expression. Any value enclosed in
parentheses must be reducible to a single value and is therefore a primary expression.
Ex: (2 * 3+4) (a=23 + b*6 ).
Primary Expressions
Expressions (2 of 9)
83Dr L.Lakshmi
84. Postfix Expressions
The postfix expression consists of operand followed by operator.
Some of the post fix expressions are function call, postfix increment, and postfix decrement.
The form of postfix expression is
Function call:
All the function calls are postfix expressions. The function is the operand and the operator is
the parentheses that follows the name. parentheses may contain arguments or empty.
Ex: printf(“hello world”) scanf()
Postfix increment/decrement:
In the post increment/ decrement, the variable value incremented /decremented by 1.
Expressions (3 of 9)
84Dr L.Lakshmi
85. Prefix Expressions
In prefix expressions, the operator comes before the operand
Prefix Increment/Decrement:
1. In C, we have only two prefix operators that form prefix expressions:
prefix increment
prefix decrement
2. Prefix increment and decrement operators are shorthand notations for adding or
subtracting 1 from variable.
3. The operand of a prefix expression must be a variable.
4. The value of (++a) is same as (a=a+1).
Expressions (4 of 9)
85Dr L.Lakshmi
86. If ++ is after the operand, as in a++, the increment takes place
after the expression is evaluated.
If ++ is before the operand, as in ++a, the increment
takes place before the expression is evaluated.
Note
Expressions (5 of 9)
86Dr L.Lakshmi
87. Unary Expressions
A unary expression, like a prefix expression, consists of one operator and one operand and
also the operator comes before the operand.
sizeof
The sizeof operator tells us the size in bytes, of a
type or a primary expression.
Ex: sizeof(int), sizeof(345.23), sizeof(x)
Unary plus/minus
Cast operator
The cast operator converts one expression type to another.
Ex: convert an integer to real number float(x)
Expressions (6 of 9)
87Dr L.Lakshmi
88. Binary Expressions
Binary expressions are formed by an operand-operator-operand combination.
Multiplicative Expressions
Multiplicative expressions include the operators multiply, divide, modulus operators. These
operators have the higher priority among the binary operators and are therefore evaluated first.
Both operands of the modulo operator (%) must be integral type.
Ex: 10*3 //evaluates to 30 10/3 // evaluates to 3
true*4 // evaluates to 4 true/4 // evaluates to 0
‘A’*2 // evaluates to 130 ‘A’/2 // evaluates to 32
22.3*2 // evaluates to 44.6 22.3/2 // evaluates to 11/15
10%3 // evaluates to 1 3/5 // evaluates to 0
‘A’%2 // evaluates to 5 3%5 // evaluates to3
22.3%2 //error
Expressions (7 of 9)
88Dr L.Lakshmi
89. Additive Expressions
In additive expressions, the second operand is added to or subtracted from the first operand ,
depend on the operator used.
Additive operators are evaluated after multiplicative expressions.
Ex: 3+7 //evaluates to 10
3-7 //evaluates to -4
Assignment Expressions
1. The assignment expression evaluates the operand on the right side of the operator(=) and
places its value in the variable on the left.
2. The value of the total expression is the value of the expression on the right of the assignment
operator(=)
3. The left operand in an assignment expression must be a single variable.
4. There are two forms of assignment
1. Simple assignment.
2. Compound assignment.
Expressions (8 of 9)
89Dr L.Lakshmi
90. Simple Assignment
1. Simple assignment is found in algebraic expressions.
2. Three examples of simple assignments are shown below
a=5 b=x+1 i=i+1
Compound Assignment
1. A compound assignment is a shorthand notation for a simple assignment.
2. It requires that the left operand be repeated as a part of the right expression
Expressions (9 of 9)
90Dr L.Lakshmi
91. Precedence
Precedence and Associativity (1 of 4)
1. Precedence is used to determine the order in which different operators in a complex
expression are evaluated .
2. C extents the concept to 15 levels.
Ex: 2+3*4=(2+(3*4))=14
-b++=(-(b++))
Associativity
1. Associativity is used to determine the order in which operators with the same
precedence are evaluated in a complex expression.
2. Precedence is applied before associativity to determine the order in which
expressions are evaluated.
3. Associativity can be left-to-right or right-to-left.
91Dr L.Lakshmi
92. Left to Right Associativity
Precedence and Associativity (2 of 4)
All the operators have the same precedence. Their associativity is from left to right. so they
are grouped as follows
Ex: 3* 8 / 4 % 4 * 5
Right to Left Associativity
All the operators have the same precedence. Their associativity is from right to left. so they
are grouped as follows
Ex: a += b *= c -= 5 which is (a=a+(b=b*(c=c-5)))
92Dr L.Lakshmi
93. Precedence and Associativity (3 of 4)
Operator Description Precedence Associativity
( )
[ ]
.
->
++ --
Parentheses (function call)
Brackets (array subscript)
Member selection via object name
Member selection via pointer
Postfix increment/decrement
1
left-to-right
++ --
+ -
! ~
(type)
*
&
sizeof
Prefix increment/decrement
Unary plus/minus
Logical negation/bitwise complement
Cast (convert value to temporary
value of type)
Dereference
Address (of operand)
Determine size in bytes on this
implementation
2 right-to-left
* / % Multiplication/division/modulus 3 left-to-right
+ - Addition/subtraction 4 left-to-right
<< >> Bitwise shift left, Bitwise shift right
5 left-to-right
93Dr L.Lakshmi
94. Precedence and Associativity (4 of 4)
Operator Description Precedence Associativity
< <=
> >=
Relational less than/less than or equal to
Relational greater than/greater than or equal
to
6 left-to-right
== != Relational is equal to/is not equal to 7 left-to-right
& Bitwise AND 8 left-to-right
^ Bitwise exclusive OR 9 left-to-right
| Bitwise inclusive OR 10 left-to-right
&& Logical AND 11 left-to-right
| | Logical OR 12 left-to-right
? : Ternary conditional 13 right-to-left
=
+= -=
*= /=
%= &=
^= |=
<<= >>=
Assignment
Addition/subtraction assignment
Multiplication/division assignment
Modulus/bitwise AND assignment
Bitwise exclusive/inclusive OR assignment
Bitwise shift left/right assignment
14 right-to-left
, Comma (separate expressions) 15 left-to-right
94Dr L.Lakshmi
95. Expression Evaluation (1 of 2)
Now we evaluate expressions as we know precedence, associativity of operators
Expressions without side effects
Ex: a*4+b/2-c*b consider a=3 b=4 c=5
Replace variables by their values
3 * 4 + 4 / 2 – 5 * 4
Apply precedence rules
(3 * 4) + (4 / 2) – (5 * 4)
Apply Associativity rules as they are left to right
associative
(((3 * 4) + (4 / 2)) – (5 * 4))
In evaluation of this expressions there are no side
effects
95Dr L.Lakshmi
96. Expression Evaluation (2 of 2)
Expressions with side effects
Now look for example with side effects and parenthesized expressions.
Ex: --a * ( 3 + b ) / 2 – c++ * b
Assume a=3 b=4 c=5
1. Calculate the value of parenthesized expressions
--a * 7 / 2 – c++ * b
2. Evaluate postfix expression
--a * 7 / 2 – 5 * b
3. Evaluate prefix expression
2 * 7 / 2 – 5 * b
4. Now apply multiply and division
14 / 2 – 5*4
5. Last step is to evaluate subtraction
7-20=-13
After the side effects the variables
have the values shown below
a=2 b=4 c=6
Warning
96Dr L.Lakshmi
97. Type Conversion (1 of 6)
Up to this point, we have assumed that all of our expressions involved data of the same type.
But, what happens when we write an expression that involves two different data types, such as
multiplying an integer and a floating-point number? To perform these evaluations, one of the
types must be converted.
Type conversion is of two types:
1. Implicit Type Conversion
2. Explicit Type Conversion (Cast)
1. Implicit Type Conversion
When the types of the two operands in a binary expression are different, C automatically
converts one type to another. This is known as implicit type conversion.
Conversion rank:
1. We assign a rank to the integral and floating point arithmetic types.
2. These ranks are known as conversion ranks.
3. Conversion ranks are shown below
97Dr L.Lakshmi
99. Type Conversion (3 of 6)
Conversions in Assignment Expressions
A simple assignment involves an assignment operator and two operands. Depending on the
difference in the rank, C tries to either promote or demote the right expression to make it the
same rank as the left variable.
1. Promotion occurs if the expression has lower rank.
2. Demotion occurs if the right expression has higher rank.
1. Promotion
1. There is normally no problem with promotion.
2. The rank of right expression is elevated to the rank of the left variable.
3. The value of the expression is the value of the right expression after the promotion.
Ex: bool b= true
char c= ‘A’
int i=1234
long double d=3458.0004
c=b //value of c is SOH (ASCII 1)
i= c //value of i is 65
d=b //value of d is is 1.0
d=i // value of d is 1234.0
99Dr L.Lakshmi
100. Type Conversion (4 of 6)
2. Demotion
Demotion may or may not create problems.
If the size of the variable at the left side can accommodate the value of the
expression, then there is no problem.
If the size of the variable at the left side can not accommodate the value of the
expression, then demotion occurs.
Ex:
bool b = false
char c = ‘A’
short int s = 78
int j = 32200
int k = 65
b=c // value of b is 1 (true)
s=j // value of s is unpredictable
c=k+1 // demotion value of c is ‘B’
100Dr L.Lakshmi
101. Type Conversion (5 of 6)
3. Conversion in other binary expressions
Conversion has a different set of rules for other binary expressions.
1. The operand with higher rank is determined using the ranking table.
2. The lower ranked operand is promoted to the rank defined in step 1. After the promotion
both expressions have the same rank.
3. The operation is performed with the expression value having the type of the promoted rank.
Ex: bool b = true;
char c = ‘A’
int i = 3650
short int s= 78
long double d = 3458.0004
b + c // b promoted: result is ‘B’
I * s // result is an integer
d * c // result is long double
101Dr L.Lakshmi
102. Type Conversion (6 of 6)
Explicit type conversion (cast)
1. In explicit type conversion we convert the data from one type to another type using explicit
type conversion.
2. Explicit type conversion uses the unary type cast operator
3. To cast the data from one type to another, we specify the new type in parentheses before
the value we want to convert.
Ex: (float) a
One use of the cast is to ensure that the result of a divide is a real number.
Ex: avg=(float) totalscores/ numscore
here totalscores is integer
numscore is int
but result is float due type cast operator before totalscores
102Dr L.Lakshmi