Sunteți pe pagina 1din 66

Chapter 01

Introductory Concepts
Computer
The word computer has originated from the word Computer the dictionary meaning of Computer is counting or calculating. Computer mainly performs mathematical, logical and decision, making tasks, So a computer can be defined as a device capable of sorting problems or manipulating information according to prescribed sequence of instructions (or programs),using some mechanical or electrical process. Computer performs important tasks. !. "t stores program in memory and e#ecute program $. "t accepts data. %. "t processes data. . "t gives output. Types of computer Computers can be classified in different in ways. &ccording to the principle of storing and manipulation data there are % types of computer' !. &nalog computer $. (igital computer %. )ybrid computer Analog computer: This type of computer use continuous changing signal or analog signal instead of digits and characters. )ence the input signal is produced from the successive change of data caused by pressure, temperature, flow of liquid etc. &n analog computer maid for one task can not be used for other task. This type of computer shows output through meter, plotter etc. *#amples+ speedometer, slider rule, operational amplifier etc. Digital computer: This computer use symbols and digits as input and shows the output through monitor or other devices. (igital computers perform tasks through the on and off of current which means ! and , respectively. These computers actually work on the basis of mathematics. Their accuracy is so high. *#ample -icro computer etc. Hybrid computer: "t combines the principles of digital and analog computer. .enerally hybrid computers accept data through analog way. Then the accepted data are converted to sights and are sent to digital part for processing. /inally results are found through monitor or other output devices. &gain according to memory capacity, speed or power computers are classified into the following' !. Super computer $. -ainframe computer %. -ini computer . -icro computer Super computer: These are the fastest and most powerful computer. They are used where very large and high speed calculations are required. They are weather forecast spacecraft.

