You are on page 1of 50

C Programming

UNIT-I INTRODUCTION: Computer Systems


A computer is a programmable machine that receives input from input devices, stores and manipulates data using memory, storage medium and CPU, and provides output in a useful format using output devices. A computer is an electronic device, which executes software programs. It consists of 2 parts !ardware and "oftware. A computer is an electronic device used to process data. A computer can convert data into information that is useful to people. A complete computer system includes four distinct parts# o o o o !ardware "oftware $ata User

%he computer system includes not only the computer, but also any software and peripheral devices that are necessary to ma&e the computer to function. Computer "ystem is group of hardware components and associated software, designed and assembled to perform a specific function or group of functions. Computer "ystem is a programmable machine. %he two principal characteristics of a computer are# '. It responds to a specific set of instructions in a well defined manner. 2. It can execute a prerecorded list of instructions. All general purpose computers re(uire the following hardware components# '. Memory : )nables a computer to store, at least temporarily, data and programs. 2. Mass storage device: Allows a computer to permanently retain large amounts of data. Common mass storage devices include dis& drives and tape drives. *. Input device : Usually a &eyboard and mouse, the input device is the conduit through which data and instructions enter a computer. +. Output device : A display screen, printer, or other device that lets you see what the computer has accomplished. ,. Central processing unit (C U!: %he heart of the computer, this is the component that actually executes instructions.

'

C Programming

"igure #$#: %loc& diagram o' Computer In addition to these components, many others ma&e it possible for the basic components to wor& together efficiently. -or example, every computer re(uires a bus that transmits data from one part of the computer to another. Computers can be generally classified by si.e and power as follows, though there is considerable overlap# o ersonal computer : A small, single user computer based on a microprocessor. In addition to the microprocessor, a personal computer has a &eyboard for entering data, a monitor for displaying information, and a storage device for saving data. (or&station : A powerful, single user computer. A wor&station is li&e a personal computer, but it has a more powerful microprocessor and a higher (uality monitor. Minicomputer : A multi user computer capable of supporting from '/ to hundreds of users simultaneously. Main'rame : A powerful multi user computer capable of supporting many hundreds or thousands of users simultaneously. Supercomputer : An extremely fast computer that can perform hundreds of millions of instructions per second.

o o o o

%he computer processes input through input devices li&e mouse and &eyboard. %he computer displays output through output devices li&e color monitor and printer.

C Programming

Computer "ystem

!ardware

"oftware

"ystem "oftware

Application "oftware

Core Part 12perating "ystem3

0emaining Part 1Utility Programs3

"igure #$): Components o' Computer System

"igure #$*: +,stract vie- o' Computer System 4odern computers are electronic and digital. %he actual machinery wires, transistors, and circuits is called hardware5 the instructions and data are called software. Computer is a programmable device that performs mathematical calculations and logical operations, especially one that can process, store and retrieve large amounts of data very (uic&ly. Computer is )lectronic machine capable of performing calculations and other manipulations of various types of data, under the control of a stored set of instructions. %he machine itself is the hardware5 the instructions are the program or software.

C Programming

C.aracteristics o' Computer


#$ Speed Computer can perform million of billion of operations on the data in one second. )$ +rit.metical and /ogical Operations In arithmetic operations, it performs the addition, subtraction, multiplication and division on the numeric data. In logical operation it compares the numerical data as well as alphabetical data. *$ +ccuracy computer gives accurate output results provided that the correct input data and set of instructions are given to the computer. 0$ Relia,ility %he electronic components in modern computer have very low failure rate. %he modern computer can perform very complicated calculations without creating any problem and produces consistent 1reliable3 results. 1$ Storage A computer has internal storage 1memory3 as well as external or secondary storage. In secondary storage, a large amount of data and programs 1set of instructions3 can be stored for future use. 2$ Retrieving data and programs %he data and program stored on the storage media can be retrieved very (uic&ly for further processing. 3$ +utomation It controls automatically different devices attached with the computer. It executes automatically the program instructions one by one. 4$ 5ersatility 6ersatile means flexible. 4odern computer can perform different &ind of tas&s one by one of simultaneously. 6$Communications %oday computer is mostly used to exchange messages or data through computer networ&s all over the world. #7$Diligence A computer can continually wor& for hours without creating any error. It does not get tired rather it wor&s with same accuracy as well as speed as the first one. ##$ No "eelings Computer is an electronic machine. It has no feelings. computer can not ma&e such 7udgments on their own. %heir 7udgments are totally based on instructions given to them. #)$ Consistency People often have difficulty to repeat their instructions again and again. A computer will carry out the activity with the same way every time. #*$ recision +

C Programming Computers are not only fast and consistent but they also perform operations very accurately and precisely.

