You are on page 1of 107

Binary Numbering System

The following 2 sections on binary numbering system and memory are optional but recommended. If youve taken a course in electronics you probably already know about this and can use the material provided here as a refresher. Having knowledge of the binary system and computer memory will help in understanding some features in programming.

The heart of the computer is the microprocessor, which is also referred to as the processor. The microprocessor is the main part of the computers CPU (central processing unit). A processor consists of millions of electronic switches; a switch can be either in ! or "" state. Thus there are onl# two distinct states possible in these de$ices. %n our real&world calculations we ma'e use of the decimal s#stem (which has () distinct states*numbers+ ) to ,). Counting up to ten is eas# for humans but would be -uite difficult for computers. %t is easier to create a de$ice capable of sensing . states than one capable of sensing () states (this also helps reduce on errors). Computers ma'e use of the binar# s#stem (i.e. the# store data in binar# format and also perform calculations in binar# format). The binar# s#stem (binar# meaning two) has /ust two numbers+ ( and ) (which correspond to the ! and "" state respecti$el# 0 this is analogous to a switch which can either be in ! state or in "" state). 1hen we ha$e different s#stems (binar#, decimal etc.), there ought to be a wa# of con$erting data from one s#stem to the other. %n the decimal s#stem the number .23 stands for 34()) 5 24()( 5 .4(). (add it up and the result will be .23; i.e. in each place we can ha$e one of the () digits and to find the actual place $alue we ha$e to multipl# the digit b# the corresponding power of ()). "or e6ample+ .23 7 (. 6 ().) 5 (2 6 ()() 5 (3 6 ())) 7 .)) 5 2) 5 3 (.89 7 (( 6 ():) 5 (. 6 ().) 5 (8 6 ()() 5 (9 6 ())) 7 ())) 5 .)) 5 8) 5 9 Note: %n C55 and most other computer languages, 4 is used as the multiplication operator. The same concept holds good for a binar# number but since onl# two states are possible, the# should be multiplied b# powers of .. Remember: A binar# digit is called a bit.

;o, what is the $alue of (()(< =ultipl# each position b# its corresponding power of . (but remember, #ou ha$e to start from .) and not from .(). The $alue for (()( is (: as illustrated in the figure below+

An alternate method to obtain the $alue is illustrated below (but the underl#ing concept is the same as abo$e)+

%t is eas# to obtain the $alues which are written abo$e each bit (.37(.9, .>7>2 and so on). 1rite these $alues on top and then write the binar# number within the s-uares. To find the e-ui$alent decimal $alue, add up the $alues abo$e the s-uare (if the number in the s-uare is (). %f a number is denoted as (()(, then this stands for the lower (or last) four bits of the binar# number (the upper bits are set to )). ?ence (()( will come under the $alues 9, 2, . and (. !ow, where$er there is a (, /ust add the $alue abo$e it (9525(7(:). Thus (: is the decimal e-ui$alent of (()( (in binar# format). To distinguish between decimal and binar# we usuall# represent the s#stem used (decimal or binar#) b# subscripting the base of the s#stem (() is the base for the decimal s#stem while . is the base for the binar# s#stem).

?ence ((:)() 7 ((()().

Computers store information in the form of bits and 9 bits ma'e a b#te. @ut memor# capacit# is e6pressed as multiples of .() b#tes (which is e-ual to ().2 b#tes). ().2 b#tes is called a Ailob#te. Bou ma# wonder wh# it is ().2 and not ())) b#tes. The answer lies in the binar# s#stem. Aeeping uniformit# with the binar# s#stem, .()7().2 and not ())) (the idea is to maintain conformit# with the binar# s#stem). Beware: The bit in position 3 in fig (.( is actuall# the 9th bit of the number (the numbering of bit starts from ) and not (). The bit in the highest position is called as the most significant bit. %n an 9 bit number, the 3th bit position is called the most significant bit (=;@) and the )th bit is 'nown as the least significant bit (or C;@). This is because the =;@ in this case has a $alue of (.9 (.9) while the C;@ has a $alue of /ust (.

Computer Memory
We know that computers can operate only on bits (0s and 1s). Thus any data that has to be processed by the computer should be converted into 0s and 1s. Let us suppose that we want to create a text file containin a sin le word !"ello#. This file has to be stored physically in the computer$s memory so that we can read the file anytime in the future. %or the time bein for et about the file&stora e part. Let$s 'ust concentrate on how the word !hello# is stored in the computer$s memory. (omputers can only store binary information) so how will the computer know which number corresponds to which alphabet* +bviously we cannot map a sin le bit to a character. ,o instead of bits we$ll consider a byte (- bits). .ow we can represent /01 characters. To perform map a character to a byte we$ll need to use some codin mechanism.

%or this purpose the 2,(33 (2merican ,tandard (ode for 3nformation 3nterchan e) is used. 3n this codin system4 every alphabet has an e5uivalent decimal value. When the computer uses 2,(334 it cannot directly use the decimal value and it will convert this into an -&bit binary number (in other words4 into a byte) and store it in memory. The followin table shows part of the 2,(33 code.

Character A @ a b

Equivalent decimal value >8 >> ,3 ,9

Binary value )()) )))( )()) ))() )(() )))( )(() ))()

3n this way each character is mapped to a numeric value. 3f we type the word hello4 then it is converted into bytes (0 bytes& one for each character) based on the 2,(33 chart and is stored in memory. ,o 6hello$ occupies 0 bytes or 70 bits in memory. .ote8 3t is very important to know the binary system if you want to use the bitwise operators available in (99. The concept of memory is useful while learnin pointers. 2 5uestion arises4 !where are the individual bits stored in memory*# :ach individual bit is stored in an electronic device (the electronic device is technically called a flip&flop) which is somethin like a switch). 2 sin le flip&flop can store one bit. (onsider the fi . below8

As mentioned earlier we deal in terms of b#tes rather than bits. The figure shows a 2&b#te memor# (which means it can hold :. bits 0 each cell can store one bit). All information is stored in memor# and the computer needs some method to access this data (i.e. there should be some wa# of distinguishing between the different memor# locations). =emor# addresses ser$e this purpose. Dach bit can be indi$iduall# accessed and has a

uni-ue memor# address. To access the first b#te, the computer will attempt to read the b#te stored at memor# address (. %f memories didnt ha$e addresses then the computer would not 'now from where it has to read data (or where it has to store data). An analog# to memor# address is the postal address s#stem used in real&life. A cit# will ha$e a number of houses and each house has a uni-ue address. Eust imagine the situation if we didnt ha$e an# postal address (we wouldnt be able to locate an# house in the cit#F). ne difference is that a memor# address can house onl# bits and nothing else. =emor# address representations are not as simple as shown abo$e. %n the abo$e case we$e considered a memor# that has capacit# to store /ust 2 b#tes. =emories usuall# contain 'ilob#tes or gigab#tes of space. As the amount of memor# a$ailable increases, so does the siGe of the address (the address number might be in the range of millions). Thus instead of using the decimal s#stem for addresses, the he6adecimal numbering s#stem is used. ?e6a means (> and the distinct numbers in this s#stem are ) to , followed b# A, @, C, H, D and " where A7 () in decimal, @7 (( in decimal and "7 (8 in decimal. Counting in he6adecimal s#stem will be )I,, A, @I", (),((,(.,(:I(,,(A, (@, (CI and so on. %t is -uite clear that () in he6adecimal does not e-ual () in decimal. %nstead, ()")(> 7 ((8)(), (())(> 7 ((>)() and ((()(> 7 ((3)() "our bits form a Jnibble. Dight bits form a Jb#te and four b#tes of memor# are 'nown as a Jword. There is some significance attached to a Jword which we shall deal with later. Another term related to memor# is Jregister. A register consists of a set of flip& flops (flip&flops are electronic de$ices that can store one bit) for storing information. An 9&bit register can store 9 bits. D$er# processor has a set of internal registers (i.e. these registers are present within the processor and not in an e6ternal de$ice li'e a hard dis'). These registers (which are limited in number depending on the processor) are used b# the processor for performing its calculations and computations. The# usuall# contain the data which the processor is currentl# using. The siGe of the register (i.e. whether the registers will be (>&bit, :.&bit or >2&bit registers also depends on the processor). The common computers toda# use :.&bit registers (or 2&b#te registers). The siGe of a register determines the Jword-size of a computer. A computer is more comfortable (and prefers) wor'ing with data that is of the word&siGe (if the word&siGe is 2 b#tes then the computer will be efficient in computations in$ol$ing bloc's of 2 b#te data). Boull understand this when we get into data t#pes in the subse-uent chapters. The different t#pes of memor# are+

(.

;econdar# storage (for e6ample the hard dis', flopp# dis's, magnetic dis's, CH& K =) where one can store information for long periods of time (i.e. data is retained in memor# irrespecti$e of whether the s#stem is running or not).

.. The KA= (random access memor#) is used b# the computer to store data needed b# programs that are currentl# running. KA= is used for the main (primar#) memor# of the computer (all programs which are e6ecuted need to be present in the main memor#). The KA= will lose whate$er is stored in memor# once the computer is switched off. :. K = (read onl# memor#)+ This contains instructions for booting up the s#stem and performing other start&up operations. 1e cannot write to this memor#. 2. The internal registers within the processor& these are used b# the computer for performing its internal operations. The compiler will decide what has to be stored in which register when it con$erts our high&le$el code into low&le$el language. As such we wont be able to use these registers in our C55 code (unless we write assembl# code).

Remember: econdary storage !also called au"iliary memory# is not directly accessible by the $%&. 'ut ()* is directly accessible !thus secondary memory is much slower than the primary memory#. +or a program to e"ecute it needs to be present in the main memory. ,hich memory has lowest access time !or which memory can the $%& access -uickly#. The internal registers can be accessed -uic'l# and the secondar# storage de$ices ta'e much longer to access. Computers also ma'e use of a cache&memor#. Cache memor# is a high&speed memor# which stores recentl# accessed data (cache access is faster than main memor# access).

Related concept: %n general cache means storing fre-uentl# accessed data temporaril# in a place where it can be accessed -uic'l#. 1eb browsers tend to cache web pages #ou $isit fre-uentl# on the hard dis'. Lenerall# when we t#pe in a website address, the browser needs to -uer# the website and re-uest for the page; which is a time consuming

process. 1hen the browser displa#s this webpage, it internall# caches (stores a cop#) this webpage on our hard dis' also. The ne6t time we time the same website address, the browser will directl# read out from the hard dis' rather than -uer# the website (reading from hard dis' is faster than accessing a web ser$er). Remember: Computers store information using the binar# s#stem, addresses are represented in the he6adecimal s#stem and in real&life we use the decimal s#stem. A :&bit number can be used to form 9 different combinations (including the ))) combination). Binary ))) ))( )() )(( ()) ()( (() ((( Decimal Equivalent ) ( . : 2 8 > 3

If / bits are used then the ma"imum possible decimal number that can be represented is 0 !not 1 because the first number is 2#. imilarly if an 1-bit number can be used to represent up to !231# different values !2 to 244 in the decimal system#. A binar# number can be either signed or unsigned. 1hen a number is unsigned (we dont bother about the sign), it means that the number is alwa#s positi$e. %f a number is signed, then it could be positi$e or negati$e. 5:: is a signed number (with a positi$e sign). %n real life, we can use 5 or 0 to indicate whether a number is positi$e or negati$e but in computers onl# (s and )s can be used. D$er# decimal number has a binar# e-ui$alent. The binar# e-ui$alent for the decimal number 9 is ))))())). %f this is a signed number

then 59 would be written as ))))())) and 09 would be denoted b# ()))())). !otice the difference between the two. The 3th bit (or the most significant bit) is set to ( to indicate that the number is negati$e. Assume the number (.3. "or 5(.3 #ou will write+ )((((((( "or 0(.3 #ou will write+ (((((((( "or .88 #ou will write+ < 1ell, the $alue for .88 cannot be written using a signed 9&bit number (because the 3th bit is reser$ed for the sign). %f the unsigned representation was used then .88 can be represented as (((((((( (in this case the =;@ signifies a $alue and is not concerned about the sign of the number). 1hat is the point to note here< @# using a signed representation the ma6imum $alue that can be represented is reduced. An 9 bit unsigned binar# number can be used to represent $alues from ) to .88 ((((((((( will mean .88). n the other hand, if the 9 bit binar# number is a signed number then it can represent from 0(.3 to 5(.3 onl# (again a total of .88 $alues but the ma6imum $alue that can be represented is onl# (.3). Beware: ;igned representation in binar# format will be e6plained in detail later. Computers store negati$e numbers in .s complement rather than storing them directl# as shown abo$e. Remember: %n signed numbers the =;@ (in the binar# representation) is used to indicate the sign of the number.

Programming Languages
The earlier first section was Binary numbers. Some people said that I ought to reduce the math in this tutorial and I felt that perhaps I should start off differently. And so I've altered the sequence of sections in this first unit.

Recap of important computer concepts:


1hen we tal' of computers, we refer to Jhardware and Jsoftware. All the ph#sical components li'e monitor, 'e#board, mouse, modem, printer etc. fall under the hardware categor#. 1e need computers to do something useful for us but computers arent smart enough to 'now what we want them to do (at least not #etF). 1e need to e6plicitl# tell the computer our re-uirements in the form of instructions. A set of instructions for doing something useful forms a Jprogram. And we refer to these programs as software (i.e. unli'e hardware, software is something that we cant touch and feel). Major hardware parts in a computer: (. Input and Output devices: (omputer can receive input from input devices (like a keyboard4 mouse or a scanner). +utput devices are used by the computer to send out information to the user) example8 monitor4 printer4 plotter etc. .. Arithmetic and Logical Unit (ALU): 2s the name implies this unit is responsible for all arithmetic calculations. 3t is part of the central processin unit. :. Memory: When our computer wants to work on some information4 it will re5uire some place where it can store data) where it can store the instructions) where it can store intermediate results of operations etc. ;emory serves this purpose and there are different types of memory (for different re5uirements)8 Primary memory: This memor# can be -uic'l# accessed b# the computer (in technical /argon we sa# that this memor# has low access time; i.e. time ta'en to access data in primar# memor# is less). Lenerall#, instructions and data needed b# the computer immediatel# for processing are placed in primar# memor#. Hata in primar# memor# is not permanent. Dach time we restart the computer, the memor# would get refreshed. econdary memory! stora"e: This is the place where we store all our data. %ts a long&term storage de$ice (li'e a hard&dis'). Access times are higher but secondar# memor# is cheaper than primar# memor#. 2. C U (Central rocessing Unit): We$ve seen computer parts to et input4 store information4 display output and also to

perform calculations. <ut there needs to be someone at a hi her level to control the individual units) someone to decide when to capture the input4 when to send output information to the monitor etc. The (=> takes up this responsibility and is termed the 6brain$ of the computer. The (=> is also called the processor (a microprocessor chip).

#he lan"ua"e computers understand: 1e ha$e a lot of languages in this world but all computers can understand onl# binar# language. The $ocabular# is $er# simple and small; it consists of onl# . things+ ) and (. This is all that a computer understands. (?umans are comfortable with the decimal s#stem & consisting of the numbers ) to ,). 1ell loo' at the binar# s#stem later in this chapter. Remember: A computer finall# needs e$er#thing in binar# language (instructions and data).

rogramming Languages:
=ro rams are written to tell the computer to do somethin useful for us. 3t mi ht be as simple a task as addin two numbers or as complex as transferrin data between / computers in a network. There are several reasons why we need pro rams. 3ma ine searchin throu h a stack of papers to search for some telephone bill. 3ma ine a company maintainin its accounts (expenses and income on a day&to&day basis) & if this was done usin the traditional file and paper method4 someone would have to keep enterin all the details in sheets of paper and then stack them into files. 3f4 in future4 someone wants to find out when a particular product was sold they would have to manually read throu h each and every paper in each and every file. (omputers can be pro rammed to perform such tasks and they will do it faster. <asically4 the computer is very ood in performin repetitive tasks. +ne point to note8 man created computers and man pro rams computers to perform certain tasks. 2 pro ram is a set of instructions that can be executed by the computer. The computer will obediently follow whatever the pro rammer instructs it to do (as lon

as it understands the instructions). The downside to this is that the computer does not have any special intelli ence) it is only as intelli ent as it is pro rammed to be. %or instance4 a robot can be pro rammed to walk. 3f it is not pro rammed to detect obstacles4 the robot will simply ban into obstacles because it does not have the intelli ence to reco ni?e and avoid obstacles. 3f the pro rammer provides such provisions4 then the robot will be able to handle such scenarios. With many software pro rams already existin 4 you may wonder why do we need more software) why not 'ust buy and use what already exists* ,oftware is usually not custom desi ned for the re5uirements of a particular company and you may not even have software for your own special re5uirement. %or example4 dentists never used to have any software specifically for their use but now you can see a ran e of dental software (the dentist can maintain details of each of his patients$ tooth in the computer). =ro rams needn$t be as complicated as dental software) you may want to have a little software to calculate your (@=2 or to calculate your rank in class. To perform such tasks a pro rammer has to write a pro ram (or a set of instructions). These instructions are written in a specific pro rammin lan ua e and the pro rammer can chose to write the instruction in any one of the available lan ua es.

Evolution of Programming Languages:


2ny pro rammin lan ua e can be cate ori?ed into one of the followin cate ories8 "i h Level ;iddle Level Low Level (machine and assembly lan ua es)

;iddle level lan ua es are sometimes clubbed to ether under the cate ory of hi h&level lan ua es. Machine Level Languages: 2 computer has a processor and if we want the computer to do somethin then we need to direct instructions at the processor. The problem is that computers can understand only binary lan ua e (i.e. the lan ua e which comprises of only 1s and 0s). 2ll instructions to the processor should be in binary and so a pro rammer can write pro rams usin a series of 1s and 0s. :very processor will understand only some instructions (this depends on how the processor was desi ned). 2n instruction to increment a variable mi ht be8

110110100011101 3ma ine havin 100 such instructions in a pro ramA The advanta e is that no conversion (or

translation) is needed because the computer can understand the 1s and 0s. This is called machine level lan ua e and this was used at the time computers came into existence. The drawbacks are 5uite clear. <y usin machine lan ua e writin pro rams is very

tedious and also prone to error (even if one bit is wron 4 the entire pro ram functionality could et altered). Tryin to identify the error will also be a very tedious 'ob (ima ine readin a series of 1$s and 0$s tryin to locate the mistake). Assem!ly Languages: ,ince it is very difficult for us to write instructions in binary lan ua e4 assembly lan ua es were developed. 3nstead of usin a set of 1s and 0s for a particular instruction4 the pro rammer could use some short abbreviations (called 6mnemonics$) to write the pro ram (for example8 2BB is a mnemonic to add two numbers). :very processor has an instruction set that describes the various commands that the processor can understand. 2 normal instruction set will have instructions like C;= ('ump)4 2BB (for addition) and so on. 2 pro rammer will write the pro ram usin these instructions and an assembler will convert the mnemonics into binary form so that the processor can understand it. The problem is that assembly level lan ua es are specific to each processor. %or example the -0-0 (the simplest microprocessor) has an instruction set different from the -0-1 microprocessor. Thus you would have to rewrite the pro ram for each microprocessor. 2nother problem with assembly level pro rammin is that the pro rammer needs to know details about the processor$s architecture such as the internal re isters where values can be stored4 how many internal re isters are available for use etc. Low level lan ua es are very close to the hardware but difficult for writin pro rams. "igh Level Languages: Writin lar er pro rams in assembly lan ua e is 5uite difficult and hence4 hi h&level lan ua es were developed (like <2,3(). These lan ua es were not close to the actual computer hardware but were very close to the :n lish lan ua e. They tried to simplify the process of pro rammin . 3n these lan ua es the pro rammer needn$t worry about internal re isters and processor architecture) instructions could be typed in almost normal :n lish. The :n lish&like instructions had to be converted to machine lan ua e usin a compiler. +ne simple example of an :n lish like command in (+<+L is8