(efense, research, fire+arms design, design of wings of supersonic aircraft, simulation and modeling etc. *#ample0 *T&+,$1. S21*3 S4"", C3&5+!. Mainframe computer : &ll kinds of peripheral system, high level language and software are used is such a computer. Some millions of data byte can be transmitted per second through the "67 system of this computer. -ore than hundred users can use a mainframe computer by time sharing process. Their data storing capacity is so high. They are used in large industries, complicated scientific research, high level technical analysis etc. *#amples 8 "9- %,, 2:";&C !!,,, C59*3 !<, etc. Mini computer ' )ere several input 6output devices are used. -ore than =, users can use mini computer together by terminals. Such a computer is used in business, industries, scientific and technological research and analysis. *#ample+ "9- S6% , "9-S6%>, 1(1 !!, :C3 S6?$?,. Micro computer : -icro computers are of micro processors. )ence the name is micro computer. Such a computer is made of a microprocessor, C12, 37- 3&- and "67 interface chip. -icro computers are also small in si@e and cheap. They are also called personal computer or 1C in brief. & micro computer is used by one user at a time. These computer are used in personal use, business, office, entertainment etc. There are different kinds of micro computer e.g. desktop, laptop, notebook, 1(& etc. *#amples 8"9- 1C , &pple 1ower 1C etc.

Components of a computer: The components of a computer are divided into


% ! $ % parts ' "nput unit Central 1rocessing 2nit (C12) 7utput unit !. Input unit : "nput unit takes input from user. These are different types of input devices. !. Aeyboard $. -ouse %. Boystick . (isk =. Scanner >. Card reader <. (igital camera C. -icrophone ?. 7ptical -ark 3eader (7-3) !,.7ptical Character 3eader(7C3) !!.-"C3 !$.(igiti@er !%. $. Central Processing Unit : This unit processes the data inputting by user Central 1rocessing unit or C12 is divided into % main units. !. &rithmetic Dogic 2nit (&D2) $. Control 2nit %. -emory The C12 is called microprocessor. Functions of CPU !. T7 control all parts of computer, $. To take data E instructions from memor %. To decode data . To perform the arithmetic E logic work =. To e#ecute the stored program in memory >. To communicate between input and output devices.

utput unit : This unit shows the output of processing of processing data by output devices. Some output devices are !. -onitor $. 1rinter %. 1lotter . -icrofilm =. (isk >. Speaker !loc" Diagram of a computer -emory "npu t processor (ata storage 7ut put

%.

Microprocessor : "t is a unit ;DS" (;ery Darge Seale "ntegration) silicon chip. -icroprocessor is made by the central processing unit of computer with ;DS" technology. "t is the brain or heart of micro computer. The capacity of computer and other properties depend on the nature and capacity of microprocessor . the internal work of computer is done by microprocessor. "n microprocessor there are necessary logic gates. #ist of $%bit microprocessor :ame Company FC, Failog >=,$ -7S Technology C,CC "nter > ,? -otorola #ist of &'%bit microprocessor :ame Company C,CC "ntel C,C> "ntel >C,, -otorola #ist of ()%bit microprocessor: :ame' Company C,%C> "ntel >C,$, -otorola Memory: The mean or carrier used for storing data in computer is called memory. -emories are of usually two types' !. 1rimary memory $. Secondary memory Primary memory' The memory which has direct access with &D2 is called primary memory. "ts storage capacity is poor. The data and instructions which are always needed are stored in primary memory. So it stores the running program, data etc. it is volatile memory i.e. when current is off it losses its stored data. "t can store data and read data very quickly. *#ample 8 !. -agnetic core memory. $. Thin film memory.

%. Semi conductor memory. . -agnetic bubble memory. =. Charge coupled memory. Secondary memory: This type of memory is non+volatile. "ts storage capacity is more. "t has no direct access with &D2. "ts speed is less. There is always passed data or instructions from primary memory to secondary memory. *#ample+ -agnetic tape. -agnetic drum. -agnetic disk. /loppy disk. )ard disk. Difference bet*een primary and secondary memory: Primary memory !. "t has direct access with C12. $. "t contains programs, data and some program used for self controlling of computer. %. "ts capacity is less than secondary memory. . "ts access time with C12 is less than secondary memory. =. "n 37- part of primary memory data or program is permanently stored but when current is off data in 3&- part is loss. Secondary memory !. "t has no direct access with C12. $. "t contains permanent stored data. %. "ts capacity is more than primary memory. . "ts access time with C12 is more than primary memory. =. Though current is off it does not losses its data.

+ M , +AM: 37- means 3ead 7nly -emory. That is data can be read from this memory but can not be written. So, if once program is written in 37- it can not be erased. "t is a non+volatile semiconductor memory used for permanently stored data. *#ample+ -37-, 137- etc. 9ut at present there are many such type of 37- is invented where data both can be read and if necessary can be written. Such as *137-, **137- etc. 3&- means 3andom &ccess -emory. The time for reading and writing is equal so it is called 3&-. (ata can be both read and write in this memory. 9ut it is volatile and so if current is off it losses its data. This type of memory is used as a media for passage of data from secondary memory to C12. *#ample+ (3&-, S(3&-, ;3&etc. Difference bet*een +AM , + M: +AM !. "ts full name is 3andom &ccess -emory. $. 9oth read and write is possible. %. "t is volatile memory. . &ctive program and repeatedly changeable data are stored here. + M !. "ts full name is 3ead 7nly -emory. $. 7nly read is possible. %. "t is non+volatile memory. . *asily unchangeable data or program is stored here.

HA+D-A+.: The physical components of computer that is all machine parts or devices are called hardware. "nitially computer hardware is % types' !. Input de/ices: Aeyboard, mouse, Goystick, disk, scanner, card reader, digital camera, microphone and so on. $. Processing de/ices: -icroprocessor, 3&-, hard disk, floppy disk, motherboard, power supply, &.1 card, sound card, C(+37- drive and so on. %. utput de/ices: -onitor, 1rinter, 1lotter, microfilm, disk, speaker and so on.

S FT-A+.: Software is a program or collection of programs that enables hardware making a relation between hardware and user. )ardware is meaningless without software. Software keeps the communication between user and hardware. Computer software is divided mainly in two' System software &pplication software C#ASSIFICATI 0 F S FT-A+.

Define bit1 byte and *ord2 !it: *very piece of information is stored in computer encoded as some unique combination of , and !. These , and ! are called bits. *ach bit is represented by an electric present or absent. !yte: 9yte is the combination of C bits. The unit of computer memory cell is e#pressed in bytes. -ord: Hord is the combination of some character which has a specific meaning and which can be stored as a unit, replaced or processed. Hords are two types' data word and instruction word. The word that stores data is called data word and stores instruction is called instruction word. "n computer every word is stored , or ! bit. Hord of C bits is called byte. Distinguis3 bet*een brand and clone computer2 !rand computer: Hhen all of the peripherals of a computer is made or assembled by the choice of company own then it is called brand computer. Clone computer: Hhen all the peripherals of a computer is made or assembled by the choice of user own then it is called clone computer. -3at do you mean by data bus and control bus4 Ans2: (ata bus' "ts work is to send and receive the data or information between different chips of computer. Control bus' "t bears the symbol or instruction from microprocessor and sends to the corresponding parts of computer. P+ 5+AMMI05 #A05UA5.: Programming language: To sort a particular set of data, a computer is given an appropriate set of instructions. & complete set of logical instructions is called programming language.

Types of programming language: There are % types of programming languages' Dow level -id level )igh level #o* le/el language: Dow level language is the set of actual instructions that the computer can understand without translator and e#ecute directly. There are two types of low level languages' -achine language &ssembly language Mac3ine language' -achine languages generally consists of strings of numbers (o and !) that instruct computer to perform their most elementary operations. This language does not need any translator. Assembly language: &ssembly language is the symbolic representation of the actual machine instructions e#ecuted by the computer. This type of language needs translator. "t is called assembler. Mid le/el language: "t combines the facilities of low level and high level language. Through this language one can control the hardware at bit level and create system program. *#ample+ C, /orth etc. Hig3 le/el language' This language allows programmers to write instructions that look almost like everyday *nglish language and contains commonly used mathematical notations. These are machine dependent language. "t needs translator. "n a high level language, a single statement corresponds to several instructions of low level languages. & special advantages of this language is the availability of library programs. *#ample 8 &D.7D, C797D, /73T3&:, 1&SC&D, 9&S"C, CII, B&;& etc. Difference bet*een mac3ine and 3ig3 le/el language Mac3ine language !. 2se , E ! i.e. binary or he# method to write instructions. $. Computer directly understand this language. %. "t does not need any translator. . 1rogram e#ecuted very fast. =. ;ery comple#, diligent and time consuming to write instructions. >. -achine language written for one computer can not e#ecute another computer Hig3 le/el language !. ;ery similar to normal *nglish language $. Computer can not directly understand this language. %. "t needs translator. . 1rogram e#ecuted slowly than machine language. =. *asy, enGoying and time saving to write instructions. >. )ere is no such problem.

Translator: The instructions we write e#cept machine language is needed to translate into computer understood instructions. & translator does this work. "t makes the source code into obGect code. There are three types of translator' &ssembler Compiler "nterpreter Assembler' "t is the translator used for assembly language. "t translates the assembly language into machine language. &ssembler program is written in machine language. Compiler' Compiler translates a high level language into an obGect program. "t translates the whole program at a time. (ifferent high level language needs different compilers because a particular compiler can convert a particular high level language into machine language. Compiler also links necessary routines with obGect program.

9esides compiler detects errors in source code. Interpreter: "nterpreter also translates a high level language into an obGect program. "t translates line of the whole program. That is it translates only one line at a time. 9ut if a line is incorrect it will not allow programmer to write forward. 7nly when the line is correct the programmer can write the ne#t line. Difference bet*een compiler and interpreter: Compiler !. "t translates the whole program together. $. "t shows the total errors after the compiling of the whole program. %. "f one line contains error program can be written forward. . "ts debugging and testing is slow. =. &fter compilation a full obGect program is created. >. & compiler is larger in si@e. Interpreter !. "t reads one line and translates it. $. "t shows the errors in one line. %. "f one line contains error program can not be written forward. . "ts debugging and testing is fast. =. &fter interpretation a full obGect program is not found. >. &n interpreter is small in si@e

Structure of a program: *very program has three parts. & full program is formed with the combination of these parts. "nput 1rocess 7utput 5eneral rules to *rite a program: !. To identify the problem. $. 3equired analysis %. &lgorithm design . /low chart =. Coding >. (ebugging and testing <. /inal implementation. Algorit3m' &lgorithm means to solve a problem step by step i.e. dividing a problem into several steps, solving these separately and in this way solve the whole problem. "t should have the following four characteristics' "t should be easy understood. *very step will be clear as computer can understand. 1roblem will be solved in limited steps. "t will be applicable widely. .6ample' Hrite an algorithm for finding the roots of the equation a# $Ib#IcJ,. Step !' Take input a, b E c. Step $' "f aJ, then one root. 1rint 4!J+c6b and end. 7therwise go to the ne#t step. Step %' Calculate (Jb$+ ac Step ' Test the sign of (J b$ + ac. &ccording to sign follow any one of followingK b a) "f (J,, roots are equal and real. 1rint 4 !, 4$J and end. 2a b) "f (L,, roots are unequal and real. 1rint 4!=
b + ( b ( and end. E 4$ = $a $a

c) "f (M,, roots are imaginary. 1rint no real roots and end -rite An Algorit3m To Find T3e 5reatest Ans2: The algorithm is as follows' !. Step !' Start the program.

f T3ree 0umbers2

$. Step $' 3ead the numbers a, b E c. %. Step %' "f aLbN Then follow one of the following. a) "f aLcN /ollow one of the forllowing ". "f yes print a is big. "". "f no go to ne#t. b) "f bLcN /ollow one of the following ". "f yes print b is big. "". "f no go to ne#t. """. 1rint c is big. . Step ' *nd the program. F# -CHA+T: )ow a program will work is shown by drawing picture in flowchart. & flowchart is some such pictures from which it is understood that to solve the problem how successively we have to move forward. & flowchart should have the following characteristics' "t will help to perform the obGect of program. "t will help to determine the errors. "t will help in changing and widening the program. "t will help to code. "t will make the comple# problem into easy one. Symbols of flo*c3art: &2 Start6 *nd %. "nput6 7utput $. Connector

. 1rocessing

=. (ecision

>. 1rint or document

<. (irection of flow C. preparatory symbol C is called a mid%le/el language: C contains certain additional features that allow it to be used as a low level language. 7n the other hand its instructions consist of terms that like to algebraic e#pressions, by certain *nglish keyword such as if, else, for, do and while. "n this respect C is similar to other high level programming languages. Thus C makes bridge reducing the gap between machine and high level language. Therefore it contains both the facilities of machine and high level languages. ThatOs why C is called mid level language. C is called structured language: C allows a variety of programming possibilities. "t directly supports several loop constructs, such as while, do+while and for. "t also

allows placing statements anywhere on a line and does not require a strict field concept. 9esides COs main structural component is the function. "n C functions are the building blocks in which all program activity occurs. They allow defining and coding separate tasks in a program, thus allowing programs to be modular. These created functions work properly in various situations without creating any side effects in other parts of the program. ThatOs why C is called structural language. Structure of a C program: 7 includeMheader fileL main() P define variablesK input functions such as scanf, getchar etcK processing by loops or defined functions or othersK output functions such as printf, putchar etc. Q

Important c3aracteristics of program:


Integrity: This refers to the accuracy of the calculations. "t is clear that if the calculations are not carried out correctly all other program enhancements will be meaningless. Thus the integrity of the calculations is an absolute necessity in any computer program. Clarity: "t refers to the overall readability of the program with particular emphasis on its understanding logic. "f a program is clearly written it is possible other programmers to follow the program logic. "t will also be possible for the programmer himself to understand the logic after a long period of time. Simplicity: The clarity and accuracy of a program are usually enhanced by keeping things as simple as possible. "n order to maintain a relatively simple, straightforward program it is desirable to sacrifice a certain amount of computational efficiency. .fficiency: "t is concerned with e#ecution speed and efficient memory utili@ation. "f a program written with efficient it will be e#ecuted quickly and output will be found quickly. Modularity: -any programs can be broken into a series of groups. "t is good programming practice to implement each of these groups as a separate program module. The use of a modular programming structure enhances the accuracy and clarity of a program. 5enerality: & program should be as general as possible with reasonable limits. This can be obtained with very little additional programming efforts. -3at is source code and ob8ect code4 Ans2: Source code is the instructions we write in programming language. 7bGect code is the transformed instructions formed after the source code is translated by any translator program. -3at in general 3appens *3en a computer program is e6ecuted4 & stored program can be e#ecuted at any time. This causes the following things to happen.+ &2 & set of information called the input data will be entered into the compiler (from keyboard, floppy disc etc) and stored in a portion of the computerOs memory2 )2 The input data will be processed to produce certain desired results, known as the out put data. (2 The output data, and perhaps some of the input data, will be printed onto a sheet of paper or displayed on a monitor (a television receiver specially designed to display computer output). This three 8 step procedure can be repeated many times if desired, thus causing a large quantity of data to be processed in rapid sequence.

Distinguis3 bet*een data and information2 Ans2: (ata is the unit of information which is unsorted. Hhen data is made into useable by sorting then it is called information. Describe t3e generations of programming languages2 Ans2: The generations of programming languages are as follows' !. /irst generation language e.g. machine language. $. Second generation language e.g. assembly language. %. Third generation language e.g. mid+level, high+level language. . /ourth generation language e.g. SRD6(S, 3&1173T, /7C2S, ":T*C*T. F# - DIA5+AM: Dra* t3e flo* diagram t3at compares t*o numbers eit3er one is greater t3an anot3er or small or bot3 e9uals2 Det variables are a, bE c

/low chart to find the greatest the three numbers.

10

T3ere are four basic system of computer:


)ardware Software 2ser 1rogram6procedure.

11

Chapter 2

C Fundamentals
&2 "dentifiers E keywords. )2 (ata type E (eclarations. (2 ;ariable E Constant. :2 *#pressions. ;2 Statement. &2 Identifier: "dentifiers are names that are given to various program elements such as variables, functions and arrays. "dentifiers consist of letters and digits, in any order, e#cept that the first character must character must be a letter. 9oth uppercase and lower case letters are permitted, though lower case letters are mostly favorable. &n underscore ( 0 ) is often used in the middle of an identifier. ;alid identifiers #! 4!$% 4y #0y 0#y T&9D* Ta#0rate !# S#T #y #+y
th

"nvalid

3easons The !st character must be a letter "llegal characters (S) "llegal characters (blank space) "llegal characters (+) The !st character must be a letter. *#cessive number must be a letter. "t is keyword.

/ile management "nt

<ey*ords: There are certain reserved words, called keywords, that have standard, predefined meanings in C. These keywords can be used only for their intended purposeK They can not be used as programmer 8 defined identifiers. The keywords are all lowercase. Standard keywords are' &uto 9reak Case Char Continue do double else enum goto int long register return signed switch typedef union unsigned volatile struct static si@eof *#tern float

12

Const (efault

for if

short Hhile

void

Constant: There are four basic types of constants in C i. "nteger constants. ii. /loating 8 point constants. iii. Character constants. iv. String constants. =ariable: & variable is an identifier that is used to represent a single data itemK i.e. a numerical quantity or a character constant. The data item must be assigned to the variable at some point in the program. The data item can then be accessed later in the program simply by referring to the variable name. *#ample' int a,b,c K char dK )ere a,b,c are integer variables and d are char type variable. Data type: 9asic data types used in C 8 program' C supports several different types of data, each of which may be represent differently within the computers memory. The basic data types are listed below' data types "nt Char /loat (ouble description integer quantity. single character. floating point number double 8 precision floating 8 point

Mention t3eir bit *idt3s , +anges:


Ho* could you e6tend t3e range of /alues of data types repress ' The basic data types can be argument by the use of the data type qualifiers 8 short, long, signed and unsigned. *#ample' integer quantities can be defined as short int, long int or unsigned int. Thus a short int may require less memory than an ordinary int or it may require the same amount of memory of memory as an ordinary int but it will never e#ceed an ordinary int in word length. Similarly a long int may require the same amount of memory as an ordinary int or may require more memory but it will be never less than an ordinary int. "f short int and int both have the same memory requirements($bytes) then long int will generally have double the requirements( bytes) 7r if int and long int both have the same memory requirements( bytes) Then short int will generally have the half memory requirements($ bytes) (ata types 9it width 6 -emory 3anges

13

"nt Char /loat (ouble

requirements $ bytes ! byte byte C byte

+%$,<>C to %$<>< +!$C to!$< %. 4 !, +%C to %. 4 !,%C !.< 4 !,+%,C to !.< 4 !,%,C

Declarations: & declaration associates a group of variables with a specific data type. & declaration consist of a data type, followed by one or more variable names, ending with a semi 8 colon. *#ample' & C program contains the following type declarations int a,b,cK float root!,root$K char flag, te#tUC,VK Thus a, b and c are declared to be integer variables root! and root$ are floating 8 point variables and te#t is an C, 8 element, char 8 type array. .6pressions: &n e#pression represents a single data item, such as a number or a character. The e#pression may consist of a single entity, such as a constant, a variable, an array element or a reference to a function. "t may also consist of some combination of such entities, interconnected by one or more operators. *#pressions can also represent logical conditions that are either true or false. .6ample: aIb e#pression with addition operator. #Jy e#pression with assignment operator. cJaIb The value of the e#pression (aIb) is assigned to variable C. #MJy e#pression with relational operator. #JJy The e#pression will have the value ! (true) if the value of # is equal to the value of y otherwise the e#pression will have the value of (false). IIi e#pression with unary operator. Statements: & statement causes the computer to carry out some action. .6ample:

a = 3; assignment type statements. c = a + b;


IIiK incrementing 8 type statement. printf (S&rea JWfT, area)K This statement causes the printf function to be evaluated. K null statement.

14

Types of statement: There are three different types of statements' i2 *#pression statements. ii2 Compound statements. iii2 Control statements. i2 .6pression statements: &n e#pression 6 simple statement consists of an e#pression followed by a semi 8 colon. *#ample' aJ%K cJaIbK IIiK printf (S&rea J Wf S,area)K K ii2 Compound statements: & compound statement consists of several individual statements enclosed within a pair of bracketsPQ. The individual statements may themselves be e#pression statements, compound statements or control statements. *#ample' & typical compound statement is shown below' P pi J %.! ! ?%K circumference J $XpiXradiusK area J piXradiusXradiusK Q Differ e6pression and compound statements' *#pression consists of an e#pression but compound statement consists of several individual statements. *#pression followed by semi 8 colon but individual statements enclosed with in a pair of brackets PQ but not end with a semicolon. iii2 Control statements: Control statements are used to create special program features, such as logical tests, loops and branches. *#amples' The following control statements creates a conditional loop in which several action is satisfiedK Hhile (countMJn) Pprintf(S#JT)K scanf(SWfT,E#)K sumIJ#K IIcountK Differ of compound statement from control statement:

15

Compound statement consists of several individual statements *nclosed with a pair of braces. The enclosed statements individual statements may themselves be e#pression statemen, other compound statements statements, branches. 9ut control statements not enclosed with a pair of braces. including or embedded control compound statements. statements. E control 9ut control statement contain e#pression statements, or compound statements create special program feature such as logical tests, loops and

16

Chapter 3

perators , .6pressions
perators: 7perators in C program is special symbol or word which directs the compiler to perform arithmetical or logical works, i.e. The characters which is used in C for special purpose such as mathematical, logical or relational purpose so this character is called operators. -ost operators allow the individual operands to be e#pressions. *#ample' aIbK )ere I is operator and a,b operand. Different categories of I2 II2 III2 I=2 =2 =I2 2nary operator. 3elational operator. Dogical operator. &ssignment operator. Conditional operator. perators: &rithmetic operator.

perand: The data items that operands act upon are called operands.

a + b a - b a and b are operand. a > b


". Arit3metic operator: There are five arithmetic operators in C. 7perator I + X 6 W 1urpose &ddition. Subtraction. -ultiplication. (ivision 3emainder after integer division.

.6ample: Suppose that a and b are integer variables whose values are !! and 8 %, respectively. Several arithmetic e#pressions, *#pression aIb a+b aXb a6b aWb ;alue C ! +%% +% $

"f a had been assigned a value of +!! and b had been assigned %. Then the value of a6b would still be +% but aWb would be +$. Similarly, if a and b had both been

17

assigned negative values (+!! and +% respectively) Then a6b would be % and aWb would be +$. The condition a J ((a6b)Xb)I(aWb) will be satisfied in each of the above cases. "". Unary operator: C includes a class of operators that act upon a single operand to produce a new value. 7perator "ncrement (ecrement 2nary minus Symbol II ++ 8 7peration 9e caused its operand to be increased by !. Causes its operand to be decreased by !. (enotes negative value.

.6amples: Suppose i be an integer variable that has been assigned a value of =. The e#pression IIi which is equivalent i JiI! causes the value of i to be increased to >. Similarly the e#pression 8i which is equivalent to iJi+! causes the value of i to be decreased to . Difference bet*een >>i and i>>: & C program includes an integer variable i whose initial value ! 1rintf(SiJ W dYnT,i)K 1rintf(SiJ W dYnT,IIi)K 1rintf(SiJ W dYnT,i)K 7ut put' iJ ! iJ$ iJ$ :ow suppose the program, 1rintf(SiJ W dYnT,i)K 1rintf(SiJ W dYnT, iII)K 1rintf(SiJ W dYnT,i)K 7ut put' iJ! iJ! iJ$ i. iII post increment operator E IIi 1re increment operator. ii. iII in compiler program, take the old value of operand but in ne#t, new sum will show in the ne#t step by adding. . i.e. the operand will be Uin $nd statement, iJiI!V

18

altered in value before it is utili@ed for its intended purposes within the program. iii. IIi in compiler at first adding ! to the old value of operand, use the sum to the program.i.e. the value of the operand will be altered before utili@e. . """. +elational operator: The operators that are used to form logical e#pressions which represent condition that are either true or false. The result will be Z!O if the condition is true and Z,O if false. There are si# relational operators in C. They are 7perator M LJ L LJ JJ [J -eaning Dess than Dess than or equal to .reater than .reater than or equal *qual :ot equal

.6ample: suppose that i, G and k are integer variables whose values are !, $ and % respectively. *#pression iMG (iIG)LJk (GIk)LiI= A[J% BJJ$ ";. "nterpretation True True /alse /alse True ;alue ! ! , , !

#ogical operator: The logical operators act upon operands that are themselves logical e#pression. i.e. the logical operator is used to perform logical purposes in C. The result of a logical operation will be true if either operands true or both operands are true. The result of a logical or e#pression will be false only if both operands are false 7perator -eaning EE and \\ or [ not .6ample: suppose i is an integer variable whose value is <, f is a floating variable whose value is =.= and C is a char variable that represents the char ZwO

*#pressions (iLJ>)EE(cJJ ZwO (iLJ>)\\(cJJ!!?) (fM!!)EE (iL!,,) (c[J ZpO \\ ((iIf)MJ!,)

"nterpretation True True /alse True

;alue ! ! , !

19

;.

Assignment operator: The operator which are used to form assignment e#pressions which assign the value of an e#pression to an identifier are known as assignment operator. The most commonly used assignment operator is J .This is written in the form 8 "dentifier J e#pression. Hhere identifier generally represents a variable and e#pression represents a constant, a variable or a more comple# e#pression. .6ample: aJ% aJy delta J,.,,! sum J aIb area J length Xwidth.

;".

Conditional operator: The operators which is used in C to perform different condition purposes i.e. these are the operators which is used to form an e#pression in simple condition operations. Conditional operator' N & conditional e#pression is written in the form *#pression!N *#pression$' e#pression% *#ample' 4J!, ,yJ= FJ(#Ly)N#'= 7utput' @J!, perator precedence: The prominence of one operator to another operator in compiler is called precedence. "f more operator is used in e#pression, the operation of operator is used in e#pression, the operation of operator depends on operator precedence.

7perator category !. &rithmetic' $. 2nary' %. relational' . logical' =. Conditional >. &ssignment Problem ?&: & C program &2 8(iIG) J +(CI=) J +!% )2 IIi J iI! J CI! J ? (2 iII J iI! J CI! J ?

7perators

&ssociativity

X6W D3 +, II, ++, [, si@eof (type) 3D M, MJ, L, LJ, JJ, [J D3 EE, \\ D3 N' 3D J, IJ, +J, 6J, WJ 3D contain declaration int iJC,GJ=K float #J ,.,,=,yJ +,.,!K

write the output of following e#pression.

20

:2 8G J G+! J =+! J ;2 II# J #I! J ,.,,= I! J !.,,= '2 y+Jy+! J +,.,! +! J !.,! @2 (#Ly) EE (iL,) EE (GM=) J (,.,,=L + ,.,!)EE(CL,)EE(=M=) J(! EE !) EE , J! EE , J, $2 (#Ly) EE (iL,)[[(GM=) J(,.,,=L + ,.,!) EE (CL,) [[=M= J! EE![[, J![[, J! A2 (iL,) EE(GM=) J(CL,)EE(=M=) J! EE , J, &?2 (iL,)[[(GM=) J![[, J! &&2 $X#I(yJJ,) J$X ,.,,= I (+,.,! J,) J$X,.,,= I, J,.,! &)2 [(iMJG) J [(CMJ=) J[, J! &(2 [(#L,) J[(,.,,=L,) J[! J, &:2 $X((i6=)I X(G+%))W(iIG+$)) J$X((C6=)I X( X(=+%)W(CI=+$)) J$X((!I( I$))W!!) J$X((!IC)W!!)) J$X(?W!!) J$X? J!C.&ns.

21

&;2 (i+%XG)W(cI$Xd)6(#+y) J(C+%X=)W(cI$Xd)6(,.,,=I,.,!) J+<W$ J ,.,!= &'2 <I%L=EE[( I<M?)\\%MJ J<I%L=EE!\\%M J!,L=EE!\\%MJ J!EE!\\%MJ J!EE!\\! J!EE! J!

22

Chapter 4

Data Input and output


Input and output function: 1. 2. 3. 4. 5. 6. !. getchar input function, a signle character. putchar output function, a single character. scanf input function, any value. printf output function, any value. gets input function, a line 6string. puts output function, a line. 5etc3ar function: .etchar function is used to receive a character from the key board. The getchar function is a part of the standard C"6, library. "t returns a single characters from a standard input device ( typically keyboard). "n general terms, a function reference would be written as character variable J getchar()K header file of getchar function ]includeMstdio.hL .6ample: & C program contains that c is a character 8 type variable and $ nd statement causes a single character to be entered from the standard input device and then assigned to c. $. putc3ar function: The C 8 library function putchar is used to display a single character on the computer. This function is complementary to the character input function getchar and is a part of Ci6, library. "t transmits a single character to a standard output device. in general, the function would be written as' putchar (character variable)' *#ample' ]includeMstdio.hL main() P char #J Z&OK putchar(Z&O)K putchar(Z9O)K Q output' &9 %. scanf function: The C library function scanf is to enter input data into the computer from a standard input device (keyboard).

23

this function can be used to enter any combination of numerical values, single characters, and strings. The function returns the number of data items that have been entered successfully. "n general terms, the scanf function is written as scanf (control string, arg!, arg$, ^^.,argn)K where control string refers to a string containing certain required formatting information and arg!, arg$, ^..argn are arguments that represents the individual data items. .6ample: & typical application of a scanf function+ ]includeMstdio.hL main() P char itemU$,VK int partnoK float costK ^^^^ scanf (SWs Wd WfT, Eitem,Epartno,Ecost)K ^^^^. Q . printf function: The C library function printf is used to write output data from the computer onto a standard output device. This function can be used to output any combination of numerical values, single characters and strings. "t is similar to the input function scanf. The printf function moves data from the computers memory to the standard output device. in general terms, the printf function is written as printf (control string, arg!, arg$,^^argn) where control string refers to a string that contains formatting information and arg!, arg$^.argn are arguments that represent the individual output data items. *#ample' ] includeMstdio.hL main() P char itemU$,VK int partnoK float costK ^^^.. printf (SWs Wd Wf T, item, partno, cost)K ^^^^

24

Q /unction !. getchar 1urpose *nter a single character from the $. putchar std input device. Send a single character from the %. scanf std output device. *nter data items from the std input . printf device Send data items from the std =. gets output device *nter a string from the std input >. puts device Send a string from the std output device Purpose of 3eader file4 Is t3e use of 3eader file absolutely necessary4 The purpose of a header file is to supply necessary information to compiler about the library function . 5es, the use of header file is absolutely necessary. 9ecause to write a program we have to use the library functions obviously. &nd as compiler canOt understand these library functions without the header file must include them. #ibrary function: C languages accompanied by a no. of Dibrary functions that carry out various commonly used operations or calculations. These Dibrary functions. are not a part of the languages part of the language purpose through all implementations of the language include them. /or e#ample, there are library functions that carry out standard input6output operations+ abs(i) 8return the absolute value of i. cos(d) + + return the cosine of d. e#p(d)_raise e to the power. pow(d!,d$)_return d! raised to the d$ power. sqrt(d)_return the square root of d. BC a program to con/ert a line of te6t from lo*er case to upper caseCB ]includeMstdio.hL stdio.h stdio.h stdio.h stdio.h stdio.h )eader file stdio.h

25

]includeMctype.hL void main() P int count,tagK char lineUC,VK printf(`*nter your te#t'`)K for(countJ,K(lineUcountVJgetchar()) [J aYnaKIIcount) tagJcountK for(countJ,KcountMJtagKIIcount) putchar(toupper(lineUcountV))K Q

26

Chapter 5

Prepairing , running a complete C program


Common errors in C:
!. Syntactic error. $. *#ecution error. %. Dogical error. !. Syntactic error: The presence of syntactic error (or grammatical errors will become readily apparent once the 3un command has been issued, since these errors will prevent the program from being compiled or e#ecuted successfully. Some particularly common errors of this type are improperly declared variables, a reference to an undeclared variables, incorrect punctuation, etc. -ost C compilers will generate diagnostic message when syntactic errors have been detected during the compilations process. These diagnostic messages are not always straightforward in their meaning and they may not correctly identify where the error occurred. $. .6ecution error: This type of errors occurs during program e#ecution after a successful compilation. Some common e#ecution errors are a numerical errors are a numerical overflow or under flow. (ivision by @ero attempting to compute the logarithm or the square root of a negative number etc. %. #ogical error: This type of errors occurs when the programmers supplied the computer instructions that are logically incorrect. Dogical errors can be very difficult to detect since the output resulting from a logically incorrect. Dogical errors can be very difficuolt to detect since the output resulting from a logically incorrect program may appear to be error + free. Debugging: (ebugging are the methods or techniques used to find the location of logical errors within a program. Some more common debugging methods are given below' !. *rror isolation. $. Tracing. %. Hatch values. . 9reak point. =. Stepping. BCa program to find root of a9uadratic e9uationX6 a#$Ib#IcJ,
x1 = -b + b 2 - 4ac x2 = -b b 2 - 4ac 2a 2a

27

input a, b, c E output #!,#$K ]includeMstdio.hL ]includeMmath.hL void main() P float a,b,c,#!,#$K printf(`entre a,b,c using space`)K scanf(`Wf Wf Wf`,Ea, Eb, Ec)K if ((bXb) + ( XaXc)) P #!J(+bIsqrt(bXb+ XaXc))6($Xa)K #$J(+b+sqrt(bXb+ XaXc))6($Xa)K Q else printf(`imaginary root`)K printf(`root ! JWf root $ JWf`,#!, #$)K Q 6Xa program to find simple compound interest problem FDPE&>i )nX6 ]includeMstdio.hL ]includeMmath.hL void main() P float p,r,n,i,fK printf(`please enter a value for the principle (p)'`)K scanf(`Wf`,Ep)K printf(`please enter a value for the interest (r)'`)K scanf(`Wf`,Er)K printf(`please enter a value for the no. of years (n)'`)K scanf(`Wf`,En)K f J pXpow((!Ii),n)K printf(`YnThe final value(/) is W$fYn`,f)K Q A C program to determine count' 5arn count J L w W l

]includeMstdio.hL main() P int numberK float D,l,H,w,:e,:m,Te#,(enierK printf (S *nter number'T)K

28

scanf(SWdT, Enumber)K switch (number)K P case !' printf(S*nter the value of D,l,H,w in yds ElbsT)K scanf(S Wf, Wf, Wf, WfT,ED,El,EH,Ew)K :eJ(DXw)6(lXH)K 1rintf(SThe count is Wf :eT,:e)K breakK case $' printf(S*nter the value of D,l,H,w in meter E kgT)K scanf(S Wf, Wf, Wf, WfT,ED,El,EH,Ew)K :mJ(DXw)6(lXH)K 1rintf(SThe count is Wf :mT,:m)K breakK case %' printf(S*nter the value of D,l,H,w in km E gmT)K scanf(S Wf, Wf, Wf, WfT,ED,El,EH,Ew)K Te#J (lXH) 6(DXw)K 1rintf(SThe count is Wf Te#T,Te#)K breakK case ' printf(S*nter the value of D,l,H,w in ?,,,m E gmT)K scanf(S Wf, Wf, Wf, WfT,ED,El,EH,Ew)K (enierJ (lXH) 6(DXw)K 1rintf(SThe count is Wf (enierT,(enier)K breakK default' printf (S There is no correct valueT)K Q Q -rite a program for grading Mar"s: ]includeMstdio.hL main() P int marksK printf(SmarksT)K if ((marksL<?) EE(marksMJ!,,)) printf(S&IT)K

29

else if ((marks ((marksL>?) EE(marksMC,)) printf(S&T)K else if ((marks ((marksL>?) EE(marksMC,)) printf(S&+T)K else if ((marks ((marksL=?) EE(marksM<,)) printf(S9T)K else if ((marks ((marksL ?) EE(marksM>,)) printf(SCT)K else if ((marks ((marksL%?) EE(marksM=,)) printf(S/T)K Q BC a program to calculate sum Ba/g of n numbersCB I2 !y for loop' ]includeMstdio.hL main() P int n,iK float #,average,sumJ,K printf(`)ow many numbers'`)K scanf(`Wd`,En)K for(iJ!KiMJnKiII) P printf (S# J S)K scanf(SWfT,E#)K sumIJ#K Q printf(SYnThe sum is Wf YnT,sum)K averageJsum6n printf(SYnThe average is Wf YnT,average)K Q II2 !y *3ile statement: ]includeMstdio.hL main() P int n,iJ!K float #,average,sumJ,K printf(`)ow many numbers'`)K scanf(`Wd`,En)K

30

while (iMJn) P printf (S# J S)K scanf(SWfT,E#)K sumIJ#K Q printf(SYnThe sum is Wf YnT,sum)K averageJsum6nK printf(SYnThe average is Wf YnT,average)K Q III2 !y do F *3ile statement: ]includeMstdio.hL main() P int n,iJ!K float #,average,sumJ,K printf(`)ow many numbers'`)K scanf(`Wd`,En)K do P printf (S# J S)K scanf(SWfT,E#)K sumIJ#K Q while (iMJn) printf(SYnThe sum is Wf YnT,sum)K averageJsum6nK printf(SYnThe average is Wf YnT,average)K Q .6ample: & simple switch statement, in which, choice is assumed to be a char 8 type variable' ]includeMstdio.hL main() P char colourK printf (S*nter colourT)K scanf (SWcT,Ecolour)K switch (choice Jgetchar)())

31

P case ZrO' case Z3O' printf(S3*(T)K breakK case ZgO' case Z.O' printf(S.3**:T)K breakK default' printf(S:o colourT)K QQ BC a program to calculate sum of series &>)>(>:>222222222222222222CB ]includeMstdio.hL main() P int n,i,sumK printf(`)ow many values'`)K scanf(`Wd`,En)K iJ!K sumJ,K while(iMJn) P sumJsumIiK iJiI!KQ printf(`sum JWd`,sum)K return(,)K Q BC a program to calculate sum of series (>'>A>22222222222222222222CB ]includeMstdio.hL main() P int #,n,i,sumK printf(`)ow many values'`)K scanf(`Wd`,En)K iJ!K #J,K sumJ,K while(iMJn)

32

P#J#I%K sumJsumI#K iJiI!KQ printf(`Wd`,sum)KQ BC a program to calculate sum of series &>:>@>222222222222222222CB ]includeMstdio.hL main() P int #,n,i,sumK printf(`)ow many values'`)K scanf(`Wd`,En)K iJ$K #J!K sumJ!K while(iMJn) P#J#I%K sumJsumI#K iJiI!KQ printf(`sum JWd`,sum)KQ BC a program to identify t3e numbers t3at e/en nor oddCB ]includeMstdio.hL ]includeMconio.hL void main() P int aK printf(`*nter the number'`)K scanf(`Wd`, Ea)K if((aW$)JJ,)printf(`*ven`)K else printf(`7dd`)K getch()K Q BC a program to find e/en and odd number by continue statementCB ]includeMstdio.hL ]includeMconio.hL void main() P int counterK clrscr()K

33

printf(`even numbers'`)K for(counterJ!KcounterMJ!,,KcouterII) Pif(counterW$[J,) continueK printf(SWdT,counter)K Q printf(`odd numbers'`)K for(counterJ!KcounterMJ!,,KcouterII) Pif(counterW$JJ,) continueK printf(SWdT,counter)K Q Q BC a program to find e/en and odd number by continue statementCB ]includeMstdio.hL void main() P int n,iK printf(`)ow many termsN `)K scanf(`Wd`,En)K printf(`Yt7dd numbers are below'Yn`)K for(iJ,KiMnKiII) P if(iW$JJ,) continueK printf(`YtWd`,i)K Q printf(`YnYnYt*ven numbers are below'Yn`)K for(iJ,KiMnKiII) P if(iW$[J,) continueK printf(`YtWd`,i)K QQ 6X a program to calculate sum of series &>&B)>&B(>&B:>222222222222222222&BnCB ]includeMstdio.hL main() P float n,i,sumK

34

printf(`)ow many values'`)K scanf(`Wd`,En)K iJ!K sumJ,K while(iMJn) P sumJsumI!6iK iJiI!KQ printf(`sum JWd`,sum)K return(,)K Q A program to determine t3e largest of t3ree integer 9uantities by return2 ]includeMstdio.hL int ma#imum (int #, int y) P int @K @J(#LJy)N #'yK return(@)K Q main() Pint a,b,c,dK printf(SYnaJT)K scanf(SWdT,Ea)K printf(SYnbJT)K scanf(SWdT,Eb)K printf(SYncJT)K scanf(SWdT,Ec)K dJmamimum(a,b)K printf(SYnYnma#imumJWdT,ma#imum(c,d))K getch() Q BCa program to calculate sum of non negati/e in a list of n numbers by using continue statementCB ]includeMstdio.hL main() P int #,n,i,sumK printf(`)ow many values'`)K scanf(`Wd`,En)K

35

iJ!K sumJ,K while(iMJn) Pprintf(`enter values`)K scanf(`Wd`,E#)K if(#M,) continueK sumJsumI#K iJiI!KQ printf(`Wd`,sum)KQ BC a program to calculate area and /olume of t3e sp3ereCB ]includeMstdio.hL ]define pi %.! != void main() P float r, a, vK printf(`*nter the radius of sphere' `)K scanf(`Wf`, Er)K a J piXrXrK v J ( XpiXrXrXr)6%K printf(`The area of the sphere' WfYn`, a)K printf(`The volume of the sphere' Wf`, v)K Q BCa program to calculate area and /olume of a cylinderCB ]includeMstdio.hL void main() P float r,pie,a,v,hK printf(`*nter the value of radius`)K scanf(`Wf`,Er)K printf(`*nter the value of height`)K scanf(`Wf`,Eh)K pieJ%.! K aJ$XpieXrXhK vJpieXrXrXhK printf(`areaJWC.$f`,a)K printf(`YnvolumeJWC.Cf`,v)K Q

36

BCa program to calculate area of a circleCB ]includeMstdio.hL ]define pie %.! void main() P float r,pie,a,v,hK printf(`*nter the value of radius`)K scanf(`Wf`,Er)K aJ$XpieXrK printf(`areaJWC.$f`,a)K Q A program to calculate t3e area of circle by function prototype . ]includeMstdio.hL ]define pi %.! != float process(float radius)K main() P float radius, areaK printf(S3ediusJNT)K scanf(SWfT,Eradius)K areaJprocess(radius)K printf(S&rea J WfT,area)K Q float process(float r) Pfloat aK aJpiXrXrK return(a)K Q A C program to calculate t3e mass of air in an automobile tire using follo*ing formula:P=D?2(@mET>:'?G ]includeMstdio.hL main() P float p,v,m,t,#,yK printf(SWsT,T1lease a value for the volume in cubic feet'T)K scanf(SWfT,Ev)K printf(SWsT,T1lease a value for the pressure in psi'T)K scanf(SWfT,Ep)K printf(SWsT,T1lease a value for the temparature in degree /'T)K

37

scanf(SWfT,Et)K mJ(pXv)6(,.%<X(tI >,))K #JpXvK yJ,.%<X(tI >,)K mJ#6yK printf(SThe value of mass is WfT,m)K Q A program to con/ert temp in degree Fa3ren3eit to degree Celsius: ]includeMstdio.hL main() P float f,cK printf(SWsT, Splease enter a value for the temp in degrees /'T)K scanf(SWfT,Ef)K cJ(=X(f+%$))6?K printf(SThe value of C is WfT,c)K Q A program to con/ersion F C , C F by s*itc3 statement. ]includeMstdio.hL void main () P char #K printf(Schoice your systemT)K printf(SYnif convert /ahrenheit type YtfT)K printf(SYnif convert Celsius type YtcYnT)K scanf(SWcT,E#)K switch(#) P case ZfO' float f,cK printf(SWsT, Splease enter a value for the temp in degrees C'T)K scanf(SWfT,Ec)K fJ(!.CXcI%$)K printf(SThe value of / is WfT,f)K breakK case ZcO' float f,cK printf(SWsT, Splease enter a value for the temp in degrees /'T)K

38

scanf(SWfT,Ef)K cJ(=X(f+%$))6?K printf(SThe value of C is WfT,c)K breakK default' printf(Syou entered wrongT)K QQ BC a program to calculate sum of seriesEodd numberG &>(>;>@>HHHHHH>nCB ]includeMstdio.hL main() P int #,n,i,sumK printf(`)ow many values'`)K scanf(`Wd`,En)K iJ$K #J!K sumJ!K while(iMJn) P#J#I$K sumJsumI#K iJiI!KQ printf(`Wd`,sum)KQ A program to find t3e root of a algebraic e9uation by iterati/e met3od: ]includeMstdio.hL ]includeMconio.hL ]includeMmath.hL ]define T32* ! ]define /&DS* , void main() P int flagJT32*,countJ,K float guess,test,root,errorK printf(`"nitial guess'`)K scanf(`Wf`,Eguess)K while(flag) P IIcountK if(countJJ=,)flagJ/&DS*K

39

test J !, + %XguessXguessK if(testL,) P root J pow(test,.$)K printf(`"teration number'Wd, #'WfYn`,count,root)K error J fabs(root+guess)K if(errorL.,,,,!)guess J rootK else P flagJ/&DS*K printf(`:o. of iteration'Wd, root'Wf`,count,root)K Q Q else P flagJ/&DS*K printf(`:o. out of range.`)K Q Q if((countJJ=,)EE(errorL.,,,,!)) printf(`Convergence not found after =, iterations.`)K getch()K Q YX & program to find all prime numbers between $ and !,,, by using nested loopXY ]includeMstdio.hL main ( ) P printf (SThe prime number is of $ to !,,, S)K for (int iJ!K iM!,,,KiII)P for(int GJ$K GM!,,,K GII) P if (iWGJJ,) breakK Q if(iJJf) printf(SWdT,i)K Q Q

40

Chapter 6

Control Statements
Control statements: Control statements are used to create special program features such as logical tests, loops and branches. &ll control statements required that other statements be embedded with in them. Classification of control statements:

ontro! "tatements #ranc$ing %& ' e!se( i&( t$en )$i!e

Looping

")itc$ statement

*o ' )$i!e

&or

!ranc3ing : & C program may require that a logical test be carried out at same particular point within the program. 7ne of several possible actions will then be carried out, depending on the outcome of the logical test. This is known as branching. #ooping: & c program may required that a group of instructions be e#ecuted repeatedly, until some logical condition has been satisfied. This is known as looping. !ranc3ing : If F else statement' The if 8 else statement is used to carry out a logical test and then take one of two possible actions, depending on the outcome of the test. The else portion of the if 8 else statement is optional, in its simplest general form, the statement can be written as' "f (e#pression) statement "n this form, the statement will be e#ecuted only if the e#pression has a non @ero value of @ero i.e. if e#pression is false, then the statement will be ignored. The general form of an if statement which includes the else clause is "f the e#pression has a non@ero value i.e. if the e#pression is true then statement ! will be e#ecuted. 7ther wise i.e. if e#pression is false, statement $ will be e#ecuted. *#ample'

42

if (#MJ%) yJ%Xpow(#,$)K *lse yJ $Xpow((#+%),$)K printf (SWf YnT,balance)K )ere # MJ % is the e#pression. "f it is true then statement ! i.e. yJ $Xpow((#+%),$)K will be e#ecuted. other wise that is, if the e#pression #MJ% is not true then statement $ will be e#ecuted. S*itc3 statement: purpose: Switch statement causes a particular group of statements to be chosen from several available groups. Hhen more comple# if else is present in programs, the use of switch statement is convenient instead of if 8 else. Format: switch(e#pression) P case e#pression!' statement ! statement $ ^^^^.. statement m breakK case e#pression $' statement ! statement $ ^^^^.. statement m breakK ^^^^^ default' statement ! statement $ ^^^^.. statement k Q Utility: switch (choice J getchar()) P

43

case Z3O' printf (S3*(T)K breakK case Z9O' printf (S9D2*T)K breakK case ZHO' printf (SH)"T*T)K breakK default' printf (S*rrorT)K Q #ooping: &2 T3e *3ile statement: The while statement is used to carry out looping operations, in which a group of statements is e#ecuted repeatedly, until some condition has been satisfied. The general formula of the while statement is Hhile (e#pression) statement The statement will be e#ecuted repeatedly, as long as the e#pression is true. This statement can be simple or compound though it is usually a compound statement. "t must include some feature that eventually alters the value of e#pression, thus providing a stopping condition for the loop. .6ample: & program to display the consecutive digits ,, !, $, %, ^^^..?. ]includeMstdio.hL main() P int digit J ,K while(digit MJ?) Pprintf( SWdYnT, digit)K IIdigitK Q Q )2 T3e do F *3ile statement: The do 8 while statement is used to carryout looping operations, in which a group of statements is e#ecuted repeatedly until some logical condition has been satisfied. Some times it is described to have a loop with the test for continuation at the end of each pass. This can be accomplished by means of the do 8 while statement. The general form of the do 8 while statement is

44

do (statement while ( e#pression)' The statement will be e#ecuted repeatedly, as long as the value of e#pression is true. "t must include some feature that eventually alters the value of e#pression so the looping action can terminate. The statement can be either simple or compound through most applications will requires. "t to be a compound statement. .6ample: & program to display consecutive digits ,, !, $, %^^^^^? ]includeMstdio.hL main() P int digit J ,K doP printf( SWdYnT, digit)K Q while(digit MJ?)K Q Purpose of do F *3ile statement ' Some times do 8 while statement is desirable to have a loop with the test for continuation at the end of each pass. This can be accomplished by means of the do 8 while statement. "n some looping situations, when it is necessary to e#ecuted the statement at least once, there the do 8 while statement used. Ho* differs bet*een do F *3ile statement , *3ile statement: I2 The test for continuation of while loop carried out at the beginning of each pass through the loop. The test for continuation of do 8 while loop is carried is carried out at the end of each pass through the loop. II2 The general form of while statement' while (e#pression) statement The general form of do while statement is do statement while (e#pression)K III2 "n case of while statement, the statement may not be e#ecuted at all. incase of do 8 while statement, the statement always be e#ecuted at once. (2 T3e for statement: The for statement is the third and perhaps the most commonly used looping statement in C. This The general form of the for statement is for (e#pression !K e#pression $K e#pression %) statement where, e#pression ! is used to initiali@e some parameters (inde#) that controls the looping action. *#pression $ represents a condition that must be true for the loop to continue

45

e#ecution and e#pression % is used to alter the value of the parameter initially assigned by e#pression !. Typically e#pression ! is an assignment e#pressionK e#pression $ is a logical e#pression or an assignment e#pression. when the for statement is e#ecuted, e#pression $ is evaluated and tested at the beginning of each pass through the loop and e#pression % is evaluated at the end of each pass. Thus , the for statement is equivalent to e#pression !K while (e#pression $ ) statement e#pression %K Q .6ample' & program to display consecutive integer quantities such as ,, !, $, ^^^^? ]includeMstdio.hL main() P int digit for (digit J ,K digitMJ?KIIdigit) printf(SWdYnT,digit)K Q Ho* for statement differ from *3ile statement: Hhile statement are generally used when the number of passes is not known in advance but for loops are generally used when the number of passes is known advance.

Conditional !ranc3ing: Hhen program is e#ecuted by the influence of


conditional statement it is called conditional program flow or branching. "f the condition in conditional program is true, output is one type and other type in case of false. mainly four types of statement used in conditional branching. ". "". """. ";. ;. ;". ;"". "f statement. "f 8 else. *lse if . Switch. /or. Hhile. (o 8 while.

46

Unconditional branc3ing: Hhen program is e#ecuted by the influence of unconditional statement, it is called unconditional program flow. Some parts of program is rotated repeatedly or Gump to a definite statement by the influence of unconditional statement. 2nconditional branching statement used. I2 II2 continue goto.

0ested if F else: "t is possible to nest (i.e. embedded) if else statements, one within another. There are several forms that nested if 8 else statements can take. The most general form of two layer nesting is ' "f e! if e$ s! else s$ else if e% s% else s where e!, e$, e% are e#pressions and s!, s$, s%, s are statements. 7ne complete if 8 else statement will be e#ecuted if e! is non@ero i.e. true and another complete if 8 else statement will be e#ecuted if e! is @ero i.e. false. "t is possible that s!, s$, s% and s will contain other if 8 else statements and would then have multilayer nesting some other forms of two layer nesting+ "f e! s! else if e$ s$ if e! s! else if e$ s$ else s% if e! if e$ s! else s$ else s% if e! if e$ s! elses s$ compare t3e use of t3e s*itc3 statement *it3 t3e use of nested if F else statement: I2 Switch statement causes a particular group of statements to be chosen from several available groups. Switch statement is used incase of more comple# if else statement. in nested if else statement, to nest (embedded) if 8 else statements, one another. II2 The general form of the switch statement is switch (e#pression) statement. The general form of two layer nesting is if e! if e$ s!

47

else s$ else if e% s% else s III2 "n practical sense, the switch statement may be thought of as an alternative to the use of nested if 8 else statements. "t can only replace those if 8 else statements that test for equality. "n such situations, the use of the switch statement is much more convenient. !rea" statement' The break statement is used to terminate loops or to e#it from a switch. "t can used within a for, while, do 8 while or switch statement. The break statement is written simply as breakK without any embedded e#pression or statements. The break statement causes a transfer of control out of the entire switch statement, to the first statement following the switch statement. "f a break statement included in a while, do 8 while, or for loop, then control will immediately transferred out of the loop when the break statement encountered. .6ample: switch(choice J toupper getchar()) P case 3' printf(S3*(T)K breakK case H' printf(SH)"T*T)K breakK case 9' printf(S9D2*T)K breakK default' printf(S*3373T)K breakK Q Continue statement: The continue statement is used to by pass the remainder of the current pass through a loop. The loop does not terminate when a continue statement is encountered. 3ather the remaining loop statements are skipped and the computation proceeds directly to the ne#t pass through the loop. The continue statement can be included within a while, a do 8 while or a for statement. "t is written simply as 8 continueK without any embedded statements or e#pressions. Program: Calculate the average of non negative numbers in a list of n numbers. ]includeMstdio.hL

48

main() P int n, count, navgJ,K float #, average, sum J,K printf(S)ow many numbersNT)K scanf(SWdT, En)K for (count J!K countMJnK IIcount) Pprintf(S#J S)' scanf(SWfT,E#)K if (#M,) continue' sumIJ #K IInavg' average J sum6navg printf(SYnThe average is Wf Yn, average)K Q Q T3e go to statement: The go to statement is used to alter the normal sequence of program e#ecution by transferring control to some other part of the program. The general form of goto statement can be written as 8 goto labelK Hhere label is an identifier that is used to label the largest statement to which control will be transferred . Control may be transferred to any other statement within the program. The largest statement will appear as Dabel' statement *ach labeled statement within the program must have a unique label i.e. no. two statements can have the same label.

.ntry control loop and e6it control loop:

49

,est condition ,r-e #ody o& t$e !oop

+a!se

#ody o& t$e !oop

,est condition ,r-e

+a!se

50

Chapter 7

FU0CTI 0
Function: & function is a self 8 contained program segment that carries out some specific, well defined task. & function is defined with two principal components' The first line (including the argument declarations) The body of the function. "n general terms, the first line can be written as' (ata 8 type name (type !, arg !. type $ arg$, ^^^,typen argn) Hhere Sdata 8 typeT represents the data item that is returned by the function, SnameT represents the function name and Stype!, type$,type%^^^..typenT represents the data type of the arguments arg!, arg$, ^^^..argn .6ample: Char lower0to0upper(char c) P char c$K c$J(c! J(c!LJ ZaO EE c!MJ Z@O)N(Z&O Ic!+ ZaO)'c!K return(c$)K Q void main(void) Pchar lower, upperK printf(please enter a lower case character'T)K scanf(SWcT, Elower)K upperJ lower0to0upper(lower)K printf(SYnThe upper case equivalent is Wc YnYnT,upper)K Q Ad/antages of Function: I2 The use of programmer defined defn functions allows a large program to be broken into a number of smaller, self 8 contained segments. *ach of which has some unique, identifiable purpose. II2 III2 The use of function avoids the needs for redundant (repeated) programming of the same instructions. The use of functions also enable the programmer to build a customi@ed library of frequently used routines. +eturn statement: "nformation is returned from the function to the calling portion of the program via the return statement.

51

The return statement also causes the program logic to return to the point from which the function was accessed. "n general terms, the return statement is written as 3eturn e#pression, The value of the e#pression is returned to the calling portion of the program. The e#pression is optional. "f the e#pression is omitted, the return statement simply causes control to revert back to the calling portion of the program, without any transfer of information. ArgumentBParameter: "nformation passed to the function from the calling portion of the program and return a single value i.e. information passed to the function via special identifiers called arguments6parameters. #ocal /ariableBFormal parameter: The arguments appearing in the function call are referred to as actual arguments6.lobal variable). The first line of the function definition is called /ormal parameter. /ormal arguments represents the names of data items that are transferred into the function from the calling portion of the program. /ormal arguments are local in sense that they are not recogni@ed outside the function. 5lobal /ariableBActual parameter: The corresponding arguments of formal arguments in the function reference are called actual parameter. They are called since they define the data items that are actually transferred. "n normal function call, there will be one actual argument for each formal argument. The actual arguments must be e#pressed as constants, single variables or more comple# e#pressions. *ach actual argument must be of the same data type as its corresponding formal argument. T3e relation bet*een Actual , Formal arguments: The actual arguments must correspond to the formal arguments in the function def n i.e. the no. of actual arguments must be the same as the no. of formal arguments and each actual argument must be of the same data type as its corresponding formal arguments. /.1 are usually written at the beginning of a program ahead of a programmer defined function (including main) ends with a semicolon

Distinguis3 bet*een local /ariable1 formal parameters and /ariables:


Docal variable !."t is declared within a /ormat parameter !."t is declared within function .lobal variable. !."t is declared out of a

52

function. $."ts scope is limited to function. %.The same name may be used as local variable in different functions. .&uto or static may precede local variables.

argument. $."ts scope is limited to function. %.The same name may be used as local variable in different functions. .2sually auto or static is not preceded formal parameters.

function . $."ts scope is through the whole program %.9ut it is not possible in data of global variable.

.*#tern is preceded global variables.

Function call: & function will carry program. The structure of function call' /unction0name()K

out its intended action (whenever it is

accessed(i.e. whenever the function is called) from some other portion of the

The function call may be a part of a simple e#pression (such as an assignment statement) or it may be one of the operands within a more comple# e#pression. =oid parameter: "f in function, no need of parameter void key word is used. )ave no return value Function prototype' Some times in C language a Ztop 8 downO approach in which main function appears ahead of the programmer 8 defined function definition. "n such situation, the function access will be defined later in the program, which is known as function prototype. The general form of function of function prototype is (ata type name (type! arg!, type$ arg$^^.typen argn)K Hhere data+type represents the data type of the item that is returned by the function, name represents the functional name, and type!, type$ ^^type n represents the data types of the arguments arg!, arg$, ^^.argn. A C program to calculate t3e factorial of an integer 9uantity: Eby using function prototypeG: 6X a program to find factorial by using function declared as a .lobal functionX6 ]includeMstdio.hL int factorial(int n)K void main()

53

P int #K printf(`enter which factorial`)K scanf(`Wd`,E#)K printf(`Wd`,factorial(#))K Q int factorial(int n) Pint iK long int yK yJ!K for(iJ!KiMJnKiII) yJyXiK return(y)K Q +ecursi/e functionB+ecursion: 3ecursion is a process by which a function calls itself repeatedly, until some specified condition has been satisfied. The process is used for repetitive computations in which each action is stated in terms of a previous result. -an iterative problems can be written in this form. "n order to solve a problem recursively two conditions must be satisfied. /irst, the problem must be written in a recursive form and $ nd the problem statement must include a stopping condition. &dvantage' :eed of less variable. Can be represent the program easily. 3eduction of comple#ity of program. A C program to calculate t3e factorial of an integer 9uantity using recursion' 6X a program to find out factorial using recursive functionX6 ]includeMstdio.hL long int factorial(int n)K void main() P int nK printf(`*nter the number'`)K scanf(`Wd`, En)K printf(`factorial of WdJWld`,n,factorial(n))K Q long int factorial(int n) P

54

if(nMJ!)return(!)K else return(nXfactorial(n+!))K Q A C program t3at reads a line of te6t and *rite it bac"*ards using recursion: ]includeMstdio.hL ]includeMconio.hL void reverse(void)K void main() P printf(`*nter your te#t'`)K reverse()K getch()K Q void reverse(void) P char cK if ((cJgetchar())[JaYna)reverse()K putchar(c)K returnK Q -rite a C program to calculate t3e factorial of n by function: BC a program to find factorial by using function declared as a local functionCB ]includeMstdio.hL int factorial(int n)K void main() P int #K printf(`enter which factorial`)K scanf(`Wd`,E#)K printf(`Wd`,factorial(#))K Q int factorial(int n) Pint iK long int yK yJ!K for(iJ!KiMJnKiII) yJyXiK

55

return(y)K Q

56

Chapter 9

Arrays
Arrays: &rrays are defined in much the same manner as ordinary variables, e#cept that each array name must be accompanied by a si@e specification. .eneral formula of array declaration+ data+type+nameUsi@eVK data+type means the type of array (int, char etc) E si@e identified by the total number of variable in array. *#ample' int iU=VK

int i.5/; *ata type 1rray name %ndex0s-bscript

Types of Array: T*o types of array% !. 7ne dimensional array. $. -ulti dimensional array. !. ne dimensional array: The array which is formed by one subscript is called one dimensional array. /or one dimensional array, the si@e is specified by a positive integer e#pression, enclosed in square brackets. "n general terms, a one 8 dimensional array definition may be e#pressed as storage class data0type array Ue#pressionVK *#ample' "nt iU=VK /loatiU=VK Static float nU$VK $. Multi dimensional array: -ulti dimensional arrays are defined in the same manner as one dimensional array e#cept that a separate pair of square brackets are required for each subscript. Thus a two dimensional array will require three pairs of square brackets and so on. & multi three dimensional array will require three pairs of square brackets and so on. & multi dimensional array is defined as storage class data type array Ue#p!VUe#p$V^.Ue#pnV

57

.6ample: int #U=VU=VK two dimensional' (ata0type array0name UrowVUcolumnVK Sorting: Sorting is a process to arrange large number of data in ascending or descending order. Met3od of sorting: !. Selection sorting. $. 9ubble sorting. %.Ruick sorting. . )eap sorting. =. -erge sorting. >."nsertion sorting. BCa program to sort t3e number descending orderCB ]includeMstdio.hL int #U!,,V,y,n,i,G,kK void main()P printf(`)ow many number do you sort`)K scanf(`Wd`,En)K for(iJ,KiMnKiII) scanf(`Wd`,E#UiV)K for(GJ,KGMn+!KGII) for(kJGI!KkMnKkII) if(#UGVM#UkV) PyJ#UGVK #UGVJ#UkVK #UkVJyKQ for(iJ,KiMnKiII) printf(`YtWd`,#UiV)K Q BCa program to sort of strings alp3abetically using t*o dimensional c3aracter arrayCB ]includeMstdio.hL ]includeMstring.hL

.2 &or decending order3!argesma!!/ 4 &or ascending order3sma!!!arge5./

58

void reorder(int n, char #UVU!$V)K main() P int n,iK char #U!,VU!$VK printf(`*nter each string on a separate line belowYn`)K printf(`Type YaendYa when finishedYnYn`)K nJ,K do P printf(`stringWd'`,nI!)K scanf(`Ws`,#UnV)K Qwhile (strcmp(#UnIIV, `end`))K n++K reorder(n,#)K printf(`Yn 3eorder Dist of strings are below'YnYn`)K for (iJ,KiMnKIIi) printf(`Yn Ws`,#UiV)K Q void reorder(int n, char #UVU!$V) P char tempU!$VK int i,GK for (GJ,KGMn+!KIIG) for (iJGI!KiMnKIIi) if(strcmp(#UGV,#UiV)L,) P strcpy(temp,#UGV)K strcpy(#UGV,#UiV)K strcpy(#UiV,temp)K Q returnK Q

59

Chapter 10

Pointers
Pointers: & pointer is a variable that represents the location of a data item, such as a variable or an array element. 1ointer variables, like all other variables, must be declared before they may be used in C program. Thus a pointer declaration may be written in general terms+ data 8type XptvarK )ere ptvar is the name of pointer variable and data type refers to the data type of the pointers obGect. -3y pointer used: 1ointer are frequently used in C as they have a number of applications+ !. 1ointers can be used to pass information back and forth betn a function and its reference point. $. 1ointers provide a way to return multiple data items from a function via function arguments. %. 1ointer also permit references to other functions to be specified as arguments to a given function. This has the effect of passing as arguments to the given function. . 1ointers also provide an alternative way to access individually array element. =. -oreover pointers provide a convenient way to represent multidimensional arrays. IntCpI&?J Cp is !, 8 element array of pointers to integer quantities. IntECpGI&?J Cp is a pointer to a !, 8 element integer array. Ad/antage of pointer: !. "n global variable, reduce function calling and easier data accessing in using of pointer. $. 3educe the length and comple#ity of program. %. -ore efficient in handling the data items. . "ncrease the program e#ecution speed. =. Saving data storage, place in memory. Disad/antage: Cannot hold the different data item. Dynamic memory allocation: EDMAG: The use of a pointer variable to represent an array requires some type of initial memory assignment before the array elements are processed. This is known as dynamic memory allocation.

60

.enerally the malloc library function is used for this purpose. &dvantages' To reserve as much memory as may be required during program e#ecuted. Difference betn Array and Pointer: &rray !. &n array contain the data . $. &rray stores variables which have common character e.g. same type same storage class. %. (ata items are predeclared. . )igh memory loss. =. $ types. >. &rray declared as storage class data type array Ue#pressionV <. Subscript is used but asteric is not used. BCa program to sort number Descending by using pointerCB ]includeMstdio.hL ]includeMstdlib.hL void main() P int X#,y,n,i,G,kK printf(`)ow many number do you sort`)K scanf(`Wd`,En)K #J(intX)malloc(nXsi@eof(int))K for(iJ,KiMnKiII) scanf(`Wd`,#Ii)K for(GJ,KGMn+!KGII) for(kJGI!KkMnKkII) if(X(#IG)MX(#Ik)) PyJX(#IG)K X(#IG)JX(#Ik)K X(#Ik)JyKQ %. -emory is allow only for input datas not for any array. . :o loss of memory. =. :o classification. >. 1ointer declared as data+type Xptvar. <. &steric (X) is used. 1ointer !. & pointer contain the address of data. $. 1ointer is a variable which represent the location of a data item.

61

for(iJ,KiMnKiII) printf(`YtWd`,X(#Ii))K Q BCa program to count no of /o*els1 consonant *3itespace1 digit , ot3ers X6 ]includeMstdio.hL ]includeMctype.hL void scan0line(char lineU V, int Xpv, int Xpc, int Xpd, int Xpw, int Xpo)K main() P char lineUC,VK int vowels J,K int consonants J ,K int digits J ,K int whitespc J ,K int other J ,K printf(`*nter a line of te#t below'Yn`)K scanf(`Ws`, line)K scan0line(line, Evowels,Econsonants,Edigits, Ewhitespc, Eother)K printf(`Yn:o. of vowels' Wd`,vowels)K printf(`Yn:o. of consonants' Wd`,consonants)K printf(`Yn:o. of digits' Wd`,digits)K printf(`Yn:o. of whitespace characters' Wd`,whitespc)K printf(`Yn:o. of other characters' Wd`,other)K Q void scan0line(char lineU V, int Xpv, int Xpc, int Xpd, int Xpw, int Xpo) P char cK int count J,K while((c J toupper(lineUcountV))[JaY,a) P if (c JJa&a \\ cJJa"a\\cJJa*a \\ c JJa7a\\ c JJa2a) II XpvK else if (cLJ a&a EE cMJaFa) II XpcK else if (cJJ a a \\ c JJ aYta) II XpwK else if (cLJ,\\cMJ?)

62

IIXpdK else II XpoK IIcountK Q returnKQ Difference bet*een ordinary /ariable and array /ariable: rdinary /ariable !. &n ordinary variable does not require si@e specification. $. "t consists of only one data of certain length according to the type. %. :o dimension. . &rguments are passed by value =.&ny change of arguments in other functions does not alter the value of variable in main function. >. 7rdinary variable declared as' (ata+type variable nameK Array /ariable !. &n array variable requires si@e specification. $."t consists of more than one data of certain length . %.7ne or more dimension. . &rguments are passed by address. =. &ny change of arguments in other functions alters the value of variable in main function. >. &rray variable declared as' data+type array name Ue#pressionV

Chapter 13

C 5rap3ics
function name: synta# arcE G barE G prototyp e synta# prototyp e far arc (int #, int y, int start, int end, int radius)K void far arc (int #, int y, int start, int end, int radius)K bar (int left, int top, int right, int bottom)K void far bar (int left, int top, int right, int bottom)K

63

bar(dE G

synta# prototyp e

circleE G clearde/ice EG clear/ie*p ortE/oidG closegrap3 EG dra*polyE G

synta# prototyp e synta# prototyp e synta# prototyp e synta# prototyp e synta# prototyp e synta# prototyp e

bar%d(int left, int top, int right, int bottom, int depth, int topflag)K void far bar%d(int left, int top, int right, int bottom, int depth, int topflag)K circle ( int #, int y, int radius)K void far circle ( int #, int y, int radius)K cleardevice (void)K void far cleardevice (void)K clearviewport(void)K void far clearviewport(void)K far closegraph(void)K void far closegraph(void)K drawpoly(int numpoints, int far Xpoints)K void far drawpoly(int numpoints, int far Xpoints)K ellipse( int #, int y, int start, int end, int #radius, int yradius)K void far ellipse( int #, int y, int start, int end, int #radius, int yradius)K fillellipse(int#, inty, int#r, int yr)K void far fillellipse(int#, inty, int#r, int yr)K fillpoly(int numpoints, int far Xpoints)K void far fillpoly(int numpoints, int far Xpoints)K floodfill(int #, int y, int border)K void far floodfill(int #, int y, int border)K getcolor(void)K int far getcolor(void)K getimage ( int left, int top, int bottom, void farXbuf)K void far getimage ( int left, int top, int bottom, void farXbuf)K getma## ( void)K int far getma## ( void)K getma#y ( void)K int far getma#y ( void)K getpi#el (int #, int y)K unsigned far getpi#el (int #, int y)K get# (void)K

ellipseEG

fillellipseE G fillpolyEG

synta# prototyp e synta# prototyp e synta# prototyp e synta# prototyp e synta# prototyp e synta# prototyp e synta# prototyp e synta# prototyp e synta#

floodfill E G getcolorE/o idG getimageE G

getma66E G getma6yE G getpi6elE G get6E/oidG

64

getyE/oidG goto6yE G initgrap3E G

prototyp e synta# prototyp e synta# prototyp e synta# prototyp e synta#

int far get# (void)K gety (void)K int far gety (void)K goto#y(int#, inty)K void goto#y(int#, inty)K initgraph(int farXdriver, int farXmode, char farXpath)K void far initgraph(int farXdriver, int farXmode, char farXpath)K line( int start#, int starty, int end#, int endy)K void far line( int start#, int starty, int end#, int endy)K movete#t( int left, int top, int right, int bottom, int newleft, int newtop)K int movete#t( int left, int top, int right, int bottom, int newleft, int newtop)K far outte#t#y(int #, int y, char Xstr)K void far outte#t#y(int #, int y, char Xstr)K outte#t (char far Xstr)K void far outte#t (char far Xstr)K pieslice( int #, int y , int start, int end, int radius)K void far pieslice( int #, int y , int start, int end, int radius)K putimage (int #, int y, void far Xbuf, int op)K void far putimage (int #, int y, void far Xbuf, int op)K putpi#el(int #, inty, int color)K void putpi#el(int #, inty, int color)K putte#t (int left, int top, int bottom voidXbuf)K int putte#t (int left, int top, int bottom voidXbuf)K rectangle( int left, int top, int right, int bottom)K void far rectangle( int left, int top, int right, int bottom)K sector( int#, inty, int end, int #r, int yr)K void far sector( int#, inty, int end, int #r, int yr)K setailpallette (struct pallettetype farX pal)K void far setailpallette (struct pallettetype farX pal)K setcolor(int color)K

lineE G

prototyp e mo/ete6tE G synta# prototyp e outte6t6yE G outte6tE G pieslice E G synta# prototyp e synta# prototyp e synta# prototyp e synta# prototyp e synta# prototyp e synta# prototyp e synta# prototyp e synta# prototyp e synta# prototyp e synta#

putimageE G putpi6elE G putte6tE G

rectangleE G sectorE G

setallpalett eEG setcolorE G

65

setfillpatte rnEG setfillstyle EG sette6tstyl eEG te6tbac"gr oundE G te6tcolorE G

prototyp e synta# prototyp e synta# prototyp e synta# prototyp e synta# prototyp e synta# prototyp e

void far setcolor(int color)K setfillpattern(char farXpattern, int color)K void far setfillpattern(char farXpattern, int color)K setfillstyle (int pattern, int color)K void far setfillstyle (int pattern, int color)K sette#tstyle ( int font, int direction, int si@e)K void far sette#tstyle ( int font, int direction, int si@e)K te#tbackground(int color)K void te#tbackground(int color)K te#tcolor(int color)K void te#tcolor(int color)K

A program to dra* a national flag: ]includeMstdio.hL ]includeMconio.hL ]includeMgraphics.hL void main ( ) P int driverJ (*T*CT, modeJ,K initgraph(Edriver, Emode, Sc'YYtcYYbgiT)K selector($)K setfillstyle(%, !%)K floodfill(!,,, !,,,$)K printf(SYnYn:ational flag of 9angladeshT)K selector($)K rectangle($,,,!=,, =,,%,,)K setfillstyle(!,$)K floodfill(%$=, $$=,$)K setcolor( )K rectangle(!C,, !=,, $,,, ,,)K circle(%$=,$$=)K setfillstyle(!, )K floodfill(%$=, $$=, )K setcolor(%)K rectangle(!C,,!=,,$,,, ,,)K setfillstyle(!,=)K floodfill(!?,, %=,,%)K selector(%) rectangle( !<,, ,,,$!,, $,)K setfillstyle( !,C)K floodfill( $,,, !,,%)K getch()K Q

66

S-ar putea să vă placă și