8ard-are Concepts
!ardware is the mechanical, magnetic, electronic, and electrical components ma&ing up a computer system. !ardware is the physical electronic components and mechanical parts that ma&e up a piece of computer e(uipment which we can see and touch. %he system unit (Cabin) is the actual computer5 everything else is called a peripheral device. %he computer8s system unit probably has at least one floppy dis& drive, and one C$ or $6$ drive, into which we can insert floppy dis&s and C$s. %here8s another dis& drive, called the hard dis& inside the system unit. !ardware is the physical electronic components and mechanical parts that ma&e up a piece of computer e(uipment. !ardware, in the computer world, refers to the physical components that ma&e up a computer system. '. 4otherboard 2. Central Processing Unit 1CPU3 *. 4emory +. Input $evices ,. 2utput $evices #$ Mot.er %oard %he motherboard serves to connect all of the parts of a computer together. %he CPU, memory, hard drives, optical drives, video card, sound card and other ports and expansion cards all connect to the motherboard directly or via cables. %he motherboard can be thought of as the 9bac& bone9 of the computer.

C Programming

"igure #$0: Mot.er %oard )$ Central rocessing Unit (C U! %he Central Processing Unit 1CPU3 is responsible for interpreting and executing most of the commands from the computer8s hardware and software. It is often called the 9brains9 of the computer. A CPU is a processing circuit that can calculate, store results and ma&es algorithmic decisions.

"igure #$1: Central rocessing Unit %he central processing unit 1C U3 is the portion of a computer system that carries out the instructions of a computer program, and is the primary element carrying out the computer8s functions. %he central processing unit carries out each instruction of the program in se(uence, to perform the basic arithmetical, logical, and input:output operations of the system. A control ,us is 1part of3 a computer bus, used by CPUs for communicating with other devices within the computer. ;hile the address bus carries the information on which device the

<

C Programming CPU is communicating with and the data ,us carries the actual data being processed, the control bus carries commands from the CPU and returns status signals from the devices %wo typical components of a CPU are the following#
'. 2.

%he arithmetic logic unit (ALU), which performs arithmetic and logical operations. %he control unit (CU), which extracts instructions from memory and decodes and executes them, and sends the necessary signals to the A=U to perform the operation needed.

*$ Memory %he 4emory unit of a computer is used to store data, instructions for processing data, intermediate results of processing and the final processed information. In general, 4emory can be classified into Primary 4emory 1internal3, "econdary 4emory 1)xternal3 and Internal Processor 4emory. *$# rimary Memory %he memory area in which all programs and data must reside before programs can be executed or data manipulated. *$#$# Random +ccess Memory (R+M! 0andom Access 4emory 10A43 is the ;or&ing or Primary or 4ain or Internal 4emory 1real storage3 in the computer. Additional 0A4 allows a computer to wor& with more information at the same time which can have a dramatic effect on total system performance. 0A4 is usually referred to as a computer8s 9memory9 meaning that it stores information that is used by running programs and applications. 0A4 is volatile i.e. As soon as the computer is shut off, whether intentionally or by an accidental power outage, every thing in 0A4 disappears.

"igure #$2: Random +ccess Memory

>

C Programming

*$#$) Read-Only Memory (ROM! %here is a type of memory that stores data without electrical current5 it is the ROM 1Read Only Memory3 or is sometimes called non-volatile memory as it is not erased when the system is switched off. %his type of memory lets you store the data needed to start up the computer.

"igure #$3: Read Only Memory $ifferent ROM type memories contain these essential start up data, i.e. %he %IOS (%asic Input Output System!: Program for controlling the system8s main input output interfaces, hence the name B O! ROM which is sometimes given to the read only memory chip of the mother board which hosts it. ?I2" is an essential component in computers, which is used for controlling hardware. It is a small software program, part of which is loaded in 024 1read only memory, which cannot be modified3. %he ,ootstrap loader# a program for loading 1random access3 memory into the operating system and launching it. %his generally see&s the operating system on the floppy drive then on the hard dis&, which allows the operating system to be launched from a system floppy dis& in the event of malfunction of the system installed on the hard dis&. %he CMOS (Complementary metal-o9ide-semiconductor! Setup is the screen displayed when the computer starts up and which is used to amend the system parameters. %he o-er-On Sel' Test 1"O!#3, a program that runs automatically when the system is booted, thus allowing the system to be tested 1this is why the system 9counts9 the 0A4 at start up3.

;hen a computer system is turned on or reset, the ?I2" does an inventory of the hardware found on the computer and carries out a test 1called OST for 9"ower-On !elf #est93 in order to verify that all of it is functioning properly.

%esting the processor 1CPU3 Chec&ing the ?I2" Chec&ing C42" configuration Initiali.ing the timer 1the internal cloc&3 Initiali.ing the $4A controller

C Programming

Chec&ing 0A4 and cache memory Installing all ?I2" functions Chec&ing all configurations 1such as the &eyboard, dis& drives, and hard drives3

*$) Secondary Memory "econdary memory is not directly accessible to the CPU. Input:output channels are used to access this non volatile memory. %his memory does not lose the data when the system is powered off. "econdary memory represents the external storage devices that are connected to the computer. Optical Disc Storage 2ptical $isc $rives use electromagnetic waves or laser light to read and write information to optical discs. %here are drives that only read while on the other hand some drives are also there that performs both reading and writing. %hese devices include C$, $6$ and ?lue ray $isc. Magnetic Tape Storage %he device that performs reading and writing of data on magnetic tapes is a tape drive. %apes can be cost effective while storing large amounts of data. %oday they are largely used for bac&ups and archives. 8ard Dis&s A !ard $is&s $rive 1!$$3 is a non volatile secondary storage device which stores digitally encoded data on the magnetic surface of it. Universal Serial %us (US%! drive U"? $rive or commonly &nown as Pen $rive is a removable storage device that is interfaced on the U"? port of a computer system. *$#$* Internal rocessor Memory %his 4emory is collection of Cache 4emory and CPU 0egisters. Cache 4emory is a component that transparently stores data such so that future re(uests for that data can be served faster. Cache memories are used for temporarily retaining data in order to achieve high speed read:write operations. CPU register 1or general purpose register3 is a small amount of storage available on the CPU whose contents can be accessed more (uic&ly than storage available elsewhere. Cache memory is extremely fast memory that is built into a computerAs central processing unit 1CPU3, or located next to it on a separate chip. %he CPU uses cache memory to store instructions that are repeatedly re(uired to run programs, improving overall system speed. %he advantage of cache memory is that the CPU does not have to use the motherboardAs system

C Programming bus for data transfer. ;henever data must be passed through the system bus, the data transfer speed slows to the motherboardAs capability.

"igure #$4: C U Registers 0$ Input Devices A device that allows the user of a system to enter information into computer system or a piece of computer hardware that allows a user to interact with a computer. :ey,oard Ceyboard is typewriter &eyboard, which uses an arrangement of buttons or &eys, to act as mechanical levers or electronic switches. A "tandard Ceyboard includes alphanumeric &eys 1alphabets and numbers3, function &eys 1-' to -'23, modifier &eys 1alt, shift and ctrl3, cursor movement &eys, spacebar, escape &ey, numeric &eypad and some special &eys such as Page Up, Page $own, !ome, )nd, Insert, $elete etc. Mouse 4ouse is a pointing device that functions by detecting two dimensional motion relative to its supporting surface. Physically, a mouse consists of an ob7ect held under one of the user8s hands, with one or more buttons. %he 4ouse allows the user to select elements on the screen, such as icons, tools and buttons, by pointing and clic&ing on them. In general, 4ouse consists of two buttons, a wheel at top and a ball at bottom. ;hen the ball moves, the cursor on the screen moves in the direction in which the ball rotates. %he left button is used to select the item and the right button is used to display the options. %he wheel is used to scroll down in a document or web page. Scanner

'/

C Programming "canner is an input device that converts documents and images as the digiti.ed images understandable by the computer system. %he digiti.ed images can be produced as blac& and white images, gray images or colored images. In case of colored images, an image is collection of dots with each dot representing a combination of red, green and blue colors varying in proportions. ;oystic& Doystic& is an input device consisting of a stic& that pivots on a base and reports its angle or direction to the device it is controlling. Doystic&s are often used to control video games, and usually have one or more push buttons whose state can also be read by the computer. Touc. screen %ouch screen is an electronic visual display that can detect the presence and location of a touch within the display area. %he term generally refers to touching the display of the device with a finger or hand. %he touch screen has two main attributes. -irst, it enables one to interact directly with what is displayed, rather than indirectly with a cursor controlled by a mouse or touchpad. "econdly, it lets one do so without re(uiring any intermediate device that would need to be held in the hand. 1$ Output Devices 2utput device is any piece of computer hardware e(uipment used to communicate the results of data processing carried out by an information processing system 1such as a computer3 to the outside world. %he data processed by the CPU or Processor is made available to the end user by the output devices. 2utput devices are things we use to get information 2U% of a computer. Monitor A monitor is the most commonly used output device that produces visual displays generated by the computer. %he monitor also &nown as "creen and is connected as an external device using cables or connected as a part of the CPU case. A 4onitor can be characteri.ed by its si.e and resolution. %he monitors can be classified as C0% 1cathode ray tube3 monitors or =C$ 1li(uid crystal display3 monitors. %he screen si.e of an approximately rectangular display is usually given as the distance between two opposite screen corners, that is, the diagonal of the rectangle. %he resolution of the screen is expressed as the number of picture elements or pixels on the screen. %he monitor with high resolution produces high (uality and clearer image. rinter Printer is a peripheral which produces a text and:or graphics3 of documents stored in electronic form, usually on physical print media such as paper or transparencies. %he printer is used to produce the hard copy of the electronic text displayed on the screen, in the form of paper sheets that can be used by the end user. %he printer is an external device that is connected to the

''

C Programming computer using cables. %he printer driver software is used to convert a document to a form understandable by the computer. %he performance of the printer is measured in terms of dots per inch 1$PI3 and pages per minute 1PP43. %he !igher $PI means the better (uality of the out and %he PP4 means the higher )fficiency of the printer. )g# $ot 4atrix, In&7et and =aser Printers. Spea&er "pea&er is an electro mechanical device the converts an electrical signal to sound. %hese are attached to computer as output devices, to produce audio output, such as warning sounds and Internet audios. %he audio drivers need to be installed in the computer to produce the audio output. 8eadp.ones !eadphones are a pair of small loudspea&ers, or less commonly a single spea&er, with a way of holding them close to a user8s ears and a means of connecting them to a signal source such as an audio amplifier, radio or C$ player. !eadphones can be used both with fixed e(uipment and with portable devices.

So't-are Concepts
Computer software, or 7ust software, is the collection of computer programs and related data that provides the instructions for the functioning of a computer to perform certain tas&s. Computer program is a se(uence of instructions written to perform a specified tas& for a computer. Instruction is a single operation of a processor. 9Instruction9 may be any representation of an element of an executable program. "oftware supports the functioning of computer system internally which cannot be seen and stored on "econdary 4emory. System so't-are "ystem software is computer so't-are designed to operate the computer .ard-are and to provide and maintain a platform for running application so't-are. System so't-are includes operating systems, which govern computing resources. System so't-are provides the basic 'unction for computer usage, which can be divided into operating system and support system. System so't-are helps run the computer hardware and computer system. System so't-are is responsible for managing variety of independent .ard-are<s, so that they can wor& together harmoniously. It includes a combination of the following#

'2

C Programming
o o o o o

$evice $rivers 2perating "ystem "ervers Utility Programs ;eb "ervers

rogramming so't-are Programming software usually provides tools to assist a programmer in writing computer programs, and software using different programming languages in a more convenient way. %he tools include#
o o o o o

compilers debuggers interpreters lin&ers text editors

An Integrated development environment 1I$)3 is a single application that attempts to manage all these functions. +pplication so't-are Application software, also &nown as an application, is computer software designed to help the user to perform singular or multiple related specific tas&s. A set of computer programs which wor& together to solve a particular problem or to be used for a particular user defined application. Application software includes end user applications of computers such as word processors or 6ideo games etc. Application is developed for some certain purpose, which either can be a certain program or a collection of some programs, such as a graphic browser or the data base management system. Using Application "oftwareAs, we are going to develop different applications depending upon end use re(uirements. %ypical applications include# o o o o o o o o o o Calculator video games (uantum chemistry and solid state physics software telecommunications databases educational software medical software Paint spreadsheet ;ord processing

'*

C Programming

+/=ORIT8M
De': - An Algorithm is a step by step process to solve a given problem. Algorithm is also &nown as Pseudo code. Algorithm is an effective method for solving a problem expressed as a finite se(uence of steps. )ach step in the Algorithm is &nown as an instruction. )ach algorithm is a list of well defined instructions for completing a tas&. An algorithm consists of a set of explicit and unambiguous finite steps which, when carried out for a given set of initial conditions, produce the corresponding output and terminate in a fixed amount of time. ?y unambiguity it is meant that each step should be defined precisely i.e., it should have only one meaning According to $.).Cnuth, a pioneer in the computer science discipline, an algorithm has five important features. i3 ii3 iii3 "initeness An algorithm terminates after a fixed number of steps. De'initeness )ach step of the algorithm is precisely defined, i.e., the actions to be carried out should be specified unambiguously. >''ectiveness All the operations used in the algorithm are basic 1division, multiplication, comparison, etc.3 and can be performed exactly in a fixed duration of time. '+

C Programming iv3 v3 Input Output An algorithm has certain precise inputs, i.e. (uantities, which are specified to it initially, before the execution of the algorithm begins. An algorithm has one or more outputs, that is, the results of operations which have a specified relation to the inputs.

=et us ta&e some example to illustrate all the features of an algorithm. >9ample #: +lgorit.m to 'ind sum o' t-o num,ers$ "tep '# "tart "tep 2# $efine a, b "tep 2# 0ead a, b "tep *# sumEaFb "tep +# Print the sum "tep ,# "top. +lgorit.m to 'ind -.et.er a num,er is even or odd$ "tep '# "tart "tep 2# $efine a "tep *# 0ead a "tep +# If aG2EE/ goto step , else goto step <. "tep ,# print )6)H5 goto step > "tep <# print 2$$ "tep ># "top. +lgorit.m to 'ind largest o' t.ree num,ers$ "tep ' # "tart "tep 2 # $efine A, ? and C "tep * # 0ead three numbers A, ? and C "tep + # If AI? goto step , else goto step @ "tep , # If AIC goto step < else goto step > "tep < # Print A is =arge , goto step '/ "tep > # Print C is =arge , goto step '/ "tep @ # If ?IC goto step B else goto step > "tep B # Print ? is =arge "tep '/# "top. +lgorit.m to 'ind "i,onacci Se?uence "tep ' # "tart "tep 2 # $efine aE/,bE',c,i,n "tep * # 0ead n "tep + # print a, b "tep , # i E* "tep < # If i J E n goto step > else goto step '2 "tep > # cEaFb "tep @ # print c "tep B # aEb, bEc "tep '/# iEiF'

>9ample ):

>9ample *:

>9ample 0:

',

C Programming "tep ''# If i J E n goto step > else goto step '2 "tep '2# "top +dvantages o' +lgorit.ms '. Provides detailed and most efficient solution to the given problem. 2. -acilitates program development by acting as design document for a given problem. *. )nsures easy understanding of a problem solution. +. "implifies the identification and removal of logical errors in the program. ,. Programmer or user understands the problem in easy and detailed manner as we are analy.ing problem in step by step process. Disadvantages o' +lgorit.ms '. In large algorithms, the flow of program control becomes difficult to understand. 2. =ac&s visual representation of programming structure. *. %oo many steps in the algorithm may confuse the programmer.

"/O(C8+RT
De': - -lowchart is a graphical or pictorial 0epresentation of algorithm or process. A flowchart is a type of diagram that represents an algorithm or process, showing the steps as boxes of various &inds, and their order by connecting these with arrows. %his diagrammatic representation can give a step by step solution to a given problem. $ata is represented in these boxes, and arrows connecting them represent flow : direction of flow of data. -lowcharts are used in analy.ing, designing, documenting or managing a process or program in various fields. A flowchart is a picture, which shows the se(uence in which data are read, Computations are performed, decisions are made and results are obtained. It ma&es use of the basic operations in programming. All symbols are connected among themselves to indicate the flow of information and processing.

Sym,ols
A typical flowchart will have the following &inds of symbols#

'<

C Programming Start and >nd (or! Terminals 0epresented as ovals or rounded rectangles, usually containing the word 9"tart9 or K?eginL and 9)nd9 or K"topL. . "lo- direction Arrow coming from one symbol and ending at another symbol represents that control passes to the symbol the arrow points to.

rocess (or! +ction 0ectangle represents the processing operation. A process changes or moves data. An assignment is normally represented by this symbol.

Input@Output 0epresented as parallelogram. %he parallelogram represents the Input:2utput function i.e. ma&ing data available for processing 1input3 or recording of the processed information 1output3.

Condition or Decision ma&ing 0epresented as $iamond or 0hombus. %hese typically contain a Mes:Ho (uestion or %rue:-alse test. %his symbol is uni(ue in that it has two arrows coming out of it, usually from the bottom point and right point, one corresponding to Mes or %rue, and one corresponding to Ho or -alse. %he arrows should always be labeled.

Connector %he circle represents a function in a flow line.

'>

C Programming

+nnotation A bro&en line and brac&et represent the annotation function N the addition of descriptive comments or explanatory notes for clarification of some statements.

"lo-c.art Design Rules '. 2. *. +. ,. <. >. 4ust begin with "%A0% and end with "%2P symbol. "tandard process flow should be either from top to bottom or left to right. Instructions specified in the flowchart should be clear and concise. Arrows must be aligned properly so as to clearly describe the flow of program control. Use of excess connectors should be avoided as they ma&e the flowchart complex. Process or Action symbol must have only one input arrow and one output arrow. %wo arrows must never intersect or cross each other. if such need arises, use appropriate ?ridge or Crossover symbols. @. Condition symbol should have one input arrow and can have maximum of two output Arrows.

+dvantages '. Communication# -lowcharts are better way of communicating the logic of a system to all concerned. 2. )ffective analysis# ;ith the help of flowchart, problem can be analysed in more effective way. *. Proper documentation# Program flowcharts serve as a good program documentation, which is needed for various purposes. +. )fficient Coding# %he flowcharts act as a guide or blueprint during the systems analysis and program development phase. ,. Proper $ebugging# %he flowchart helps in debugging process. <. )fficient Program 4aintenance# %he maintenance of operating program becomes easy with the help of flowchart. It helps the programmer to put efforts more efficiently on that part /imitations '. Complex logic# "ometimes, the program logic is (uite complicated. In that case, flowchart becomes complex and clumsy. 2. Alterations and 4odifications# If alterations are re(uired the flowchart may re(uire re drawing completely. *. 0eproduction# As the flowchart symbols cannot be typed, reproduction of flowchart becomes a problem. +. %he essentials of what is done can easily be lost in the technical details of how it is done.

'@

C Programming

Computer /anguages
Computer =anguage is a language which used in communication with computer. Mac.ine /anguage o 4achine language is collection of binary digits 1/,'3 that the computer reads and interprets. o 4achine language is a system of instructions and data executed directly by processor. o Also &nown as 4achine code or 2b7ect code. o Cnown as -irst generation language and ?elongs to category of =ow =evel =anguage. o 4achine =anguage is a computer language that is directly executable by a computer without the need for translation by a compiler or an assembler. o 4achine language is the only language that can be understood by computer and are almost impossible for humans to use because they consist entirely of numbers. "ig #$6: 8ierarc.y o' Computer /anguages /imitations

'B

C Programming '. ItAs difficult to understand and remember the various combinations of /As and 'As representing data and instructions. 2. "ince every machine has its own machine language, the user cannot communicate with other computers. +dvantages '. 2. *. +. 4ost efficient in terms of storage area use. 4ost efficient in terms of execution speed Allows programmer to utili.e the computer8s potential for processing data. Ho need of Interpreter, Compiler or Assembler.

+ssem,ly@Sym,olic /anguage o Assembly language is a language where /A' and 'As of machine language are replaced with some mnemonic codes or abbreviations. o Cnown as "econd generation language and ?elongs to category of =ow =evel =anguage. o Assembly =anguage contains the source code of programs is composed of mnemonic instructions, each of which corresponds directly to a machine instruction for a particular processor. o It implements a symbolic representation of the binary machine codes and other constants needed to program a given CPU architecture. o %he mnemonic code is called the operation code or opcode, which specifies the operation to be performed on the given data. o )xample opcodes are 426, =$A, C4A, IHC, A$$, "%A, !=%, "U?, $I-, )H$ etc. o An +ssem,ler is a utility program that ta&es basic computer instructions in Assembly =anguage and converts them into a pattern of bits i.e. 4achine =anguage 1binary digits3 that the computer8s processor can use to perform its basic operations. o "ource code and ob7ect code refer to the 9before9 and 9after9 versions of a computer program that is compiled before it is ready to run in a computer. +dvantages '. ;e can identify syntax errors and debug easily. 2. ItAs easier to develop computer application in comparison to machine language. 8ig.-level languages o !igh level programming language is a programming language with strong abstraction from the details of the computer. o !igh level language isolates the execution semantics of computer architecture from the specification of the program.

2/

C Programming o !igh level language refers to the higher level of abstraction from machine language. o 0ather than dealing with registers, memory addresses and call stac&s, high level languages deal with variables, arrays, ob7ects, complex arithmetic or ?oolean expressions, subroutines and functions, loops, threads, loc&s, and other abstract computer science concepts, with a focus on usability over optimal program efficiency. Advantages '. User friendly 2. "impler and understandable with respect to a low level language. !igh level languages can be classified into three categories. '. Procedure 2riented =anguages 2. Problem 2riented =anguages *. Hatural =anguages #$ rocedure-Oriented /anguages o $esigned to solve general purpose problems and to develop domain specific applications. o $esigned to express logic and procedure for a given problem. o Also &nown as %hird generation languages 1*O3. o Uses )nglish li&e commands. o "yntax of these programming languages are different. o 4ain advantage is portability. o ;e can use compiler or interpreter to create the 2b7ect code. o )xamples are ?A"IC,C2?2=,-20%02H,C,CFF and Dava )$ ro,lem-Oriented /anguages Used to solve specific problems. Also &nown as -ourth generation languages 1+O3. Includes Puery languages, 0eport and Application generators. )nglish li&e "yntax rules. 0educed programming effort and overall cost of software development. "ingle statement in +O can perform same tas& as multiple lines of *O. Uses 6isual or %ext environment for program development 7ust li&e *O. Programmer Dust need to drag and drop from toolbar to create buttons, text boxes and labels etc. o Programmer can (uic&ly create the prototype of software application. o Provides ;M"I;MO 1;hat Mou "ee Is ;hat Mou Oet3 environment. o -aster, Convenient and -lexible application development for the user. o o o o o o o o

2'

C Programming o )xamples are "P=, 4A%=A?, P=:"P=, Audit Command =anguage, -lash etc. *$ Natural /anguages $esigned to ma&e a computer behave li&e an expert and solve problems. Also &nown as -ifth generation languages 1,O3. Programmer 7ust need to specify the problem and constraints for problem solving. Ho need to specify the method to solve problem. =I"P 1=ist Processing3 and P02=2O 1=ogic Programming3 are mainly used to develop Artificial and expert systems. o Allows the user to communicate with the computer in easy and simple manner. o Programmers can use normal )nglish words while interacting with the computer. o )xamples are =I"P, P02=2O, AI, Heural Hetwor&s, Image Processing etc o o o o o

Execution models %here are three models of execution for modern high level languages# Interpreted Interpreted languages are read and then executed directly, with no compilation stage. 0eads human readable code, line at a time, and produces and executes machine instructions. An interpreter must read its input program line by line or instruction by instruction to compute the results, but a compiler translates it only once. Compiled Compiled languages are transformed into an executable form before running. Compiler will translate a computer program into machine code that executes at a later time. Compiler ma&es the conversion 7ust once, while an interpreter typically converts it every time a program is executed. %here are two types of compilation# $% Ma&hine &ode 'eneration 22

C Programming "ome compilers compile source code directly into machine code. %his is the original mode of compilation, and languages that are directly and completely transformed to machine native code in this way may be called 9truly compiled9 languages. 2. ntermediate representations ;hen a language is compiled to an intermediate representation, that representation can be optimi.ed or saved for later execution without the need to re read the source file. Translated A language may be translated into a low level programming language for which native code compilers are already widely available. %he C programming language is a common target for such translators.

RO=R+M D>5>/O M>NT ST> S


Program is combination of instructions and data. %he steps involved in a program development are# #$ ro,lem Speci'ication %his step involves analy.ing the inputs provided, (uestions as&ed and output specifications of the problem are specified. )$ Outlining t.e Solution ;hen once the problem is clear, there may be several methods to have a solution. %he choice is made based on time consumed and how far it is error free. *$ +lgorit.m %he solution method is described step by step here. %he step by step procedure of the solution is an algorithm. "o, an algorithm for the solution method is developed. 0$ "lo-c.art %he algorithm prepared above has to be converted into pictorial representation for better understandability of the solution. 1$ Coding

2*

C Programming Coding is the process of creating, writing, editing, lin&ing, compiling, debugging, executing and maintaining computer code. Coding is the )xecutable art of program. )xecuting a program involves following steps. '. Creating the program 2. Compiling the program *. =in&ing the program with library functions +. )xecuting the program Creating t.e program 2nce we load 2perating "ystem into the memory, the computer is ready to receive the program. %he program must be entered into the file and file name must be valid and all files should be saved with K.cL extension. Compiling t.e program "ource program instructions are now translated into a form that is suitable for execution by the computer. Compiler will examine each instruction for itAs correctness and if there are no errors, 2b7ect code or 4achine code will be created. /in&ing t.e program -it. li,rary 'unctions =in&ing is the process of putting together other program files and functions that are re(uired by the program. >9ecuting t.e program %he )xecutable ob7ect code will be loaded into memory and executes the instructions. $uring execution, %he program may re(uest some data from &eyboard. In case of source program is modified, the entire process of compiling, lin&ing and executing should be repeated till we get correct result. 2$ Testing %esting is the process of finding the errors or bugs and assurance of software (uality. )rrors are of mainly two types. Synta9 errors or Compile-time errors )rrors in syntax 1grammar3 of the program. )rror message is displayed by the compiler while executing the program. "yntax errors are code errors. )x# missing semicolon Semantic or /ogical >rrors or Run-time errors )rrors in the meaning and =ogic of the program. ;e get wrong outputs. Compiler cannot identify these &ind of errors. )x# divide by .ero %o remove such errors we re(uire %esting and testing can be performed in two ways.. %lac& %o9 Testing %he functionalities involved in the program are tested here. )g# calculations, input testing, error handling etc. (.ite %o9 Testing %his testing mainly concentrates on the control structure of the program. )g# path testing, condition testing etc. 3$ De,ugging

2+

C Programming Process of deleting and removing errors is called debugging. $ebugging is a methodical process of finding and reducing the number of bugs, or defects, in a computer program. 4$ Documentation $ocumentation is the information that explains the usage as well as functionality of the software and meant for future reference. Operational Documentation It provides the information regarding the input and output formats, operating instructions, different &inds of user interaction with the program and limitations if any. Tec.nical Documentation It provides the technical details including the design aspects and brief explanation of the procedures involved, hardware to be operated. 6$ Maintenance "oftware maintenance is the modification of a software product after delivery to correct faults, to improve performance or to adapt the product to a modified environment. er'ective maintenance is any modification of a software product after delivery to improve performance or maintainability. Corrective maintenance is the reactive modification of a software product performed after delivery to correct discovered faults. +daptive maintenance is the modification of a software product performed after delivery to &eep a computer program usable in a changed or changing environment. reventive maintenance refers to software modifications performed for the purpose of preventing problems before they occur.

"ystem 0eady

Program Code

)nter Program "ource program )dit "ource Program