2BB incentive T+ basic @3D3.@ salary. The instruction is 5uite self&explanatory (2dd 6incentive$ and 6basic$ and store the result in 6salary$). (+<+L is also a hi h&level lan ua e. 2s pro rams rew lar er (for example8 maintainin a record of all employees4 accounts maintenance etc.)4 even hi h level lan ua es had certain drawbacks. These lan ua es are also referred to as unstructured form of pro rammin . The reason they are unstructured is because when a lar e pro ram is written4 it becomes very difficult to analy?e the pro ram at a later date (by someone else or even by the ori inal pro rammer himself). There are many reasons for this) one is the use of statements like @+T+ in hi h&level lan ua es. 3n any pro ram some tasks will either be performed repetitively or the pro rammer mi ht want the pro ram to execute a different set of instructions if some condition is satisfied. %or example in a division pro ram4 in case the denominator is 0 then the pro ram should not divide the two numbers) instead it should display an error messa e. +nly if the denominator is not 0 should the pro ram divide the two numbers. This kind of pro rammin is referred to as pro ram flow control. 3n a lar er pro ram there could be various other possibilities and all this was dealt with by usin the @+T+ statement. 3f you$ve used <2,3( you will be aware that for every instruction that you type4 you have to specify a line number (example 104/04E0 and so on). @+T+ will be followed by some line number (indicatin the instruction that has to be executed next. :x8 10/0 @+T+ 00 means that now you want the pro ram flow to o to line number 00). The problem with this is that in a lar e pro ram it will become very difficult for anyone to understand the pro ram lo ic. 3ma ine readin throu h 100 lines and then findin one @+T+ statement to the /00th line. Then on the /00th line there could be another @+T+ statement directin you to the 100th line. This should make it clear as to what is meant by the term 6unstructured$. This is a ma'or problem with hi h level lan ua es. 2nother fact is that hi h level lan ua es are very far away from the actual hardware. :xamples of hi h&level lan ua es are <2,3(4 %ortran (%ormula Translation)4 (+<+L ((ommon <usiness +riented Lan ua e) and L3,T (List processin ). Thus to take advanta e of hi h level and low level lan ua es4 middle level lan ua es like ( and (99 were developed. They were easy to use and tried to retain the advanta es of low level lan ua es (i.e. bein closer to the architecture).

C and C++

Hennis Kitchie de$eloped C and it was -uite popular. An interesting feature in C is the use of functions. The programmer could write a function for chec'ing whether a number is odd or e$en and store it in a separate file. %n the program, whene$er it is needed to chec' for e$en numbers, the programmer could simpl# call that function instead of rewriting the whole code. Usuall# a set of commonl# used functions would be stored in a separate file and that file can be included in the current pro/ect b# simpl# using the Minclude NfilenameO s#nta6. Thus the current program will be able to access all functions a$ailable in Jfilename. Programs written in C were more structured compared to high le$el languages and another feature was the abilit# to create #our own data t#pes li'e structures. "or instance if #ou want to create an address boo' program, #ou will need to store information li'e name and telephone number. The name is a string of characters while the telephone number is an integer number. Using structures #ou can combine both into one unit. ;imilarl# there are man# more ad$antages of using C. Though C seemed to be ideal, it was not effecti$e when the programs became e$en more comple6 (or larger). ne of the problems was the use of man# functions (de$eloped b# $arious users) which led to a clash of $ariable names. Though C is much more efficient than @A;%C, a new concept called b/ect riented Programming seemed better than C. P was the basis of C55 (which was initiall# called JC with classes). C55 was de$eloped b# @/arne ;trastroup. %n ob/ect oriented programming, the programmer can sol$e problems b# brea'ing them down into real&life ob/ects (it presented the programmer with an opportunit# to mirror real life). 1hat is an ob/ect< This topic is dealt with e6tensi$el# in the chapter on J b/ects and Classes but a brief introduction is pro$ided here. Consider the categor# of cars. All cars ha$e some common features (for e6ample all cars ha$e four wheels, an engine, some bod# colour, seats etc.). Are all cars the same< f course not. A "iat and a "ord arent the same but the# are called as cars in general. %n this e6ample cars will form a class and "ord (or "iat) will be an ob/ect.

"or those people who 'now C programming, it would be useful to 'now the differences between C and C55. @asicall# C55 includes e$er#thing present in C but the use of some C features is deprecated in C55.

C does not ha$e classes and ob/ects (C does not support ;tructures in C cannot ha$e functions.

P)

C does not ha$e namespaces (namespaces are used to a$oid name collisions). The %* functions are entirel# different in C and C55 (e6+ printf( ), scanf( ) etc. are part of the C language). Bou cannot o$erload a function in C (i.e. #ou cannot ha$e . functions with the same name in C). @etter d#namic memor# management operators are a$ailable in C55. C does not ha$e reference $ariables (in C55 reference $ariables are used in functions). %n C constants are defined as macros (in C55 we can ma'e use of Jconst to declare a constant). %nline functions are not a$ailable in C.

Cets recap the e$olution of programming languages+ initiall# programs were written in terms of (s and )s (machine language). The drawbac' was that the process was $er# tedious and highl# error&prone. Assembl# language was de$eloped to write programs easil# (short abbre$iations were used instead of (s and )s). To ma'e it e$en simpler for programmers, high le$el languages were de$eloped (instructions were more similar to regular Dnglish). As the comple6it# of programs increased, these languages were found to be inade-uate (because the# were unstructured). C was de$eloped but e$en that was not capable of dealing with comple6 or larger programs. This led to the de$elopment of C55. Note: ;ometimes languages are di$ided into low le$el and high le$el onl#. %n such a classification, C*C55 will come under high le$el languages.

#hy do you need to learn C$$% There are man# people who as' the -uestion, Pwh# should % learn C55< 1hat use is it in m# field<P %t is a well&'nown fact that computers are used in all areas toda#. Programming is useful where$er computers are used because it pro$ides #ou the fle6ibilit# of creating a program that suits #our re-uirements. D$en research wor' can be simulated on #our computer if #ou ha$e programming 'nowledge. Construction and programming ma# appear to be miles apart but e$en a ci$il engineer could use C55 programming. Consider the case of constructing a ph#sical structure (li'e a pillar) in which the ci$il engineer has to decide on the diameter of the rods and the number of rods to be used. There are . $ariables in this case+ (. The number of rods needed (lets denote it as Jn) and .. The diameter of each rod (lets call it as Jd) The ci$il engineer might ha$e to ma'e a decision li'e+ P%s it cost&effecti$e for me to ha$e () rods of 8cm diameter or is it better to ha$e 9 rods of >cm diameter<P This is /ust one of the simple -uestions he ma# ha$e in his mind. There are a few related -uestions+ P1hat is the best combination of number of rods, their diameters and will that combination be able to handle the ma6imum stress<P Usuall# e-uations are de$eloped for each of the factors in$ol$ed. %t would be much easier if the ci$il engineer could simpl# run a program and find out what is the best combination instead of manuall# tr#ing out random $alues and arri$ing at a solution. This is where programming 'nowledge would benefit the engineer. An# person can write a good program if he has ade-uate 'nowledge about the domain (domain refers to the area for which the software is de$eloped. %n this case it is construction). ;ince the ci$il engineer has the best domain 'nowledge he would be able to write a program to suit his re-uirements if he 'new programming. Programming is applicable to almost e$er# field& ban'ing (for maintaining all account details as well as the transactions), educational institutions (for maintaining a database of the students), supermar'ets (used for billing), libraries (to locate and search for boo's),

medicine, electrical engineering (programs ha$e been de$eloped for simulating circuits) etc.

Terms used in C++

Compiler : @efore pro$iding a technical e6planation a compiler in la#mans language is a

program which will read through the C55 program code (code refers to the program written b# the programmer) line b# line. The compiler will read each and e$er# character that has been t#ped in the program code. After reading the entire code, the compiler will con$ert the code into machine le$el format (i.e. )s and (s). The compiler is $er# dedicated and hard wor'ing since it will meticulousl# read each and e$er# character. Technicall# spea'ing, the microprocessor in a computer can understand onl# binar# numbers (onl# )s and (s). %t is not possible for us to write programs in binar# numbers. Compilers will con$ert the coding for a program into machine understandable form (i.e. it will con$ert the instructions we t#pe into machine understandable form). The instructions we t#pe (in something similar to Dnglish), is 'nown as the source code. The compiler con$erts the source code into the ob/ect code (which the microprocessor understands and we cannot understand). There is a detailed discussion on this topic in the chapter QAd$anced TopicsR. If you are new to programming you might wonder as to where you should type your $55 program. "irst of all #ou should ha$e a C55 compiler. There are man# compilers a$ailable for free on the !et and the# can be downloaded from the !et. After downloading the compiler, create a new C55 source file and t#pe the C55 code in the compiler. Cater on in this boo', we shall see how to run a C55 program in the compiler. A few compilers a$ailable on the !et are + (. @orland C55 compiler + www.borland.com*bcppbuilder*freecompiler*

.. @loodshed He$ C55 compiler + www.bloodshed.net*de$cpp.html :. HELPP C55 compiler 2. "or Cinu6*Uni6 the L!U C55 compiler is a$ailable in standard installations of the operating s#stem. =ost compilers nowada#s pro$ide an %ntegrated He$elopment Dn$ironment (%HD), i.e. the# ha$e an editor, a compiler, a lin'er and some e6tra tools (li'e a debugger). %n schools and colleges the most commonl# used compiler is Turbo C55. =ost of the programs written in this boo' are compatible with Turbo C55. %t is better to use Sisual C55 because ad$anced features li'e namespaces and e6ception handling are not a$ailable in older $ersions of Turbo C55. All compilers will support the basic features of C55. %f #ou are using Cinu6*Uni6 then #ou will be ha$ing the L!U C55 compiler in #our Cinu6 distribution CH (this compiler is freeware but it doesnt ha$e a graphical user interface& it can onl# be used from the command line; refer to the Appendi6 section).

$eywords :

6eyword is a word that the compiler already knows, i.e. when the compiler sees a 'e#word somewhere in the program it 'nows what to do automaticall#. +or e"ample, when the compiler encounters the 'e#word Jint, it 'nows that Jint stands for an integer. r if the compiler reads a Jbrea', then it 'nows that it should brea' out of the current loop.

%ariable and Constant :

As the name suggests, a $ariable is something whose $alue can be changed throughout the program. %t is not fi6ed. n the other hand, a constant is one whose $alue remains the same (constant) throughout the program.

&perators and &perands:

perator is something that performs operation on a $ariable. "or e6ample 5 is an operator that performs the addition operation. The terms on which the operator operates are 'nown as the operands. %n the e6pression 65# 6 and # are 'nown as the operands and 5 is the operator.

E'pression:

D6pression performs an operation and consists of operators and operands (or $ariables). aOb This is an e6pression in which a and b are the operands. O is the operator.

Binary and (nary:

@inar# means Jtwo and Junar# means one. A binar# operator operates on two operands (or two $alues) whereas a unar# operator operates on /ust one operand.

De)inition and Declaration :

%n C55 these two terms are used fre-uentl#. Heclaration of a $ariable means telling the compiler that this $ariable is an integer, or this $ariable is a character. A declaration will inform the compiler about the t#pe of a $ariable. Hefining a $ariable means allocation of memor# space b# the compiler for that particular $ariable. %n the case of $ariables, a single statement performs both declaration and definition. "or e6ample+ the statement int 6; declares and defines J6 as an integer. Kemember that declaration is /ust declaring the t#pe of something (telling the compiler what data t#pe it belongs to) but definition means allotting space to it. %t ma# seem as if both are one and the same; in man# cases the# are but in a few places the# are not (these cases will be dealt with later).

*nitiali+ation :

%nitialiGation refers to the first (initial) assignment of a $alue to a $ariable. 6 7 8); This initialiGes the $alue of 6 to 8). Alwa#s remember that the $alue to the right of the e-ual sign will be assigned (or stored) to the $alue on the left of the e-ual sign. +or e"ample7 a 7 b; This means that $alue of b is assigned to a.

Parentheses, braces, an"le and square brac-ets :

There are different t#pe of brac'ets+

Parentheses are /ust the normal brac'ets ( ). @races are T U. Angular brac'ets are N O. ;-uare brac'ets are V W.

All of these brac'ets are used in C55 but each one is used for different purposes.

Character:

Characters include alphabets, numbers and other special s#mbols as well (li'e 4, *, & etcI). Usuall# one tends to thin' of characters as onl# alphabets; but remember a character could be an#thing (an alphabet, a number, a special s#mbol on #our 'e#board or e$en a blan' white space is a character).

ynta' : D$er# language has its own Js#nta6. @# the term s#nta6 we refer to the

structure of a language and use of correct language. Dnglish has its own set of rules while "rench has slightl# different rules. The $ocabularies of both the languages are also different. Programming is also another language (thats it is called programming language). Eust li'e an# other language it has its own set of rules that must be complied with. This is 'nown as the s#nta6. nl# if the programmer adheres to the s#nta6 will the compiler understand the instructions.

Errors: This is a $er# common term in programming languages. %n fact it is $er#

common to hear someone sa#, P;#nta6 DrrorP. Drror means a mista'e and s#nta6 error means that there is a mista'e in the s#nta6. The compiler reads the entire program before e6ecution. 1hile reading the program, if the compiler disco$ers that it cant understand some instruction it will displa# an error message. Till the error is cleared, the program cannot be e6ecuted. The compiler will gi$e a s#nta6 error if the s#nta6 has not been adhered to properl#. Drrors generated b# the compiler are 'nown as compile&time errors. There are other t#pes of errors as well. The compiler is not intelligent to detect all t#pes of errors. "or instance if the programmer ma'e a logical error, the compiler will ne$er

'now it. ;uppose a program is written for adding two numbers and in the coding, instead of the 5 operator, the 0 operator has been used. The compiler will not recogniGe an# error during compilation and the program will e6ecute (but the programmer will not get the desired output). This is a logical error and as a programmer #ou ha$e to be $er# careful while coding. The compiler is not brilliant enough to 'now what is in the programmers mindF

E'ecutable )ile and lin-ers:

D6ecuting refers to the process of running a program. 1e$e tal'ed about ob/ect file, but can we e6ecute ob/ect files directl#< The compiler produces an ob/ect code but this ob/ect code generall# depends on some other e6ternal files. "or e6ample+ if #ou are using comple6 mathematical functions, #ou might ma'e use of functions which ha$e been defined b# some other programmer. That programmer would ha$e created a librar# which #ou can include in #our source code (instead of creating those functions in #our program). A librar# is a collection of ob/ect files. Thus #our program will actuall# depend on the other ob/ect files for some of the comple6 mathematical functions which #ou$e used. ;omeone now has to lin' up all these ob/ect files to produce an e6ecutable file. This wor' is done b# the Jlin'er. =ost modern compilers ha$e a lin'er included in them. Cin'ers are discussed in detail later. Remember: Dach C55 source code needs to be compiled separatel# to produce an ob/ect code (ten source codes mean that well ha$e ten ob/ect codes). "inall# the lin'er has to combine these ten ob/ect codes to produce one single e6ecutable module.

Debu""in":

is the process of troubleshooting a program (of course its done when the program doesnt wor' up to #our e6pectationF). Hebugging is the process of identif#ing bugs in the code. A bug is a programming term for an Jerror.

Some extra details:


.n interestin" point /about $ilo, Me"a etc01:

Bou might ha$e read that (Ailob#te 7 ().2 b#tes and perhaps #ou thought about it as well, Q;houldnt (Ailob#te 7 ())) b#tes<R Cets start with our familiar decimal s#stem. %n the decimal s#stem, ( Ailo unit 7 ())) units. "or e6ample+

( Ailometer 7 ())) meters 7 (): meters ( Ailogram 7 ())) grams 7 (): meters ( =egawatt 7 ())) Ailowatts 7 ()))))) watts 7 ()> watts

This is fine as far as the decimal s#stem is concerned. ?ere the base used is () and we e6press e$er#thing in powers of (). Computers spea' in binar# language and the base used here is .. Cets e6tend the concept of J'ilo to the binar# s#stem. Can we represent the $alue ())) as a power of .< Cets tr#+ Power .) .( .. .: .2 .8 .> .3 .9 ., .() %alue ) . 2 9 (> :. >2 (.9 .8> 8(. ().2

opsF 1e$e /ust e6ceeded ())) in .(). %n the binar# s#stem, the closest we come to ())) is ().2. Thus ( Ailob#te 7 ().2 b#tes (but for rough calculations we assume it as ())) b#tes).

Recap of the First Unit:


