PC - Unit-1
PC - Unit-1
COMPUTER :
It is a high speed electronic device that accepts and stores input data and
instructions, processes the data and produces the desired output.
COMPUTER SYSTEMS
A computer is a system made up of 2 major components
They are :
(1) Hardware
(2) Software
) Computer Hardware :
1) Input Devices
2) Output Devices
3) CPU
4) Primary Storage
ALU CU
Input Output
Devices Devices
Primary Memory
Secondary Memory
1) Input Devices
These are used to enter data and programs into the computer.The
most wellknown input device is the keyboard. These are for man to machine
communication.
Examples of other input devices include mouse, scanner, touch screen, a pen or
stylus, audio input.
2) Output Devices
These are used to get the desired output from the computer. The
output unit of a computer provides the information and results of a computation
to outside world .Printers and monitors are the commonly used output devices.
Other commonly used output devices are floppy disk drive, hard disk drive, pen
drive and magnetic tape drive. These are for machine to man communication
Control Unit
Memory Unit
The various storage devices of a computer system are divided into two
categories.
4) Primary Storage
Eg: RAM
The cost of the primary storage is more compared to the secondary storage.
Therefore most computers have limited primary storage capacity .
5) Secondary Storage
The secondary memory is slower and cheaper than the primary memory.
i. System Software
ii. Application Software
i) System Software
The following fig represents the relationship between system and application
software.
In this figure,
(5) A computer can work with out (5)A computer can not work with out
application system
software software
COMPUTER LANGUAGES
00000000 00000100
0000000000000000
11101111 00010110
000000000000101
Advantages :
2) Symbolic Languages
It is also called as assembly language.
It was developed to overcome some of the many inconveniences of machine
language.
This is another low level but a very important language in which operation codes and
operands are given in the form of alphanumeric symbols instead of 0’s and l’s.
Because of this feature it is also known as ‘Symbolic Programming Language’.
These alphanumeric symbols will be known as mnemonic codes and can have
maximum up to 5 letter combination
e.g. ADD for addition, SUB for subtraction, START,LABEL etc.
Since a computer does not understand symbolic language,it must be translated to the
machine language.A special program called assembler translates symbolic code into
machine language.
Advantages :
A set of languages which are very close to our native languages are called
“ high-level languages”.
High-level languages are basically symbolic languages that use English words and/or
mathematical symbols rather than mnemonic codes
Since a computer does not understand high-level languages,it must be
translated to the machine language.A special program called compiler
translates high-level languages into machine language
Examples of high level languages are FORTRAN, COBOL, PASCAL, C, C+
+,JAVA, etc..
Compiler /
High language program Machine
Interpreter
Language code
Advantages :
These are Similar to English with vocabulary of words and symbols.Therefore it is easier
to learn.
Disadvantages :
The software used to write programs is known as text editor .Users can
enter, change and store character data using text editors.
A special text editor is often included with a compiler.
Some of the features we look in our editor are search commands to locate
and replace statements,copy and paste commands to copy or move
statements from one part of a program to another, and formatting
commads that allows us to set tabs to align statements.
After completing writing program, save the file to disk. This file will be
input to the compiler: It is known as ‘source file’ .
a) Preprocessor
b) Translator
a) Preprocessor
The preprocessor reads the source code and prepares it for the translator.
While preparing the code it scans for special instructions known as ‘preprocessor’
commands. These commands tell the preprocessor to look for special code
libraries and make substitutions in the code, and in other ways prepare the code
for translation into machine language. The result of preprocessing is called
‘translation’ unit
Preprocessor
Source File translation unit
b) Translator
After the preprocessor prepared the code for compilation, the translator
does the actual work of converting the program into machine language. The
translator reads the translation unit and writes the resulting ‘object module’ to
a file that can be combined with other precompiled units to form the final
program. An object module is the code in machine language.
Translator
Translation unit Object Module .obj file
00110 100
10101 010
3) Linking programs
.exe file
Linker
Object file executable file 1011001100
110111011
1100101010
4) Executing Programs
1. Input
2. Output
3. Finiteness
4. Definiteness
5. Effectiveness
1. Input : An algorithm must have zero (or) more number of inputs
2. Output: Algorithm must produce one (or) more number of outputs
3. Finiteness : An algorithm must terminate in countable number of steps
4. Definiteness: Each step of the algorithm must be stated clearly
5. Effectiveness: Each step of the algorithm must be easily convertible into
program statements
Example
1. start
2. Read 2 numbers a,b
3. Compute sum = a+b
4. Print sum value
5. Stop
Algorithm for finding the average of 3 numbers
1. start
2. Read 3 numbers a,b,c
3. Compute sum = a+b+c
4. compute avg = sum/3
5. Print avg value
6. Stop
1. start
1. start
2. Read Celsius
3. f = 1.8*c+32;
4. Print f value
5. Stop
1. Start
2. read number
3. if number%2 is 0 then
Print number is even
4. Else
Print umber is odd
5. Stop
1. Start
2. read age
3. if age>=18 then
Print “eligible to vote”
4. Else
Print “not eligible to vote”
5. Stop
1. Start
2. I = 1;
3. Repeat
print i
i=i+1
Until I <=10
4. Stop
1. Start
2. I = 1;
3. Sum=0
4. Repeat
Sum = sum + i
i=i+1
Until I <=10
5. Print sum
6. Stop
FLOW CHART
1)Auxilary symbols
The auxiliary symbols shows the start and stop points, the order and sequence
of actions, and how one part of a flowchart is connected to another. These
auxiliary symbols are shown in fig:
Symbol Name
Application
Fig:Auxilary symbols
Terminal
Flow Lines
We use only one connector symbol, a circle with a number in it, to show
connectivity. It is used in the following situation
When we reach the end of a column or page, but our chart is not finished.
In this case, at the bottom of the flow we use a connector to show
that the flow continues at the top of the next column or page. This condition is
shown in following fig:
2)
Primary symbols
Sequence
a)Assignemnt
b)Input/Output
c)Module call
d)compound statement
a)Assignemnt Statement
Variable expression
b)Input/Output statement
c)Module-Call statement
The symbol used for a module call is a rectangle with two vertical bars inside.
The flowchart for called module must be somewhere else.
Unlike the sequence statements, conditional statements can cause the flow of
the program to change. They allow the execution of selected statements and the
skipping of other statements.
Two-way selection
A decision always has two branches. The statement in each branch can be null
or a compound statement.
Multiway selection
Advantages of flow chart
oval
Rectangle
Diamond
Pentagon
Printout
Example
Start
Read 3 Numbers
a,b,c
Compute sum
a+b+c
Compute avg
sum/3
Stop
‘C’ is a high –level programming language developed in 1972 by Dennis Ritchie at AT & T Bell
Laboratories
It was primarily developed for systems programming i.e. for designing operating systems ,
compilers etc
1. It is a robust language, whose rich set of built-in functions and operations can be used to
write any complex program
2. It is a middle level language because the ‘C’ compiler combines the capabilities of an
assembly language with the features of a high-level language and therefore it is well suited for
writing both system software and business packages.
3. ‘C’ Programs are efficient and fast
4. C is highly portable, that is c programs written for one computer can be run on another with
little (or) no modification.
5. ‘C’ Language is well suited for structured programming, thus requiring the user to think of a
problem in terms of function modules (or) blocks.
It was named ‘C’ because it is an offspring of BCPL (Basic Combined Programming Languages)
which was popularly called ‘B’ language.
Preprocessor Directives
Global Declarations
void main( )
Local declarations
Statements
} // end of main
Every C program is made of one or more preprocessor commands, a global declaration section ,
and one or more functions.
Preprocessor directives are special instructions to the preprocessor that tell it how to prepare
the program for compilation. One of the most important of the preprocessor commands used in
every program is include. The include command tells the preprocessor that we need
information from selected libraries known as header files.
Global declaration section comes at the beginning of the program. This declaration is visible to
the entire program.
The work of the program is carried out by its functions. A C program can contain many number
of functions but one and only one function must be named main. The main() is a special
function used by the C system to tell the computer where the program starts.Every program
must have exactly one main function. If we use more than one main function, the compiler
cannot understand which one marks the beginning of the program. Always the execution starts
from the main function.
All functions in a program, including main, are divided into two sections:
The declration section is at the beginning of the function. Declarations inside a function are
known as local declarations because they are visible only to the function that contains them.
The statement section follows the declaration section. It contains the instructions to the
computer, such as add two numbers. In C, these instructions are written in the form of
statements.
---------------------------------------------- 0 ------------------------------------------------
Example
#include <stdio.h>
int main(void)
printf(“Hello World”);
return 0;
Preprocessor commands
The preprocessor commands come at the beginning of a program. All preprocessor commands
start with a pound sign(#); Preprocessor commands can start in any column, but they
traditionally start in column1.
The preprocessor command #include <stdio.h> tells the compiler to include the standard
input/ouput library file in the program. We need this library file to print a message to the
terminal. Printing is one of the input/output processes identified in this library.
main
The executable part of the program begins with the function main, which is identified by the
function header shown below :
int says that the function will return an integer value to the operating system; main is the name
of the function and it has no parameters(here the parameter list is void).
The function main starts with an open brace ({) and terminates with a close brace (}). All the
statements between these two braces form the function body. The function body contains a set of
instructions to perform the given task.
In the above example with in the main there are two statements: one to print the message “Hello
World” and one to terminate the program.
The print statement uses a library function(printf) to do the actual writing to the monitor. To
invoke or execute this print function(printf) we must call it. All function call statements consist
of the name of the function (in this case printf) , followed by a parameter list (in thi case “Hello
World”)enclosed in parentheses. The \n at the end of the message tells the computer to go to the
next line in the output.
The last statement in the program, return 0, terminates the program and returns control to the
operarting system.
Comments :
Comments are used in the program to enhance its readability and understanding. They are
mainly used for documentation. A comment can be inserted any where in the program.
Comments are not executable statements and therefore anything between the comments is
ignored by the compiler. Since comments do not affect the execution speed and the size of a
compiled program, we should use them liberally in our programs.
The second format, the single line comment, uses two slashes (//) to identify a comment. This
format does not require an end- of-comment token; the end of line automatically ends the
comment. Programmers generally use this format for short comments.
Ex
1) Block comment :
It is a multi line comment used to comment several lines. It is also called as format block
comment
because it uses opening and closing comment tokens. A token is one or more symbols
understood by the compiler. The opening token is /* and the closing token is */ .Everything
between the opening and closing comment tokens is ignored by the compiler. The tokens can
start in any column, and they do not have to be on the same line. The only requirement is that
the opening token must precede the closing token.
Ex:
Although comments can appear anywhere in the program, they cannot be nested i.e we cannot
have comments inside comments. Once the compiler finds an opening token, it ignores
everything until it finds a closing token. Therefore, the opening token of the nested comment is
not recognized.
----------O-----------
Character set
The characters that can be used to form words, numbers and expressions depends upon the
computer on which the program is run. The characters in C are grouped into the following
categories:
1)Letters
Lowercase a----z
2)Digits
3)Special characters
4)White spaces
The compiler ignores white spaces unless they are a part of string constant. White spaces may
be used to separate words, but are prohibited between the characters of keywords and
identifiers.
C Tokens
In a C program the smallest individual units are known as C tokens. C has six types of tokens
shown in following fig. C programs are written using these tokens and syntax of the language.
Keywords
All keywords have fixed meanings and these meanings cannot be changed.
Keywords, also known as reserved words, include syntactical words, such as if and while.
static while
ANSI C Keywords
-----------------------------------------------------0----------------------------------------------------------
Identifiers
Identifiers refer to the names of variables, functions and arrays. These are user defined names
and each identified object in the computer is stored at a unique address.
3)First 63 charactes of an identifier are significant. But first eight characters are treated as
significant by many compilers
Example:
a $sum
student_name 2names
_anyname sum-salary
int_min int
C is case sensitive. This means that even though two identifiers are spelled the same, if the case
of each corresponding letter does not match, C thinks of them as different names. Under this
rule num, Num, NUM are three different identifiers.
--------0-----------
Variable
It is the name given to a memory location that may be used to store a data value.
A variable may take different values at different times during execution of a program.
A variable name may be chosen by the programmer in a meaningful way so as to reflect its
function (or) nature in the program . Eg: sum, avg , total etc.
Each variable in a program must be declared and defined. Declaration gives a symbolic name
and definition reserves memory for the variable.
Variable declaration:
After designing suitable variabe names, we must declare them to the compiler. Declaration does
two things:
data-type v1,v2,----------vn;
A variable’s data-type can be any one of the data types, such as character, integer or real. A
variable cannot be type void. v1,v2,--------vn are the names of variables. Variables are seperated
by commas. A declaration statement must end with a semicolon.
After declaring a variable define the variable by using assignment (=) operator as follows
An assignment statement implies that the value of the varialbe on the left of the ’equal ssign’ is
set equal to the value of the quantity on the right
We can initialize a variable at the same time that we declare it. This takes the following form
Many compilers display a warning message when a variable is accessed before it is initialized.
-----------------------------------0----------------------------------------------------------
Constants
Constants in C refer to fixed values that do not change during the execution of a program. Like
variables constants have a type. C supports several types of constants as illustrated in fig:
Integer constants
An integer constant refers to a sequence of digits. It should not contain a decimal point. There
are three types of integers namely
1) decimal integer,
2) octal integer and
3) hexadecimal integer.
An octal integer constant consists of any combination of digits from the set 0 through 7, with a
leading 0.
0X2,0X9F,0Xbcd,0x
Embedded spaces, commas and nondigital characters are not permitted between digits.
Examples of some invalid integer constatnts are 20,000 $100
Real constants
These numbers are shown in decimal notation, having a whole number followed by a decimal
point and the fractional part. It is possible to omit digits before the decimal point, or digits after
the decimal point, For example , the following are all valid real numbers
mantissa e exponent
The mantissa is either a real number expressed in decimal notation or an integer. The exponent
is an integer number with an optional plus or minus sign. The letter e separating the mantissa
and the exponent can be written in either lowercase or uppercase.
Exponential notation is useful for representing numbers that are either very large or very small
in magnitude. For example, 75000000 may be written as 7.5E7 or 75E6.
A single character constant contains a single character enclosed within a pair of single quote
marks. Examples of character constants are: ‘5’ ‘X’ ‘‘
The last constant is a blank space. Character constants have integer values known as ASCII
values. For example the following statement would print the number 97, the ASCII value of the
letter a.
printf(“%d”, ‘a’);
Printf(“%c”, 97);
a to z : 97-122
A to Z : 65 -90
String constants
A string constant is a sequence of characters enclosed in double quotes. The characters may be
letters, numbers, special characters and blank space. Some of the examples of string constants
are :
------------------------------------------------------0------------------------------------------------------
Data Types
Data type specifies the set of values and the type of data that can be stored in a variable.
They are
Integer (int)
Character (char)
void
1.Integral data type
Integral data types are used to store whole numbers and characters
Integers are whole numbers with a range of values supported by a particular machine
In order to provide some control over the range of numbers and storage space , C has 3 classes
of integer storage namely, short int, int and long int in both signed and unsigned forms.
Signed integers (+ve or _ve) use first bit for storing the sign of the number and remaining bits
for the magnitude of the number.
Unlike signed integers, unsigned integers use all the bits for the magnitude of the number and
are always positive.
The use of qualifier signed on integers is optional because the default declaration assumes a
signed number.
The qualifier signed or unsigned may be explicitly applied to char. The use of qualifier signed
is optional because the default declaration assumes a signed character.
Floating-point numbers are defined in C by the keywod float. float data type gives 6 digits of
precision after decimal point.
---------------------------------------0------------------------------------------------------
Input / output
There are number of input/output functions in C based on the data types. The I/O functions are
classified inot two types
The formatted I/O functions read and write all types of data values. They require conversion
symbol to identify the data type. Hence they can be used for both reading and writing of all data
values. The formatted functions return the values after execution. The return value is equal to
the number of variables successfully read/written.
The unformatted I/O functions only work with the character data type. They do not require
conversion symbol for identification of data types because they work only with the character
data type. There is no need to convert the data. In case, values of other data types are passed to
these functions, they are treated as the character data. The unformatted functions also return
values, but the return values of unformatted function is always the same.
In C, data is input to and output from a stream. A stream is a source of or destination for data. It
is associated with a physical device, such as terminal, or with a file stored in auxiliary memory.
A binary stream consists of a sequence of data vlues such as integer, real, or complex using their
memory representation.
A terminal(keyboard, monitor) can be associated only with a text stream because a keyboard
can only send a stream of characters into a program and a monitor can only display a sequence
of characters. A file on the other hand can be associated with a text or binary stream.
The printf function converts data stored in the program into a text stram for output to the
monitor;
The scanf function converts the text stream coming from the keyboard to data values and stores
them in program variables.
In other words, the printf and scanf functions are data to text stream and text stream to data
converters. Text streams often represent different data types such as ineger, real and Boolean.
The ouput formatting function is printf . 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. For example, an integer 234 stored in the
program is converted to a text stream of three numeric ASCII characters( ‘2’ , ‘3’ and ‘4’ ) and
then is sent to the monitor. What we see on the monitor is these three characters, not the integer
234.
The general format of printf statement is :
2)Format specifications that define the ouput format for display of each item.
The control string indicates how many arguments follow and what their types are. The
arguments arg1,arg2,--------argn are the variables whose values are formatted and printed
according to the specifications of the control string. The arguments should match in number,
order and type with the format specifications.
The conversion specification contains a start token(%), a conversion code, and upto four
optional modifiers.
Only the field-specification token(%) and the conversion code are required(mandatory).
Conversion codes are used to describe data types. Converison code to describe integer data
type is (d), floating point is (f) and character data type is (c) .
The size modifier is used to modify the type specified by the conversion code. There are four
different sizes: h,l(el), ll (el el) and L.
The h is used with the integer codes to indicate a short integer value.
The ll(el el) is used to indicate a long long integer value; and
Precision modifier specifies the number of decimal places to be printed (if a floating-point
number is being printed). The precision modifier has the fomat
.m
where m is the number of decimal digits. If no precision is specified, printf prints six decimal
positions.
Minimum width modifier is used to specify the minimum number of positions in the output. If
the data requires more space than specified width , then printf overrides the width. It is very
useful to align output in columns.
When both width and precision are used, the width must be large enough to contain
the integral value of the number, the decimal point, and the number of digits in the decimal
position.
The Flag modifier is used for four print modifications: justification, padding, sign and numeric
conversion variants.
Justification controls the placement of a value when it is shorter than the specified width.
Justification can be left or right. The default is right justification. To left justify a value, the flag is
set to minus(-).
Padding defines the character that fills the unused space when the value is smaller than the
print width. Character can be a space, any symbol or zero. If there is no flag defined for padding,
the unused width is filled with spaces.
Sign flag defines the use or absence of a sign in numeric value. We can specify one of three
formats: default formatting, print signed values, or prefix positive values with a leading space.
When the flag is set to plus(+), signs are printed for both positive and negative values.
If the flag is space, then positive numbers are printed with a leading space and negative
numbers with a minus sign.
printf never supplies a newline automatically and therefore multiple printf statements may be
used to build one line of output. A new line can be introduced with the help of a new line
character ‘\n’
23 z 4.100000
23 z 4.10
Input formatting function: scanf
The standard input formatting function in C is scanf. This function takes a text stream from the
keyboard, extracts and formats data from the stream according to a format control string, and
then stores the data in specified program variables.
Syntax
Like the control string for printf, the control string for scanf is enclosed in a set of quotation
marks and contains one or more conversin specifications that describe the data types and
indicate any special formatting rules and/or characters.
Conversion specification
Conversion specification contains a start token(%), a conversion code, and upto three optional
modifiers. Only the field specification token and(%) and the conversion code are required.
There is only one flag for input formatting, the assignment suppression flag(*). The assignment
suppression flag(*) tells scanf that the next input field is to be read but not stored. It is
discarded.
The following scanf statement reads an integer, a character, and a floating-point number from
the input stream. The character is discarded. The other fields are read, formatted, and stored.
Note that there is no matching address parameter for the data to be discarded.
The Maximum width modifier specifies the maximum number of characters that are to be read
for one format code. When a width specification is included, therefore, scanf reads until the
maximum number of characters have been processed or until scanf finds a whitespace character.
If scanf finds a whitespace character before the maximum is reached, it stops.
The size modifier is used to modify the type specified by the conversion code. There are four
different sizes: h,l(el), ll (el el) and L.
The h is used with the integer codes to indicate a short integer value.
The ll(el el) is used to indicate a long long integer value; and
The L is used with floating-point numbers to indicate a long double value.
Conversion codes are used to describe data types. Converison code to describe integer data
type is (d), floating point is (f) and character data type is (c) .
Input parameres
For every conversion specification there must be a matching variable in the address list. The
address list contains the address of the matching variable. Addresses are indicated by prefixing
the variable name with an ampersand (&). In C the ampersand is known as the address operator.
Using the address operator, if the variable name is price, then the address is &price.
The first conversion specification matches the first variable address, the second
conversin specification matches the second variable address, and so on. It is also very important
that the variable’s type match the conversion specification type.
---------------------------------------------0---------------------------------------------------------
C supports a rich set of built-in operators. An operator is a symbol that tells the computer to
perform certain mathematical or logical manipulations. Operators are used in programs to
manipulate data and variables.
Arithmetic operators.
Relational operators.
logical operators.
Assignment operators.
Bitwise operators.
Conditional operators.
Special operators.
1). Arithmetic operators
C provides all the basic arithmetic operators. These can operate on any built-in data type
allowed in C.These operators are used for numerical calculations (or) to perform arithmetic
operations like addition, subtraction etc.
Integer Arithmetic
When both the operands in a single arithmetic expression such as a+b are integers, the
expression is called an integer expression, and the operation is called integer arithmetic. Integer
arithmetic always yields an integer value.
During integer division, if both the operands are of the same sign, the result is truncated
towards zero. If one of them is negative, the direction of truncation is implementataion
dependent. Integer division truncates any fractional part.
The modulo division operator produces the remainder of an integer division. The modulo
division operator(%) cannot be used on floating point data.During modulo division, the sign of
the result is always the sign of the first operand(the dividend).
That is -14 % 3 = -2
-14 % -3 = -2
14 % 3 = 2
Program:
main ( )
Real Arithmetic
An arithmetic operation involving only real operands is called real arithmetic. A real operand
may assume values either in decimal or exponential notation. Sice floating point values are
rounded to the number of significant digits permissible, the final value is an approximation of
the correct result.
Mixed-mode arithmetic
When one of the operands is real and the other is integer, the expression is called a mixed-mode
arithmetic expression. If either operand is of the real type, then only the real operation is
performed and the result is always a real number. Thus
15/10.0 = 1.5
Where as 15/10 = 1
2)Relational operators :
Comparisions can be done with the help of relational operators. An expression such as
a < b or 1 < 20
20 < 10 is false
C supports six relational operators. These operators and their meanings are shown in table
== equal to a= =b 10 == 20 0
A simple relational expression contains only one relational operator and takes the following
form:
ae-1 and ae-2 are arithmetic expressions, which may be simple constants, variables, or
combination of them.
Given below are some examples of simple relational expressions and their values:
a+b = c+d TRUE only if the sum of values of a and b is equal to the sum of values of c and
d.
When arithmetic expressions are used on either side of a relational operator, the arithmetic
expressions will be evalueated first and then the result is compared. That is, arithmetic
operators have a higher priority over relational operators.
Relational expressions are used in decision statements such as if and while to decide the action
of a running program.
Among the six relational operators, each one is a complement of another operator.
== is complement of !=
Program
main ( )
{
Output
int a= 10, b = 20;
}
3. Logical Operators
|| ------ logical OR
The logical operators && and || are used when we want to test more than one condition and
make decisions .
An expression of this kind, which combines two or more relational expressions is termed as a
logical expression or a compound relational expression. Like a simple relational expression , a
logical expression also yields a value of one or zero according to the truth table shown below
T T T
T F F
F T F
F F F
Logical OR( || )
T T T
T F T
F T T
F F F
Logical NOT (!)
exp !(exp)
T F
F T
&& logical AND (a>b) && (a<c) (10>20) & & (10<30) 0
The logical expression a >b && x==10 is true only if a>b is true and x==10 is true. If either of
them are false, the expression is false.
main ( )
4. Assignment operators
Assignment operators are used to assign the result of an expression to a variable. In addition to
= , C has a set of shorthand assignment operators of the form
v op= exp;
Example : x += y; is equivalent tp x = x + y;
1. What appears on the left-hand side need not to be repeated and therefore it becomed easier
to write
Types
simple assignment
compound assignment
= Simple a=10
assignment
C allows two very useful operators increment and decrement operators ++ and --.
The operator ++ adds 1 to the operand, while - - subtracts 1. Both are unary operators and take
the following form:
We use the increment and decrement statements in for and while loops extensively.
While ++m and m++ mean the same thing when they form statements independently. They
behave differently when they are used in expressions on the right-hand side of an assignment
statement. Consider the following:
m = 5;
y = ++m;
In this case, the value of y and m would be 6. Suppose, if we rewrite the above statement as
m=5;
y = m++;
A prefix operator(ex: ++ m) first adds 1 to the operand and then the result is assigned to the
variable on left.
A postfix operator(ex: m ++) first assigns the value to the variable on the left hand and then
increments operand.
When postfix ++ (or --) is used with a variable in an expression, the expression is evaluated first
using the original value of the variable and then the variable is incremented ( or decremented)
by one.
When prefix ++ (or --) is used in an expression, the variable is incremented ( or decremented)
first and then the expression is evaluated using the new value of the variable.
main ( )
Program
{
main ( )
int a= 10, z;
{ Output
Output z= a++;
int a= 10, z; z=10
z=11
printf (“z= %d”,
z= ++a a = 11
a =11 z);
printf (“z= %d”, z); printf (“a=%d”,
} }
Program:
main ( )
main ( )
{
{
int a= 10, z;
int a= 10, z; Output
Output z= a--;
z= --a z=10
z=9
printf (“z= %d”,
printf (“z= %d”, z); a=9
a =9 z);
printf (“ a=%d”, a);
printf (“a=%d”,
a);
}
}
6. Bitwise Operators
Unlike other operators, bitwise operators operate on bits (i.e. on binary values of on operand).
Bitwise operators manipulate data at bit level. These operators are used for testing the bits or
shifting them right or left. Bitwise operators may not be applied to float or double.
Operator Description
| Bitwise OR
^ Bitwise XOR
~ One’s complement
The bitwise and(&) is a binary operator that requires two integral operands. It does a bit- by-bit
comparision between the two operands. The result of the comparision is 1 only when both bits
are 1; it is 0 otherwise.
Bitwise AND
a b A &b
0 0 0 8 4 2 1
0 1 0 a =12 1 1 0 0
1 0 0 b =10 1 0 1 0
eg: let a= 12, b=10
1 1 1 a &b 1 0 0 0
a&b = 8
Bitwise incluseive or operator
The bitwise or operator(|) is a binary operator that requires two integral operands. It does a bit-
by-bit comparision between the two operands. The result of the comparision is 0 if both
operands are 0; it is 1 otherwise.
Bitwise OR
8 4 2 1
a b a|b
a =12 1 1 0 0
0 0 0
b =10 1 0 1 0
0 1 1
a|b 1 0 1 0
1 0 1
1 1 1 a | b = 14 a|b
The bitwise exclusive or operator is a binary operator that requires two integral operands. It
does a bit-by-bit comparision between the two operands. The result of the comparision is 1 only
if one of the operands is 1; it is 0 if both operands’ bits are 0 or 1—that is, if they are both the
same.
Bitwise XOR
a b a ^b 8 4 2 1
0 0 0 a =12 1 1 0 0
0 1 1 b =10 1 0 1 0
1 0 1 a ^b 0 1 1 0
1 1 0
a^b=6
Program
main ( )
The one’s complement operator is a unary operator applied to an integral value. It complements
the bits in the operand. The result is 1 when the original bit is 0; it is 0 when the original bit is 1.
The bitwise shift left 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. With
this operator the leftmost digits are lost and zero digits are added on the right. If the value of a
variable is left shifted one time, then its value becomes double the original value.
32 16 8 4 2 1
a=10
1 0 1 0
a<<1 = 20
Bitwise Shift-Right operator
The bitwise shift right operator 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.
If the value of a variable is right shifted one time, then its value becomes half the original value
8 4 2 1
a=10
1 0 1 0
a>>1 0 Discard it
0 1 0 1
a>>1 = 5
Ones complement
8 4 2 1
a=5
1 0 1
~a
0 1 0
~a = 2
Program
main ( )
11
printf (“ %d”, a<<1);
7. Conditional operator (? :)
It is also called ternary operator and is available in C to construct conditional expressions of the
form
Syntax:
The operator (? :) works as follows: exp1 is evaluated first , if it is nonzero(true), then the
expression exp2 is evaluated and becomes the value of an expression. If exp1 is false, exp3 is
evaluated and its value becomes the value of the expression. Note that only one of the
expressions (either exp2 or exp3) is evaluatd. For example consider the following statements.
a = 10;
b = 15;
x = (a > b) ? a : b;
In this example x will be assigned the value of b. This can be achieved using the if --- else
statements as follows:
If ( a > b)
x = a;
else
x = b;
Program
main ( )
{ int z;
Output
1
z = (5>3) ? 1:0;
printf (“%d”,z);
8) special operators
C supports some special operators such as comma operator, ampersand operator(&), pointer
operator(*), size of operator, member selection operators( . and ->).
a) coma: ( , )
The comma operator can be used to link the related expressions together. A comma-linked list
of expressions are evaluated left to right and the value of right-most expression is the value of
the combined expression.
First assigns the value of 10 to x, then assigns 5 to y, and finally assigns 15 (i.e 10 + 5) to value .
Since comma operator has the lower precedence of all operators, the parentheses are necessary.
b) Address:(&)
C) Sizeof ( ) :
The sizeof is a compile time operator and, when used with an operand, it returns the number
of bytes the operand occupies. The operand may be a variable, a constant or a data type qualifier.
Examples:
m = sizeof(sum);
n = sizeof(long int);
k = sizeof(235L);
It is also used to to allocate memory space dynamically to variables during the execution of a
program.
Program:
main ( )
int a=10;
float b=20 ;
} a b
10 20.00
Out Put :
Adderss of a =1 2 3 4
-----------------------------------------o------------------------------------------------------------------
EXPRESSIONS
Expressions can be simple or complex. A simple expression contains only one operator. For
example 2+5 is a simple expression whose value is 7. Similarly, -a is a simple expression. A
complex expression contains more than one operator. An example of a complex expression is
2+5*7. An expression always reduces to a single value.
We can divide simple expressions into six categories based on the number of operands, relative
positions of the operand and operator, and the precedence of operator.
eg; z = 3+2*1
z=5
Types Expression
1. Primary expressions
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. A primary
expression is evaluated first in a complex expression.
Names
A name is any identifier for a variable, a function, or any other object in the language.
Literal constants
The second type of primary expression is the literal constant. A constant is a piece of data whose
value cannot be changed during the execution of the program.
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. This
includes any of the complex expressions when they are enclosed in parentheses. Thus, a
complex expression can be enclosed in parentheses to make it a primary expression.
Ex: (2 * 3 + 4) (a = 23 + b * 6)
2. Postifix expressions:
Psetfix expression consists of one operand followed by one operator. The operator will be after
the operands in a postfix expression
Postfix increment
In the postfix increment, the variable is increased by 1. Thus a++ results in the variable a being
increased by 1. The effect is same as a=a+1
Eg:
z=a++ ===> z= a
a = a+1
Postfix decrement
In the postfix decrement, the variable is decreased by 1. Thus a-- results in the variable a being
decreased by 1. The effect is same as a=a-1
Eg:
z=a-- ===> z= a
a = a-1
3. Prefix expressions
Prefix increment
In the prefix increment, the variable is increased by 1. Thus ++a results in the variable a being
increased by 1. The effect is same as a=a+1
z= a
Prefix decrement
In the prefix decrement, the variable is decreased by 1. Thus --a results in the variable a being
decreased by 1. The effect is same as a=a-1
Eg:
z=-- a ===> a= a - 1
z=a
4. unary expression:
A unary expression, like prefix expression, consist of one operator and one operand. The
operator comes before the operand.
Sizeof
The sizeof operator tells the size, in bytes, of a type or primary expression. We can use the sizeof
operator with the integer type as shown below.
sizeof(int)
It is also possible to find the size of primary expression. Here are two examples
Unary plus/minus
The unary plus operator does not change the value of the expression. If the expression’s value is
negative, it remains negative.; if the expression’s value is positive, it remains positive.
Thr unary minus operator changes the sign of a value algebraically.—that is to change it from
plus to minus or minus to plus.
Cast operator
The third unary operator is cast operator. The cast operator converts one expression type to
another. For example, to convert an integer to a real number, we would use the following unary
expression.
float (x )
5. Binary expression
It contains 2 operands and one operator. There are many binary expressions.
Multiplicative expressions:
Multiplicative expressions include the multiply, divide and modulus operators. These operators
have the highest priority among the binary operators and are therefore evaluated first among
them.
The result of a multiply operator (*) is the product of the two operands. The operands can be
any arithmetic type (integral or floating – point)
Ex: 10 * 3 // evaluates to 30
The result of a divide operator (/) depends on the type of the operands. If one or both operands
is a floating- point type, the result is a floating-point quotient. If both operands are integral type,
the result is the integral part of the quotient.
Ex: 10 / 3 // evaluates to 3
The modulus operator (%) divides the first operand by the second operand and returns the
remainder.
Both operands must be integral types and the operator returns the remainder as an integer type.
Ex: 10 % 3 // evaluates to 1
22.3 % 2 //error
Additive expressions:
In additive expressions, the second operand is added to or subtracted from the first operand.
The operands in additive expressions can be any arithmetic types (Integral or floating-point).
Additive operators have lower precedence than multiplicative operators, therefore they are
evaluated after multiplicative expressions.
Ex: 3 + 7 // evaluates to 10
3 – 7 // evaluates to -4
Assignment expressions
The assignment expression evaluates the operand on the right side of the operator (=) and
places its value in the variable on the left.
Simple assignment
Ex: a = 5 b= x + 1 I=I+1
Compound assignment
A compound assignment is a shorthand notation for a simple assignment. It requires that the
left operator be repeated as part of the right expression.
Ex: x *= 3 //evaluates to x = x * 3
6. Ternary expression
The operator (? :) works as follows: Exp1 is evaluated first , if it is nonzero(true), then the
expression Exp2 is evaluated and becomes the value of an expression. If Exp1 is false, Exp3 is
evaluated and its value becomes the value of the expression. Note that only one of the
expressions (either Exp2 or Exp3) is evaluatd. For example consider the following statements.
a = 10;
b = 15;
x = (a > b) ? a : b;
In this example x will be assigned the value of b. This can be achieved using the if --- else
statements as follows:
If ( a > b)
x = a;
else
x = b;
Precedence of operators refers to the order in which they are operated in a program. The
following table provides a list of the precedence of operators.
Operator Precedence Chart
+ Unary plus
- Unary minus
++ Increment
-- Decrement
! logical negation
Unary Operators right-to-left
~ ones complement
* Pointer reference
& address
/ division
% modulus
+ addition
- subtraction
== Equality
!= In equality
| Bitwise OR
^ Bitwise XOR
|| Logical OR
?: Conditional expression
*=
/=
%= Assignment operators
+=
-=
&=
^=
|=
<<=
>>=
, comma operator
Precedence rules decide the order in which different operators are applied.
Associativity rules decides the order in which multiple occurrences of the same level
operator are applied.
Expression Evaluation
Expressions are evaluated by the ‘C’ compiler based on precedence and associativity rules.
If an expression contains different priority operators then precedence rules are considered.
C = 30 - 10 * 2
2
2
1
3
Here, 10*2 is evaluated first since ‘*’ has more priority than ‘-‘ and ‘=’
If an expression contains same priority then assoiciativity rules are considered i.e. left right (or
right to left)
eg: z= a*b/c
z = 40 * 20 / 10
8
2
z
8
3
Here ‘*’ and ‘/’ have same priority so, left to right associativity is considered
Eg: x =5 *4 + 8/2 x = 5 * 4 + 8 / 2
1 2
x = 24
Parenthesis has highest priority and comma has least priority among operators
2) If parentheses are nested, the evaluation begins with the innermost sub-expression
4) The associativity rule is applied when two or more operators of the same precedence level
appear in a sub-expression
5) Arithmetic expressions are evaluated from left to right using the rules of precedence.
6) When parentheses are used, the expression within parentheses assumes highest priority
Converting one data type into another is the concept of type conversion.
C permits mixing of constants and variables of different types in an expression.
Thre are 2 type conversions
1. Implicit type conversion
2. Explicit type conversion
Implicit type conversion is automatically done by the compiler by converting smaller data type
into a larger data type. If the operands are of different data types, the lower type is automatically
converted to the higher type before the operation proceeds.
float f;
double d;
long int l;
x = l / i + i - f - d
long float
long float
float
Float
Double
int double
The sequence of rules that are applied while implicit type conversion is as follows:
1. if one of the operands is long double, the other will be converted to long double and the result
will be long double
2. else, if one of the operands is double, the other will be converted to double and the result will
be double.
3. else, if one of the operands is float, the other will be converted to float and the result will be
float.
4. else, if one of the operands is unsigned long int, the other will be converted to unsigned long
int and the result will be unsigned long int .
5. else, if one of the operands is long int, the other will be converted to long int and the result
will be long int .
6. . else, if one of the operands is unsigned int, the other will be converted to unsigned int and
the result will be unsigned int.
The final result of an expression is converted to the type of the variable on the left of the
assignment sign before assigning the value to it. However the following changes are introduced
during the final assignment.
Long int to int causes dropping of the excess higher order bits.
Explicit type conversion is done by the user by using (type) operator
Rather than let the compiler implicitly converts data, we can convert data from one type to
another ourself using explicit type conversion. Explicit type conversion uses the unary cast
operator.
To cast data from one type to another, we specify the new type in parentheses before the value
we want converted. For example to convert an integer, a, to a float, we code the expression
shown below.
(float)a
Note that in this operation, the value stored in a is still of type int, but the value of the expression
is promoted to float.
float b;
c = (int) a + b
int float
float
int
Here, the resultant of ‘a+b’ is converted into ‘int’ explicitty and then assigned to ‘c’
Program:
main ( )
{
Output
printf (“%d”, 5/2);
2
printf (“%f”, 5.5/2);
2.75
printf (“%f”, (float) 5/2);