Download as pdf
Download as pdf
You are on page 1of 38
Seripking language Seipling language are programming languages thak contrel an application, seripts can execute independent @f any other appltcatien They ave mostly embedded To the application that ‘they contro! and ave used to arterrate frequently execubed tases Like Communicating with extesnal preagrare « Examples : Apple seripe » Vv? se v7pe Mark ap languages A markup language that uses annotutions Lhe texk 16 to be displayed. eg an axtificlal language be text that clepine Examples + HTML XML con current programming language Concurrent pregramening 78 ex computer pergrarming technique thet pwovides for the execition o operakion cencurtrently, either with ina Single cai mpekes os acxoss ao number Yy Systems ye AL@ORITHHIC PROBLEM ZOELVING Examples Joule Limbo Object owiented programming language object ovlented prograrmmiog fe a pregramming paradigm based on the concepk of objects cahith may contaie daka in the fern ef procedures efken knewn as methods , Eocarmple - Java Moko Gaderstand the problem pecide ont computation a. means ,eract Va-approsicnabe Sewing , algorithrn design -teebriqué Analyze the algon fam code. the algor' thro Figure” Algorithea design ane analy si pretese Algevithmia Problem Solving Algorithmic problem solving means selving problems | that require the formulation of an algorittrn for tnetr Zolulien, rb freludes mainly the following eight Bleps- They ave} the problem | |. Understanding Lies a te computational 2. Ascerkain the capabili device 3. Ezack: [ approximate. solution | 4. Decide on the appropriate data Strecture 5. Algorithm design techniques 6. Methods ef Specifying 27 algori they TW. Proving an algovithe coirectnes® @. Analyzing an algorithm . 1. Understanding the problem: tven ghould be understood completely = the poblem g check tf fk fe similar to ome skandard problems and tf a known algorittn extsla. therwiee a rew algorithm has to be devised => creating an algorithm 76 an ark which may vever be fully aubemabed. Ar design rs to specify an impostant Step in the tnstan ce of the problem hae 2, Aecertain the capabilities oy the compulakienal device = ie understood the aapaldilities => Once a problem agerloined , ef the cormpubing device has to be “hts can be done by keewing the archi beckure , speed be memory availability / type 2 the 2 Exact | approximate Selubion ; underslood the gapatilities > one algori then 16 of menos af has is be Ascerbained £ ean be done By kmowing > s ht => Once algorithm 16 devised, it 76 neces2ary to show thak rt the possible legal inputs. ‘the solution * fn two owes: Eaack golukion oF approxir ache Sdubien = Some examples of problems where an exact glukion canrot be obtained axe * (i) Finding a Sqpare sont of oumber (i) Solutions ef nen linear equations appropriake daba struchure 4+ Decide on the | 2 Some algorithms donek demand any ingenuily — a oh i vepre senting their inpues + S0eme others are ice fack are predicled on ingenious data skweluves A daka type ad well-defined collection %} dala with a well-defined set of operations on if. > A daka gkwuclute 15 ap ackual fmplementakion of & particalan absteack daba bipe. seme a) the elementery dake Shuckuvas are arrays, 6. Algos Eno design bechniques : Ifsk, Set => creaking an alepithm te an avt which may never automated. By mastering these design be fully Sbategies, TL will devise useful algorithms - become easier for gou pew and = some of the techniques age especially computer sdlence Buch as zeal jn fields other than operation aeseath and elestical engineering Zeme ‘imporkant design techniques aes - Brube force * Girreedy method evivide and conquer . pynanié programming + Backtrackin J NAW + Branch and bound » Linear programming 6b. Methods of Specifying an alg ostthen ; = There ave mainly two spliens for Specifying an algorither : () use of nakural language © Peeudocede % flowcharts > A pseudo code fe a mixtuve of natural lanquage & programming language like gonstrucks . Flower ia methed of expressing an aalgori then by & collection of. connecked geometric shapes 4. Proving algevithm's covredtness * > once algorithm is devised, Tt is necessary to show tha 1b compukes answer ger all the et | tigate this fa + sauve. took possible lega np 76 fa to a ue ants algorithm will work correctly independent ning preegreering language tk af issues concet coill be atten in =o A proof af corveckness eegebees thak the be slated ta ewo forms . one fore _Ge\uki on te usually as * pregram wh by a sel of assertions abouk we fel fe. anne teked Foput ).go and eukpuk variables ef a program. _» The second form i called a spect freakion, and be expreased tn the predreate thet congrats ey Shewiag to that for Hive may also Calculus. preos Lrese lwo downs a7e equivalent they describe Same every a legal Fret, oukpuk . => A compleke prod of pregarn corseckness stateren= ef programing equines thak each depived and all. baste language be precisely opexalions be proved peared All these Adnde may poise pret te be very much lenges than the program. 3 Analyzirg algorithms : => AS an algori Eben fe exerted, TE uses the unit be peor cenbal prcessing computers ike memory + hold the pregany operation ane! and data. => Analysis of ail gosi Urns and performance analysis vefers to the das of determining hou much éoraputting Lime and Sbesage an algodt theo equi ves 7 se) => his is a challenging area in which SEN | Zomelimes requires mathe malt cal ws thak tk An tmporbaok vesult of. this study do make quanti bakive Judgement s ef one algorithm ovey another . allows us abouk the value = tk also allows you te predict whether the Bef pws re wil! meek any efpiciency con shaink thak ]extte- eo SIMPLE. straTeaies FoR DEVELOPING ALGORITHMS (C LTERATION, RECURSION) Theve ave different strategies for develeping algorithms. seme af the Simple strakegies ave * D rtervation 2) Recursion Thervative algovithens ! they use repetitive constwcks \ike loops ¢ fer, while, do-wnhile ) and sometimes additienal date st vucbures ite slacks be golve the giver problems. Recursive algorither atk is one thak invokes jkeelf ~vepeatedly unt] a certain condition Calso known as termi nabien condition ) 1.52 ig mel. same problems ane. naturally suited des one fmplementation or the other . Example : Etbontee? sevtes ave the numbers in the following Sequence : 0, |, 2, 3, 5,8, 13 By definition, the frst jwo numbers ave oandl and each sabsequent numbers in the tevies is lo WA ‘Bom ign Ge Pevens bwe numbers. a FOND =| when n <=! emda. Ear Elna)! alten Bd FONSI ie Flo)=0 FC2) = ECa-() +F (2-2) =FU) +F Cod =|l+o =| Tkerakive algerithen for Fibonacci Sevies Set fo to 0 and fi te! Display fort! for loop <= ! to? fir = fe +f! fo Beme examples of ave + . computing a” . computing nl Seleckion sort ~ heb » Bubble sort 3 nital Zearch +Exhauslve seach; Traveling salesman problem, knapsack problem. Gireedy Method : => jn greedy algorithm ef optimizing Solution Lhe best solukion fs cheasen at ary moment . A greedy algoxithra is vey easy bo apply to complex proviens: tke decides which step will provide the moze accurate solulion in the neak Skep. = this alge rithm fe called greedy because when the opined 4olubkian te the Smaller instante 76 provided, the algorithe dacs not consider the total program as @ whole gree a Solubion 7s considered , the greedy Algovither never censideve the same solution again . Stk wows veeursively exealing a geep at eljecks frre the 2rvallesk possible to a specific problem te dependent on the Le7 Zoluktor af the smaller Instance OF thak problem = Examples* « Minimal spanning shortest distance ir graphs . Grveedy algoritha jer the ana woblern dyée the coin exchange problee Huffman trees for optimal enceding Divide and Con quer Method => an the divide and eonguey approach , the problem 76 divided Inko Several small ‘Then the Sub—problem s conikined Sega! 4ub= problems. are Solved recursively and olution of the original problem the Jollewlng steps al each —> st Tavolves leve\ eDivide t The original problem 7a divided into Sub - problerns + Conquer; the Sub —preblens ave selved recursively . she solubions ef the sub-problens «Combine *% wr to get the Solution are combioed togeth 58 af the exiginal problem . => the divide and conquer approach ts applted in the Dynamic programning 12 an optimization Lechnique yp which divides -the problem into emalles . Sub-pro bles and afley solving each 4ub- problem , dynamte prog rarerniog combines au the slubions to get ulkimabe solukron , > Unlike divide and conquer methed, dynamfe progiamming rveuses the solution bo the Sub- problems reany Limes | — PRecarsive algovither for fibenacci series ts an example of dynamic progranming _ 1.5F Backtracking => Brack evacking jean optimization technique te Zolve tombinalfonal problems. Te 1s applied bo both prog rarnenadie and veal—life problem? Erght gpeen problem, Sudoku puzzle and geieg tprough a maze are populax examples ewhere! banetrackirg algoxi then fe used, = th backtracking, we kart wilh o possible _solubien, which satis fres 4! the wrequived ye te the nexk level L produce & Zaliefacloy back and skert eonadittens: Then we wo and if thal Jewel does 7° golukion, we qekunn One level wile om nee epHier Branch -and- bound > A branch and bound alg osithrr ae an ahien -bechorque te geb an optimal opbient = fer the best * solution tc the problem . TE looks aelulton for & giver problem jo the ae beanies T the Junckion merged with the value epthre the solution . Space ay be be opeimtzed ave af the lakes beak Zelukion => rt allows the algerithe do find tks pats af the _ solubion space cormpletely - % tbo i ges Renal il ae, aly bo maintain the lavest - cast path boa target Once a solution i found, iL can keep improving bre olution. the branch and bound searth is implemented iin depth - hounded search and depth- fist Searth. Linear programming = LHrea programming dearbes a wide clats of opttrization jor where both the optinization the con ge the skrainks ave linear funchions best cukcome {Pie eek cask crjlenten and rt te & technique te Lb, Shortest path o* maxims pref low a se of variables are => an th*s progeareming, sakisty a sek of assigned with absoluke values +0 neat equakions and +0 mopdetze oF minimize a given linear objeckive punckion 2 Exarple : Maximum flew problem oe divecked grap eb Liluseralis : 1-6 us ve problems: Find minimum ip a list insert a card tna list af sorted cards “ f 2 guess an integer number fn a range et Towers of Hanol. {-6-1 Find minima fr a liek the preblero 16 do find the rminimum element In the giver [vet of elements Algotitem + Beep |! Read n and the Ifet Led Skepas ek MIN as pis steps: fow THe ton xf Lora= MIN then fon = ela Step 4 > Print * The minirourn value of the liek as MIN’ Brep Ss? Skop Python progranr B= Crs, bey Sots 24d prink oO minimus =a [od for number [0 Ge LG Tf mintraurn > number minimum = number print " The erintmun nurcber of the jist" prink ouput 4 python moedin « py minimurs Cia, 10, 5¢,te9 ,243 The minimurd numbey 710 |}.62 Guess ar znbeger nurpber addressed here ta a guessing fnteger within ina vange The pwobler game. The bask *2 © guess an a specific range - the computes -randoraly selects wange pe iter. an inkeget from a spect fred The. user guesses wpe) the purmber %S equal te the compute - the choice JY Alger thre Step ls Beleck an integer free the specified range Cl ton? and gek 7k as oum stepa: User prompas a number as gress Step 3 - ty guess equal +40 pure then pine >You. wer’ Steps rf guess fe lesser than num then print * Ty Highes auncl gote step 2 6s Step 5; If guess is greater than nurm then \ Tay Lewes’ and ge 40 step? print pager progror jenpowe sandam nun = rrandarn wrrand tok CLiee) while True | prin’ ('Guese a number between | and 100") guess = Fnpul Bs fs ink (ques2? prine (> you Wor} } 1) break fe ferent pink ic seragg Highet 4 oukpak = Lekween land 190 fiiess a nurnbet ' srry Higher Guess a namber bebween | and lee 30 TY Lowey rues a number between and 1De lo Yeu wion 1) 1b» (63 InservE a card tha Wel of sort eae The. problem is to fnses& & card ina liek of Soited cards. Algosithen * step |+ Read the Bequence of cards Bkep 2. Sort the Begprence Kead. the card numbe th each ‘ elemené bin he cored ekep3- eo © te be jnserted sbepe Cotnpare © wi in the Beqpence and inser position | step s+ Pein€ the madifiel sequence of Cards. Python program a= £142,105 b= Sorted (a) print Che ested sequence) prink b ak U' Enket the card number Le be inserted!) pi 2 = tnpakO fos f 10 range C lench5 ff beri>e! index =! break debpis +£ed + Lig prine ( the mod ified Se oe? pata ee output ‘ the sorted sequence Lie, 12, 197 Eoler the card number te be inserted 12> the mod ixed seqpence Crore) 13,19 boy Towers of Hanoi <> The Tower of Hanoi, a mathematical wae tayerged by be Less and a ewhtch game or puzete, in |9¢3. cE consisks of three rodS, number of dalsks ef difpevent sizes zan altde onte ang aod, the dfses fa a Black are arranged in ascending ordes ec top, thus making af size or pre. wd, the Smallest at th a conteal shape of thts puzzle fs te move the ne yod te another aod the following are =4 the objective entive stack for “ei using an qbermediake rod, the three wles* thy e@nly one désk can be moved aba lime. Each move Consists A taking the “ppet lacing ot aise from one of the steeks and pl 1.be ft on top ef anothey Shack ie, a disk can only be moved ff fk ts the uppermost clés on a Stack. (TD No larger disk may be placed on top of a smaller disk = the Hree rods ate narned a4 source, destinabion and ausciltary Conly bo help moving tne disks from Beurce to degtinakion). A — source wood = B = aurilfavy wrod c- destination vod walle bl) oJ LL “lh “Lib => If there fs enly one disk, then Tt can easily be moved from source to destinabion ved & Solution for 2 dides « * First, move the smaller Ctop) acs to auzxcilfary ved . then eiove. the lager Cbottem) disk to deskinakion od. ler disk foro + And Finally , move the 2m auxiliary +0 destinalion ved . — The algerithra fer moving in! déek Ss Step!t Meve o-! disks from source be ecu ail rary woe step: Move al* disk fxom Source to destinalion Sepa: Move r-t dieks from auxiliary to destination A -recumsive algorithm fer Tower of Hanef fs giver below + START procedure Hanoi ( disk, Source, desk, aun > ZF dfsk ==), THEN move disk from source to desk ELSE 1.68 Hanet (disk—1, source, aux dest) sstepa Wmove disk from Seuvce todesk Wstep2 Haro’ (difsk-l aux, desk, source) Mstep 2 ENDIF END Procedure STOP Python program: Tewer of Hanoi withs disks and 3 *ods def moveTewer (height, fromPole, tofble , wi thFole): ig height er le move Taxuiev ( hetght -!, promfPole , withPele , 4ovole> move Disk (from Pele , toPole> rove Tower ( height -L, with Pole, toPole, fromPole) def movebtsk Cfp, tp): print ("moving disk from", $3 "bo", tp) move Tewer ( 3,"a',"e", "8" oubput Crmoving disk from %, ‘Al, 1404 2) (‘meving disk feoel, SA", Meat, Maly (‘meving Atox pum’, "2", Veo! ty 1264 Kd ‘moving digk frora', Ail, ‘to, e%5 , : ' ; € moving dtex from’, \ a!) be! "A') C'meving disk drom', spt, eel, “eld Crmoving ara from’, ail, > eel, ws pat gxamples Example t, Wribe a prograc avea and cir Algor thre Step |\* Stare Steps: Step 3: af the clrel find the ayvea and e using the cferrmula . prea < Biyper a7 circumference < a RH Soly we Step 4: Pink the avéa and ci¥ af the circle. atceps 1 Skop Pseudecade : Set irikial = Renp te tadétus of the civele - Find the avea and circumference 10 ko find the cumfervence of the civede Inpuk the radfus of the circle CivcumpEerence curnference ex to Area, Civcum ference pf the civcle using formula Areas Sy woe Civeumference = 2 # Biik amr were eukpub af grea and ¢lveursfewence of the circle Flow chart Beavk aveazsBlyxax7y | | clreumference = 2 xB Print area, Circumference Stop Example a: Weike ao Program to find the rookS af the gpadatic equation. Algorithm : Skerrk} Stepat shark Bkep 21 Enter the Value af a,b,< sbep a> Find the value of ‘pv! af wing the fornula pe bxb-4*ma eC sep 4% Tf D'S greater than ov egal fe zewo then fina wok De ¢€-b+ 2g cad) / Ca» ® yok 2< (-b— Sat (ad) Ca a) the two roots ave Shep 5: Pstnt the fwo roots, rookl, soot > steph: Tf 1s ook greaker thantegual te 22m, ther prick the yeekS ave innag ira ay step 7: skep Flow chavt pe bxb-hk xe ake Yes. Roots [-b +6qrxe CAI {C2* A a sqrt CA) T/C 2m a) Rook 2 L-b Peeudoco de Bet initial zevo to Yeot!, wr00b 2 READ the value of a,bje Find deseximinank’ Debye b-y eae © I-F Dp>=O THEN Calceuloke rook! = (-b + sq7e C D))/czxad soak = (= b- grt (PD) Ca #4) Eréee Rooks ave imaginary ENDIF WRITE wookl, rook 2 Examples: Write a pregram to ind the factorial of the given number Algowi tore . Step | + Stave Step a: Read the value of ” Step 3: get initial values te fack 2T<) Steps = Ts jesn ele Grelo steph 5 Sep aul Pack <= (Pack vel shepaaas fe rH Skep 5s Giobo skep 4 Btepbs Pink Fack top see lee Pseudocede Bet tetHal one te faeces i pean n value to find -fackorial fee Ct 2=9) THEN Fack = Fack x? fo ati ENDIF WRITE fackovial of a numbey Algowi then : Step! + Stave Step2: Enter the value of yn Exareple >: Write a program to find the giver number fs an Awmstvong number or nok. Step2: Assign aen, V=0 Sa Slep4: IF m>0 ELSE Gols step 6 Step ge pore med \o Seep 4-2 1 Sum &- Sur + TREY n= odiv to Step 4-3 step 5 + Golo step 4 Step & + TE assum THEN peink Axeeghong Eise psink Nek Asnskyorg Step : slop Flew chart ( Stark venmed 10 Sums Sun +t THY n=ndivie mE nok Armstmrg Pseudocode *. Set initial a=n, Sum=0, 7=0 READ the value Of 1 WHILE (nN >od += Nelo Sum ssam + Te FT n=rhe END WHILE Repeak while unkil Ehe condition fail te (4am == a) THEN WRITE the resull 18 Atmetrong ELSE WRITE the Tesalk Fs nok Armstrong ENDIF Excample & Write & program to find the giver yeor fa a leap year oF not. Algovibora : Step 1s stast Seep 2% Read the year slep32 rr ( yeay med 4) =O THEN’ prink “ tk fs a leap gear” Seep4i ELse Print "Tk fa nok leap Yer” Sklep 5: Stop Print Leap Yeay Peeudocode Reap the year rr ( year 4 = 0) THEN WRITE the year ie leap yeav ELSE weire the year is nok a leap ye EnDIe Example 6t Write a program to generate the fibonace? series. Algorithm $ Step! + Stark Fle 0, F2<1,F +e Sepa: Assign Step 3! Pink Fl, F> ja Step 4 + FeFl+FR Step & i READ N Step 6: TF (Fan) ELSE Goto Step step G1t FS FI+F2 Step 6:23 Fi< F2 Atep 6.2 + Beep by + Prink F fa Max then Max= alid Step Tt Tf aLtyT MaAx then max salts For ar 4 tr alfi< min Lhen Mine alf end - fer print MAX, MIN

You might also like