computer programming unit-i -...
TRANSCRIPT
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 1
UNIT-I
Introduction to Programming: Computer system, components of a computer system,
computing environments, computer languages, creating and running programs, Algorithms,
flowcharts.
Introduction to C language: History of C, basic structure of C programs, process of compiling
and running a C program, C tokens, keywords, identifiers, constants, strings, special symbols,
variables, data types, I/O statements
INTRODUCTION TO PROGRAMMING
COMPUTER SYSTEM
Computer is an electronic device which operates under the control of instructions stored in its
own memory. A computer can take data from the user through input devices (Input), process the
user given data (Processing), produces the result to the user through output devices (Output)and
stores data (Information) for future use. Computer can be defined as follows...
Computer is an electronic device which operates under the control of instructions stored in
its own memory and it takes the data from the user, process that data, gives the result and
stores the result for future use.
COMPONENTS OF A COMPUTER SYSTEM
A computer is a system made up of two major components:
Computer Hardware.
Computer Software.
The following figure shows a computer system.
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 2
COMPUTER HARDWARE:
The computer hardware is the physical equipment. The hardware component of computer system
consists of 5 parts
1. Input Devices.
2. Central Processing Unit ( CPU ).
3. Primary Storage.
4. Output Devices.
5. Auxiliary Storage Devices.
The following figure shows the hardware components.
A. Input Devices: The input device is usually a keyboard where programs and data are entered in
to the computer. Other Input Devices : a touch screen , a mouse , a pen , an audio input unit.
B. Central Processing Unit ( CPU ): It is responsible for executing instructions such as arithmetic
calculations , comparisons among data and movement of data inside the system. Today‟s
computers may have one or more CPU‟s
C. Primary Storage: It is also known as main memory . It is a place where the programs and data
is stored temporarily during processing. The Data in primary storage is erased, when we turn off
a personal computer or when we log off from a time-sharing computer ( volatile ).
D. Output Devices: The output device is usually a monitor or a printer to show output. If the
output is shown on the monitor, it is a soft copy and if the output is printed on the printer, it is a
hard copy.
E. Auxiliary Storage Devices ( secondary storage devices ): It is used for both input and output.
It is also known as secondary storage. It is a place where the programs and data are stored
permanently. when we turn off the computer the programs and data remain in the secondary
storage, ready for the next time when we need them.
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 3
COMPUTER SOFTWARE:
Software is the collection of Programs ( instructions ) that allow the hardware to do its job.
They are two types of Computer Software.
A. System Software
B. Application Software
The following figure shows the Computer Software.
A. System Software:
System Software consists of programs that manage the hardware resources of a computer and
perform required information processing tasks.
These programs are divided in to three classes.
i. Operating System Software.
ii. System Support Software.
iii. System Development Software.
i. Operating System Software: It provides services such as a user interface, files and data base
access and interfaces to communication systems such as Internet protocols. The primary purpose
of this software is to keep the system operating in an efficient manner while allowing the users
access to the system.
ii. System Support Software : System Support Software provides system utilities and other
operating services. Examples of system utilities are sort programs and disk format programs.
Operating services consist of programs that provide performance statistics for the operational
staff and security monitors to protect the system and data.
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 4
iii. System Development Software: It includes language translators that convert programs in to
machine language for execution , debugging tools to ensure that programs are error - free and
computer -assisted software engineering ( CASE ) systems.
B. Application Software: It is directly responsible for helping users to solve their problems.
Application software is broken in to two classes.
i. General - Purpose Software
ii. Application - Specific Software
i. General Purpose Software: It is purchased from a software developer and can be used for
more than one application. Examples: word processors, database management systems,
computer–aided design systems. They are labeled general purpose because they can solve a
variety of user computing problems.
ii. Application Specific Software: It can be used only for its intended purpose. Example: A
general ledger system used by accountants.
They can be used only for the task for which they were designed. They can not be used for other
generalized tasks.
Relationship between system and application software is shown in the figure:
Each circle is an interface point. The inner core is hardware. The user is represented by the outer
layer. To work with the system , the typical user uses some form of application software. The
application software in turn interacts with operating system ( OS ), which is part of system
software layer. The System software provides the direct interaction with the hardware. The
opening at the bottom of the figure is the path followed by the user who interacts directly with
the Operating System when necessary.
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 5
COMPUTING ENVIRONMENTS
When we want to solve a problem using computer, the computer makes use of various devices
which work together to solve that problem. There may be various number of ways to solve a
problem. We use various number of computer devices arranged in different ways to solve
different problems. The arrangement of computer devices to solve a problem is said to be
computing environment. The formal definition of computing environment is as follows...
Computing Environment is a collection of computers which are used to process and exchange the
information to solve various types of computing problems.
Types of Computing Environments
The following are the various types of computing environments...
1. Personal Computing Environment
2. Time Sharing Computing Environment
3. Client Server Computing Environment
4. Distributed Computing Environment
5. Grid Computing Environment
6. Cluster Computing Environment
Personal Computing Environment
Personal computing is a stand alone machine. In personal computing environment, the complete
program resides on stand alone machine and executed from the same machine. Laptops, mobile
devices, printers, scanners and the computer systems we use at home, office are the examples for
personal computing environment.
Time Sharing Computing Environment
Time sharing computing environment is stand alone computer in which a single user can perform
multiple operations at a time by using multitasking operating system. Here the processor time is
divided among different tasks and this is called “Time sharing”. For example, a user can listen to
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 6
music while writing something in a text editor. Windows 95 and later versions of windows OS,
iOS and Linux operating systems are the examples for this computing environment.
Client Server Computing Environment
The client server environment contains two machines (Client machine and Server machine).
These both machines will exchange the information through an application. Here Client is a
normal computer like PC, Tablet, Mobile, etc., and Server is a powerful computer which stores
huge data and manages huge amount of file and emails, etc., In this environment, client requests
for data and server provides data to the client. In the client server environment, the
communication between client and server is performed using HTTP (Hyper Text Transfer
Protocol).
Distributed Computing Environment
In the distributed computing environment, the complete functionality of a software is not on
single computer but is distributed among multiple computers. Here we use a method of computer
processing in which different programs of an application run simultaneously on two or more
computers. These computers communicate with each other over a network to perform the
complete task. In distributed computing environment, the data is distributed among different
systems and that data is logically related to each other.
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 7
Grid Computing Environment
Grid computing is a collection of computers from different locations. All these computers work
for a common problem. A grid can be described as distributed collection of large number of
computers working for a single application.
Cluster Computing Environment
Cluster computing is a collection of inter connected computers. These computers work together
to solve a single problem. In cluster computing environment, a collection of systems work
together as a single system.
COMPUTER LANGUAGES
Generally, we use languages like english, hindi, telugu etc., to make communication between
two persons. That means, when we want to make communication between two persons we need
a language through which persons can express their feelings. Similarly, when we want to make
communication between user and computer or between two or more computers we need a
language through which user can give information to computer and vice versa. When user wants
to give any instruction to the computer the user needs a specific language and that language is
known as computer language.
User interacts with the computer using programs and that programs are created using computer
programming languages like C, C++, Java etc.,
Computer languages are the languages through which user can communicate with the
computer by writing program instructions.
Every computer programming language contains a set of predefined words and a set of rules
(syntax) that are used to create instructions of a program.
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 8
Computer Languages Classification
Over the years, computer languages have been evolved from Low Level to High Level
Languages. In the earliest days of computers, only Binary Language was used to write programs.
The computer languages are classified as follows...
Low Level Language (Machine Language)
Low Level language is the only language which can be understood by the computer. Binary
Language is an example of low level language. Low level language is also known as Machine
Language. The binary language contains only two symbols 1 & 0. All the instructions of binary
language are written in the form of binary numbers 1's & 0's. A computer can directly understand
the binary language. Machine language is also known as Machine Code.
As the CPU directly understands the binary language instructions, it does not requires any
translater. CPU directly starts executing the binary language instructions, and takes very less
time to execute the instructions as it does not requires any translation. Low level language is
considered as the First Generation Language (1GL).
Advantages
A computer can easily understand the low level language.
Low level language instructions are executed directly without any translation.
Low level language instructions require very less time for thier execution.
Disadvantages
Low level language instructions are very difficult to use and understand.
Low level language instructions are machine dependent, that means a program written for
a particular machine does not executes on other machine.
In low level language, there is more chance for errors and it is very difficult to find
errors, debug and modify.
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 9
Middle Level Language (Assembly Language)
Middle level language is a computer language in which the instructions are created using
symbols such as letters, digits and special characters. Assembly language is an example of
middle level language. In assembly language, we use predefined words called mnemonics.
Binary code instructions in low level language are replaced with mnemonics and operands in
middle level language. But computer can not understand mnemonics, so we use a translator
called Assembler to translate mnemonics into binary language. Assembler is a translator which
takes assembly code as input and produces machine code as output. That means, computer can
not understand middle level language, so it needs to be translated into low level language to
make it understandable by the computer. Assembler is used to translate middle level language to
low level language.
Advantages
Writing instructions in middle level language is easier than writing instructions in low
level language.
Middle level language is more readable compared to low level language.
Easy to understand, find errors and modify.
Disadvantages
Middle level language is specific to a particular machine architecture, that means it is
machine dependent.
Middle level language needs to be translated into low level language.
Middle level language executes slower compared to low level language.
High Level Language
High level language is a computer language which can be understood by the users. High level
language is very similar to the human languages and have a set of grammar rules that are used to
make instructions more easily. Every high level language have a set of predefined words known
as Keywords and a set of rules known as Syntax to create instructions. High level language is
more easier to understand for the users but the computer can not understand it. High level
language needs to be converted into low level language to make it understandable by the
computer. We use Compiler or interpretor to convert high level language to low level
language.
Languages like COBOL, FORTRAN, BASIC, C ,C++, JAVA etc., are the examples of high
level languages. All these programming languages use human understandable language like
english to write program instructions. These instructions are converted to low level language by
the compiler so that it can be understood by the computer.
Advantages
Writing instructions in high level language is more easier.
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 10
High level language is more readable and understandable.
The programs created using high level language runs on different machines with little
change or no change.
Easy to understand, create programs, find errors and modify.
Disadvantages
High level language needs to be translated to low level language.
High level language executes slower compared to middle and low level languages.
Understanding Computer Languages
The follwing figure provides few key points related to the computer languages.
CREATING AND RUNNING PROGRAMS
It is the job of programmer to write and test the program. The following are four steps for
creating and running programs:
A. Writing and Editing the Program.
B. Compiling the Program.
C. Linking the Program with the required library modules.
D. Executing the Program.
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 11
A. Writing and Editing Program : The Software to write programs is known as text editor. A
text editor helps us enter , change and store character data. Depending on the editor on our
system, it could be used to write letters, create reports or write programs.
Example : word processor.
The text editor could be generalized word processor, but every compiler comes with associated
text editor. Some of the features of editors are
Search : To locate and replace statements.
Copy , Paste : To copy and move statements.
Format : To set tabs to align text.
After the program is completed the program is saved in a file to disk. This file will be input to
the compiler, it is known as source file. The following figure shows the various steps in building
a C – program.
B. Compiling Programs: The code in a source file on the disk must be translated in to machine
language. This is the job of compiler which translates code in source file stored on disk in to
machine language. The C compiler is actually two separate programs: the preprocessor and the
translator. The preprocessor reads the source code and prepares it for the compiler. It scans
special instructions known as preprocessor commands. These commands tell the preprocessor to
take for special code libraries, make substitutions in the code. The result of preprocessing is
called translation unit. The translator reads the translation unit and writes resulting object module
to a file that can be combined with other precompiled units to form the final program. An object
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 12
module is the code in machine language. This module is not ready for execution because it does
not have the required C and other functions included.
C. Linking Programs: C programs are made up of many functions. Example: printf ( ) , cos ( )…
etc Their codes exists else where , they must be attached to our program. The linker assembles
all these functions , ours and the systems, in to a final executable program.
D. Executing Programs : Once our program has been linked, it is ready for execution. To execute
a program, we use operating system command, such as run to load the program in to main
memory and execute it. Getting program in to memory is the function of an Operating System
programs called loader. Loader locates the executable program and reads it in to memory. In a
typical program execution, the program reads data for processing, either from user or from file.
After the program processes the data, it prepares output. Data output can be to user‟s monitor or
to a file. When program has executed, Operating System removes the program from memory.
ALGORITHM
Algorithm is the step-by-step procedure for solving a problem. Algorithm is a recipe for finding
the right answer to a problem or to a complex problem by breaking down the problem into
smaller simple sub problems. An algorithm must possess the following properties:
1. Finiteness: An algorithm must terminate after finite number of steps. 2. Definiteness: Each step of the algorithm must be precisely and unambiguously stated.
3. Effectiveness: Each step must be simple and can be performed exactly in a finite amount
of time.
4. Generality: Algorithm should be complete in itself, so that it can be used to solve all problems of given type for any input data.
5. Input & Output: An algorithm must take zero, one or more quantities as input data and
gives one or more output values.
Advantages of Algorithms:
It provides the core solution to a given problem.the solution can be implemented on a
computer system using any programming language of user‟s choice.
It facilitates program development by acting as a design document or a blue print of a
given problem solution.
It ensures easy comprehension of a problem solution as compared to an equilavent
computer program.
It eases identification and removel of logical errors in a program.
It facilitates algorithm analysis to find out the most efficient solution to a given problem.
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 13
Dis advantages of Algorithms:
In large algorithms the flow of program control becomes difficult to track.
Algorithms lack visual representation of programming constructs like flowcharts; thus
understanding the logic becomes relatively difficult.
Example1 : Add two numbers.
Step 1: Start
Step 2: Read 2 numbers as A and B
Step 3: Add numbers A and B and store result in C
Step 4 : Display C
Step 5: Stop
Example2: Average of 3 numbers.
1. Start
2. Read the numbers a , b , c
3. Compute the sum and divide by 3
4. Store the result in variable d
5. Print value of d
6. End
Example3: Average of n inputted numbers.
1. Start
2. Read the number n
3. Initialize i to zero
4. Initialize sum to zero
5. If i is greater than n
6. Read a
7. Add a to sum
8. Go to step 5
9. Divide sum by n & store the result in avg
10. Print value of avg
11 . End
FLOWCHART
A flowchart is a visual representation of the sequence of steps for solving a problem . A
flowchart is a set of symbols that indicate various operations in the program. For every process ,
there is a corresponding symbol in the flowchart . Once an algorithm is written , its pictorial
representation can be done using flowchart symbols. In other words, a pictorial representation of
a textual algorithm is done using a flowchart.
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 14
A flowchart gives a pictorial representation of an algorithm.
The first flowchart is made by John Von Neumann in 1945.
It is a symbolic diagram of operations sequence, dataflow, control flow and processing
logic in information processing.
The symbols used are simple and easy to learn.
It is a very helpful tool for programmers and beginners.
Purpose of a Flowchart :
Provides Communication.
Provides an Overview.
Shows all elements and their relationships.
Quick method of showing Program flow.
Checks Program logic.
Facilitates Coding.
Provides Program revision.
Provides Program documentation.
Advantages of a Flowchart :
Flowchart is an important aid in the development of an algorithm itself.
Easier to Understand than a Program itself.
Independent of any particular programming language.
Proper documentation.
Proper debugging.
Easy and Clear presentation.
Limitations of a Flowchart :
Complex logic.
Drawing is time consuming.
Difficult to draw and remember.
Technical detail.
FLOWCHART SYMBOLS
i)Terminal:
The oval represents any terminal point in a program and generally contains such words as BEGIN, START, END or STOP.
ii) Input/Output:
The parallelogram represents the Input/Output function i.e. making data availiable for processing (input) or recording of the processed information (output). This step implies
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 15
obtaining a number from an Input device (say, the keyboard). iii) Process: The rectangle represents the processing operation. a process changes or moves data.
An assignment is normally represented by this symbol. iv)Flow direction: Lines or arrows represent the flow direction function – the flow of control. Normal flow direction is from left to right or from
v)Annotation: A broken line and bracket represent the annotation function – the addition of descriptive comments or explanatory notes for clarification of some statements.
vi)Decision making symbol:
The diamond represents a decision or switching type of operations that determines which of the alternative paths is to be followed.
vii) Connector: The circle represents a function in a flow line. It represents the continuation of the flow of steps when a flow chart continues to the next page.
viii) Pre-defined process: The double sided rectangle represents a named process that consists of one or more operations or programming steps that are specified elsewhere.
ix) Loops: Hexagon symbol represents loops.
//Flow chart for swapping two numbers
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 16
//Find the largest among two numbers.
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 17
INTRODUCTION TO C LANGUAGE
History of C
C is a programming language developed at AT&T‟s Bell Laboratories of USA in 1972. It
was designed and written by Dennis Ritchie.
By 1960, computer languages had come into existence, almost each for specific purpose.
Example, COBOL used for Commercial Applications, FORTRAN for Engineering and Scientific
Applications and so on. At this stage, people started thinking why not single language which a
program all possible applications. Therefore, a committee formed and came up with language
called ALGOL 60. It is too abstract, too general. So, it was not popular. A new language called
Combined Programming Language(CPL) was developed at Cambridge University. CPL turned
out to be so big, having so many features, that it was hard to learn and difficult to implement.
Basic Combined Programming Language(BCPL) aimed to solve this problem bring CPL
down to its basic good features. But unfortunately it turned out to be too less powerful and too
specific Around the same time a language called B was written by Ken Thompson at AT&T‟s
Bell Labs. Ritchie inherited the features of B and BCPL, add some of his own and developed C.
1. In 1967, Martin Richard developed a language called Basic Combined Programming
Language or BCPL.
2. Ken Thompson followed in 1970 with similar language called B.
3. B was used to develop the first version of Unix .
4. Finally in 1972, Dennis Ritchie developed C which took many concepts from ALGOL,
BCPL and B .
5. The 1972 version of C language is known as traditional C language.
6. In 1983, the American National standards Institute(ANSI) Began the definition of
standard for C.
7. In 1995, minor changes were made to the standard known as C95.
Applications of C
C is perfectly suited for both systems programming suited for both systems programming
and application programming. It is exclusively used for developing
General Applications
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 18
Database Systems
Spread Sheets
Graphic Packages
CAD/CAM applications
Word Processors
Scientific/Engineering applications
Advantages of C
The increasing popularity of C is probably due to its many desirable qualities.
C is general purpose structured programming language
C is robust language whose rich set of built in functions and operators can be used to
write any complex program.
It is well suited for writing both system software and application software.
Programs written in C are efficient and fast.
Several standard functions are available which can be used for developing programs
C is highly portable: This means that C programs written for 1 computer can be run on
another computer with little or no alterations.
C is Compact: Statements in C are short but very powerful. Several operators can be
combined together in just one statement.
C is fast: After writing the program, the program must be compiled and executed. The
time taken for compilation and execution in C is very less.
C is simple: C has the ability to extend itself. We can add our own functions to the C
library with the availability of a large number of functions. The programming task
becomes simple.
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 19
BASIC STRUCTURE OF C PROGRAMS
Documentation section:
This section consists of comment lines giving the name of the program, author
and many other details (It doesn‟t include any logic to implement or execute).
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.
Comments are of two types:
1. Single line comment (//): Comments are non executable code used to provide
documentation to programmer. Single line comment is used to comment out just
single line in the code. It is used to provide one liner description of line.
Note:
1. Single line comment can be placed anywhere.
2. Single line comment starts with //
3. Any symbol written after // are ignored by compiler.
Documentation section
Link section
Definition section
Global declaration section
main() {
Declarations
Execution part
}
Subsection
User defined Functions() { }
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 20
Example:
#include<stdio.h>
void main()
{
printf("Hello"); //Single Line Comment
printf("By");
2. Multi line comment (/* … */):
1. Multi line comment can be placed anywhere.
2. Multi line comment starts with /*
3. ends with */
4. Anything written between /* and */ are ignored by compiler.
Example:
#include<stdio.h>
void main()
{
printf("Hello");
/* Multi
Line
Comment
*/
printf("By");
}
Link section:
This section provides header files to the compiler each header files to the
compiler.
Each header file has the extension “.h”.
It should be included using”#include” directive.
Example: #include<stdio.h>
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 21
Definition section:
This section defines all symbolic constants.
This is started with “#define”
Example #define pi 3.14. If we define like this, whenever we write “pi” in the
program it takes the value 3.14.
Global declaration section:
There are some variables that are used in one or more functions, such variables
are called global variables.
This type of variables are declared in this section.
Note: this section must be declared outside of all the functions.
Main function:
Every C program must contain main function.
The execution of the program begins with main()
The program execution starts with‟{„ and ends with‟}‟
Every C program should contain only one main function.
It consists of two parts
Declaration part:
1. It declares all the variables that are used in the executable part.
2. In this section, initial values are also given to the variables.
Executable part:
1. It contains the statements which executes or provides the logic to
be implemented.
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 22
User defined functions:
If we declare any functions in the main function, the logic of that function should
be specified here.
Rules to write C program:
All C statements must end with a „;‟.
All C statements should be written in lower case letters. Upper case letters are only used
for symbolic constants.
C is case sensitive i.e., upper case and lowercase characters are different. Ex: IT , it
A comment can be split in to more than a line but comments cannot be nested
First C Program
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(})
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 23
Starting of C
Instead of straight-away learning how to write programs, we must first know what
alphabets, numbers and special symbols are used in C, then how using these constants, variables
and keywords are constructed and finally how are these combined to form an instruction A group
of instruction would be combined later on to form a program. This is illustrated as follows
Alphabets Keywords
Digits Identifiers Instructions Program
Special Symbols Variables
Constants
Note : Keywords, Identifiers, Variables, constants can also be termed as C Tokens.
C Character Set
A character denotes any alphabet, digit or special symbol used to represent information.
Following table shows the valid Alphabets, numbers and special symbols allowed in C
Alphabets A,B,…Z , a,b,…z
Digits 0,1,2,3,4,5,6,7,8,9
Special symbols ~!@#%^&*( )_ -+=| \{ } [ ] : ; “ ” „ ‟ < > . , ? /
C TOKENS
Each individual unit in a program line is called a token.
In C they are called C – tokens
They are classified into different types. They are
Keywords
Identifiers
Constants
Variables
Strings
Special symbols
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 24
Keywords or Reserved words:
These are the pre-defined tokens in C.
These are also called as reserved words.
Keywords are the words whose meaning has already been explained to the
compiler. The keywords are reserved words. The keywords cannot be used as
variable names.
There are 32 keywords in C language and they are as follows:
1. Auto 2. Break 3. Case 4. char 5. const 6. continue
7. default 8. do 9. double 10. else 11. enum 12. extern
13. float 14. for 15. goto 16. if 17. int 18. long
19. register 20. return 21. short 22. signed 23. sizeof 24. static
25. struct 26. switch 27. typedef 28. union 29. unsigned 30. void
31. volatile 32. while
Rules:
All keywords must be written in lower case letters
Blank spaces should not be allowed in between the keywords.
1.6 IDENTIFIERS
Identifiers allow us to name data and other objects in the program. Each identified object in the
computer is stored at a unique address. Without identifiers, we would have to know and use
objects addresses.
Different programming languages use different syntactical rules. Good identifier names
are descriptive but short. C allows names to be up to 63 characters long. If the names are longer
than 63 characters, then only the first 63 are used. Few rules of identifiers in C are as follows
1. First character must be alphabetic character or underscore.
2. Must contain only of alphabetic characters, digits or underscores.
3. First 63 characters of an identifier are significant.
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 25
4. Cannot duplicate a keyword.
C is case sensitive language. This means that even though two identifiers are spelled the
same, if the case of each corresponding letter doesn‟t match, C thinks of them as different
names. Under this rule num, Num, NUM are three different identifiers
1.7 DATA TYPES
A type defines a set of values and a set of operations that can be applied on those values.
The C language has defined set of types that can divided into four general categories:
void
Integral
floating-point
Derived
void
The void type designated by the keyword void, has no value and no operations.
Which mainly used with functions and pointers.
Valid Names Invalid Names
a //Valid but poor style $sum //$ is illegal
student _name 2names // First char is digit
_aSystemName Sum-salary // contains hyphen
_Bool //Boolean System Id stdt Nmber // Contains spaces
INT_MIN //System Defined Value int // keyword
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 26
Integral
The C language has three integral types: Boolean ,character and integer.
Integral types cannot contain fractional part; they are whole numbers 1. Boolean Data Type
a) With the release of C99, the C language incorporated a Boolean data type.
b) The Boolean type, is referred by keyword bool, range of bool is 0(false) and 1(true).
c) To support Boolean data type we should include header file stdbool.h
Ex : bool b=1;
2. Character Data Type
a) Character data type occupies 1 byte of memory. i.e. 8bits of memory is occupied.
b) Keyword used to represent character data type is char.
c) Range of char varies from -128 to 127.
d) Control string used for char is %c.
e) When printed using %d control string, corresponding ASCII number is printed.
3. Integer Data Type
An integer type is a number without fractional part.
C supports four different sizes of integer data type: short int, int, long int and long long int
Note: sizeof (short) ≤ sizeof (int) ≤ sizeof (long) ≤ sizeof (long long)
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 27
Floating Point
The C language recognizes three floating-pint types: real, imaginary and complex.
There is a standard library, float.h, for the floating point values
The real type values are always signed.
1. Real Type
The Real type holds values that consist of an integral and fractional part, such as 43.32.
The C language supports three different sizes of real types: float, double and long double.
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)
2. Imaginary Data Type
a) C defines an imaginary type. It is referred by keyword imaginary.
b) An imaginary number is used extensively in engineering and mathematics.
c) An imaginary number is a real number multiplied with the square root of -1.
d) The imaginary type can be float imaginary, double imaginary, long double imaginary.
e) Most C implementations do not support the imaginary type.
3. Complex Data Type
a) C defines complex data type, which is implemented by most compilers.
b) A complex number is a combination of both real and an imaginary number.
c) The complex type can be float complex, double complex, long double complex.
d) The size needs to be the same in both the real and the imaginary part.
e) To support complex data type we should include header file complex.h
Ex : double complex x = 3 + 4 * I;
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 28
1.8 VARIABLES
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.
Rules:
A variable length varies from compiler to compiler. Generally most of compilers support
up to 8 characters.
The first character in variable name must be an alphabet.
The variable should not be a keyword.
Variable name must be without spaces and no other special character except underscore (
_ ) is permitted.
Variable names may be combination of upper and lower characters. Ex. „suM‟ is not
same as „sum‟.
Ex: sum, total_sum, avg_2009 etc
Type Declaration Instruction
The variables must be declared before they are used in the program. Declaration provides
two things.
i) Compiler obtains variable name.
ii) It tells to the compiler data type of variable being declared and helps in allocating
memory
Syntax:
data_type variable_name;
Example
char ch; // Variable named „ch‟ of character data type is declared
int age; // variable named „age‟ of integer data type is declared
float salary; // variable named „salary‟ of float data type is declared
The variables can be assigned or initialized using an operation „=‟. The declaration and
initialization can also be done in same line.
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 29
Example: 1) int a; declaration of variable „a‟ of integer data type
a = 10; Initialization of variable „a‟
2) int a=10; declaration and initialization of variable „a‟
Note : Variables are not initialized automatically. When variables are defined, they usually
contain garbage values.
1.9 CONSTANTS
Constants are data values that cannot be changed during the execution of program.
Constant Representations
We use certain symbols to represent constants. They can be classified as follows
i) Boolean Constants
ii) Character Constants
iii) Integer Constants
iv) Real Constants
v) String Constants
Boolean Constants
A Boolean constants can take only two values. The values are true and false.
A Boolean value can have only one of the two values 0 (false) and 1 (true).
To use Boolean constants, we should include stdbool.h library.
Character Constants
A Character constant is either a single alphabet, a single digit or a single special symbol
enclosed within single inverted commas.
Maximum length of a character constant can be 1 character. Ex. „A‟, „5‟, „=‟
In addition to the character, we can also use a backslash(\) before the character.
The backslash is known as the escape character.
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 30
The escape character says that what follows is not the normal character but something
else.
Integer Constants
An integer constant must have at least one digit
It must not have a decimal point
It could be either positive or negative.
If no sign precedes an integer constant it is assumed to be positive.
No commas or blanks are allowed within an integer constant.
The allowable range for integer constants is -32768 to +32767.
Ex: 426, -7605, +782
Real Constants
Real constants often called as Floating Point constants. The real constants can be written
in two forms, Fractional form and Exponential form.
Rules for decimal form:
A real constant must have at least one digit.
It must have a decimal point.
It could be positive or negative. Default sign is positive.
No commas or blanks are allowed with in real constant.
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 31
Ex: 426.0, -32.76, +67.98
The exponential form of representation consists of two parts. The part appearing before
„e‟ is called mantissa, where as the part following „e‟ is called exponent.
Rules for exponential form:
The mantissa part and the exponential part should be separated by letter „e‟.
The mantissa part may be positive or negative. Default sign in positive.
Decimal point is allowed in the mantissa part.
The exponent part must have at least one digit which may be positive or negative. Default
sign in positive.
The decimal point is not allowed in the exponent part.
Range of real constants expressed in exponential form is -3.4e38 to 3.4e38
Ex: +3.2e5, 3.2e-5, -4e7, -5e-6
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.
String Constants
String constants are sequence of characters enclosed within a double quote marks.
The string may be combination of all kinds of symbols.
Ex. “Hell0”, “12345”, “a”, “a#5”
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 32
Coding Constants
We code constants in three ways in our programs. They are as follows :
(i) Literal Constants.
(ii) Defined Constants
(iii) Memory Constants
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.
Literals are coded as a part of statement.
Ex : 3x + y = 20 , here 3, 20 are called literal constants.
Defined Constants
A constant can be designated by using preprocessor command define.
The define command are placed at the beginning of the program, although they are legal
anywhere.
Ex: #define MAX 50
Considering above example, while the preprocessing is being performed, each defined name
MAX in the program is replaced by value 50.
Memory Constants
Memory constants use a C type qualifier const to indicate that the data cannot be
changed.
The format is
const data_type identifier = value;
ex : const int a = 10;
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 33
1.10 INPUT / OUTPUT
Stream
1. In C data is input to and output from a stream.
2. A stream is source of or destination for data.
3. 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.
4. 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.
5. 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
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);
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 34
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.
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.
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
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 35
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
width
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.
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
#include <stdio.h>
int main()
{
printf("%10s%10d%10c%10f\n\n", "hello", 7, 'a', 1.23);
printf("%-10s%-10d%-10c%-10f\n", "hello", 7, 'a', 1.23);
//padding
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 36
printf("%10s%010d%10c%010f\n\n", "hello", 7, 'a', 1.23);
//sign
printf("%10s%+10d%10c%+10f\n\n", "hello", -7, 'a', 1.23);
return 0;
}
OUTPUT
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);
Conversion Specification
1. There is no precision in an input conversion specification.
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 37
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
1.11 OPERATOR
An operator is a symbol which helps the user to give instruction to the computer to do a
certain mathematical or logical manipulations.
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.
1) Arithmetic Operators
C provides five arithmetic operators, they are
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
Example: Suppose m and n are integer variables whose values are 11 and 4 respectively
Expression Value
m + n 15 (11+4)
m – n 7 (11- 4)
m * n 44 (11 * 4)
m / n 2 (11/4)
m % n 3 (11%4)
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 38
If both operands represent integer quantities, the result of integer division is always integer, that
is the decimal part of the result is always truncated.
Example: Suppose a and b are floating variables whose values are 12.5 and 10.0 respectively
Expression Value
a + b 22.5 (12.5 + 10.0)
a - b 2.5 (12.5 – 10.0)
a * b 125.00 (12.5 * 10.0)
a / b 1.25 (12.5 / 10.0)
If both operands represent float quantities, the result of float division is always float. The
modulus operator cannot be used with float quantities.
Example: Suppose a and b are floating and integer variables respectively whose values are 14.5
and 10 respectively
Expression Value
a + b 24.5 (14.5 + 10)
a - b 4.5 (14.5 – 10)
a * b 145.0 (14.5 * 10)
a / b 1.45 (14.5 / 10)
If one operand represent integer quantity and other represent float quantity, the result is always
float. The modulus operand cannot be used with integer and float combination.
Precedence( Priority of operators)
* / % Higher Precedence --- They are applied from Left to Right
+ - Lower Precedence --- They are applied from Left to Right
Example : If a=10, b = 16 and c=5 then find the value of n if
n= a – b / 4 + c * 2 – 3 .
Solution : n = 10 – 16 / 4 + 5 * 2 – 3
Step1 n = 10 – 4 + 5 * 2 – 3
Step 2 n = 10 – 4 + 10 – 3
Step 3 n = 6 + 10 – 3
Step 4 n = 16 – 3
Step 5 n = 13
/*Program to demonstrate arithmetic operators */
#include <stdio.h>
void main()
{
int a , b;
printf("Enter two numbers :");
scanf("%d%d", &a, &b);
printf(" Sum = %d", (a+b));
printf(" Difference = %d", (a - b));
printf(" Product = %d", (a*b));
printf(" Division = %d", (a/b));
printf(" Modulus = %d",(a%b));
}
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 39
Output :
Enter two numbers : 25 10
Sum = 35 Difference = 15 Product = 250 Divison = 2 Modulus = 5
2) Relational Operators
C supports following 6 relational operators
Operator Meaning
> Greater than
> = Greater than or equal
< Lesser than
< = Lesser than or equal
= = Equal
! = Not Equal
Each of these relational operators require two operands and can be combined together to form
relational expressions, which represent conditions that are either true or false. The resulting
expressions are of type integer, since in C true is represented by integer value 1 and false is
represented by integer value 0.
Precedence of Operators
> >= < <= High Priority ---- The operator will be evaluated from Left to Right
== != Low Priority ---- The operator will be evaluated from Left to Right
Examples: Suppose a is an integer whose value is 10. b is floating variable whose value is 2.5
i.e. a= 10, b=2.5
Expression Value Explanation
a > 5 1 10>5 is true
(a + b) < 12 0 (10+2.5)<12 i.e. 12.5<12 is false
b * 6 >= a + b 1 2.5 * 6 >= 10+2.5 i.e. 15.0 >=12.5 is true
a / 5 <= b – a 0 10 / 5 <= 2.5 – 10.0 i.e. 2 <= -7.5 is false
a * a == 10 0 10 * 10 = =10 i.e. 100 == 10 is false
b + a != 5 1 2.5 + 10.0 != 5 i.e. 12.5 != 5 is true
/*Program to demonstrate relational operators*/
void main()
{
printf(“ 5>2 is %d”,5>2);
printf(“\n 5>=2 is %d”,5>=2);
printf(“\n 5<2 is %d”,5<2);
printf(“\n 5<=2 is %d”,5<=2);
printf(“\n 5==2 is %d”,5==2);
printf(“\n 5!=2 is %d”,5!=2);
}
Output
5>2 is 1
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 40
5>=2 is 1
5<2 is 0
5<=2 is 0
5 == 2 is 0
5 != 2 is 1
3) Logical Operators
In addition to the relational operators discussed, C supports three logical operators that
act upon logical expressions. These are
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Thus logical operators can be used to form more complex conditions that are either true or false.
&&(AND) Operator
1. Evaluates true when both the relational expression are true.
2. Evaluates false when any one of the relational expression is false.
The following is truth table for AND operator
Condition1 Condition2 Output
False (0) && False (0) = False (0)
False (0) && True (1) = False (0)
True (1) && False (0) = False (0)
True (1) && True (1) = True (1)
||(OR) Operator
1. Evaluates false when both the relational expression are false.
2. Evaluates true when any one of the relational expression is true.
The following is truth table for OR operator
Condition1 Condition2 Output
False (0) || False (0) = False (0)
False (0) || True (1) = True (1)
True (1) || False (0) = True (1)
True (1) || True (1) = True (1)
!(NOT) Operator
This is a unary operator that negates the value of a relational or logical expression.
1. Evaluates true when the relational expression is false.
2. Evaluates false when the relational expression is true.
Condition Output
! False (0) = True (1)
! True (1) = False (0)
Precedence of Operators
! High Priority ---- This operator evaluates from right to left
&& Medium Priority--- These operators evaluates from left to right
|| Low Priority ---- This operator evaluates from left to right.
Example : Suppose a is an integer variable whose value is 10, is a floating-point variable whose
value is 2.5 then
Expression Value Explanation
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 41
(a>b) &&(b>5) 0 (10>2.5) && (2.5>5) i.e. true && false = false
(a>b) || (b>5) 1 (10>2.5)|| (2.5>5) i.e. true || false = true
! (a>b) 0 (10>2.5) is true. i.e NOT true = false
4) Assignment Operator
Operator Meaning
= assign
+= add and assign
- = subtract and assign
* = multiply and assign
/ = divide and assign
These operators execute from right to left. The right side expression is evaluated and assigned to
left variable.
Example: Let a, b, c, d are integer variables whose values are 10, 12, 14, 16 respectively
Expression Output Explanation
x=10; --- Value „10‟ is assigned to variable „x‟
a+=10 20 a = a+ 10 i.e. 10+10 = 20
b - = 5 7 b = b – 5 i.e 12 – 5 = 7
c * = b 70 c = c * b i.e. 14 * 5 = 70
d / = 4 4 d = d / 4 i.e 16 / 4 = 4
/*Program to demonstrate usage of assignment operators*/
void main()
{
int a=7,b=5,c=2,d=3,e=60;
printf(“Before operation a=%d, b=%d, c=%d, d=%d, e=%d”,a,b,c,d,e);
a=10;
b+=a;
c-=a;
d*=b;
e/=b;
prinf(“\nAfter operation a=%d, b=%d, c=%d, d=%d, e=%d”,a,b,c,d,e);
}
Output
Before operation a=7, b=5, c=2, d=3, e=6
After operation a=10, b=15, c= - 8 , d=45, e=4
5.Increment and Decrement Operator
C includes two useful operators, which are generally not found in other computer
languages developed prior to C.
Operator Meaning
++ increment by 1
- - decrement by 1
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 42
To be precise
x = x+1 can be written as x++;
x = x – 1 can be written as x- -;
Example : If a = 5, then a++ =6 i.e. a= a+1 = 5+1
If a = 6, then a - - = 5 i.e. a = a – 1 = 6 – 1
Both the operators may either precede or follow the operand i.e.
x = x+1 can be written as x++ or ++x
x = x – 1 can be written as x - - or - - x
Here, x++ is known as post increment operator
++x is known as pre increment operator
x - - is known as post decrement operator
- - x is known as pre decrement operator.
The difference between pre- and post- fixing the operator is useful when if used in an
expression. When the operator precedes the operand, C performs the increment or decrement
before using the value of the operand.
Ex: If x =5 and y = + + x then y = 6 and x = 6
If x = 8 and y = - - x then y = 7 and x = 7
When the operator follows the operand, the value of operand is used before incrementing or
decrementing the operand value.
Ex: If x =5 and y = x + + then y = 5 and x = 6
If x = 8 and y = x - - then y = 8 and x = 7
1. /* Program to show the affect of increment operator as suffix */
#include <stdio.h>
void main()
{
int a, z, x = 10, y = 20;
z = x * y ++;
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 43
a= x*y;
printf(" z =%d, a = %d", z , a);
}
Output : z =200, a= 210
2. /*Program to show effect of increment operator as a prefix */
#include <stdio.h>
void main()
{
int a, z, x = 10, y = 20;
z = x * ++y ;
a= x * y;
printf(" z =%d, a = %d", z , a);
}
Output : z =210, a= 210
6.Bit wise Operator
C supports six bit wise operators. These operators can operate only on an integer
operands such as int, char, short, long int etc. These do not work with float operands like float,
double .
Operator Meaning
>> Right Shift
<< Left Shift
& Bitwise AND
| Bitwise OR
~ Ones Complement (Bitwise NOT)
^ Exclusive OR
Example: Let a, b are integer variables whose values are 8,3 respectively. Then
Representation of 8 is 0000 0000 0000 1000
Representation of 3 is 0000 0000 0000 0011
1) a >> b i.e. 8 >> 3 means right shift three bits in representation of 8
0000 0000 0000 0001
Therefore 8 >>3 = 1
2) a << b i.e. 8 << 3 means left shift three bits in representation of 8
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 44
0000 0000 0100 0000
Therefore 8 << 3 = 64
3) a & b i.e. 8 & 3
0000 0000 0000 1000 8
0000 0000 0000 0011 3
-------------------------------
0000 0000 0000 0000 8&3 = 1
4) a | b i.e. 8 | 3
0000 0000 0000 1000 8
0000 0000 0000 0011 3
---------------------------------
0000 0000 0000 1011 8 |3 = 11
5) a ^ b i.e. 8 ^ 3
0000 0000 0000 1000 8
0000 0000 0000 0011 3
--------------------------------
0000 0000 0000 1011 8 ^ 3 = 11
6) ~a i.e. ~8
0000 0000 0000 1000 8
1111 1111 1111 0111 ~8
7. Conditional Operator
C offers a ternary operator pair „ ? : ‟ that can be used to carry out simple conditional
operations. The syntax is as follows
expression 1 ? expression 2 : expression 3
where expression 1 is logical expression, while expression 2 and expression 3 can be constants,
identifiers or other complex expressions.
When a conditional operator is used, expression 1 is first evaluated. If expression 1 is
true then expression 2 is evaluated. If expression 1 is false then expression 3 is evaluated.
Example : (a> b) ? 5 : 10 If the expression a>b is true then output is 5 else output is 10
/* Program to find the largest of two numbers using conditional operator*/
#include<stdio.h>
void main()
{
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 45
int num1, num2, max,min;
printf(“Enter two numbers”);
scanf(“%d%d”,&num1, &num2);
max = (num1 >num2) ? num1 : num2;
printf(“\nLargest Number = %d”,max);
min = (num1 < num2) ? num1 : num2;
printf(“\nSmallest Number = %d”,min);
}
Output
Enter two numbers : 6 7
Largest Number = 7
Smallest Number = 6
8.Other Operators
a) Comma Operator (,)
The comma operator is used to separate two or more expressions. The comma operator
has the lowest priority among all the operators.
Example : a=10, b, c=a+b;
b) sizeof() operator
The sizeof() operator is used to find the size occupied by a particular data type. Sizeof()
is a function which takes a single parameter. It returns an integer value
Syntax : sizeof(data_type)
Ex : sizeof(int)
/*Program to illustrate usage of sizeof() operator */
void main()
{
printf(“ Integer = %d, Float = %d, Character = %d”,sizeof(int), sizeof(float), sizeof(char));
}
Output
Integer = 2, Float = 4, Character = 1
c) Unary Plus (+) and Unary Minus (-) Operators
„+‟ and „- ‟ can also be used with single operand. „+‟ is used to indicate positive sign. „-‟
is used to indicate negative sign.
Ex : +7 indicates positive 7
- 7 indicates negative 7
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 46
d) Address operator (&)
„&‟ symbol is termed as address operator. It is used in mostly used in scanf() statement.
The address operator is used to get the memory address location of an identifier.
Ex. &a indicates address of operator
/*Program to demonstrate usage of address operator*/
void main()
{
int a;
float b;
printf(“Address of a = %u”,&a);
printf(“Address of b = %u”,&b);
}
Output
Address of a = 65524
Address of b = 65520
1.12 EXPRESSIONS
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.
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 47
Primary Expression
A primary expression consists of only one operand with no operator. In C, the operand in
primary expression may be a name, a constant or a parenthesized expression. Primary expression
is evaluated first in a complex expression.
Name : A name is any identifier for a variable, a function or any other object in language.
a s12 price calc INT_MAX
Literal Constants : A constant is a piece of data whose value can‟t change during the execution
of the program.
5 123.98 „A‟ “Hai”
Parenthetical Expressions : 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.
(2 * 3 + 5) (a=10+b)
Postfix Expression
The postfix expression consists of one operand followed by one operator.
Syntax : operand operator
There are several postfix expressions. Few of them are function call, postfix increment and
postfix decrement.
Ex : printf(), a++, a- -
Function calls are postfix expressions. The function name is the operand and the operator is the
parentheses that follow the name. The parentheses may contain arguments or be empty. When
present, the arguments are part of the operators.
Note : ++, - - can be called as postfix operators when used in postfix expression
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 48
Prefix Expression
The prefix expression consists of one operator followed by one operand.
Syntax : operator operand
Examples for prefix expressions are prefix increment and prefix decrement.
Ex : ++a, - - a
Note : ++, - - can be called as prefix operators when used in prefix expression
Unary Expressions
The unary expression, like a prefix expression, consist of one operator and one operand.
Although prefix expressions and unary expressions look the same, they belong to different
expression categories because the prefix expression needs a variable as the operand while the
unary expression can have an expression or a variable as the operand.
Syntax : operator operand
Example for unary expressions are positive/negative sign, sizeof operator, Logical NOT
operator, etc
Ex : +5, -7, sizeof(int), !a, ~10, &c
Note : Unary Plus (+), Unary Minus ( -), Logical NOT (!), ones complement (~), address (&),
sizeof() are called as unary operators.
Binary Expressions
Binary expressions are the combinations of two operands and an operator in between
them.
Syntax : operator operand operator
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 49
Arithmetic expressions, relational expressions, logical and expression, logical OR expression,
assignment expression etc are examples of binary expressions
Ex. a+b, a – b, a * b, a/ b, a%b, a>b, a<b, a>=b, a<=b, a==b, a!=b, a&&b, a||b, a&b, a|b, a^b,
a<<b, a>>b, a=b, a+=b, a=-b, a*=b, a/=b, a%=b
Note : Addition(+), subtraction (-), multiplication (*), division (/), modulus (%), less than (<),
less than equal to (<=), greater than (>), greater than equal to (>=), equal to (==), not equal to
(!=), Bitwise AND (&), Bitwise OR (|), Bitwise XOR(^), Logical AND(&&), Logical OR(||),
assignment (=) are called binary operators.
Ternary Expression
Ternary Expression is an expression which consists of three operands and a pair of
operator. Condition expression is an example for ternary expression.
Ex: (a>b) ? a: b
Note : Conditional operator(?:) is called ternary operator
1.13 PRECEDENCE AND ASSOCIATIVITY
Precedence is used to determine the order in which different operators in a complex expression
are evaluated.
Ex: 2+3*4=(2+(3*4))=14
-b++=(-(b++))
Associativity is used to determine the order in which operators with the same precedence are
evaluated in a complex expression.
Precedence is applied before associativity to determine the order in which expressions are
evaluated.
Associativity can be left-to-right or right-to-left.
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 50
The following table determines the Precedence and associativity of operators.
Operators Operation Associativity Precedence
( )
[ ]
->
.
Function Call
Array expression
Structure Operator
Structure Operator
Left to Right
1
+
-
++
--
!
_
*
&
Unary Plus
Unary Minus
Increment
Decrement
Logical NOT
One‟s complement
Pointer Operator
Address Operator
Right to Left
2
*
/
%
Multiplication
Division
Modular Division
Left to Right
3
+
-
Addition
Subtraction
Left to Right 4
<<
>>
Left Shift
Right Shift
Left to Right 5
<
<=
>
>=
Less than
Less than or equal
Greater than
Greater than or equal
Left to Right
6
==
!=
Equality
Not Equality
Left to Right 7
& Bitwise AND Left to Right 8
^ Bitwise XOR Left to Right 9
| Bitwise OR Left to Right 10
&& Logical AND Left to Right 11
|| Logical OR Left to Right 12
? : Conditional Operator Right to Left 13
= += -= *= /= &= |=
^= <<= >>=
Assignment Operator Right to Left 14
, Comma Operator Left to Right 15
Side Effect
A side effect is an action that results from the evaluation of an expression. For example,
in an assignment, C first evaluates the expression on the right of the assignment operator and
then places the value in the left variable. Changing the value of the left variable is called side
effect.
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 51
Example expression without side effects
a * 4 + b / 2 – c * b
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
Example expression with side effects
- - a * (3 + b) / 2 – c ++ * b
Now look for example with side effects and parenthesized expressions.
Ex: --a * ( 3 + b ) / 2 – c++ * b
Assume a=3 b=4 c=5
Calculate the value of parenthesized expressions
--a * 7 / 2 – c++ * b
Evaluate postfix expression
--a * 7 / 2 – 5 * b
Evaluate prefix expression
2 * 7 / 2 – 5 * b
Now apply multiply and division
14 / 2 – 5*4
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
1.14 TYPE CONVERSION
If we write an expression that involves two different data types, to perform these
evaluations, one of the types must be converted. There are two types of type conversions.
a) Implicit Type Conversion
b) Explicit Type Conversion
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 52
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. For implicit type
conversion, C has several complicated rules.
In C, we can assign a rank to the integral and floating-point arithmetic types.
Example : bool (Rank 1), char (rank 2), int (rank 3), long (rank 4), float (long 5), double (rank 6)
Let us consider 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.
Promotion occurs if the right expression has lower rank. There is normally no problem with
promotion.
Example of promotions
char c= „A‟;
int i= 124;
double d = 345.236;
i = c; // value of i is 65
d = i; // value of d is 124.0
Demotion occurs if the right expression has higher rank. It may or may not create problems.
When an integer or a real is assigned to a variable of type character, the least significant byte of
the number is converted to a character and stored. When a real is stored in an integer, the fraction
part is dropped. However, if the integral part is larger than the maximum value that can be
stored, the results are invalid and unpredicatable.
Examples of demotions are
COMPUTER PROGRAMMING UNIT-I
Prepared by P. Madhuravani 53
char c = „A‟;
int k = 65;
c=k+1; //value of c is „b‟
Explicit Type Conversion
Rather than let the compiler implicitly convert data, we can convert data from one type to
another our self using explicit type conversion. Explicit conversion uses the unary cast operator,
which has a precedence of 14. To cast data from one type to another, we specify the new type in
parenthesis before the value.
Ex: (float) a/10 // converting the „a‟ to float data type
avg = (float) (sum/6) // converting the result value into float