C Compiler

Compile "ource Program

"ystem =ibrary

"ynta x )rror s =in& with "ystem =ibrary

Mes

2,

C Programming

Ho

2b7ect code

)xecutable 2b7ect code Input $ata )xecute 2b7ect Code

=ogic and $ata )rror $ata )rrors Ho Correct 2utput

Mes =ogic )rror

"%2P "igure #$#7: rogram Development cycle

INTRODUCTION TO C
%he programming language C was developed in 'B>2 by $ennis 0itchie at A% Q % ?ell =aboratories, U"A. %his was derived from a language called ?, which was developed by Cen %hompson in 'B>/. %he language ? was derived from an existing language ?CP= 1?asic Combined Programming =anguage3 which was developed by 4artin 0ichards in 'B<>. A=O2= 1Algorithmic =anguage3 1?y International Committee, 'B</3

CP= 1Combined Programming =anguage3 1?y Cambridge and =ondon Universities, 'B<*3

?CP= 1?asic Combined Programming =anguage3 1?y 4artin 0ichards,'B<>3

2<

C Programming

? 1?y Cen %hompson, 'B>/3

C 1?y $ennis 0itchie, 'B>23 C.aracteristics o' C /anguage: o "tructured programming and high level language i.e., a C program can be divided into multiple bloc&s where each bloc& represents a function. o "uitable for developing both application software as well as system software. o It has wide variety of derived data types li&e arrays, structures, pointers and unions apart from fundamental data types li&e integers, floating point numbers and characters o !ighly portable language. i.e., programs written in one machine can be easily run on some other machine without any modifications. o -ast execution of programs when compared to other languages. o Provides a rich set of built in functions and also has the ability to extend itself by defining own functions. o 6ariables may be hidden in nested bloc&s o C is Case "ensitive =anguage. o Complex functionality such as I:2, string manipulation, and mathematical functions consistently delegated to library routines o A relatively small set of reserved &eywords o A large number of compound operators, such as FE, E, RE, FF etc. o =ow level 1?itwise3 programming readily available. o Pointer implementation extensive use of pointers for memory, array, structures and functions. o C re(uires a semicolon at the end of every statement. STRUCTUR> O" C RO=R+M C Program can be viewed as a group of building bloc&s called functions. A -unction is a single instruction or set of instructions designed to perform specific tas&. A -unction is a subroutine that may include one or more statements or instructions designed to perform a specific tas&. SCA Program contains the following sections. $ocumentation "ection =in& "ection