F F (omputers only understand binary lan ua e (1s and 0s). - bits form a byte.

The different types of stora e are8 internal (=> re isters4 G2;4 G+; and secondary stora e. G2; is used as main memory and data is present only as lon as the computer is switched on. ;ain memory is directly accessible by the computer whereas secondary memory is not. Burin execution pro rams should be present in the main memory. Word&si?e of a machine depends on the si?e of the processor$s internal re isters. ;achine level lan ua e is written in 1s and 0s. 2ssembly level lan ua es make use of mnemonics (mnemonics are abbreviated :n lish words used to represent instructions). "i h level lan ua es like <2,3( are in simple :n lish but they are far away from the real hardware of the system. ( has the advanta es of both hi h level and low level lan ua es. <ut it doesn$t support +b'ect +riented =ro rammin (++=). (99 is actually ( with classes (i.e. it supports ++=). 2 compiler is re5uired to convert the source code (i.e. the instructions we type in :n lish) into the ob'ect code (i.e. the machine lan ua e which the computer understands). 1 kilobyte H 10/7 bytes (and not 1000 bytes).

F F F F F

F F

our very first C++ Program


All the e6ample programs in this boo' ha$e been tested in Turbo C55 compiler (the programs were also tested in Sisual C55 >.)). The# should run on other C55 compilers as well. Cet us start with a basic C55 program. This will gi$e #ou an idea about the general structure of a C55 program. Cets write a program in which the user can enter a character and the program will displa# the character that was t#ped+

** =# first C55 program M include Niostream.hO int main( ) T char letter; cout NN PDnter an# letterP ; cin OOletter; cout NN PThe letter #ou entered is + P NNletter; return ); U

8"planation for the above program7

!! My )irst C22 pro"ram+ The first line in the abo$e program forms the Jcomments. %n C55, an# line that is t#ped after the two slashes ( ** ) is 'nown as comments. The compiler does not read comments. Comments can be used an#where in a program and #ou can write an#thing that #ou want in the comments. Comments are useful when a programmer (or someone else) reads the source code in the future. Proper comments will ma'e it easier for an#one to understand the program logic. 1hen #ou write a $er# long program, #ou will appreciate the use of comments. 3 include 4iostream0h : !e6t comes the pre&processor directi$e. Preprocessor directi$es are instructions meant specificall# for the preprocessor. @efore compiling a program, the preprocessor will scan the program and perform te6t substitutions in the source code. The preprocessor directi$e usuall# comes at the beginning of the program (all directi$es for the preprocessor start with the M s#mbol). 4.h files are 'nown as header files. There are man# other header files li'e+ conio.h, graphics.h etc. There are certain operations that #ou will fre-uentl# use in a C55 program. Hefining these operations in each program is a cumbersome process and leads to more lines of code. Thus these standard operations ha$e been written in header files which a programmer can include in his coding (rather than coding e$er#thing again). 1e can also create our own header files (well loo' at this later). 1hen the preprocessor encounters Minclude Niostream.hO, it will ph#sicall# include the iostream header file in #our source code (i.e. the entire file called iostream.h file will be pasted in #our source code). This is one of the standard header files which #oull use in almost all of #our C55 programs.

int main/ 1 + D$er# C55 program has to ha$e one Jmain function. "unctions will be e6plained later. Kemember that the compiler will e6ecute whate$er comes within the Jmain function. ?ence the instructions that ha$e to be e6ecuted should be written within the Jmain function. Eust as the name implies, Jmain is the main part of the C55 program and this is the entr# point for a C55 program. 5 + "unctions are defined within a bloc' of code. D$er#thing within the opening and closing braces is considered a bloc' of code. Jmain is a function and hence we define this function within braces. This is as good as telling the compiler, QThe Jmain function starts hereR. char letter6 + Jletter is the name of a $ariable. %nstead of the name Jletter we could also use an# other name. Jchar defines Jletter as a character $ariable. Therefore, the $ariable Jletter will accept the $alue of onl# one character. cout 44 7Enter any letter7 6 + This is followed b# the NN operator ('nown as the insertion operator). "ollowing this operator, an#thing t#ped within double -uotes will be displa#ed on the screen. Kemember that cout and NN go together. Jcout is 'nown to the compiler alread# (since it is defined in the iostream header file which has been included). ;o when the compiler comes across coutNN, it 'nows what to do. cin 88letter6+ cin is the opposite of cout. cinOO is used to obtain the $alue for a $ariable from the user. (OO is 'nown as the e6traction operator). %nput is usuall# obtained from the 'e#board. return 96 + This statement tells the compiler that the Jmain function returns Gero to the operating s#stem (return $alues will be discussed in the chapter on functions). :+ The closing brace is used to tell the compiler that Jthis is the end of the function. %n our case, it is the end of the Jmain function and this indicates the end of the program as well.

Bou might ha$e noticed in the abo$e program that e$er# statement is terminated with a semi&colon (;). That is e6actl# the use of the semi&colon. %t is used to tell the compiler that one instruction line is o$er. %f #ou dont put semi&colons in #our program, #ou will get errors while compiling. A $ariable is used for temporar# storage of some data in a program. %n the abo$e e6ample, Jletter was a $ariable. D$er# $ariable belongs to a particular t#pe (referred to as data t#pe). The different data t#pes in C55 are discussed later. %n the abo$e program+ char letter6

declares Jletter as a character $ariable (a character is one of the basic data t#pes in C55). 1hen the compiler encounters this statement, it will allocate some memor# space for this $ariable (i.e. an# $alue which is assigned to the $ariable Jletter will be stored in this allocated memor# location). 1hen the re-uired memor# space has been allocated we sa# that the $ariable has been defined (in this case a single statement will declare and define the $ariable Jletter).

ome points to remember: 1hen we want to displa# something on the screen we will code it as+ coutNNvariable-name; 1hen we want to obtain a $alue for a $ariable from the user we will sa#+ cinOOvariable-name; @eware of the direction of the OO and NN operators. %n the statement coutNN$ariable; information flows from the $ariable into Jcout (which means it goes to the monitor displa#). 1hen we sa# cinOO$ariable; information (the $alue of the $ariable) flows from Jcin (which would be the 'e#board) into the $ariable (i.e. the $alue is stored in the $ariable). %nformation will flow in the direction of the arrows (NN or OO). Jcout is lin'ed to the standard displa# de$ice (i.e. the monitor) while Jcin is lin'ed to the standard input de$ice (i.e. the 'e#board). ?ence, #ou cant use coutOO$ariable; This will cause an error while compiling. Jcout and Jcin are alread# pre&defined and so #ou can use them directl# in #our programs. Xiostream.h is a header file that is used to perform basic input and output operation (or general %* li'e using Jcin and Jcout). Remember: C55 is a case&sensiti$e language, which means that the compiler will not consider Jletter, JCDTTDK and JCetter as the same.

!o" to run your first program in t#e $ompiler%

&aving and compiling the program: There are man# C55 compilers a$ailable in the mar'et. ;ome of them are freeware (meaning that the# are free to use) while others ha$e to be paid for. Turbo C55 compiler might be the simplest to use (but it is not freeware). ;impl# choose P!ew "ileP and t#pe out the program coding. ;uppose #ou are using some other compiler, clic' on "ile and choose P!ewP. ;ome compilers ma# ha$e the option of creating a C55 source file while other compilers ma# re-uire a new pro/ect to be created. 1hate$er the method #ou will ultimatel# come to the step of creating a C55 source file. After t#ping the code in the compiler, sa$e the file b# gi$ing it some name. The P;a$e AsP option will appear under the P"ileP menu. Li$e a name (for e6ample+ first). !ow the file is sa$ed as first.cpp. All C55 source files are sa$ed in 4.cpp format. Eust li'e 4.doc represents a 1ord document file, 4.cpp denotes a C55 (C Plus Plus) source file. %n the compiler program there will be an option called JCompile in the menu bar. ;elect the compile option and the compiler will do its wor'. %t will compile the program (or in other words, it will read whate$er has been t#ped) and in case there are an# errors, the compiler will point out the line where the error was detected. Chec' whether the program has been t#ped e6actl# as gi$en earlier. D$en if a semi&colon is missing, it will lead to errors. %f the compiler sa#s no errors (or if the message Pcompiled successfull#P appears), then #ou can go to the ne6t stage+ building the 4.e6e file. 4.e6e file e6tension stands for e6ecutable files. A 4.cpp file cannot be run directl# on the computer. This has to be con$erted into a 4.e6e file and to do so select the P=a'e or @uild e6eP option in the compiler. The file Jfirst.e6e will be created. !ow the program can be e6ecuted from the H ; prompt b# t#ping Jfirst. @ut instead of running the program e$er# time from H ;, it will be con$enient to run the program from the compiler itself and chec' the output. %n the compiler there will be another option called PKunP. Eust clic' on this and the program will run from the compiler itself (#ou neednt switch bac' and forth between H ; and the compiler screen).

The figure should gi$e #ou a rough idea as to how the e6ecutable file is created from the C55 source code.

The source code is the program that #ou t#pe. ;ource code is con$erted into ob/ect code b# the compiler. The lin'er will lin' #our ob/ect code with other ob/ect codes. This process of creating a C55 program is discussed in the last chapter.

Modi)ication that mi"ht be needed in )irst0cpp /dependin" on your compiler1:

A little problem might be encountered while running #our program from the compiler (this problem will e6ist in Turbo C55 compiler). 1hile running the program from the H ; prompt, this problem will not occur. 1hats the problem< 1hen first.cpp is e6ecuted from the compiler the program will as' the user to enter a character. nce a character has been entered, the program will return to the compiler screen. Bou wonXt see #our outputF %t might appear as if there is some problem with the program. 1hat happens is that the program displa#s the character on the screen, immediatel# terminates the program and returns to the compiler screen. This happens so fast that #ou cant see the output being displa#ed. *odify your program as shown below !if you are using Turbo $55#7 ** Bour first program modified+ first.cpp M include Niostream.hO M include Nconio.hO int main( ) T char letter; coutNN PDnter an# letterP ; cinOOletter; coutNN PThe letter #ou entered is + P NNletter; getch( ); return ); U

Another header file called conio.h has been added. The function getch( ) is used at the end of the program. getch ( ) is defined in the conio.h header file. getch( ) stands for JLet Character. 1hen getch ( ) is e6ecuted, the program will wait till the user t#pes a character (an# character). nl# after a character is t#ped will the program mo$e to the ne6t instruction. %n the abo$e program, there is no statement other than return ); after getch ( ). ?ence program flow is as follows+ The program as's the user to enter a letter. The user enters a letter. Then the program displa#s the t#ped letter on the screen. The program will not -uit at this point since there

is a statement getch ( ). %t will wait till the user t#pes another character. 1hen the user presses a character the program will -uit. T#pe the abo$e program, sa$e and run it from the compiler. ;ome compilers ha$e named the function getch( ) as Ygetch( ). This function also re-uires the conio.h header. Remember: conio.h is not a$ailable with all compilers and getch( ) function is not a standard C55 function. ;ome compilers pro$ide it but most do not. %n other compilers if a similar problem is encountered while displa#ing the result tr# using getchar( ); instead of getch( ); getchar( ) function doesnt re-uire the conio.h header file. %f the compiler does not recogniGe getchar( ), then instead of adding an# of the in&built functions, /ust add another line as follows+ cinOOletter; at the end of the program /ust before return ); The program flow will be the same as described earlier. The latest compilers, li'e SC55 (=icrosoft Sisual C55 compiler) do not ha$e an# of the abo$e problems e$en if the program is run from the compiler. SC55 will alwa#s as' the user to press a character to terminate the program. Another alternati$e is to use a function called Js#stem, which is defined, in the header file+ stdlib.h.

s#stem(PPAU;DP);

can be used to pause the program (i.e. e6ecution of the program will continue onl# when the user presses a 'e#).

s#stem(PCC;P);

can be used to clear the displa# screen. To use these two functions #ou ha$e to t#pe Minclude Nstdlib.hO header file in #our source code. The s#stem( ) function actuall#

e6ecutes a H ; command. (Tr# gi$ing the commands Jcls and Jpause in #our H ; prompt).

&ata Types
The following topics are co$ered in this section+

%ntroduction %nteger "loating T#pe Houble Character @oolean Hata T#pe Kanges and determining the ranges =ore on @inar# !umbers

D$er# piece of data has to belong to some basic categor#. Consider a simple e6ample in real life+ e$er# number has to be of a particular t#pe. The number 8 is a natural number (or it can be called as a whole number). >.8 is a real number (it has a decimal point). ;imilarl#, in programming we ha$e what are called as data t#pes. 1hen a $ariable is declared, the programmer has to specif# which data t#pe it belongs to. nl# then will the compiler 'now how man# b#tes it should allocate for that particular $ariable. r in other words, each data t#pe occupies a different memor# siGe and if a $ariable is declared as belonging to one particular data t#pe it cannot be assigned a different data t#pe $alue. %n simpler terms, suppose the $ariable J6 is declared such that it can hold onl# whole numbers; then it cannot (and should not) be assigned some alphabet. There are two categories of data t#pes+ fundamental data t#pes and user&defined data t#pes. The second category of data types will be dealt with later. The fundamental (or built&in or primiti$e) data t#pes are+

%nteger "loating Point Character Houble

@ool

The first three data t#pes+ integer, floating point and character are used fre-uentl#.

'nteger (int):
An integer can contain onl# digits (numbers) from ) to ,. D6amples of integers are+

) () :28 >39, &.: &>))

%t includes positi$e and negati$e numbers but the numbers ha$e to be whole numbers. %t does accept the decimal point. ?ence the following numbers are not integer data t#pes+

:.8 2.9 )..:

These numbers come under the second categor# (floating point t#pe) and not under integers. %f the program has to accept such $alues from the user do not declare the $ariable as an integer. %f a $ariable is declared as an integer and the user enters a $alue of ..:, the program will assign . as the $alue for that integer $ariable. ;imilarl#, if the user enters :.., the program will assign : to the integer $ariable. Remember: nce a $ariable is declared as an integer, it will onl# store whole numbers (if the user t#pes a $alue with the decimal point, the program will ignore e$er#thing that is t#ped after the decimal point). ?ow to declare a $ariable as belonging to the t#pe integer< The s#nta6 is+ int variable-name; Dach data t#pe occupies a certain amount of memor# space. An integer will occup# . b#tes of memor# (which means (> bits). "rom this it is possible to calculate the ma6imum and minimum $alues that an integer can store. .Z(> 7 >88:> (hence >88:> different combinations of (> bits are possible). Hi$ide this b# . because integers (b# default) range from negati$e to positi$e $alues. 1e ha$e a ) in between and so subtract

one from this to get :.,3>3. ?ence an integer can ta'e $alues from 0:.,3>9 up to 5:.,3>3 (a total of >88:> different $alues). A natural -uestion springs to mind, P1hat would happen if a $alue greater than :.,3>3 is entered<P ;ince this $alue cannot be accommodated within the allocated two b#tes, the program will alter the $alue. %ts not e6actl# altering the $alue; it will basicall# change #our $alue into something different. The user might enter (.:28> as the integer $alue but the program will store it as 03>.: or something li'e that. 1hene$er #ou use $ariables ensure that #ou ha$e declared them as belonging to the correct data t#pe. This restriction on ma6imum range might seem to be a problem. %n C55 J-ualifiers can be used to $ar# the range of fundamental data t#pes. [ualifiers are onl# supplements to the basic data t#pes and the# cannot be used separatel# on their own. The# wor' onl# with a basic (or fundamental) data t#pe. The 2 -ualifiers a$ailable in C55 are+ (. .. :. 2. ;hort Cong ;igned Unsigned

;igned and unsigned integers were discussed in the first chapter. 1hen an integer is specified as signed, then automaticall# the most significant bit of the number is used as a sign bit (to denote the sign of the number). ?ence it can be used if the programmer needs positi$e and negati$e number $alues for the $ariable. @# declaring a $ariable as an integer, b# default #ou can specif# both positi$e and negati$e $alues. @# default an integer is a signed integer. %n other words, int variable-name9 is the same as signed int variable-name; %n the second form, Jsigned is the -ualifier and it is used to e6plicitl# state that the $ariable is a signed integer. "or an unsigned integer the s#nta6 will be+ unsigned int variable-name; An unsigned integer can hold a $alue up to >8,8:8 (a signed integer can hold onl# up to :.,3>3). f course, in an unsigned integer #ou cannot assign a negati$e $alue. The range is from ) to >8,8:8. To go be#ond >8,8:8 and ma'e use of both positi$e and negati$e $alues as well, the -ualifier long should be used.

long int variable-name; Cong integers occup# 2 b#tes of memor# (:. bits). Kemember, long int actuall# means signed long int (#ou can gi$e positi$e and negati$e $alues). %f #ou specif# unsigned long int variable-name; #ou can onl# assign positi$e $alues to the $ariable. Thus, two -ualifiers can be used together with a basic data t#pe. 1hat about the Jshort -ualifier< ;hort integer is the same as a signed integer. %t occupies two b#tes and has the same range of positi$e and negati$e $alues as the normal integer case. int 6; is usuall# the same as short int 6; Compilers (depending on the operating s#stem) will assume Jint as a Jlong int or a Jshort int. SC55 (since it wor's in the 1indows ;) will default to Jlong int if #ou specif# a $ariable as t#pe Jint (i.e. it will allocate 2 b#tes to an Jint $ariable). Turbo C55 (which is a H ; based compiler) will default to Jshort int when #ou specif# a $ariable as t#pe Jint. Thus the statement+ int $ar; will allocate J$ar 2 b#tes if #ou are using SC55 but the same statement will allocate . b#tes if #ou are using Turbo C55 compiler. Programmers sometimes prefer to e6plicitl# state what t#pe of integer the# want to use b# ma'ing use of the Jshort and Jlong -ualifiers. Jshort int alwa#s occupies onl# . b#tes (irrespecti$e of whether the ; is 1indows or H ;) while a Jlong int alwa#s occupies 2 b#tes. Two -ualifiers can be used together, but do not tr# using+ short long int variable-name; This will cause a compile&time error. ;o be careful with what -ualifiers #ou use. And remember that the default for int is e-ui$alent to short si"ned integer.

*loating Types (float):