2>

C Programming $efinition "ection Olobal $eclaration "ection main13 function "ection "ubprogram "ection

"igure #$##: Structure o' C rogram Documentation Section It consists of a set of comment lines which contains user interested details li&e name of author, program and any other details which ma&es the program more easy to understand. Comment lines should be enclosed within :R and R: for multiple lines and :: for single line and can appear anywhere in the program. %hese comment lines are omitted by the compiler at the time of compilation. )g# :R ;elcome to PI" College of )ngineering and %echnology 2ngole R: :: ;elcome /in& Section C has a rich set of built in functions which can be used to write any complex program. %hese standard functions are &ept in various system libraries such as stdio.h 1standard input output header file3, math.h 1mathematical functions header file3, ctype.h 1character testing and conversion functions header file3, string.h 1string manipulations header file3, conio.h 1configuration input output header file3 etc. If we want to use the functions of these libraries, we have to provide instructions to the compiler to lin& the functions from the corresponding system

2@

C Programming library. %his can be achieved through lin& section of the SCA program structure by using Tinclude directive. )g# TincludeJstdio.hI TincludeJmath.hI TincludeJconio.hI De'inition Section "ome programs re(uire constant values which are going to be used more than once with in the program. "mall changes in that value re(uires multiple changes in the program. "uch complications can be avoided using symbolic constants and these can be defined in definition section using KTdefineL directive. )g# Tdefine pi *.'+ =lo,al Declaration Section %here may be some variables that are used in more than one function. "uch variables are called global variables and are declared in global declaration section i.e., outside of all the functions in general these variables are declared above main13 function. %his section also declares all user defined functions. main( ! 'unction Section main1 3 indicates starting of the program. )very SCA program must have one main1 3 function section. %his section contains two parts. o $eclaration "ection o )xecutable "ection $eclaration part declares all the variables used in the executable part and the entire code for the program is written in the executable part. %hese two parts must appear between the opening and closing braces. %he program execution begins at the opening brace and ends at the closing brace. All the statements in declaration part and executable part end with a semicolon 153. "yntax# main13 U $eclaration Part5 )xecutable Part5 V Su,program Section %his section can consists of one or more user defined functions. %hese functions can be called from main1 3 function or any other user defined function. User defined functions are placed immediately after the main1 3 function and they may appear in any order. Hote#- All sections except the main1 3 function section may be absent whey they are not re(uired.

2B

C Programming

%+SIC D+T+TA >S +ND SIB>S


$ata %ype in a programming language is a set of data with values having predefined characteristics. %he data type defines# '. %he amount of storage allocated to variables. 2. %he values that they can accept. *. %he operations that can be performed on variables. $ata types are classified into %hree. '. Primary data type 2. $erived data type *. User defined data type #$ rimary data type All C Compilers accept the following fundamental or Primary data types. 1a3 integer 1b3 floating point 1c3 character 1d3 double 1e3 void or )mpty dataset (a! integer: Integers are whole numbers with a machine dependent range of values. A good programming language as to support the programmer by giving a control on a range of numbers and storage space. C has * classes of integer storage namely Kshort intL, KintL and Klong intL. All of these data types have signed and unsigned forms. A short int re(uires half the space than normal integer values. Unsigned numbers are always positive and consume all the bits for the magnitude of the number. %he long and unsigned integers are used to declare a longer range of values. (,! 'loating point# -loating point number represents a real number with < digits precision. -loating point numbers are denoted by the &eyword float. (c! c.aracter# A single character can be defined as a defined as a character type of data. Characters are usually stored in @ bits of internal storage. %he (ualifier signed or unsigned can be explicitly applied to char. ;hile unsigned characters have values between / and 2,,, signed characters have values from N'2@ to '2>. (d! dou,le# ;hen the accuracy of the floating point number is insufficient, we can use the double to define the number. %he double is same as float but with longer precision. A double data type number uses <+ bits with a precision of '+ digits. %o extend the precision further we can use long double which consumes @/ bits of memory space. (e! void:- %he void type has no value. Using void data type, we can specify the type of a function. %he type of function is said to be void when it does not return any values to the calling function. */

C Programming

Ta,le #$#: SiCe and Range o' Data Types TA > char or signed char unsigned char int or signed int unsigned int short int or signed short int unsigned short int long int or signed long int unsigned long int float double long double Hote# ' ?yte E @ ?its )$ Derived data type $erived data type is a data type which is derived from intrinsic data types or previously defined primary types. %he set of values for a specific derived type consists of all possible se(uences of component values permitted by the definition of that derived type. )xamples for $erived data types are arrays, functions, structures, unions and pointers etc. *$ User-de'ined data type In C language a user can define an identifier that represents an existing data type. %he user defined data type identifier can later be used to declare variables. typedef and enum are examples for user defined data types. (a! typede'# typedef is a user defined data type used to define an identifier that would represent an existing data type. SIB> (%ytes! ' ' 2 2 ' ' + + + @ '/ Range '2@ to '2> / to 2,, *2><@ to *2><> / to <,,*, '2@ to '2> / to 2,, 2'+>+@*<+@ to 2'+>+@*<+> / to +2B+B<>2B, *.+ e *@ to *.+ eF*@ '.>e */@ to '.>eF*/@ *.+ e +B*2 to *.+ eF+B*2

*'

C Programming "yntax# typedef type identifierD !ere type represents existing data type and SidentifierA refers to the new name given to the data type. >g:TincludeJstdio.hI TincludeJconio.hI void main13 U typedef int numberD number a, b, c 5 printf1K)nter teo numbers# K35 scanf1KGdGdL,Qa,Qb35 cEaFb5 printf1K"umEGdL,c35 V