"loating t#pe data include integers as well as numbers with a decimal point. %t can also ha$e an e6ponent. D6ponent means () to the power of some integer $alue (whole number). .)))) 7 . 6 ()Z2 7 .e2 7 .D2. %f #ou specif# decimal numbers, floating point data t#pe will store up to a precision of > digits after the decimal point. ;uppose ).(.:28>3 is assigned to a floating&point $ariable, the actual $alue stored would be ).(.:283 (it will round up to the si6th digit after the decimal place). Salid floating&point numbers are+

).(.3> (..: (.) ().. .e8 (this will be t#ped in #our code as .e8)

Ho not use an e6ponent with a decimal point. "or e6ample+ .e... is an in$alid floating point because the e6ponent has to be an integer. "loating point numbers use 2 b#tes of memor# and has a much greater range than integers because of the use of e6ponents. The# can ha$e $alues up to ()Z:9 (in positi$e and negati$e direction). The same -ualifiers used for an integer can be applied to floating point numbers as well. To declare a floating $ariable, the s#nta6 is+ float variable-name9

&ouble (double):
This is similar to the floating&point data t#pe but it has an e$en greater range e6tending up to ():)9. The s#nta6 to declare a $ariable of t#pe double is+ double variable-name9 Beware: Sisual C55 (SC55) usuall# uses its default as Jdouble instead of Jfloat. ;uppose we t#pe+ float 67:(.82; #ou will get a warning message sa#ing that a Jdouble (i.e. :(.82) is being con$erted into a floating point. %t is /ust to warn #ou that #ou are using a Jfloat and not a Jdouble. (D$en if there are warnings, there wont be an# problem in running #our program).

C#ara$ter ($#ar):

A character uses /ust one b#te of memor#. %t can store an# character present on the 'e#board (includes alphabets and numbers). %t can ta'e numbers from ) to , onl#. The following are $alid characters+

A @ : a + J *

%f the number (: is entered as the $alue for a character, the program will onl# store ( (i.e it will store the first character that it encounters and will discard the rest). A character is stored in one b#te (as a binar# number). Thus whate$er the user enters is con$erted into a binar# number using some character set to perform this con$ersion. =ostl# all computers ma'e use of the A;C%% (American ;tandard Code for %nformation %nterchange). "or e6ample, according to the A;C%% coding, the letter JA has a decimal $alue of >8 and the letter Ja has a $alue of ,3. There is another form of coding called the D@CH%C (D6tended @inar# Coded Hecimal %nformation Code) which was de$eloped b# %@= and used in %@= computers. ?owe$er, A;C%% remains the most widel# used code in all computers. The table at the end of the boo' gi$es a listing of the A;C%% $alues and their e-ui$alent characters. The s#nta6 to declare a $ariable which can hold a character is+ char variable-name9

Boolean Type (bool)


This data t#pe will onl# accept two $alues+ true or false. %n C55, Jtrue and Jfalse are 'e#words. Actuall# a $alue of true corresponds to ( (or a non&Gero $alue) and a $alue of false corresponds to ).

Minclude Niostream.hO int main( ) T bool chec'; chec' 7 true; coutNNchec'; return ); U

**output will be ( (since Jchec' is true)

Remember: The siGe of data t#pes gi$en abo$e is a general case. Hata t#pe siGes depend on the operating s#stem. ;o it ma# $ar# from s#stem to s#stem.

&ata Type +anges


Bytes Name /Compiler dependent1 char bool short long ( ( . 2 Description Character or 9 bit integer. @oolean t#pe. %t ta'es onl# two $alues. (> bit integer. :. bit integer. Ran"e /depends on number o) bytes1 signed+ &(.9 to (.3 unsigned+ ) to .88
true

or false

signed+ &:.3>9 to :.3>3 unsigned+ ) to >88:8 signed+&.(2329:>29 to .(2329:>23

int

.*2

%nteger. Cength depends on the siGe of a Jword used b# the perating s#stem. %n =;H ; Hepends on whether .*2 b#tes. a word is . b#tes and so an integer is also . b#tes. "loating point number. double precision floating point number. :.2e 5 * & :9 (3 digits) (.3e 5 * & :)9

float double

2 9

Remember: Jshort int alwa#s occupies onl# . b#tes (irrespecti$e of whether the ; is 1indows or H ;) while a Jlong int alwa#s occupies 2 b#tes. Determinin" the ran"e:

Bou might be wondering wh# the ranges are from &(.9 to (.3 or from &:.3>9 to :.3>3< 1h# not from 0(.9 to (.9< 1ell ta'e the case of signed characters to understand the range. A character occupies one b#te (9 bits). %n a signed character the =;@ (i.e. the 3th bit is used to denote the sign; if the =;@ is ( then the number is negati$e else it is positi$e). The binar# number+ )((( (((( represents 5(.3 in decimal $alue (we$e seen about con$ersion from binar# to decimal numbers in the first chapter). The number )))) )))) represents ) in decimal. @ut what about ())) ))))< ;ince the =;@ denotes a negati$e number, does this stand for 0)< ;ince there is no point in ha$ing a 0) and a 5), computers will ta'e ())) )))) as 0(.9. )))) )))) is ta'en to be Gero. Thus in the negati$e side we ha$e a least $alue of 0(.9 possible while in the positi$e side we can ha$e a ma6imum of onl# 5(.3. Another point to note is that negati$e numbers in computers are usuall# stored in .s complement format. "or e6ample+ ())) )))( actuall# stands for 0( but if this number is stored in .s complement format then it stands for 0(.3. ;imilarl# ())) ))() would appear to be 0. but is actuall# 0(.>. To understand .s complement #ou should 'now about (s complement. Cet us sa# we ha$e a signed binar# number+ ())) )))(. The (s complement of this number is (((( ((() (i.e. to find the (s complement of a binar# number /ust change the (s to )s and )s to (s but do not change the sign bit). To find the .s complement /ust add ( to the (s complement. ?ence the .s complement of ())) )))( is (((( (((( (or 0(.3). %n the same wa# the .s complement of (((( (((( (&(.3) is ())) )))( (or 0(). Thus the computer instead of storing (((( (((( (for 0(.3) will store the .s complement of the number (i.e. it will store ())) )))(). Remember: 1hen con$erting a number to its .s complement lea$e its sign bit unchanged. And numbers are stored in .s complement format onl# if the# are negati$e. Positi$e numbers are stored in the normal format.

More on Binary Numbers: D$er#thing in the computer is stored in binar# format. D$en if we as' the computer to store an octal number or a he6adecimal number in a $ariable, it will still be stored in binar# format (well see this later) because computers onl# understand )s and

(s. ?ow does a computer perform calculations< Bes, it has to do it in binar# format. Cets ta'e an e6ample of binar# addition+ ) ) ( ) ( ( ) ( ( ) ) ( ( ) ) ) (()>)() (8.)()

&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& ( ) ) ( ( ( ( )

"irst of all, what . decimal numbers are we adding< Con$ert them to decimal and #oull get+ ()> and 8.. 1hen the computer has to add ()> and 8., it would in effect be adding the . binar# numbers as shown abo$e. @inar# arithmetic is simple+ )5)7) (5)7( )5(7( ( 5 ( 7 ) and a carr# of (

Use this and tr# out the addition of ()> and 8.. SoilaF Boull get the answer of (89. Proceeding further, we need to in$estigate as to how negati$e numbers are reall# stored in computers. 1e discussed earlier that if 5() is represented as )))) ()() then &() would be represented as ())) ()() (since the =;@ is considered as the sign bit). Kight< Cets chec' it out. %f we add &() to () then we should get the answer as Gero. ) ( ) ) ) ) ) ) ( ( ) ) ( ( ) )

&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& ( ) ) ( ) ( ) )

And the answer is< &.). ;o, where did we go wrong< ne -uestion #ou might ha$e is wh# did we add the sign bit also< The computer isnt smart enough (or rather it doesnt ha$e the circuitr#) to separate the sign bit from the rest of the number. The . numbers that #ou want to add, are fed as input to an adder circuit which will blindl# add up both the numbers and gi$e the result. To o$ercome this problem, we can ma'e use of .s complement. "or e6ample+ ())) )))( actuall# stands for 0( but if this number is stored in .s complement format then it stands for 0(.3. ;imilarl# ())) ))() would appear to be 0. but is actuall# 0(.>. To understand .s complement #ou should 'now about (s complement. Cet us sa# we ha$e a signed binar# number+ ( ) ) ) ) ) ) (

The (s complement of this number is ( ( ( ( ( ( ( )

To find the (s complement of a binar# number /ust change the (s to )s and )s to (s but do not change the sign bit. !e6t, to find the .s complement /ust add ( to the (s complement. ( ( ( ( ( ( ( ) ( &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& ( ( ( ( ( ( ( (

?ence the .s complement of ())) )))( is (((( (((( (or 0(.3). %n the same wa# the .s complement of (((( (((( (&(.3) is ())) )))( (or 0(). Thus the computer instead of storing (((( (((( (for 0(.3) will store the .s complement of the number (i.e. it will store ())) )))(). 1h#< Cets go bac' to our initial problem of adding 5() and &(). !ow lets assume that the computer stores &() in .s complement format. The addition will now be+ ) ( ) ( ) ( ) ( ( ) ) ( ( ( ) ) (5()) (&())

&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& ) ) ) ) ) ) ) )

SoilaF The answer is ). @ut #ou ma# as' Jwhat about the carr# of (<. 1ell, since it is an e6tra bit, it o$erflows (which means it is lost and we neednt worr# about it). %m not going to get into more details of .s complement since this should be sufficient for learning C55. To learn more on this sub/ect, #ou can chec' out boo's on digital s#stems or computer s#stem architecture. Note: 1hen #ou perform binar# addition, ( 5 ( is e-ual to ) and a carr# of ( (because in the binar# s#stem we onl# ha$e . states+ ( and ); so we cant ha$e ( 5 ( 7 . in binar#). Remember: 1hen con$erting a number to its .s complement its sign bit is unchanged. !umbers are stored in .s complement format onl# if the# are negati$e. Positi$e numbers are stored in the normal format.

Simple C++ Program


A few simple programs are e6plained in this section to help #ou get a feel of C55. "irst, lets write a program to calculate the area of a circle. The $ariables needed in this program are the radius of the circle (which can be obtained as input from the user) and the constant Jpi (whose $alue can be pro$ided in the code itself). ** To Calculate the Area of a Circle M include Niostream.hO int main( ) T float P% 7 :.(2; ** $ariables can be initialiGed during declaration int rad; coutNN PDnter the radiusP ; cinOOrad; coutNN PArea of the circle is PNN P% 4 rad 4 rad; return ); U The preprocessor has onl# one directi$e and it will include the iostream.h header file into the source code. The compiler will start reading the code from the main ( ) function onwards. Remember: 1hate$er is t#ped within the main ( ) function will be e6ecuted. The main ( ) function is used as the entr# point for a C55 program.

P% is a $ariable name and is declared as a float -uantit# (because the $alue of P% has a decimal point). At the point of declaration, P% is initialiGed to a $alue of :.(2. This means that whene$er P% is used in the program, the compiler will use :.(2 instead of P%. The line+ coutNNPDnter the radiusP; will cause Dnter the radius to be displa#ed on the screen. This is because PDnter the radiusP is t#ped within double -uotes following Jcout and the insertion operator. An#thing between double -uotes, along with coutNN will be displa#ed on the screen /ust as it appears within the double -uote. The $alue entered b# the user will be stored in the $ariable Jrad. Then the statement PArea of the circle is P will be displa#ed on the screen. The compiler will calculate the $alue of JP% 4 rad 4 rad and displa# it at the end (4 is the multiplication operator in C55). The output for the above program is: Dnter the radius ; .rea o) the circle is <=>0?> Bold indicates that the user entered the $alue. %n this case , was entered as the radius. ;uppose we t#pe coutNN PradP; the output will be /ust the word rad The $alue of the $ariable Jrad will not be displa#ed. Remember: 1hen #ou want to displa# some $ariables $alue on the screen, H ! T D!CC ;D %T %! H U@CD [U TD;; /ust mention the name of the $ariable after the insertion operator.

*nitiali+in" variables: %t is a good idea to initialiGe $ariables at the time of declaration. D$en if #ou are unsure of the $alue #ou can still initialiGe it to ). %f #ou are wondering wh#, /ust consider the e6ample below+ Minclude Niostream.hO int main( ) T int correct, choice; coutNNP\nDnter #our guess of the luc'# number+ P; cinOOchoice; if (choice7 7correct) T coutNNP\nCongrags. Bou are correctFP; U else T coutNNP\n;orr#. 1rong guessP; U coutNNcorrect; **uninitialiGed $ariable return ); U Cets not get into the details of this program for the time being (well discuss about the Jif statement, escape se-uences \n later). Bou should ha$e got a rough idea as to what the program is about. 1e as' the user to enter a number and if that number matches the number we$e decided upon then we displa# a message sa#ing JCongrags. The users $alue is stored in the $ariable Jchoice and the actual correct $alue should ha$e been stored in the $ariable Jcorrect. Kun the program and #oull get something li'e the following+ Dnter #our guess of the luc'# number+ 8 ;orr#. 1rong guess 2>,33. The problem is that in the program we ha$ent assigned a $alue to the $ariable Jcorrect and neither ha$e we initialiGed it. Thus this $ariable has an un'nown $alue (also called garbage $alue). There are . wa#s to initialiGe $ariables+ int correct 7 .8; or

int correct(.8); The second form is called functional notation and we generall# dont use this to initialiGe in&built data t#pes (li'e integers, characters, double etc.). This form is used to initialiGe user defined data t#pes (which well discuss in the chapter on Classes).

.nother e'ample pro"ram: ::$an you guess what this program is for and how it works. MincludeNiostream.hO int main( ) T char chec'; int i; coutNNPDnter the character that #ou want to con$ert to A;C%% + P; cinOOchec'; i 7 chec'; coutNNPThe A;C%% $alue for PNNchec'NN P is PNNi; return ); U The abo$e program is for finding out the A;C%% $alue for an# character that #ou t#pe. ?ow does it wor'< Alwa#s go line b# line and put #ourself in the position of the compiler. Jchec' is declared as a character and Ji is declared as an integer. The first $alue entered is stored in the $ariable Jchec'. Jchec' is a character but Ji is an integer $ariable. ?ow can we e-uate Jchec' to Ji< 1ont there be some problem< %t is not ad$isable to e-uate one data t#pe to another. =an# a times this could lead to errors (usuall# logical errors) but in the abo$e program this is done purposel#. Jchec' is a character (one b#te) but it is stored as a number in memor# (for e6ample+ an Ja is not stored as an Ja in memor#. %t is con$erted into a decimal number using the A;C%% code and then into binar# form and stored in memor#). A character occupies one b#te while an integer occupies . b#tes. A character has a range from 0(.3 to (.3 while an integer has a much greater range. Thus, whate$er $alue is held b# Jchec' can be held b# the integer Ji as well. And this $alue is actuall# the A;C%% $alue for the character that the user t#pes. Bou might wonder, wh# not use the statement below since Jchec' also has the same $alue+ coutNNchec'; This will displa# the same character that #ou entered and not the A;C%% $alue. 1h#< @ecause when something is stored as a character (though it is stored in integer format), it

will go through the same process of A;C%% coding and find out what is the e-ui$alent character (and displa# the character). @ut when something is stored as an integer, the number will be displa#ed as it is (without going through the A;C%% coding process). #ry it: 1rite a program that will do the re$erse process (i.e. t#pe a number and the program has to displa# the corresponding character).

'dentifiers, *ile Nomen$lature, -ey"ords, Constants, Comments


The following topics are co$ered in this section+

%dentifiers "ile !omenclature Ae#words Constants Comments

'dentifiers:
%dentifiers are $er# important in C55 and are used in all programs. 1hat is an identifier< %n the pre$ious program Jchec' was declared as a character $ariable. The identifier in this case is Jchec'. @asicall# identifiers are names that are gi$en to $ariables, constants or functions. %n the pre$ious program there are two identifiers+ Jchec' and Ji. C55 permits the use of a huge $ariet# of names for identifiers li'e+

test Test intYtest $ar( $ar(.: cYbYf Y$ar

Almost an# name #ou can thin' of can be used as an identifier but there are some restrictions. An identifier should not start with a number. The first character of an identifier should be an alphabet or an underscore ( Y ). After the first character, numbers can be used in the identifier. Kemember the following+

!e$er start an identifier with an#thing other than a letter or an underscore.

%t is better to use a letter than starting with underscores. Ho not use 'e#words as identifiers (e6+ do not name an identifier as int). Uppercase and Cowercase identifiers are different (Chec' is different from chec'). @e careful when using characters that loo' similar to each other. "or e6ample J( (the number one) and Jl (the lowercase alphabet C) loo' ali'e. Use names that are eas# to understand (if #ou are storing the salar# of a person, name the $ariable as Jsalar# instead of declaring it as J6. Ho not use $er# long names. Ho not name man# $ariables with similar names (a$oid using identifiers li'e+ count, counter, counting etc.).

-ey"ords:
Ae#words are reser$ed words in C55 programming. The# should not be used as identifiers and all 'e#words should be in lower case. The >: 'e#words are tabulated below. Asm Class Houble "alse %nt Protected ;iGeof Throw Unsigned Auto Const H#namicYcast "loat Cong Public ;tatic True Using bool constYcast else "or mutable register staticYcast Tr# $irtual brea' continue enum friend namespace reinterpretYcast struct t#pedef $oid case default e6plicit goto new return switch t#peid $olatile Catch Helete D6port %f perator ;hort Template t#pename wcharYt char do e6tern inline pri$ate signed this union while

*ile Naming Convention:


A few points regarding file nomenclature are+

%n =;H ; a filename cannot ha$e more than 9 characters whereas in 1indows there is no such restriction. Use meaningful names (depending on what the program performs). A$oid using underscores in the file names. @e careful when using characters that loo' similar to each other. "or e6ample J( (the number one) and Jl (the lowercase alphabet C) loo' ali'e. @ile #ype C55 source file C55*C header file C source file D6ecutable file b/ect Code Te6t file 1ord document %mage*graphics file E'tension used 4.cpp 4.h 4.c 4.e6e 4.ob/ 4.t6t 4.doc 4./pg* 4.gif* 4.bmp

Constants:
Constants are used in e6pressions and their $alues cannot be changed. The# are used in the program code without using an# $ariable name to refer to them. "or e6ample consider the statements+ int 6 7 8; float # 7 :.::; %n this, 8 is an integer constant and :.:: is a floating t#pe constant. Bou cannot change 8 or :.:: but #ou can assign these $alues to $ariables (the $ariables in the abo$e code fragment are J6 and J#). Constants can be classified based on their data t#pe as follows+

!umeric t#pe constants (includes integers, floating&point etc.) Character Constants ;tring Constants

Numeric Constants: !umeric constants consist of a series of digits. %nteger constants can be written in different number s#stems+ he6adecimal (base (>), octal (base 9) or in decimal (base ()).

A decimal integer constant is an# normal whole number (can consist of digits from ) to ,)+

.,:2, ()), ,)), (28> etc.

An octal integer constant can contain digits from ) to 3 onl# and it should start with a Gero (so that the computer will 'now it is an octal number). "or e6ample+

).:, )8>3, ).(2 etc.

A he6adecimal integer constant should start with )6 or )] and can consist of digits from ) to , and A to " (uppercase and lowercase letters are allowed). "or e6ample+

)6(), )6("" etc.

"loating point constants will ha$e the decimal point in the number.

Character and trin" Constants:

Character constants are single characters enclosed within two single -uotes (or between two apostrophes). "or e6ample+ Ja Jb J6 J( JA J4

A single character enclosed within single -uotes is a character constant. All character constants will ha$e an integer $alue (determined from the A;C%% table). A C55 statement+ char ch 7 J@; will assign the character constant J@ to the character $ariable ch.

;tring constants consist of a series of characters enclosed within double -uotes. "or e6ample+ PhelloP PThis is a stringP P6P D$en P6P is a string because it is enclosed in double -uotes. P6P is different from J6 (this is a character constant). The reason is because P6P actuall# consists of J6 and J\) (the null character which will be e6plained later).

Constants are also called as Jliteral. Bou might come across the terms character literal, integer literal, string literal etc.

Beware: The constants described in this section are different from $ariables using the Jconst 'e#word (this is discussed in Unit >).

Comments:
Comments are not meant for the compiler to read. The# are meant to ma'e the program easier to understand for humans who might read the coding later. %t is a good practice to write comments (e$en for small programs). 1hat should be written in the comments< "irst of all, a couple of lines about the aim of the program should be mentioned. Bou should also mention the name of the programmer and the date when the program has been modified. Comments should be updated e$er# time #ou modif# the code. As the program gets larger, it is ad$isable to write comments for the $arious functions that are used in the program. "or instance, if a function is used to calculate the sum of numbers, then this could be mentioned in the comments. @asicall# #ou are permitted to write an#thing within comments because it will not affect the program. There are two methods used to denote comments+

;ingle line commenting (**) =ultiple line commenting (*4I..4*)

"or single line comments use double slashes (**) followed b# the comments (but it should be on the same line as the double slash). D6ample+ ::this is a single line comment =ultiple line commenting permits #ou to write line after line of comments. %t will be as follows+ :; *ultiple line commenting< <this is also part of the comment< <<comment continued<< ;: D$er#thing in between *4 and 4* will be commented. @# using multiple line commenting the programmer neednt use double slashes for each and e$er# line.

+e$ap:

The file iostream.h pro$ides the general basic input and output functions. Jcout is used to displa# data on the screen while Jcin is used to obtain inputs from the user. D$er# $ariable*function in C55 has to ha$e a name. This name is called an identifier. Ae#words are speciall# reser$ed words in C55. The# cannot be used as identifiers. There are two data t#pes in C55+ fundamental and user&defined. Sariables are named memor# locations (their name is pro$ided b# the programmer) where $alues can be stored and changed fre-uentl# in the program. Constants are usuall# used to assign $alues to the $ariables. All data t#pes ha$e different siGes and are used for specific purposes. The t#pe of a $ariable determines what it can store. Comments are written for eas# understanding of the program (the# are not processed b# the compiler).

C++ .perators / '


The following topics are co$ered in this section+

Arithmetic perators Dscape ;e-uences

01 2rit#meti$ .perators
These operators are used to perform basic mathematical operations li'e addition, subtraction, di$ision and multiplication. &perator ymbol 5 & 4 * ^ Addition ;ubtraction =ultiplication Hi$ision =odulo operator (Kemainder after di$ision) &peration per)ormed

The modulo operator is not used to calculate the percentage. %t is used to find the remainder after integer di$ision. "or e6ample+ > ^ 2 7 . (because di$iding > b# 2 produces a remainder of .). The modulo operator can operate onl# on integers. ;ince the modulo operator is used to determine the remainder after di$ision, it is also called the remainder operator. Arithmetic operators are binar# operators since the# need two -uantities (or operands) to perform an operation. Minclude Niostream.hO int main( ) T int num(, num.; coutNNPDnter the two numbers + P; cinOOnum(OOnum.; coutNNPThe product is + PNNnum(4num.; coutNNPThe sum is + PNNnum(5num.; coutNNPThe difference is + PNNnum(&num.; coutNNPThe -uotient is + PNNnum(*num.; coutNNPThe remainder is + PNNnum(^num.; return ); U %n the program, we declare two integers Jnum( and Jnum. and obtain their $alues from the user through the statement+

cinOOnum(OOnum.; This is a method of obtaining multiple inputs using a single statement. The abo$e statement is e-ui$alent to writing+ cinOOnum(; cinOOnum.; The two numbers, when entered b# the user, can be separated b# a space or b# a new&line (i.e. the first number is t#ped and then after pressing the Jenter 'e# the second number is t#ped). When you run the program you would get the following on your screen: Dnter the two numbers + A > The product is + :.The sum is + (.The difference is + 2The -uotient is + .The remainder is + ) ;omething is not right in this output; the results are correct but the displa# is on a single line. To displa# the output in an organiGed manner, the program should print each output on a new line. "or this purpose of formatting the output C55 pro$ides us with Jescape se-uence.

Es$ape Se3uen$es4 Ba$5slas# C#ara$ter Constants


%f #ou remember, whate$er #ou t#pe within double -uotes following coutNN, will be printed as it is on the screen. There is a problem in case #ou want to print a new line, or #ou want to use tabs (because whate$er #ou t#pe within double -uotes will be displa#ed directl# on the screen). To sol$e this problem, escape se-uences were de$eloped. Eust as the name implies, these escape se-uence characters are used to escape from the normal se-uence of e$ents. An escape se-uence alwa#s begins with a bac'slash ( \ ). "or a new line, the escape se-uence is \n (n for new line). %f #ou want to push the tab setting then \t should be used (t for tab). The modified program for doing simple arithmetic operations is as follows+

Minclude Niostream.hO int main( ) T int num(, num.; coutNNPDnter the two numbers + P; cinOOnum(OOnum.; coutNNP\n The product is + PNNnum(4num.; coutNNP\n The sum is + PNNnum(5num.; coutNNP\n The difference is + PNNnum(&num.; coutNNP\n The -uotient is + PNNnum(*num.; coutNNP\n The remainder is + PNNnum(^num.; return ); U When you run the program you would get the following on your screen: Dnter the two numbers + A > The product is + :. The sum is + (. The difference is + 2 The -uotient is + . The remainder is + ) There are a few other useful escape se-uence characters as well+ Escape Sequence \n \t \a \\ \< \P \ \) new line horiGontal tab bell sound @ac'slash -uestion mar' (<) double -uotation Apostrophe !ull character (used in strings) Meaning

Though escape se-uences consist of . characters the# represent onl# a single character (for e6ample+ \< represents the -uestion mar' character). Dscape se-uences are character constants and are denoted as J\\, J\<, J\) etc. Beware: J\) is not e-ui$alent to Gero. J\) represents a null character (used in strings). #ry it: Use the abo$e escape se-uences in a C55 program to see their effects. The \a escape se-uence will literall# ma'e a sound of a bell. Remember: Dscape se-uences alwa#s start with a bac'slash ( \ ) and ha$e to be followed b# $alid characters (li'e n, a, t etcI). %f #ou happen to use some other character (li'e w), the compiler will displa# a warning message (the program will run and usuall# the compiler will ignore the character or displa# the character on screen). Coming bac' to the program with arithmetic operators; what would be the output if 8 and . are entered as the two numbers< 1hat will the -uotient and remainder be< The result will gi$e a -uotient of . and a remainder of (. @ut isnt 8*. 7 ..8< The answer to this lies in the declaration of the $ariables Jnum( and Jnum.. ;ince these two $ariables are declared as integers, all the results of arithmetic operations will also be in the integer format. ;uppose Jnum( and Jnum. are declared as floating point data t#pe, then the result of di$ision would be ..8 instead of .. %n this case, what do #ou thin' will be the remainder< 1ill it be Gero alwa#s< Remember: The modulo (^) operator can operate onl# on two integers and not on an# other data t#pe. %f the remainder operator is used on floating point numbers, the compiler will produce an error message. The other arithmetic operators can be used on integers as well as floating&point numbers. The following topics are co$ered in this section+

Assignment perators T#pe Con$ersion

61 2ssignment .perators
The assignment operator assigns the $alue on its right&hand side to whate$er is present on the left&hand side. The Je-ual to s#mbol ( 7 ) is the C55 assignment operator. "or e6ample, the statement 6 7 .;

assigns the $alue on the right&hand side of the Je-ual to sign to the term on the left (i.e. the $alue . is assigned to the $ariable 6). The term which appears on the left&hand side of the assignment operator (usuall# a $ariable) is called the Jtarget. Bou will alwa#s assign a $alue to some $ariable but not to a constant. . 7 6; **Drror

is a wrong statement because #ou cannot assign the $alue of 6 to . (. is an integer constant and #ou cannot change its $alue). The $alue on the right side of the assignment operator can be an e6pression as shown below (or a function that returns a $alue)+ 6 7 num( 5 num.; # 7 84>; Compilers often use the terminolog# Jl$alue (or C$alue) and Jr$alue especiall# in error messages. The Jl$alue refers to the operand on the left&hand side of the assignment operator while the Jr$alue refers to the operand on the right&hand side of the assignment operator. The l$alue can be a $ariable or a pointer but it should not be a constant. The r$alue can be a constant, $ariable, an e6pression or a function call. Beware: C$alue can be used as r$alue (i.e. on the right&hand side of an assignment) but r$alue cannot be used as C$alue. C55 permits multiple assignments (i.e. more than one $ariable can be assigned a $alue using one statement). "or e6ample let 6, # and G be integers, then 6 7 # 7 G 7 :; is an e6ample of multiple assignment. The process of assignment will be from right to left; : is assigned to JG and the $alue of JG (which is now :) is assigned to J# and #s $alue is assigned to JG. The abo$e multiple assignment is e-ui$alent to the following set of statements+ G 7 :; # 7 G; 6 7 #; and all the three $ariables 6,# and G are assigned the $alue of :. %s this $alid< 6 7 #5( 7 :;

This sort of a statement is not $alid in C55. Bou cannot use arithmetic operators in between multiple assignments (the compiler will not 'now how to sol$e this statement).

Type Conversion
Dach data t#pe has a different range because of the different siGes that the# occup#. A character is allotted ( b#te while an integer might be allotted .*2 b#tes. 1hat will happen if we assign an integer to a character or a double to an integer< Assigning a $ariable of one data t#pe to a $ariable of another data t#pe is 'nown as t#pe con$ersion. 1hen assigning between numeric t#pes, whate$er is on the right hand side of the assignment will be assigned to the $ariable on the left. %f a $ariable of a smaller t#pe is assigned to a $ariable of a larger t#pe, no information will be lost on con$ersion (because a smaller t#pe can be accommodated into a larger t#pe). "or e6ample a character (which occupies onl# ( b#te) can be con$erted into an integer without an# loss of information (because an integer occupies more b#tes). ?owe$er if #ou attempt to assign an integer to a character #ou will lose the higher order bits of the integer (onl# the lower 9 bits of the integer will be retained in the character). Cet us assume that an integer occupies two b#tes and a character occupies one b#te. unsigned int a78(); unsigned char 6; 67a;

As can be seen from the figure, the upper 9 bits are lost due to the t#pe con$ersion and the $alue of the character will be onl# .82. The following program illustrates a few t#pe con$ersions+

Minclude Niostream.hO int main( ) T char ch; double db; float f; short int i; db788e2; ch 7 i 7 f 7 db; coutNNchNNP , PNNiNNP , PNNfNNP , PNNdb; return ); U The output will be: p , .83(. , 88)))) , 88)))) ;ome compilers will produce a warning message warning+ assignment to Jshort int from Jfloat A program with warnings can be e6ecuted. A warning is a caution produced b# the compiler when it feels that the programmer might ha$e done something b# mista'e (in this case an assignment from a larger t#pe to a smaller t#pe). To a$oid warnings we will need to ma'e use of t#pecasts (which will be e6plained later). Remember: @e $er# careful if #ou ma'e use of t#pe con$ersion because it can lead to loss of information.

C++ .perators / '''


T#e follo"ing topi$s are $overed in t#is se$tion:

2ssignment 2rit#meti$ .perators +elational .perators

71 2ssignment 2rit#meti$ .perators4S#ort#and .perator/5 7, & 7, 4 7, * 7)


Assignment arithmetic operator is a combination of an arithmetic operator and the assignment operator. Consider the e6ample+

] 5 7 :; The abo$e statement is the same as+ ] 7 ]5:; i.e. the $alue of ] is incremented (or increased) b# : and the new incremented $alue is assigned to ]. ;o if ] had a $alue of . before this e6pression, then ] will be 8 after this e6pression is e6ecuted. &perator a57b a&7b a47b a*7b a^7b &peration per)ormed a7a5b a7a0b a7a4b a7a*b a7a^b

81 +elational .perators ( N , O , 7 7 , F 7 , O7 , N7 )
Kelational operators are also binar# operators (since the# operate on two operands). The# are used for comparing two $alues and the result of the comparison is either true ($alue () or false ($alue )). ;ome e6amples are gi$en below+ 8O2 will return a $alue of True (() .O: will return a $alue of "alse ()) %n programs that #ou write, comparisons will usuall# be made between one $ariable and a constant or between two $ariables. "or e6ample+ 6O# GO() O means Jgreater than while O7 stands for Jgreater than or e-ual to.

6O7# will #ield a true $alue e$en if 6 7 # whereas 6O# will #ield a $alue of false when 6 7 #. @e clear as to what relation #ou want to test when using these operators. ;uppose #ou want to test whether two $ariables are e-ual, #ou ha$e to ma'e use of the e-ualit# operator. The e-ualit# operator is denoted b# 7 7 (double e-ual to signs). Remember: =an# beginners in programming use the e-ualit# operator and assignment operator interchangeabl#. The assignment operator is a single Je-ual to sign and it is meant onl# for assigning $alues to $ariables. The e-ualit# operator (a double Je-ual to sign) is used to chec' whether two $alues are e-ual. Relational Operator 6O# 6N# 6O7# 6N7# 677# 6F7# Operation Performed %s 6 greater than #< %s 6 less than #< %s 6 greater than or e-ual to #< %s 6 less than or e-ual to #< %s 6 e-ual to #< %s 6 not e-ual to #< Result of Operation True*"alse True*"alse True*"alse True*"alse True*"alse True*"alse

1ell write a simple program for comparing two numbers and displa#ing the appropriate result. Minclude Niostream.hO int main( ) T float num(, num.; coutNNPDnter the two numbers + P; cinOOnum(OOnum.; if (num(Onum.) T coutNNPThe number PNNnum(NNP is greater than PNNnum.; U if (num(7 7num.) T

coutNNPThe number PNNnum(NNP is e-ual to PNNnum.; U if (num(Nnum.) T coutNNPThe number PNNnum(NNP is less than PNNnum.; U return ); U

%t might appear as if there is a white space between the two Je-ual to s#mbols used in the e-ualit# operator but this is not the case. =o not leave a blank space between the two symbols !this will produce a compile error#. 1e still ha$ent co$ered the topic on Jif conditions but #ou should be able to understand the wor'ing of the abo$e program. The two numbers that are obtained from the user are compared using three Jif conditions. Hepending on which condition is satisfied, the corresponding output will be displa#ed. An example for the output displayed is: Dnter the two numbers + = B The number 8 is less than > Ser# fre-uentl# the abo$e program is written with a small mista'e which will lead to se$ere logical errors. %nstead of t#ping num(7 7 num. within the Jif condition, the following mista'e is made+ if (num1 = num2) !ogical Error T coutNNPThe number PNNnum(NNP is e-ual to PNNnum.; U 1hat do #ou thin' will happen< Cet us assume that the two numbers are 3 and 8. The output will be: Dnter the two numbers + C =

The number 3 is greater than 8The number 8 is e-ual to 8 1hen the following code is encountered+ if (num( 7 num.) the computer assumes that this is an assignment and not a comparison (because the assignment operator has been used). ?ence in this line of coding, the $alue of Jnum. will be assigned to Jnum( (both Jnum. and Jnum( are now 8). !ow within the Jif condition we ha$e a non&Gero positi$e $alue (this $alue is 8 and is e-ui$alent to Jtrue). ;o, the compiler will e6ecute the cout statement within that Jif condition irrespecti$e of the $alues of Jnum( and Jnum.. This should gi$e #ou a good idea as to how a small mista'e can completel# alter the logic of the program. The Jif statement will be dealt in Chapter 2, but for the time being /ust remember that whate$er #ou t#pe within an Jif statement will be e6ecuted if the condition is true. 1hen testing whether a $ariable is e-ual to a constant some programmers prefer to use the following method+ if (()) 7 7 6) instead of the usual+ if (6 7 7 ())) The ad$antage of the first method is that e$en if the programmer commits the mista'e+ if (()) 7 6) the compiler will produce an error (since #ou cannot assign a $alue to a constant). %n the following program, we ha$e coded to displa# the result of numO8. Ho #ou thin' it is $alid< Minclude Niostream.hO int main ( ) T int num; coutNN PDnter the numberP; cinOOnum; coutNN(numO8); !!De"alE return ); U

Alwa#s remember that the result of a comparison #ields a $alue of TKUD (() or "AC;D ()). ?ence the abo$e program is perfectl# correct. %n case #ou enter a $alue that is greater than 8 #ou will get the output as ( else #ou will get ). ) is considered as false and all other $alues are considered to be true.

T#e follo"ing topi$s are $overed in t#is se$tion:


Logi$al .perators 9nary .perators

:1 Logi$al .perators & A!H ( __ ) K ( `` ) ! T (F)


These operators are used to combine two or more e6pressions. The wa# in which the# combine the e6pression differs depending on the operation used. The# are used when we need to test multiple conditions. "or e6ample #ou ma# write a program that has to chec' whether the mar's scored b# a student is greater than 3) and less than 9). %f it is so then #ou will want the program to displa# a J@ grade. To chec' whether the a$erage mar' is greater than 3) #ou ha$e to use one e6pression and to chec' whether the a$erage is less than 9) #ou should use another e6pression. Thus in simple Dnglish #our statement will be+ %f (a$erage mar' is greater than 3) A!H a$erage mar' is less than 9)) Print P@ gradeP .ND: it combines two conditional e6pressions and e$aluates to true onl# if both the conditions are true. "irst #ondition "alse "alse True True Second condition "alse True "alse True Result of $%& operation "alse "alse "alse True

%f the first condition and the second condition are both true then the result of the A!H operation will also be true. D6ample+

** To chec' whether the gi$en number is e$en M include Niostream.hO int main ( ) T int num; coutNN PDnter the numberP; cinOOnum; if ( (numF7)) __ ((num^.)7 7)) ) conditions ha$e to be true T coutNNP\n D$en !umberP; U return ); U

** Two

%n this program we need to chec' for two conditions (the number entered should not be Gero and the number when di$ided b# . should not produce a remainder). nl# if both these conditions are satisfied should the program displa# that the number is e$en. The A!H operator is used to combine the two conditions that are to be tested and if both are true then the message is displa#ed. &R: operator combines two conditions and e$aluates to true if an# one of the conditions is fulfilled (i.e. onl# one of the conditions need to be true). %t is designated b# using two parallel bars*pipes ( ` ` ). "irst #ondition "alse "alse True True Second condition "alse True "alse True Result of OR operation "alse True True True

The JA!H and J K operators can be used on a se-uence of conditions (i.e. at a time #ou can chec' for multiple conditions). "or e6ample the following code is legal+ if ( (6O#) __ (#O8) __ (GO#) __ (6O2) ) T ::body of the >if condition< U

%n this case onl# if all the four conditions are true will the bod# of the Jif condition be e6ecuted. N&#: ! T is a unar# operator. Unli'e JA!H and J K, ! T operates onl# on one operand. The logical $alue of the operand is re$ersed. %f the operand is true, then after the ! T operation it will be become false. Bou might be thin'ing that the ! T operator can operate onl# on ( and ). Actuall#, an# number greater than ) will be considered as a true $alue. ?ence the following would gi$e+

F8 will gi$e ) F) will produce ( F( is e-ual to ). #ondition "alse True Result of %O' operation True "alse

@asicall#, an# number other than Gero is considered as true. J!ot of an# number (other than )) will gi$e #ou "AC;D (or Gero). Chec' out the following program that illustrates the ! T operator.

MincludeNiostream.hO int main ( ) T int num, result; coutNN PDnter the numberP; cinOOnum; result 7 (Fnum); coutNNresult; return ); U

;1 9nary .perators (.+T operator A4 increment operator 994 decrement


operator &&) Unar# operators operate on onl# one operand, which could be a constant or a $ariable. 1e$e alread# discussed about the ! T operator. Another simple unar# operator is the

unar# minus operator. This will act on onl# one operand and will change the sign of the number it operates on. "or e6ample+

&(8) 7 &8 &(&8) 7 58

The 55 and 0 operator are $er# important if #ou are ta'ing a course in C55 (teachers usuall# lo$e this topic and the# are bound to as' some -uestions on unar# operators). 55 is 'nown as the increment operator and it can be used in two wa#s.

As a prefix + i.e. when the operator precedes the $ariable (as in 55 i, where i is the integer $ariable)

%f we write+ i( 7 (); i. 7 55 i(; This is the same as+ i( 7 (); i( 7 i( 5 (; i. 7 i(; At the end of these steps the $alue of both i( and i. will be ((. 1hen used as a prefi6, the $ariable is first incremented and later assigned.

As a suffix+ i.e. when the $ariable precedes the operator (as in i 55).

%f we write+ i( 7 (); i. 7 i( 55 ; This is the same as writing+ i( 7 (); i. 7 i(; i( 7 i( 5 (; At the end of these steps the $alue of i. will be () and that of i( will be ((. 1hen used as a postfi6, the $ariable $alue is first assigned and later incremented.

The decrement operator wor's in the same wa#. The onl# difference is that it decreases the $alue of the operand b# one. Again the decrement operator also can be used in two wa#s+ as a prefi6 or as a suffi6 (or postfi6). ;uppose we ha$e the following coding in a program, what will be the $alue of Jsum at the end of each statement< int sum78; coutNNsum55; it be > coutNNP PNNsum; **Jsum is 8 ** Jsum is 8. nl# in the ne6t reference to Jsum will **Jsum is now >

Thus in the case of the postfi6 operator the $alue is assigned first and increment is carried out in the ne6t step. %f #ou ma'e use of the prefi6 operator then+ int sum78; coutNN55sum; coutNNP PNNsum; **Jsum is 8 ** Jsum is immediatel# > **Jsum is >

Remember: 1hen used as a prefi6 ( 55i ) compiler will first increment and then assign. 1hen used as a suffi6, assignment is done first and then incrementing is performed. Beware: The 55 and 0 operators cannot be used on e6pressions (i.e. 55 (# 5 (); is an incorrect statement and will lead to a compiler error).

More on .perators (<)


T#e follo"ing topi$s are $overed in t#is se$tion:

Si=eof .perator Conditional .perator .perator Pre$eden$e 2sso$iativity Comma .perators Bit"ise .perators

Si=e.f .perator (si=eof)


This is again another unar# operator. Eust as the name implies, this operator returns the length (in b#tes) of the $ariable that is mentioned in the parentheses. "or e6ample the siGe of a character is ( (i.e. ( b#te).

** Using siGeof operator Minclude Niostream.hO int main ( ) T int a; coutNNsiGeof (a); ** ;ince a is an integer, the output will be 2 coutNNsiGeof(char); ** utput will be ( return ); U %t is not a must to mention a $ariable within the parentheses; #ou could also mention one of the in&built data t#pes. ;ome operating s#stems allocate a different memor# space for data t#pes and it is better to use the JsiGeof operator to determine the siGe of data t#pes instead of assuming that all s#stems use the same number of b#tes.

Conditional .perator (%:)


The conditional operator is a ternar# operator (i.e. it operates on : operands at a time). 1ell ta'e a closer loo' at it in the ne6t chapter. "or the time being /ust remember that it needs three operands and it is denoted b#+ E:

.perator Pre$eden$e
1hen a statement has more than one operator, the operator precedence determines as to which operator is gi$en priorit#. "or e6ample if #ou ha$e a 4 and a 5, the compiler has to decide whether it will multipl# and add or add and multipl#. This will depend on the operator precedence. The parentheses ha$e the highest precedence. "or instance if #ou write+ (85:)48 the result will be (9)48 or 2). %f #ou write the same without using parentheses as 85:48 the result will be .) (because 4 has a greater priorit# than 5). The order for operator precedence is listed below (starting from the highest priorit#)+

Parentheses ( ) Unar# perators F Unar# minus & =ultiplication 4 Hi$ision * =odulo ^ Addition 5 ;ubtraction & Kelational perators N N7 O O7 D-ualit# operator 77 %ne-ualit# operator F7 Cogical perator __ `` Conditional operator <+ Assignment 7 Arithmetic assignment 47, *7 , ^7 , 57 , &7 Beware: %t is better to write long e6pressions using parentheses otherwise it could lead to a lot of confusion and also to potential logical errors.

2sso$iativity
%f two operators ha$e a different priorit# le$el then their e6ecution order depends on the operator precedence. 1hat will happen if two operators ha$e the same priorit# le$el< 1hen . operators in an e6pression ha$e the same priorit#, the e6pression is e$aluated using their associati$it#. Consider the statement+ net 7 basic 5 allowance 0 ta6; @oth 5 and 0 ha$e the same priorit# le$el. Almost all of the operators e6cept the assignment (and arithmetic assignment) operators ha$e associati$it# from left to right. The assignment operator has associati$it# from right to left. ;ince the 5 and 0 binar# operators ha$e an associati$it# of left to right the e6pression for Jnet is the same as+

net 7 (basic 5 allowance) 0 ta6; 1hen #ou perform multiple assignments+ 6 7 # 7 ); the associati$it# of the assignment operator (7) is ta'en into account and thus the order of e$aluation will be+ # 7 ) (which will gi$e J# a $alue of )) followed b# 6 7 # (which will assign ) to J6).

Comma .perator
The comma operator can accept two e6pressions on either side of the comma. 1hen e6ecuted, the left side e6pression is first e$aluated followed b# the right side e6pression. Ultimatel# it is the e6pression on the right side that will be the $alue of the entire e6pression. int 6,#; coutNN(6 7 (, # 7 8); ** 8 will be displa#ed

"irst the J6 will be assigned ( and then J# is assigned a $alue of 8. The comma operator is e-ui$alent to sa#ing Pdo this tas' and do this alsoP. %n this case the compiler will do+ 6 7 ( and then # 7 8 The rightmost e6pression is #78 and hence the $alue of the entire e6pression (67(,#78) is 8. @e careful while assigning the $alue of a comma separated e6pression to a $ariable. The comma operator has lower operator precedence than the assignment operator. %f we t#pe+ # 7 (6 7 ( , 6 7 8 , 6 5 ()); 6 will ha$e a $alue of 8 while # will be (8. %f we t#pe+ # 7 6 7 (, 6 7 8 , 65();

the $alue of J# will be ( and that of J6 will be 8. This is because the compiler will perform the following operations+ # 7 6 7 (; 6 7 8; 6 5 (); ** # and 6 are set to ( **6 $alue is 8 **the $alue of the entire comma separated e6pression is (8

The comma operator will be used usuall# in Jfor loops.

Bit"ise .perator:
The bitwise operators a$ailable in C55 are tabulated below+ (it)ise Operator S*mbol _ ` Z a OO NN "unction A!H indi$idual bits K indi$idual bits D] K indi$idual bits ! T of indi$idual bits (or complement operator) Kight&shift operator Ceft&shift operator

These operators will operate on indi$idual bits of the operand (i.e. on the binar# representation of data). These operators are dealt with in detail in Chapter (:. Remember: Ho not confuse the __ and _ operators or the `` and ` operators (logical operators are entirel# different from bitwise operators).

+e$ap

Arithmetic operators are used to perform mathematical operations. The modulo*remainder operator is applicable onl# on integer operands. Dscape se-uences are character constants that are used to format the output displa#ed on the screen.

7 is the assignment operator and the K$alue is assigned to the target (or the C$alue). %nformation will not be lost when con$erting from a smaller data t#pe to a larger data t#pe. ;horthand operators are a combination of one of the arithmetic operators and the assignment operator. Kelational operators are used to compare two $alues or e6pressions. The# will return a $alue of true or false. Cogical operators are used to combine two or more e6pressions. The operator precedence determines which operator has a higher priorit#. 1hen . operators ha$e the same priorit# the e6pression is e$aluated based on their associati$it#. @itwise operators are used to operate on indi$idual bits.

T#e basi$s ($#apters 0 to 7)


This is an evaluation test !don?t worry@ no one is going to grade you#. $hoose the answers and click on the A ubmitA button to view your score. The correct answers with e"planations will be shown after you take the evaluation test. (updated 12 %o+ 2,,-)
?0F1 Ghat do you thin- is the outputEEE int main( ) T int a7:,b; b7a55 5 a55; coutNNendlNNPb $alue 7 PNNb; a 7 :; b755a 5 55a; coutNNendlNNPb $alue 7 PNNb; return ); U .nswer01 8,() >,() 8,(( Hepends on compilerF >,((

<0F1 #he )ollowin" codin": a7:; int c 7 55a; int d 7 55a; int b H c 2 d6 a7:; b H 22a 2 22a6 1hat are the $alues for XbX in both cases<

.nswer01 9,, (),() ,,() , (sure), () (mostl#) ,,,

.nswer01 I0F1 *n the )ollowin" piece o) codin" what do you thin- is the value o) jE char i7(.3; int /; i7i5(; /7i; coutNN/; (.9 (.3 &(.3 &(.9

.nswer01 >0F1 JcoutK and JcinK are -eywordsE True "alse

=a01 @or each o) the questions below assume: int i 7 .; int / 7 8; int '; "ind out t.e +alue of /01 (not all )ill .a+e +alues because some are illegal statements)2 '7 (/55); .nswer01 8 > 2

.nswer01 : =b01 '7 .55; 2 8 %llegal .nswer01 =c01 '7 i55 5 55/; , 3 9 %llegal

.nswer01 =d01 ' 7 i55555/; , 3 9 %llegal

.nswer01 =e01 '7 i 7 (/ 7 (); ( . 8 %llegal

.nswer01 =)01 (7.; ( . %llegal

C+.SS>.+& (C#apters 0 to 7)/ Basi$s


Instructions for use The clues will appear on the status bar of your browser (ri ht at the bottom) and also at the top of the applet. (lick once on the applet for it to start workin . Iou can use the arrow keys as well as the mouse to move around the s5uares. To delete use JB:LJ key (perhaps B:L and backspace mi ht not work& 3Km not sure why because they work fine on my =( but when uploaded they donKt seem to work& anyway4 it shouldnKt affect the functionality). >se the ,=2(:<2G to alternate between 2(G+,, and B+W.. 3f the letter you type is correct4 the letter will be in <L2(L color. 3f it is wron it will be in G:B color. @et all black and youKve cracked the crossword.

S$ore tra$5er
0

Number o) attempts:

If all s-uares are black then you?ve cracked the crossword. A score less than (:) is good (())&(() is great). An#thing more than (2) means #ouX$e tried to guess man# of the s-uares.

%f the grid doesnXt appear #ou can clic' here to $iew a snapshot of the grid Across: 1.) We work in the decimal system but addresses are represented in this format. (11) E.) ,hould 3 play now or should 3 study* These statements can help youA (-) 0.) :ven an arm has oneA (E) -.) 3n some machines this is 11 bits and in some it is E/ bits. This determines the si?e of an inte er. (7) M.) :rrors prevent execution but 3 allow execution. <ut beware. (N) 1E.) =ro rammers are reluctant (and la?y) to use me but if used 'udiciously 3$m very helpful later. (N) 17.) 3 take only true or false for an answer and nothin else. (7) 10.) To be +G not to beA (7) 11.) When stren ths are e5ual4 this determines who is evaluated first. (1E) 'o(n: /.) To et somethin from the ri ht side to the left4 we need to use this operator. (10) 7.) (99 H ( 9 this concept. (E) 1.) +perator to obtain the remainder. (1) N.) Bictionary says !memory aid#. 2ssembly pro rammers need (and use) them the most. (-) 10.) 3f 6<$ has a value of 11 and 6b$ has a value of M- then you are usin this code. (0) 11.) 3t is present in alliterate and is another name used for a constant. (N) 1/.) Lawyers4 in movies fre5uently4 retort4 6;y Lord 3 O$ (ompilers convert into this code. (1)

More 3uestions on t#e basi$s ($#apters 0 to 7)


F01 Can we write a pro"ram as the one below: int main( ) T int 6;coutNNP\nDnter the $alue of 6+P;cinOO6;coutNNPBou entered+PNN6; return ); U .01 Bes. The program is $alid since the compiler brea's up C55 statements on the basis of the semicolon and not on the basis of the new&line. The abo$e program is e-ui$alent to writing+ int main( ) T int 6; coutNNP\nDnter the $alue of 6+P; cinOO6; coutNNPBou entered+PNN6;

return ); U

F01 Ghat are to-ensE GhatKs le'ical analysisE 1hat is the output of+ int i78,/7.; coutNNendlNN(i&&&/); i78,/7.; coutNNendlNN(i&& &/); i78,/7.; coutNNendlNN(i& &&/); A.) D$er# C55 statement we write can be bro'en down into to'ens (also called s#mbols). The compiler goes through a number of steps before finall# con$erting high& le$el language into ob/ect code and one of these steps is Jle6ical anal#sis (this stage follows the preprocessing stage). %n this stage (le6ical anal#sis) the compiler identifies all the to'ens used in the program. perators, identifiers, 'e#words etc. are all to'ens (white space is not a to'en but white space helps separate to'ens). D$er# C55 statement is a combination of to'ens. "or e6ample, in the statement+ a7b5c; the s#mbols are+ a,7,b,5,c a, b, c are identifiers and 5, 7 are the operators. A -uestion arises, how does the compiler decide how long a to'en is< ?ow does the compiler 'now when to consider one character for a to'en and when to consider more< To simplif# this situation, the compiler tries to e6tract the largest possible chun' in a statement to form a to'en (in other words itll tr# to e6tract the largest to'en while scanning from left to right). %n our statement+ a7b5c; the compiler cannot consider a7 as a single to'en (because it 'nows that 7 is the assignment operator). ;o it pic's Ja as a s#mbol and so on. This might not seem to be a significant point but itll help us tac'le the second -uestion+ int i78,/7.; coutNNendlNN(i&&&/);

1e$e used three consecuti$e 0Xs in i&&&/. Bou might be tempted into thin'ing this would cause a compile error but it wont because of the wa# le6ical anal#sis is performed. Kemember+ alwa#s e6tract largest possible to'en. %n i&&&/, the compiler will find i&& as the largest to'en. i&&& cant be considered because we dont ha$e an# such operator and i alone would be the smallest possible to'en. Another possibilit# is to chose i& but the compiler is designed to ta'e the largest to'en and that is+ i&&. !e6t it is left with &/ which is e-ui$alent to the unar# & operator. Thus the e6pression reduces to+ i&& &/; which is as good as 8&. (because in i&& we$e used the postfi6 decrement operator). %n the ne6t two e6amples+ i&& &/ and i& &&/ since there is a blan' space (white space), the compiler doesnt ha$e an option of deciding upon the s#mbol. The resultant output for the code fragment will be+ : : 2 Note: %n the pre$ious -uestion the following was termed illegal+ ' 7 i55555/; %n this case, the compiler would brea' up the statement as+ ' 7 (i55)55 5 /; Upto ' 7 i55 e$er#thing is fine, but after that it cant form a legal to'en and thus produces a compile time error. %t will form+ (i55)55 which is not $alid.

%t is better to a$oid coding statements li'e i&&&/ e$en though the# produce the desired result (such code is neither pleasing to the e#e nor the mindF). F01 Deduce the output in both o) the )ollowin" cases: a01 int 678; if ( (67 78) `` (673) ) T coutNNPTrueP; U coutNN6; 1hat do #ou thin' is the $alue of J6< A.) ;ince J6 is 8, the first condition is satisfied. 1hen we use an K operator, the program will not e$aluate the second condition if the first is true. Thus the $alue of J6 will be 8 and the output will be+ True8 b01 int 678; if ( (67 78) __ (673) ) T coutNNPTrueP; U coutNN6;

1hat do #ou thin' is the $alue of J6< A.) ;ince J6 is 8, the first condition is satisfied. 1hen we use an A!H operator, the program will e$aluate the second condition if the first is true. %n the second condition we ha$e assigned a $alue of 3 to 6. Thus the $alue of J6 will become 3 and the program will output+ True3

F01 Gill the )ollowin" pro"ram /not havin" an iostream0h1 compile and e'ecuteE E'plain with reasons0 int main( ) T return ); U

A.) iostream.h is needed when we use cin, cout, NN, OO and similar ob/ects (which we use in most of our programs). therwise #ou can do without iostream.h and the abo$e program will compile and e6ecute successfull#.

*nterview!%iva! #est questions /alon" with the lo"ical questions solved earlier1: (. 1hat is the difference between a compiler and an interpreter< .. 1h# does (Ab 7 ().2 b#tes and not ()))< :. Histinguish between machine language, assembl# language and middle le$el languages< 2. ?ow do the post increment and pre increment operator function< Are the# the same< 8. ?ow man# bits are present in a nibble, a b#te and a word< >. 1h# do we need to gi$e iostream.h< 3. %s the statement+ int 6; a declaration or a definition<

.t#er ?uestions and Programs:


F01 Ghat is an interpreterE %nterpreters are programs which will interpret the source code line&b#&line and e6ecute them. Compilers, on the other hand, read through the entire source code and con$ert it into an ob/ect code (the# do not e6ecute the code). The U!%]*Cinu6 shell is a command interpreter (it e6ecutes #our instructions on a line&b#&line basis). The H ; command.com is an interpreter. %nterpreters do not produce ob/ect code (which means that each time #ou run a program in an interpreter, the interpreter will repeatedl# chec' the s#nta6 etc. before e6ecuting the code). There are some languages which are called interpreted languages (i.e. these languages are alwa#s interpreted). C*C55 is not an interpreted language. F01 Ghat is a lin-er and a loaderE Lenerall# when writing a program, #ou will ma'e use of different libraries and other source files. n compiling each source file we obtain an ob/ect code. All the ob/ect codes need to be put together to form an e6ecutable (because one code might call a function written in another code and onl# the lin'er will be able to resol$e this). This is the basic function of a lin'er. A loader is generall# a program which loads the program (the e6ecutable) into main memor#. All our programs and applications reside on a secondar# storage de$ice (hard dis') but the processor re-uires programs to be present in the main memor# (KA=)& access time for main memor# is much lower than secondar# storage (i.e the CPU can

access main memor# -uic'er than secondar# memor#). The loader ta'es the program from secondar# and loads it into main memor#. Bou will be clear about a lin'er when we discuss about multiple file programming.

[.) Histinguish between machine language, assembl# language and middle le$el languages< [.) 1h# do we need compilers< [.) 1hat is the difference between a constant and a $ariable< [.) 1rite a C55 program to input the name and age of the user and then displa# a sentence on the screen along with these two data. [.) 1rite a program to con$ert a gi$en amount from U; dollars into %ndian Kupees (assume the con$ersion rate as U;H ( 7 Ks.28). Also displa# a statement. [.) 1rite a program that will calculate the compound and simple interest on a principal amount for a gi$en number of #ears (also obtain the rate of interest from the user). [.) 1rite a program to help a shop'eeper calculate the percentage profit he ma'es when he sells an item (obtain the bu#ing price and selling price as inputs from the shop'eeper). [.) 1rite a program to sol$e -uadratic e-uations of the form+ a6. 5 b6 5 c 7 ) btain the $alues of a, b and c from the user and find out the $alues for 6.

*or Loops in &ept#


T#e follo"ing topi$s are $overed in t#is se$tion:

%ntroduction "or Coop ;tatement =ore of "or loops @od# of "or loops !esting "or loops

Statement and Expression


A statement in C55 refers to a part of the code that is terminated in a semicolon. %t is the smallest part of the program that can be e6ecuted. "or e6ample+ sum 7 a 5 b; is a statement. A C55 program will consist of a set of statements. An e6pression is a grouping of $ariables, constants, function calls and operators (arithmetic, logical, relational) to return a $alue. %n the abo$e e6ample, a 5 b is an e6pression. 1hile dealing with control mechanisms #ou will come across bloc's of instructions. A bloc' of instruction refers to a set of statements grouped together within a bloc'. The bloc' is identified b# using the curl# braces JTJ to start the bloc' and JU to end of the bloc'. Pro"ram )low and control: 1hat is program flow< 1hene$er we write a program we ha$e to decide on the se-uence of operations that the program has to perform. Lenerall# this is represented in the form of an algorithm. 1riting algorithms for simple programs might seem tri$ial but when #ou write comple6 programs, the algorithm helps reduce programming errors. Cets ta'e a loo' at a simple algorithm to calculate the a$erage weight of : persons+ ;tep (+ ;tart the program. ;tep .+ btain the weight of all : persons (in weight(, weight., weight:). ;tep :+ Calculate the a$erage weight as a$erage 7 (weight( 5 weight. 5 weight:)*: ;tep 2+ Hispla# the result ;tep 8+ ;top the program @# loo'ing at the algorithm a programmer can easil# write the entire program. 1hen #ou ha$e a comple6 program, if #ou ha$e written an algorithm then #ou can eliminate potential logical errors in this stage itself. %n the algorithm we define the wa# in which the program control should flow. "irst the program should get the : inputs from the user, then it should calculate the $alue for a$erage and finall# it should displa# the result. Thus we can sa# that the program flow has been clearl# defined. @ut program flow neednt alwa#s be so simple. Bou might need to ta'e some decisions and alter program flow.

Control refers to that part of the program which is currentl# being e6ecuted. Cets write an algorithm to di$ide . numbers obtained from the user. ;tep (+ ;tart the program. ;tep .+ btain the . numbers (num and den) from the user. ;tep :+ Chec' if den is Gero. %f it is then go to step 2 else go to step 8. ;tep 2+ Hispla# QHenominator is Gero. Cannot perform di$isionR. Lo to step 3. ;tep 8+ Calculate the -uotient b# di$iding num b# den. ;tep >+ Hispla# the result. ;tep 3+ ;top the program. %n this e6ample, there are . routes the program can ta'e. %f the user enters the denominator as ) then the error should be produced else normal di$ision should be performed. The pictorial representation of an algorithm is called a flowchart.

Loops
;uppose #ou want to add the numbers from ( to (), what would #ou do< f course #ou could write a long statement that would calculate (5.5:525I5(). 1hat if () were changed to ()) or ()))< 1hene$er there are statements to be repeated #ou can ma'e use of loops (in fact #ou should ma'e use of loops). 1hen using loops, some condition should be specified so that the loop will terminate (otherwise the set of statements within the loop will 'eep e6ecuting infinitel#).

*or loop statement


"or loop is used for performing a fi6ed number of iterations (or repetitions). The s#nta6 is+ for !initialize-variables9 condition-to-test 9 assign-new-values-tovariables# T ::statements to be repeated !or the body of the loop# U The Jfor loop has three e6pressions that ha$e to specified.

*nitiali+e variables: This e6pression is e6ecuted onl# once (when the program flow enters the loop for the first time). %t is usuall# used to assign the loop $ariable an initial $alue. Condition to test: in$ol$es relational operators. %t is e6ecuted each time before the bod# of the loop is e6ecuted. nl# if the condition is true will the loop bod# be e6ecuted. %f it is false then the loop is terminated and the control passes to the statement following the Jfor loop bod#. .ssi"n new value to variable: %t is e6ecuted at the end of e$er# loop after the loop bod#. Usuall# it is used for assigning a new $alue to the loop $ariable. 8"ample7 ** To find s-uare of numbers from ( to () Minclude Niostream.hO int main( ) T int $ar; for ($ar 7 ( ; $arN7(); $ar55) T **beginning of Jfor bloc' coutNN P;-uare of PNN$arNN PisP NN$ar 4 $ar; U return ); ** ;tatement after the Jfor loop bod#. U

%n this program, J$ar is the loop $ariable. The loop $ariable controls the loop. 1e ha$e initialiGed this $ariable to(. The condition that is to be tested before e6ecuting the loop each time is+ %s J$ar less than or e-ual to () (i.e. $arN7())< Thus each time $ar satisfies the abo$e condition the loop bod# will be e6ecuted. J$ar is re&initialiGed with a $alue at the end of e$er# loop using the e6pression+ $ar55 (i.e. incrementing the $alue of $ar b# ( each time the bod# of the loop is e6ecuted). ;o, to put the program flow in se-uence, it would be as follows+

%nitiall# J$ar is assigned a $alue of (. The condition is tested. ;ince ( is less than (), the bod# of the loop is e6ecuted. %n the bod# of the loop we displa# the s-uare of $ar (in this case it is the s-uare of (). 1ith this, the loop has completed one c#cle. %n programming terms this is called as Jone iteration. The $ariable J$ar is then assigned a new $alue depending on what is specified in the Jfor loop. %n this program we ha$e written+ $ar55 Thus J$ar is incremented b# one. !ow, the new J$ar $alue is .. Again . is less than () and so the bod# is again e6ecuted with the J$ar $alue as .. This will be the second iteration. This process is repeated until J$ar becomes (). 1hen J$ar is (), the condition is again tested. ;ince () is e-ual to () the condition will return a true $alue (meaning that the condition is satisfied). The loop bod# is e6ecuted again. "or the ne6t iteration, J$ar is ((. @ut since (( is greater than () the condition to test returns a false $alue and the loop bod# terminates. Program flow goes to the line after the Jfor loop bod#. %n this case, it happens to be return ) (which signals the end of the program). Beware: for ($ar 7 ( ; $ar4 H(); $ar55) **1ill lead to an error T coutNN P;-uare of PNN$arNN PisP NN$ar 4 $ar; U 1hen #ou ma'e use of relational operators be careful that #ou do not lea$e a whitespace between N and 7. Bou should write the coding as+ 4H and not as 4 H

More on @forA Loops


1eX$e seen the usual Jfor loop but there are some interesting modifications to the Jfor loop. The normal s#nta6 for the Jfor loop is+ for !initialize-variables9 condition-to-test 9 assign-new-values-tovariables# T ::statements to be repeated !or the body of the loop# U Have you wondered what will happen if we don?t specify one of the three parts of the >for loop.

Minclude Niostream.hO int main( ) T int i 7 .; for ( ; iN9 ; i55 ) ** !o initialiGation of loop $ariableF T coutNNi; U return ); U The Jfor loop does not ha$e an# initialiGation e6pression. 1ill it run< Bes it will because XiX has been initialiGed outside the Jfor loop. This is perfectl# $alid and the output would be+ .:28>3 @ut if #ou donXt specif# i 7 . and tr# to compile the program, the program would still run (but #ou wonXt 'now what $alue of Ji has been assumed b# the compiler). Thus the initialiGation e6pression can be left out in a Jfor loop if #ou ha$e initialiGed the $ariable with a $alue before entering the Jfor loop. @asicall#, it is not a must that we ha$e to specif# all the : parts in a Jfor loop. Chec' out the following program+ Minclude Niostream.hO int main( ) T int i; for ( i 7 (; i F7 . ; i55 ) T coutNNi; U return ); U 1hat do #ou thin' the output will be< The output will be: (

Ji starts from (, when it goes to the $alue . the condition i F7 . becomes false (because Ji is now e-ual to .). 1hene$er the condition becomes false the Jfor loop will immediatel# terminate. ;uppose instead of for ( i 7 (; i F7 . ; i55 ) we had coded as for ( i 7 .; i F7 . ; i55 ) what will happen< ;imple, the Jfor loop will be terminated instantaneousl#; in other words the program will not enter the Jfor loop e$en once because the condition becomes false in the first test itself. Another $ariation of the for loop is shown below+ for ( ; ; ) T **bod# of loop will run infinitel# without an end unless a brea' condition is used U This is called an infinite loop. %f #ouXre wondering wh# one would want an infinite loop; well, #ou can use it to create time dela#s or #ou could specif# some condition within the loop to cause it to brea' out of the loop. @rea'ing out from a for loop (or an infinite for loop) can be accomplished b# using a Jbrea' statement (this will be discussed later). ;o far we$e seen Jfor loops using onl# one loop $ariable. @ut #ou can ha$e Jfor loops with two loop $ariables as well. Minclude Niostream.hO int main( ) T int 6,#; for (67(,#7(; 6N(),#N8 ; 655,#55) T coutNNP\nPNN6NN#; U return ); U ?ere we$e made use of two Jfor loop $ariables (6 and #). @oth are initialiGed to (. There are two conditions specified+

6N(), #N8 This actuall# means that 6 should be less than () and # should be less than 8. %f both are satisfied then the loop bod# will be e6ecuted. %f e$en one isnt satisfied the loop will terminate. The output will be: (( .. :: 22 Remember: Bou ha$e to ma'e use of comma (,) to sa# that #ou want to initialiGe 6 to ( and # to (. %t is a comma and not a semi&colon (man# beginners use the comma and semi& colon interchangeabl#). ;emi colon is used in the Jfor loop to separate each of the e6pressions (to separate the : parts of a Jfor statement+ the initialiGe, test and re&initialiGe parts). Bou might wonder whether #ou could use more than two loop $ariables< The answer is #es. Bou can use more loop $ariables but usuall# #ou wont need to use more than .. Empty J)orK loops: %f the Jfor loop has no bod# to e6ecute then it is called an empt# Jfor loop. "or e6ample+ for (int /7); /N()); /55); The Jfor loop has been terminated b# the semi&colon. This Jfor loop has no bod# and it will simpl# 'eep incrementing the $alue of J/ from ) to ()). This can be used to produce an# re-uired dela# (because the loop has to be repeated ()) times). Hela#s can be useful in %* operations or e$en while displa#ing (if the output is appearing too fast).

Body of t#e @forA loop


The bod# of the Jfor loop is the statement that immediatel# follows the Jfor statement if the bod# of the loop hasnt been enclosed within braces. "or e6ample+ for ( / 7 ); /N(); /55) coutNN PhiP; coutNN / ; The compiler will onl# consider the statement+

coutNN PhiP; as belonging to the Jfor loop bod#. ?ence the abo$e code fragment would print PhiP ten times and the $alue of J/ will onl# be printed once. The abo$e set of statements is e-ui$alent to+ for ( / 7 ); /N(); /55) T coutNN PhiP; U coutNN / ; %t is good programming practice to clearl# specif# the bod# of loops using braces (the same holds good for Jwhile loops and Jif statements).

Nesting @forA Loops


The term nesting is fre-uentl# used in programming languages. !esting means one within the other. "or e6ample+ when we sa# nesting of Jfor loops it means that there is one Jfor loop within the bod# of another Jfor loop. for (I..;I.;I..) T **bod# of (st for loop (called the outer Jfor loop) for (I.; I..; I..) T **bod# of .nd for loop (called the inner loop) U U Bou might wonder as to how the program e6ecutes in the case of two Jfor loops. Cets assume that the outer Jfor loop has a loop $ariable J/ that ta'es $alues from ( to () in increments of one. Cet the second loop $ariable be J' assuming $alues from ( to .). Thus initiall# /7(, and the program will encounter the second Jfor loop. !ow '7( and the bod# of the second (inner) loop is e6ecuted. Then ' is incremented to . (while / is still at () and the inner loop is e6ecuted again. !e6t '7: while / is still ( and the inner loop is e6ecuted once more. 1hen the J' $alue reaches .), the inner loop terminates and onl# then will J/ be incremented to .. Again for a J/ $alue of ., the inner loop will be repeated .) times (since ' will ta'e $alues from ( to .)) and so on. ?ow man# iterations are performed totall#< A total of () 4 .) (7.))) iterations are performed using these two Jfor loops.

>#ile Loop

T#e follo"ing topi$s are $overed in t#is se$tion:


1hile Coop Ho...1hile Coop

>#ile loop
1e saw that the Jfor loop has : parts in its s#nta6 (initialiGation, testing and then re& initialiGing the loop $ariable). The Jwhile loop has onl# one e6pression; the test condition. The Jwhile loop 'eeps on repeating the loop bod# as long as the loop condition is true. The s#nta6 is+ while !test-condition# T :: repeat the statements as long as condition is true U @efore illustrating the Jwhile loop using an e6ample, #ou should 'now an important fact about relational operators and characters. Bou might recall that a character can hold a single character. 1e ha$e seen comparison of numbers using relational operators but what about comparing characters< There are man# instances when #ou will want to chec' whether the user entered a particular character. "or e6ample+ #ou ma# want to chec' whether the user entered a # (for #es) or an n (for no). Hepending on what was entered #our program should continue on two different lines. %f Jletter is a character $ariable, we will obtain the input from the user using the statement+ cinOOletter; %f #ou want to chec' whether the user has entered a J# or an Jn #ou can do the following+ if (letter 7 7 J#) T **bod# of if statement ) Bou should not compare characters as shown below+ if (letter 7 7 #) **1K !L

This method of comparing a character $ariable with a character constant is 1K !L. %t will #ield an error. The character constant should alwa#s be enclosed in single -uotes.

Beware: @eginners often forget the single -uotes while using character constants.

**To find the s-uare of a gi$en number M include Niostream.hO int main( ) T char repl#; int num, s-uare; coutNN PHo #ou want to find the s-uare of a number(#*n)< P; cinOOrepl#; while (repl# 7 7 X#X) !!No blan-Lspace between the two equal si"ns0 ee note0 T coutNNP\nDnter the number + P; cinOOnum; s-uare 7 num4num; coutNN PThe s-uare is + P NNs-uare; coutNN P\nHo #ou want to s-uare another number (#*n)< P; cinOOrepl#; U return ); U Note: A blan' space has been left between the two Je-ual to s#mbols /ust to ma'e it clear that there are two e-ual signs. Ho not lea$e a space between the two 7 s#mbols when #ou write #our program. At the start of the program, if the user t#pes a J# the program will e6ecute the loop bod#. At the end of the while loop, the program will prompt the user to enter the $alue for Jrepl#. %f the user again t#pes J#, then the program will e6ecute the while bod# a second time. ?ence, at the end of each loop the program obtains the $alue for Jrepl# and chec's whether the test condition is true. As long as the test condition is true, the while loop is e6ecuted o$er and o$er again. The difference between the Jwhile loop and the Jfor loop is that the Jwhile loop does not ha$e a fi6ed number of repetitions of the loop bod#. As long as condition is true it 'eeps e6ecuting the loop bod#. Usuall# the Jwhile loop is used when the programmer is not sure about the number of iterations that need to be performed. The Jfor loop is used when the programmer 'nows how man# iterations are to be performed. f course, the use of both can be interchanged as well. %n fact, a Jfor loop can be modeled into a Jwhile loop. The e-ui$alent Jwhile loop for a Jfor loop will be as below+

Initialize a variable value9 while !condition involving the variable# T ::body of the loop ::assign a new value to the loop variable9 U %f we use the coding+ while((7 7 () B ::body of loop C the while loop becomes an infinite loop (because ( is alwa#s e-ual to ().

&oB>#ile loop
The JdoIwhile loop is a modification of the Jwhile loop. %f #ou noticed in the earlier program for the Jwhile loop, initiall# we ha$e to as' the user whether he*she wants to find the s-uare of a number. nl# if the user t#pes a J# will the program enter into the Jwhile loop. ?ence in the program we ha$e to as' the user twice whether he*she wants to s-uare a number (once outside the loop and once inside the loop). The Jdo while loop, eliminates this repetition. 1hen #ou ma'e use of the Jdo&while loop, the bod# of the loop will be e6ecuted at least once. After the first iteration, if the loop condition holds true then the loop is repeated again. Thus the first iteration is compulsor# in the JdoIwhile loop. The program to find the s-uare of a number can be re&written as follows+ Minclude Niostream.hO int main( ) T char repl#; int num, s-uare; do T coutNNP\nDnter the number + P; cinOOnum; s-uare 7 num4num; coutNN PThe s-uare is + P NNs-uare; coutNN P\nHo #ou want to s-uare another number (#*n)< P; cinOOrepl#;

Uwhile (repl# 7 7 X#X); return ); U

%n this program, the bod# of the loop will be e6ecuted once for sure. After the first iteration, the user has the option of terminating the program or continuing to use the program for s-uaring another number. Beware: when using the JdoIwhile loop, ma'e sure that #ou put a semicolon at the end of the while statement+ while (repl# 7 7 X#X);

&e$ision Statements ('*)


;o far we ha$e seen statements that help #ou in repeating a particular tas' as long as #ou desire. Another important form of program flow control is to be able to ma'e a decision as to how #ou want the program to continue. ;tatements of this 'ind are referred to as decision statements (sometimes also called selection statements).

T#e follo"ing topi$s are $overed in t#is se$tion:


%f else !ested %f Conditional perator

'fBElse 'fBelseB
Jif&else is one of the decision statements a$ailable in C55. This enables the programmer to pro$ide different paths for the program flow depending on certain conditions. "or e6ample+ consider a program for di$iding two numbers. Hi$ision b# Gero will lead to an error. To a$oid this from happening, after obtaining the two numbers from the user the programmer will want to ensure that the denominator is not Gero. ?ence there needs to be two different program flow options. %f the denominator is Gero a message sa#ing, PHi$ision not possibleP should be displa#ed. therwise the program should carr# out the di$ision and displa# the results. %n simpler terms this can be stated as+

%f the denominator is Gero, then displa# a message and do not di$ide else perform di$ision and displa# the output. ;#nta6+ if !condition# T ::statements to be e"ecuted9 U else T ::statements to be e"ecuted9 U The program flow is as follows+ %f the condition being tested within the Jif statement is true, then the bod# of Jif will be e6ecuted otherwise the bod# of Jelse will be e6ecuted. Thus the program ta'es a decision as to what it should do ne6t. Bou can also ma'e use of the Jif statement alone (Jelse is not compulsor#) or #ou can e$en ma'e use of a series of Jif...else statements as follows+ if !conditionD# T ::body U else if !condition2# T **bod# U else T ::body U D6ample+ ** To find the greater among two numbers Minclude Niostream.hO int main( ) T int a, b; coutNN PDnter the two numbers #ou want to compare + P; cinOOaOOb; if (a 7 7b)

T cout NN PThe two numbers are e-ualP; U else if (aOb) T cout NNaNN P is greater than PNNb; U else T cout NN bNN P is greater than PNNa; U return ); U %n the abo$e program, we ha$e used a series of JifIelse statements. The first condition is+ if (a 7 7b) so the program will chec' whether Ja is e-ual to Jb. %f it is e-ual then the bod# of the Jif statement will be e6ecuted. nce the statement is e6ecuted, the compiler will not bother about the ne6t Jelse if and Jelse statements because one condition has been satisfied. Program flow will then go to return ); %f the first Jif condition is not satisfied, the program control will go to the following Jelse if statement+ else if (aOb) D$en if this is not satisfied then onl# will it go to the ne6t statement, which is an Jelse statement. ;ince Ja was not greater than Jb, and e-ualit# was also tested earlier the onl# possibilit# is that Jb is greater than Ja. Thus if the first two conditions ha$e failed then the program flow will go to the bod# of the Jelse bloc'. Remember: Using the JifIelse..if format, onl# one of the bodies will be e6ecuted (not all). %f one condition is satisfied the rest of the Jelse..ifIelse is ignored. 1hen we use the Jif..else if construct, if one of the conditions is satisfied that corresponding bod# will be e6ecuted and the rest will be ignored. @ut what would happen if we use a series of Jif statements alone<

Minclude Niostream.hO int main( ) T char letter; coutNNP\n Dnter the alphabet XaX or XAX+ P; cinOOletter; if (letter7 7XaX) T coutNNP\n Bou entered an XaXP; U if (letter7 7XAX) T coutNNP\n Bou entered an XAXP; U return ); U %n the abo$e program, the compiler will chec' for Ja first and then it will chec' for JA also. D$en if the first condition is satisfied, it will still chec' for the second Jif condition. %n such cases it would be better to use the following+ if (letter7 7XaX) T coutNNP\n Bou entered an XaXP; U else if (letter7 7XAX) T coutNNP\n Bou entered an XAXP; U !ow if the user enters an Ja then the program will not enter the Jelse if statement to chec' whether the letter is an JA. Remember: %t is better to ma'e use of Jif&else&if instead of a series of Jif statements because in that wa# #our program need not chec' all the conditions unnecessaril#. And whene$er #ou use a series of Jif&else&if statements, test the condition that is most li'el# to be true first (so that the program need not waste time in chec'ing more conditions).

Nested 'f
Bou can ha$e an Jif statement within another Jif statement. This is 'nown as nested Jif. The program flow will enter into the inner Jif condition onl# if the outer Jif condition is satisfied. %n general form nested Jif will be of the form+

if (condition() T **code to be e6ecuted if condition( is true if (condition.) T **code to be e6ecuted if condition. is true U U There can be more than one Jif condition (i.e. #ou can nest as man# Jif statements as #ou want). An e6ample code fragment is gi$en below (Jmonth and J#ear are integer $ariables whose $alues are obtained from the user)+ if (month7 7.) T coutNN PThe month is "ebruar#P; if ( (#ear^2) 7 7 )) T coutNN PThis month has ., da#s.P; U else T coutNN PThis month has .9 da#s.P; U U %n the abo$e code fragment, onl# if the $ariable Jmonth is e-ual to . will the program enter into the Jif bloc'. 1ithin this bloc' it will print+ The month is "ebruar# Then it will chec' as to whether the gi$en #ear is a leap #ear or not. %f it is a leap #ear then it will displa# that the month has ., da#s else it will sa# the month has .9 da#s. Empty Ji)K statement: 1e ha$e seen the use of empt# Jfor statements but empt# Jif statements might not be useful. %n fact empt# Jif statements are usuall# logical error (because the programmer places the semi colon b# mista'e at the end of the Jif statement). D6ample+ if (num(Nnum.); TcoutNN Pnum( is less than num.P;U

;ince the Jif statement has been terminated the displa# will be produced irrespecti$e of the $alues of Jnum( and Jnum.. Chec-in" multiple conditions: %n mathematics #ou will encounter e6pressions such as+ :)N#N2). This actuall# means that the $alue of J# is greater than :) and less than 2). %n C55 #ou cannot use such an e6pression directl#. Bou cannot write+ if (:)N#N2)) because #ou cannot cascade relational operators. Bou ha$e to mention the conditions separatel# and combine them using the logical operators. if ( (:)N#) __ (#N2)) )

Conditional .perator (%:)


The conditional operator is a ternar# operator and this operator is an alternati$e to JifI else statements. The s#nta6 is as follows+ test-condition E valueD : value2; The test condition will be e$aluated and if it is true then J$alue( will be the $alue for the e6pression. %f the condition is false then J$alue . is the $alue for the entire e6pression. "or e6ample consider the coding+ a78; b7>; # 7 aOb<()+.); The $alue of # will be .) because Ja is not greater than Jb. This sort of e6pression can be written using the Jif statement as+ a78; b7>; if (aO7b) T # 7 (); U else T # 7 .); U

Beware: %ts /ust that #ou could reduce the amount of coding b# using the ternar# operator. @e careful that #ou dont confuse the logic while tr#ing to reduce the length of the codeF

&e$ision Statements (S"it$# Case)


There are man# instances wherein #ou ma# want to test for a series of conditions one after the other. "or e6ample+ ;uppose #ou obtain the input of month from the user in as a number and #ou want to displa# the corresponding name of the month; what would #ou do< Bou could write a series of twel$e JifI.else ifI.else ifIelse ifI statements. The JswitchIcase format pro$ides a con$enient alternati$e to using multiple Jif&else statements when #ou are testing for a single $ariable alone. The switch statement successi$el# tests the $alue of a $ariable against a list of integer or character constants. %f a match is found then the statement associated to that particular case will be e6ecuted. "irst of all, before entering the switch case statement, we ha$e to obtain the $alue of the switch $ariable from the user. The switch $ariable refers to the $ariable whose $alue #ou want to chec'. %n the case of con$erting numbers into corresponding months, the switch $ariable will be the month number. ynta"7 switch !variable:e"pression that evaluates to an integer# T case char:integer-constant + T **body U case char:integer-constant + T **body U U +or e"ample7

M include Niostream.hO int main ( ) T int month; coutNN PDnter the month of the #ear+ P; cinOOmonth; switch (month) :: month is the switch variable T case ( + :: if month is D then the statements are e"ecuted T coutNNPThe month is Eanuar#P; brea'; U case . + T coutNNPThe month is "ebruar#P; brea'; U ::write case statements for / to D2 Eust as shown above case (( + T coutNNPThe month is !o$emberP; brea'; U case (. + T coutNNPThe month is HecemberP; brea'; U default + :: If value of day is something other than D to 0 T coutNNPBou entered an in$alid numberP; brea'; U U return ); U As #ou can see, the compiler gets the $alue of the $ariable Jmonth from the user. This is called the Jswitch $ariable. %f the $alue of Jmonth is (, then the compiler performs what is specified under case (. %f the user enters ., then the output will be "ebruar# and so on. ;ince a #ear has onl# (. months, if the user t#pes ) or (2 then the program should displa# that the user has t#ped the wrong number. The Jdefault statement is used for this

purpose. The Jdefault statement pro$ides the program with an option to do something in case the switch $ariable does not match an# of the case constants. %n this program, Jmonth is called the switch $ariable and the integer constants from ( to (. are called case constants (i.e. the# are the $alues for which the switch $ariable is tested). Brea-: %t causes an e6it from the switch construct (bod#). "or instance, after printing that PThe month is Eanuar#P #ou dont want the compiler to go into the other cases. ?ence #ou as' it to brea' out of the JswitchIcase bod#. %f there is no brea' for each case then the program will perform all the remaining cases as well. #ry it: Kemo$e all the brea' statements from the abo$e program and e6ecute #our program. %f #ou now t#pe a $alue of (, the program will print+ The month is Eanuar# The month is "ebruar# <and so on< Beware: A mista'e that beginners commit is that the# tend to forget the Jbrea' statement. Alwa#s use Jbrea' after each case and also ma'e sure that #ou ha$e a Jdefault option in #our JswitchIcase bod#. The Jdefault case is e6ecuted onl# if the user enters a $alue other than the case constants. %t does not matter whether #ou place the default case at the starting of the switch&case bod# or at the end (but usuall# programmers prefer to place the default case at the end of the switch&case construct). ;uppose #ou want to test the switch $ariable against a set of character constants then ensure that #ou enclose #our case constants within single -uotes. Suppose the switch variable month is a character then the program would be: switch (month) T case XaX + /a1 is )it.in single quotes because it is a c.aracter constant T **bod# of the case brea'; U **the remaining cases U

Beware: There can be an e6pression in the switch part but it should e$aluate to an integer. The switch $ariable and the case constants should be integers (or characters). Bou should not use other data t#pes.

Controlling flo" "it#in a loop statement


1e$e seen a few wa#s of looping within a program. There are a few occasions when #ou might want to brea' out of a loop when some particular condition occurs. r in other words #ou ma# not want to go through the all the iterations within a Jfor loop. r #ou ma# want to brea' out of the loop for /ust one particular $alue of the loop $ariable. C55 pro$ides a mechanism to brea' from loops using the Jbrea' and Jcontinue statements. These are also called as J/ump statements. T#e follo"ing topi$s are

$overed in t#is se$tion:


@rea' Continue Lo To Keturn Appl# what #ouX$e learnt Kecap of the entire Unit

Brea5
1e$e alread# seen the use of the Jbrea' statement in the JswitchIcase construct. A Jbrea' statement can also be used to terminate (or brea' out) from a loop (li'e the Jfor and Jwhile loops). ;uppose #ou are using nested loops, then a Jbrea' specified in the bod# of the inner loop will lead to brea'ing out from the inner loop alone. MincludeNiostream.hO MincludeNstdlib.hO int main ( ) T int 6, i; for (i 7 ); iN(8; i55) T 6 7 rand( ); if (6O8))) T coutNNP\n %teration number PNNiNNP random $alue is + PNN6; coutNNP\n\n e6ceeded ()) in iteration number PNNi; coutNNP\n @rea'ing out from loopP; brea'; U

coutNNP\n %teration number PNNiNNP Kandom $alue is + PNN6; U return ); U

"irst of all, in the abo$e program the librar# function rand( ) has been used. This function is defined in the header file stdlib.h. rand ( ) is used for generating random numbers. Can #ou find out whats the logic of the abo$e program< The Jfor loop is supposed to run (8 times. @ut within the Jfor loop we$e specified a condition wherein if the random $alue generated e6ceeds 8)) the program will brea' out of the Jfor loop. The output for the program will be: %teration number ) Kandom $alue is + 2( %teration number ( random $alue is + (92>3 D6ceeded ()) in iteration number ( @rea'ing out from loop

Continue
;ometimes #ou ma# not want to brea' out of a loop permanentl#. Bou ma# want to abort one particular iteration and then continue with the remaining iterations. "or this purpose, the Jcontinue statement is used. Cets suppose that #ou ha$e a Jfor loop with a loop $ariable named J/ and #ou want the loop to run () times e6cept for the $alue of /78. %n other words, #ou want the loop to run with all J/ $alues e6cept the $alue of 8. ?ence, when the compiler enters the loop with the J/ $alue of 8, the loop should terminate temporaril# and then continue with the ne6t J/ $alue. Consider a simple e6ample+

int main ( ) T int /; for (/7(; /N9; /55) T if (/7 78) T continue; U coutNNP\n This is Kound PNN/; U return ); U The output would be: This is Kound ( This is Kound . This is Kound : This is Kound 2 This is Kound > This is Kound 3 !otice that PThis is Kound 8P is not displa#ed because that iteration was not performed. Remember: J@rea' is used to terminate permanentl# from a loop whereas Jcontinue is used to terminate onl# a particular iteration.

Co To
To use the Jgoto statement #ou should use Jlabels. 1ell start with an e6ample+ Minclude Niostream.hO int main ( ) T int i; i 7 (; C P + if (iN()) T coutNNi; i7i5(; goto C P; U return );

The above program will display the following: (.:28>39, C P is a label. 1hen the compiler encounters goto C P, it will go to the label named C P and continue e6ecuting from there. The logic of the program should be eas# to comprehend. The abo$e program can be easil# written using a Jfor loop. A few beginners use the Jgoto statement e6cessi$el# instead of using the other looping options a$ailable. f course theres nothing wrong with goto but it could lead to confusion when #ou start using man# Jgotos in #our program. %t is ad$isable and good programming practice to a$oid the use of Jgoto statements (unless it is reall# needed). Beware o) jumpin" initiali+ations usin" M&#&: Chec' out the following code, which ma'es use of the goto statement+ Minclude Niostream.hO int main( ) T char ans; coutNNPDnter #*n + P; cinOOans; if (ans77XnX) T goto done; U int 678; **DKK K done+ coutNN6; return ); U

%n C55, a $ariable can be declared and initialiGed an#where in the C55 code. Bou can e$en declare and initialiGe a $ariable /ust before the statement return );. @ut the abo$e program will lead to an error in compilation. 1h#< %n C55, the goto statement should not /ump (or s'ip) a declaration and initialiGation. ;o, if #ou replace int 678; b# int 6; 678; the compiler will accept the program. #ry it: Tr# the abo$e program with the modification and gi$e an input of Jn and see what happens. The result will be some weird answer and ! T 8 because the goto statement will b#pass the initialiGation of the $ariable J6 and hence #ou get an ambiguous answer. @e $er# careful when using Jgoto in #our program.

+eturn
The Jreturn statement will be co$ered while discussing about functions. 1hen using an# looping techni-ue within a function, the return statement can be used to brea' out from the loop and return control to the caller. 1e shall loo' at this later. "or the time being /ust remember that the Jreturn statement can be used to brea' out from a loop.

2pply t#e te$#ni3ues


Cets write a program that co$ers most of the techni-ues that we$e learnt. Problem+ 1rite a program in C55 to obtain a date from the user. The user will enter the date in the format+ dd*mm*####. ur program should print the corresponding month and also the number of da#s in that particular month. The program should also inform the user as to whether the #ear is a leap #ear or not. "or e6ample if the user enters+ ?? ?9 ?;A9 then the displa# should be+ ctober ((,(,9).This month has :( da#s. This is a leap #ear. ;olution+ (. "irst obtain the inputs in three different $ariables (i.e. the da#, month and #ear). .. 1rite a Jswitch case statement to chec' for the month. :. 1ithin the case statements print the month and also set some other $ariable to the number of da#s present in that month. 2. utside the Jswitch case bloc', print the date.

8. Using an Jif condition chec' whether the #ear is di$isible b# 2 (which means it is a leap #ear). Minclude Niostream.hO int main( ) T int d,m,#,da#s; coutNNP\nDnter the Hate (HH == BBBB)+ P; cinOOdOOmOO#; switch(m) **To print the month T case (+ coutNNP\nEanuar#P; da#s7:(; brea'; case .+ coutNNP\n"ebruar#P; brea'; case :+ coutNNP\n=archP; da#s7:(; brea'; **Iwrite the remaining cases case ((+ coutNNP\n!o$emberP; da#s7:); brea'; case (.+ coutNNP\nHecemberP; da#s7:(; brea'; default+ coutNNP\n%n$alid monthP; return ); **-uit the programF brea'; U coutNNP PNNdNNP,PNN#NNP.P; **displa# the date. if (m77.) **"ebruar# could be .9*., da#s T if(#^277)) T da#s7.,; U else T

da#s7.9; U U coutNNPThis month has PNNda#sNNP da#s.P; **displa# number of da#s in the month if (#^277)) **chec' whether it is a leap #ear T coutNNP This is a leap #ear.P; U else T coutNNP This is not a leap #ear.P; U return ); U A leap #ear is actuall# a #ear that is di$isible b# 2 and not b# ()) or a #ear that is di$isible b# 2)). Bou can add these two conditions in the abo$e program. =ore -uestions are gi$en in the e6ercise section for this chapter.

+e$ap

A C55 statement is an e6ecutable line of coding and it is terminated in a semi& colon. "or performing an# repetiti$e tas', looping techni-ues are used. The $arious looping options a$ailable are Jfor, Jwhile and Jdo&while loop. The Jfor loop is used when the number of iterations are 'nown. The Jdo&while loop will e6ecute the loop bod# once and onl# then will it chec' for the test condition. "or ta'ing decisions the programmer can use+ Jif&else statements, Jswitch&case statements. %t is possible to brea' out from a loop using either the Jbrea' or Jcontinue statements. The Jgoto statement is less fre-uentl# used in C55 programming. Jbrea' statement is used to terminate a loop while the Jcontinue statement is used to terminate specific iterations. The loop statements as well as the decision statements can be nested.

You might also like