(,! enum# An enumerated data type is a list of possible values, each of which is assigned a se(uential number. %his allows us to write code that can compare values easily. "yntax# enum identifier Uvalue', value2 W. 6alue nV5 %he identifier is a user defined enumerated data type which can be used to declare variables that have one of the values enclosed within the braces. After the definition we can declare variables to be of this SnewA type as below. enum identifier 6', 62, 6*, WWW 6n %he enumerated variables 6', 62 .. 6n can have only one of the values value', value2 .. value n. >g# enum day U4onday, %uesday, W. "undayV5 enum day wee&Xst, wee& end5 wee&Xst E 4onday5 wee&Xend E -riday5 if1w&Xst EE %uesday3 wee&Xen E "aturday5

"ormatted Input and Output


scan'(! :%he formatted input refers to input data that has been arranged in a particular format. Input values are generally ta&en by using the scanf function. %he scanf function has the general

*2

C Programming form. scanf 1Kcontrol stringL, arg', arg2, arg* WWWW,argn35 %he format field is specified by the control string and the arguments arg', arg2, W.argn specifies the address of location where address is to be stored. %he &ontrol strin' specifies the field format which includes format specifications and optional number specifying field width and the conversion character G and also blan&s, tabs and new lines. print'(! :%he printf 1 3 function is (uite flexible. It allows a variable number of arguments, labels and sophisticated formatting of output. %he formatted output refers to output data that will be printed in screen. 2utput values are generally printed by using the printf function. %he printf function has the general form# printf 1Kconversion stringL, variable list35 Conversion Strings and Speci'iers: %he conversion string includes all the text labels, escape character and conversion specifiers re(uired for the desired output. %he variable includes all the variable to be printed in order they are to be printed. %here must be a conversion specifies after each variable. Speci'ier Meaning Gc N Print a character Gd N Print a Integer Gi N Print a Integer Ge N Print float value in exponential form. Gf N Print float value Gg N Print using Ge or Gf whichever is smaller Go N Print actual value Gs N Print a string Gx N Print a hexadecimal integer 1Unsigned3 using lower case a N GY N Print a hexadecimal integer 1Unsigned3 using upper case A N Ga N Print a unsigned integer. Gp N Print a pointer value Ghx N hex short Glo N octal long Gld N long Gld N double

C8+R+CT>R S>T Instructions in C language are formed using syntax and &eywords. =i&e any other language, C has itAs own vocabulary and grammar. It is necessary to strictly follow C language "yntax1grammatical3 rules. %hese "yntax were maid using some symbols and words. Any

**

C Programming instructions that mis matches with C language "yntax generates an error while compiling the program. %he character set in C =anguage can be grouped into the following categories. '. =etters a to CE + to B 2. $igits 7 to 6 *. "pecial Characters E $ D : F G H I @ J K - L M N O P Q R S T ( ! U V W X Y Z +. ;hite "paces ?lan& "pace, !ori.ontal %ab, Carriage 0eturn, Hew =ine, -orm -eed %he compiler ignores the white spaces unless they are part of string constant. ;hite spaces are used to separate words, but should not be used between the characters of &eywords and identifiers. C TO:>NS In a C source program, the basic element recogni.ed by the compiler is the 9to&en.9 A to&en is source program text that the compiler does not brea& down into component elements. %he smallest individual units are &nown as C to&ens.

"igure #$#): C To&ens -it. e9amples ID>NTI"I>RS 9Identifiers9 or 9symbols9 are the user defined names supplied for variables, data types, functions, and labels in your program. Identifier names must differ in spelling and case from any &eywords. Mou create an identifier by specifying it in the declaration of a variable, type, or function. 2nce declared, you can use the identifier in later program statements to refer to the associated value. ?oth uppercase and lowercase letters are permitted. %he underscore character 1 X 3 is also permitted in identifiers to lin& two words. %he name of a variable is an identifier. )g# TincludeJstdio.hI TincludeJconio.hI void main13 U int aE'/,bE2',result5 resultEaFb5 *+

C Programming printf1KsumEGdL,c35 V In this example, result is an identifier for an integer variables, and main and printf are identifier names for functions. 0ules for Identifiers# '. -irst character must be an alphabet 1or underscore3 2. Identifier names must consists of only letters, digits and underscore. *. A identifier name should have less than *' characters. +. Any standard C language &eyword cannot be used as a variable name. ,. An single identifier should not contain a space. :>A(ORDS Ceywords are the C language words which have fixed meaning which cannot be changed. Ceywords in C language cannot be used as a variable name. %hey are specifically used by the compiler for its own purpose and they serve as building bloc&s of a c program. All &eywords must be in lower case. some compilers may have additional &eywords or less than what we mentioned. Ta,le #$): /ist o' :ey-ords .else .register .enum .extern .float .for .goto .if .int .return .short .signed .si.eof .static .struct .switch

Auto .brea& .case .char .const .continue .default .do CONST+NTS (/IT>R+/!

.union .unsigned .void .volatile .while double. .long. typedef.

Constants refer to the fixed values that do not change during the execution of a program. Constants Humeric constants Integer constants Character constants "tring constants

0eal constants "ingle character constant "igure #$#*: Constants in C

*,

C Programming Integer Constants An integer constant is a se(uence of digits. %hey are numbers that do not have a decimal point or an exponential part. %here are * types of integers namely decimal integer, octal integers and hexadecimal integer. Decimal Integers consists of a set of digits / to B preceded by an optional F or "paces, commas and non digit characters are not permitted between digits. )xample for valid decimal integer constants are '2*, *', /, ,<2*2', F >@ "ome examples for invalid integer constants are ', >,/ 2/,/// 0s. '/// sign.

Octal Integers constant begins with the digit / and contains any of the digits / through >. "ome examples of octal integers are /2<, /, /*+>, /<>< 8e9adecimal integer constant begins with the / digit followed by either an x or Y, followed by any combination of the digits / through B and the letters a through f or A through -. %he letters A 1or a3 through - 1or f3 represent the values '/ through ',, respectively. )xample of valid hexadecimal integers are /Y2, /Y@C, /Yadf, /x Hote# ;e rarely use octal and hexadecimal numbers in programming. Real Constants 0eal Constants consists of a fractional part in their representation. Integer constants are inade(uate to represent (uantities that vary continuously. %hese (uantities are represented by numbers containing fractional parts li&e 2<./@2. A floatin'-point &onstant consists of the following#
o o o o

An integral part A decimal point A fractional part An exponent part

?oth the integral and fractional parts are made up of decimal digits. Mou can omit either the integral part or the fractional part, but not both. Mou can omit either the decimal point or the exponent part, but not both. )xample of real constants are /.//2< /.B> +*,.2B F+@>./ we can omit digits before the decimal point, or digits after the decimal point. +2'. .>@ .*+ F.+ are valid real numbers. 0eal Humbers can also be represented by exponential notation. %he general form is mantissa e e9ponent %he mantissa is either a real number expressed in decimal notation or an integer. %he exponent is an integer number with an optional plus or minus sign. %he letter e separating mantissa and exponent can be written either in lower case or upper case. *<

C Programming )xamples are /.>'e+ '2e 2 '.*eF* >.,)B '.'2) > >.,)B E >,//////// '.'2) > E /.//////''2 Single C.aracter Constants A "ingle Character constant represent a single character which is enclosed in a pair of single (uotation symbols. )xample for character constants are 8,8 8x8 858 8 8 etc All character constants have an e(uivalent integer value which are called A"CII 6alues. %o &now the A"CII values of each character, 7ust write below program. TincludeJstdio.hI TincludeJconio.hI void main13 U int i5 clrscr135 for1iE/5iJ'2@5iFF3 printf1KGc GdL,i,i35 getch135 V String Constants A string constant is a set of characters enclosed in double (uotation mar&s. %he characters in a string constant se(uence may be a alphabet, number, special character and blan& space. )xample of string constants are KCrishnaL K2//+L K2F+L KZ...[L Hote# A single character constant S$A is not e(ual to string constant K$L. -urther, a single character string constant does not have an e(uivalent integer value where as single character constant has an integer value.

%ac&slas. C.aracter Constants U>scape Se?uencesV ?ac&slash character constants are special characters used in output functions. Although they contain two characters they represent only one character. Ta,le #$*: /ist o' ,ac&slas. c.aracters Constant Meaning Constant Meaning [Ja[ [J,[ [J'[ [Jn[ Audible Alert 1?ell3 ?ac&space -orm feed Hew =ine [Jv[ [J[[ [J\[ [JF[ 6ertical %ab "ingle Puote $ouble Puote Puestion 4ar&

*>

C Programming [Jr[ [Jt[ Carriage 0eturn !ori.ontal tab [JJ[ [J7[ ?ac& "lash Hull

5+RI+%/>S A variable is a named memory, that can be used to read and write information. In this sense, variables are nothing more than 9buc&ets9 that can be used to store whatever values are needed for a specific computation. we have different types of variables for the various contents that can be stored in it. A variable is a meaningful name of data storage location in computer memory. ;hen using a variable you refer to memory address of computer. 6ariable is a data name which can be used to store a data value. A variable is referenced to by an identifier, and denotes a memory area that can be manipulated through the use of the identifier. %he difference between a variable and an identifier is the same as between a person and his or her name. A variable is not an identifier. A variable has an identifier. It also has a type, and 1if it is initiali.ed3 a value. Unli&e constants that remains unchanged during the execution of a program, a variable may ta&e different values at different times during execution. Naming 5aria,les %he name of variable can be called identifier or variable name in a friendly way. 2f course, the variable name should be meaningful to the programming context. It has to follow these rules# '. %he name can contain letters, digits and the underscore. 2. %he -irst letter must be a letter or the underscore. *. 4aximum distinguishable length should be @ characters. +. Ceywords cannot be used as variable name. ,. ;hite spaces are not allowed. "ome valid examples are totalXavg, Dohn, intXtype, 7ohn "ome invalid examples are 'avg, Dohn\, int ,total avg , '*+, G Declaring 5aria,les %o declare a variable you specify its name and &ind of data type it can store. %he variable declaration always ends with a semicolon, for example# "yntax# data type var',var2,var*WWvarn5 int count5 char c5 float avg5 Mou can declare variables at any point of your program before using it. %he best practice suggests that you should declare your variables closest to their first point of use so the source code is easier to maintain. In C programming language, declaring a variable is also defining a variable.

*@

C Programming

InitialiCing 5aria,les Mou can also initiali.e a variable when you declare it, for example# int countE/5 char cEA$A5

O >R+TORS
An operator is a symbol which helps the user to command the computer to do a certain mathematical or logical manipulations on data and variables. %he value on which an operation is performed is called operand. C has a rich set of operators which can be classified as '. Arithmetic operators 2. 0elational 2perators *. =ogical 2perators +. Assignment 2perators ,. Increments and $ecrement 2perators <. Conditional 2perators

*B

C Programming >. ?itwise 2perators @. "pecial 2perators #$ +rit.metic operators All the basic arithmetic operations can be carried out in C. All the operators have almost the same meaning as in other languages. ?oth unary and binary operations are available in C language. Unary operations operate on a singe operand, therefore the number , when operated by unary N will have the value N,. Operator F R : G Meaning Addition or Unary Plus "ubtraction or Unary 4inus 4ultiplication $ivision 4odulus 2perator

Integer division gives coefficient part where as the modulus operator produces the remainder of the operands after division. )g# '+:*E+ '+G*E2 %he modulo division operator cannot be used on floating point data. )g# '+:*E+.<<<<<> '+G*Einvalid Integer +rit.metic ;hen an arithmetic operation is performed on two whole numbers or integers than such an operation is called as integer arithmetic. It always gives an integer as the result. )g# =et a E *' and b E + a F b E *, a b E 2> a R b E '2+ a:bE> aGbE* An expression containing operator and integer operands is &nown as Kinteger expressionL. $uring integer division, if both operands have same sign, the result is positive where as if one of them is negative, the result will be negative. 'B : + E + 'B : + E + 'B : + E + 'B : + E + $uring modulo division, the sign of the result is always the sign of the first operand 1dividend3. 'B : + E * 'B : + E * 'B : + E * 'B : + E *

+/

C Programming Real or "loating point arit.metic ;hen an arithmetic operation is preformed on two real numbers or floating point numbers or fraction numbers, such an operation is called floating point arithmetic. %he floating point results can be truncated according to the properties re(uirement. %he remainder operator is not applicable for floating point arithmetic operands. )g# =et a E *'./ and b E +./ a F b E *,.////// a b E 2>.////// a R b E '2+.////// a : b E >.>,//// if x and y are float numbers. %hen x E <./:>./ E /.@,>'+* y E './:*./ E /.****** Mi9ed mode arit.metic ;hen one of the operand is real and other is an integer and if the arithmetic operation is carried out on these 2 operands then it is called as mixed mode arithmetic. If any one operand is of real type then the result will always be real thus *+:'/$/ E *$+///// )$ Relational Operators 2ften it is re(uired to compare the relationship between operands and bring out a decision and program accordingly. %hese comparisons can be done with the help of operators &nown as Krelational operatorsL. An expression containing relational operator is &nown as Krelational expressionL. Operator J JE I Meaning is less than is less than or e(ual to is greater than Operator IE EE ZE Meaning is greater than or e(ual to is e(ual to is not e(ual to

A simple relational expression contains only one relational operator and ta&es the following form. exp' relational operator exp2 ;here exp' and exp2 are expressions, which may be simple constants, variables or combination of them. 0elation )xpression returns non .ero value if the condition is %0U) otherwise returns .ero when the condition is false. <.>JE'/ >.,J '/ %0U) -A=")

+'

C Programming +2IE/ '/JBF+ aFbEEcFd -A=") %0U) %0U) only if sum of a Q b and sum of c Q d are e(ual otherwise -A=").

0elational expressions are used in decision ma&ing statements of C language such as if, while and for statements to decide the course of action of a running program. *$ /ogical Operators %he logical operators are used when we want to test more than one condition and ma&e decision. C has the following logical operators, they compare or evaluate logical and relational expressions. Operator QQ ]] Z Meaning =ogical AH$ =ogical 20 =ogical H2%

/ogical +ND (MM! %his operator is used to evaluate 2 conditions or expressions with relational operators simultaneously. If both the expressions to the left and to the right of the logical operator is true then the whole compound expression is true. )xample a I b QQ x E E '/ %he expression to the left is a I b and that on the right is x EE '/ the whole expression is true only if both expressions are true i.e., if a is greater than b and x is e(ual to '/. /ogical OR (NN! %he logical 20 is used to combine 2 expressions or the condition evaluates to true if any one of the 2 expressions is true. )xample a J m ]] a J n %he expression evaluates to true if any one of them is true or if both of them are true. It evaluates to true if a is less than either m or n and when a is less than both m and n.

+2

C Programming /ogical NOT (I! %he logical not operator ta&es single expression and evaluates to true if the expression is false and evaluates to false if the expression is true. In other words it 7ust reverses the value of the expression. )xample Z 1x IE y3 %he H2% expression evaluates to true only if the value of x is neither greater than or e(ual to y 0$ +ssignment Operators %he Assignment 2perator evaluates an expression on the right of the expression and substitutes it to the value or variable on the left of the expression. Synta9: 6ariable E )xpression5 )g:- x E a F b !ere the value of a F b is evaluated and substituted to the variable x. s.ort.and assignment operators var oper E exp5 !ere var is a variable, exp is an expression and oper is a C binary arithmetic operator. %he operator oper E is &nown as shorthand assignment operator )g:- x F E ' is same as x E x F ' %he commonly used shorthand assignment operators are as follows

+ssignment Operator S.ort.and Operator aEaF' aEa ' aEaR1pF'3 aEa:1pF'3 aEaG1pF'3 aFE' aEa ' aRE1pF'3 a:E1pF'3 aGE1pF'3

1$ Increment and Decrement Operators %he increment and decrement operators are one of the unary operators which are very useful in C language. %hey are extensively used in for and while loops. %he syntax of the operators is given below '. FF operand 2. operand FF *. N N operand +. operand N N

+*

C Programming %he increment operator FF adds the value ' to the current value of operand and the decrement operator N N subtracts the value ' from the current value of operand. FFoperand and operandFF mean the same when they form statements independently, ?ut they behave differently when they are used in expression on the right hand side of an assignment statement. )g '# -or1iE/5iJ+5iPP3 for1iE/5iJ+5PPi3 Printf1K GdL, i35 printf1K GdL, i35 2utput# / ' 2 * 2utput# / ' 2 * !ere increment operator is used independently, so iFF or FFi gives the same output. )g 2# m E ,5 y E FFm5 1prefix3 In this case the value of y and m would be < "uppose if we rewrite the above statement as m E ,5 y E mFF5 1post fix3 %hen the value of y will be , and that of m will be <. A prefix operator first adds ' to the operand and then the result is assigned to the variable on the left. 2n the other hand, a postfix operator first assigns the value to the variable on the left and then increments the operand. %he same rules will be applied to operandN N and N Noperand. 2$ Conditional or Ternary Operator %he conditional operator consists of 2 symbols the (uestion mar& 1[3 and the colon 1#3 %he syntax for a ternary operator is as follows exp' [ exp2 # exp* %he ternary operator wor&s as follows exp' is evaluated first. If the expression is true then exp2 is evaluated Q its value becomes the value of the expression. If exp' is false, exp* is evaluated and its value becomes the value of the expression. Hote that only one of the expression is evaluated. "or e9ample a E '/5 b E ',5 x E 1a I b3 [ a # b

++

C Programming !ere x will be assigned to the value of b. %he condition follows that the expression is false therefore b is assigned to x. 3$ %it-ise Operators ?itwise operators manipulates data at bit level. A bitwise operator operates on each bit of data. %hose operators are used for testing, complementing or shifting bits to the right on left. ?itwise operators may not be applied to a float or double. Operator Q ] ^ _ JJ II Meaning ?itwise AH$ ?itwise 20 ?itwise )x 20 ?itwise H2% =eft shift 0ight shift

4$ Special Operators C supports some special operators of interest such as comma operator, si.e of operator, pointer operators 1Q and R3 and member selection operators 1. and I3. %he si.e of and the comma operators are discussed here. Comma Operator %he comma operator can be used to lin& related expressions together. A comma lin&ed list of expressions are evaluated left to right and value of right most expression is the value of the combined expression. >g:value E 1p E '+, ( E +, p F (35 -irst assigns '+ to p and + to ( and finally assigns '@ to value. "ince comma has the lowest precedence in operators the parenthesis is necessary. "ome examples of comma operator are for 1nE', mE'/, n JEm5 nFF,mFF3 ;hile 1cEgetchar13, c ZE S'/A3 t E x, x E y, y E t )xchanging values Comma 2perator will be used to declare different variables for a data type. )g# int a,b,c5 siCeo' Operator %he Ksi.eofL gives the si.e of the data type or variable in terms of bytes occupied in the memory. %he operand may be a variable, a constant or a data type (ualifier. %he 0eturned value ;ill be in integer ?ytes. >g:int m,n,&EpEsumD

+,

C Programming m E si.eof 1sum35 n E si.eof 1long int35 & E si.eof 12*,=35 p E si.eof 1'//35 2 + + 2

%he si.e of operator is normally used to determine the lengths of arrays and structures when their si.es are not &nown to the programmer. It is also used to allocate memory space dynamically to variables during the execution of the program.

>9pressions
An expression is a combination of variables, constants and operators written according to the syntax of C language. In C, every expression evaluates to a value i.e., every expression results in some value of a certain type that can be assigned to a variable. "ome examples of C expressions are shown in the table given below. +lge,raic >9pression C >9pression axbNc aRbNc 1m F n3 1x F y3 1m F n3 R 1x F y3 1ab : c3 aRb:c *x2 F2x F ' *RxRxF2RxF' b2 +ac bRb +RaRc >valuation o' >9pressions )xpressions are evaluated using an assignment statement of the form 6ariable E expression5 6ariable is any valid C variable name. ;hen the statement is encountered, the expression is evaluated first and then replaces the previous value of the variable on the left hand side. All variables used in the expression must be assigned values before evaluation is attempted. >g: xEaRbNc yEb:cRa . E a N b : c F d5 recedence in +rit.metic Operators An arithmetic expression without parenthesis will be evaluated from left to right using the rules of precedence of operators. %here are two distinct priority levels of arithmetic operators in C. !igh priority R : G =ow priority F Rules 'or evaluation o' e9pression

+<

C Programming '. -irst parenthesi.ed sub expression left to right are evaluated. 2. If parenthesis are nested, the evaluation begins with the innermost sub expression. *. %he precedence rule is applied in determining the order of application of operators in evaluating sub expressions. +. %he associability rule is applied when two or more operators of the same precedence level appear in the sub expression. ,. Arithmetic expressions are evaluated from left to right using the rules of precedence. <. ;hen Parenthesis are used, the expressions within parenthesis assume highest priority.

Conditional >9pression
Any expression which uses Conditional 2perator or %ernary 2perator1[#3 is &nown as conditional expression. Alternative for ifW.else statements. Synta9: )xpression' [ )xpression 2 # )xpression *

!ere first )xpression' is evaluated and if it returns non .ero value i.e. if the )xpression' is %0U) means )xpression 2 is evaluated otherwise )xpression* is evaluated.

Type conversions
Implicit or +utomatic type conversion C permits mixing of constants and variables of different types in an expression. C automatically converts any intermediate values to the proper type so that the expression can be evaluated without loosing any significance. $uring evaluation, if the operands are of different types the lower type is automatically converted to the higher type before the operation proceeds. %he result is of higher type. %he following rules apply during evaluating expressions All short and char are automatically converted to int then '. If one operand is long double, the other will be converted to long double and result will be long double. 2. If one operand is double, the other will be converted to double and result will be double. *. If one operand is float, the other will be converted to float and result will be float. +. If one of the operand is unsigned long int, the other will be converted into unsigned long int and result will be unsigned long int. ,. If one operand is long int and other is unsigned int then a. If unsigned int can be converted to long int, then unsigned int operand will be converted as such and the result will be long int. b. )lse ?oth operands will be converted to unsigned long int and the result will be unsigned long int. <. If one of the operand is long int, the other will be converted to long int and the result will be long int.. >. If one operand is unsigned int the other will be converted to unsigned int and the result will be unsigned int. +>

C Programming

1high3 long double double float unsigned long int long int unsigned int int short or char 1low3 >9plicit Type conversion or Type Casting 4any times there may arise a situation where we want to force a type conversion in a way that is different from automatic conversion. Consider for example the calculation of average of * numbers int m',m2,m*5 float avg5 avgE1m'Fm2Fm*3 : *5 "ince m',m2 and m* are declared as integers, the decimal part will be rounded off and its ratio will represent a wrong figure. i.e. for three set of values li&e 1*/,</,B/3, 1*',</,B/3 and 1*2,</,B/3, the average will be </.//////. %his problem can be solved by converting locally one of the variables to the floating point as shown below. avgE 1float3 1m'Fm2Fm*3 : *5 %he operator float converts the m'Fm2Fm* expression into floating point for the purpose of evaluation of the expression. %hen using the rule of automatic conversion, the division is performed by floating point mode, thus retaining the fractional part of the result. %he process of such a local conversion is &nown as explicit conversion or casting a value. %he general form is 1typeXname3 expression

Operator precedence and +ssociativity


)ach operator in C has a precedence associated with it. %he precedence is used to determine how an expression involving more than one operator is evaluated. %here are distinct levels of precedence and an operator may belong to one of these levels. %he operators of higher precedence are evaluated first. %he operators of same precedence are evaluated from right to left or from left to right depending on the level. %his is &nown as KassociativityL property of an operator. %he below table shows the operator precedence and their associativity.

+@

C Programming

Operator

Description

+ssociativity

+B

C Programming 13 `a . I FF FF F Z _ 1type3 R Q si.eof R : G F JJ II J JE I IE EE ZE Q ^ ] QQ ]] [# E FE E RE :E GE QE ^E ]E JJE IIE , Parentheses 1function call3 1see Hote '3 ?rac&ets 1array subscript3 4ember selection via ob7ect name 4ember selection via pointer Postfix increment:decrement 1see Hote 23 Prefix increment:decrement Unary plus:minus =ogical negation:bitwise complement Cast 1change type3 $ereference Address $etermine si.e in bytes 4ultiplication:division:modulus Addition:subtraction ?itwise shift left, ?itwise shift right 0elational less than:less than or e(ual to 0elational greater than:greater than or e(ual to 0elational is e(ual to:is not e(ual to ?itwise AH$ ?itwise exclusive 20 ?itwise inclusive 20 =ogical AH$ =ogical 20 %ernary conditional Assignment Addition:subtraction assignment 4ultiplication:division assignment 4odulus:bitwise AH$ assignment ?itwise exclusive:inclusive 20 assignment ?itwise shift left:right assignment Comma 1separate expressions3

left to right

right to left

left to right left to right left to right left to right left to right left to right left to right left to right left to right left to right right to left right to left

left to right

,/

You might also like