You are on page 1of 21
01 - Programmes & Programming Languages / @@eé@ ©) Ceuta ea ema cnn can in RB ae uA oe =: Generally, a program is a sequence of instructions, written in a programming language to perform a specified task on a computer Boum OPsdond og eBommend O62 Dov¥s mbwax 99 md OHO aqw oSoaim enuOdial Gam 4 coord gnaeed, eM Aer 6 Programmer is very much like an architect, a composer or a writer, _oedamewn, av ASG EEBUM., ABs GHSoumd ows eCamoaRd gmoost we eb, zs Tasks of a programmer / )Os00n= mbacst * Forman outline ~ Macro Level * Translate the outline into a design ~ Micro Level o Iteratively refine the design till it achieves the intended objectives = Programming can be viewed as the process of breaking a large, complex task into smaller and smaller subtasks until the subtasks are simple enough to be performed with one of the instructions provided by the language. DAwIwBmdcsed § dae oB5S QoeCID ME wy QH Co mdaOeda,, 69 ov mobuet wowed qu Creqsd al ont ade Cvequdal Gaslom me mH nADad emde mdg Ger. 4.3. Why Programming Languages / oS@som me qOws qu? es A computer cannot understand the words spoken by us, and this necessitate the need of artificial languages, which can instruct machines to carry out computations we desire. qo mm mdm Ost SHoaMad oTh® OD om 1S d,Oo 68 quod eDexmd gQ B80 edgedat Gn® BBoeme OGat mast 99 md | HS/eBouns sem Eder Cvecd CH 200 maAB meOat Bax 08 2A programming language can be considered as a tool which can be used in problem solving, Bane muda asin, 00g 5a8® sem mOm me Huh c80COx oct e.CBHu mS o. Mea eu et eR el ee No universally agreed definition, Although, more attention on the following couple of definitions commonly. addnasd oce Ome Ou 18 do guides qatda eo mS «. Cod HOF own quieda ghd qutB® gbxi0e CO OB gdaanaw om mE mS a. © Any notational system for describing algorithms and data structures in both machine sy ig alg readable and human readable form and which can be implemented on a computer. SbasaGSad GaOEO aha aH Oo SE © MIGNO GoHo wc am S09 GaHo ox Ge BOe5 eeSd qd aGem6o8 ow edo paaf Sdad S680 eme axle) Beax® qoSo o€0608. © An artificial language that can be used to control the behavior of a machine, particularly a computer. Sedeead shade O28 GdQOD HcBO8 NEHS G80 MOm wE ox mi mMOB. (PHauCunsdanr ein heeue L ee aot ok om ed BS ye Re MCl ig ie teen le) os B20.) “% 1GL | First Generation Prograraming Language Machine Language MdGo oe Ye 2GL_— Second Generation Programming Language Assembly Languages men8DE mH 3k 3GL | Third Generation Prograraming Language High Level Languages. @@ ©0008 1") se 4GL | Fourth Generation Programming Language Artificial Languages maGO 0) ‘« Program written in | « Less instructions that | Program writing is less | « Used to program computers ‘machine code are represented by ‘complex because of the to make decisions in real-life 2,ad0s Bom symbolic names such | vocabulary, which is easy | situations. Used to build ‘ete? 0 eal am as ADD, SUB learning. Based on expert systems, ewoxig§e ond 888, Bae 980 wstgon languages closer to B56 HO en SSOGD wend eoodad adc | hiimans such as English.-| ose oat qnendis0 Bas gg Be. wSomm geedane HWOrese 9d KD. | Bee enttessiba 2 w. © Too many instructions.| + Called Symbolic «Tt can be called a + Computers understand Programs coding are | Language as symbol procedural language. natural human languages extremely difficult. was used in the program] Ex. Fortran, Algol, Cobol | _ using these programming Ban phrae Bae8.| c-onto mdm S80 2885 Procedural moms ai | _!anguages easily oxtamdes qBaBs | Sm c-crlo mw cce | sen mend a. BAe woo DD me geod. 1B a. e518 oS20 soya, * Depend on the * Depend on the machine | ¢ Not depend on the machine « Closer to human languages ‘machine type. type. tis machine independent. | _ such as English. esiga 8 moon axige en woo alg On nese mmdst | 9-98 Odi G00 eowrdafo e040. wombs. arend oo om ns BS. ‘Translator was not | « Aspecial translator | « Needs a translator such | « Used in roboties to program wanted. called “Assembler” is} that Compiler and ‘computers to see, hear and SBbsmm Sagemoasi| used to convert the ‘Interpreter. react to other sensory stimuli, bam ameB 0. symbols into 05 and 15. | » g@engan ew go sfomde0 G20, HBP: Assembler tas Doman jh ebdtam | m aodende cHlersm eBdnws emp ovtny Sagoo qden Ba. eee y8Ges 8880 ecsoad ¢ = axipic g8edans 368. > Programmer should | + Programmer should | « Training a programmer is | + These languages are aimed have a comprehensive | have a comprehensive | easy. at reducing the time taken to Knowledge about the | knowledge about the | p@ecamm gues 880 | write programs. hardware, hardware, ined, 290 wom, 2Ou00st “peedanad gina | a8ecdmud ato 8599 on 85 mes gh Beg ged am@at | S€aq 0 ge¢ eae Om oce gown m6 Sea, Bo gh 0. 88a gn 3. + Ability to debug * Ability to debug ‘* Error diagnostic messages | + Ability to lear the programs more. programs (debugging) | given and easy to test. languages within a short ‘difficulty than the more easily than the Dio Hgem Hod v&HO|_ time of period. other generations. programs in IGL. Cm ocSci ode Bopd | end mcuis! 89 mu» DSadwsOe ede | seGedeonbo0 | BSS Ob omg moe, geo o B08 m Bad Brads S800 ogie Boma o8, gooat wceemonio | mdad dm ong «. | 6s gute “+ Program processing — | » Processing speed + Processing speed is slow | Ability to accomplish a task is slow than first eymge eos exteos8.® | by using a less number of GLimachine language. | ag eB. "| commands relative to the exmp® eos asty | MS Visual Basic, C,C++, | “ther types of languages. ‘werusbd enodie® 59 | CH Delphi, Java, Ruby, | 329 Sm 0-dn0de4 owtst Bg 20. Python, Ada, ...¢tc, mbaast 2d op mS «. | _LISP, Prolog, MATLAB [es This app ranks the popularity of dozens of programming languages. You can filter them by listing only. those most relevant to particular sectors, such as "Web" or "embedded programming," Rankings are |: created by weighting and combining 12 metrics from 10 sources. We offer preset weightings-the default is our IEEE Spectrum ranking-but there are presets for those interested in what's trending or most looked for by employers. Designed to allow the creation of programs that can run on different platforms with little or no modification, Java is a popular choice for Web applications. Cis used to write software where speed and flexibility is viv important, such as in embedded systems or high- performance computing. Essentially a version of C with built-in support for oy: “objects"--self-contained modules of code and data—C++ proved to be a natural fit for software driven by graphical user interfaces. Created by Mcrf for ce ELE SAW FF the .NET framework, which supports many applications running on Windows. Designed for programming statistical analysis and data- mining applications. + A scripting language primarily designed to support dynamic websites. A scripting language used primarily to add functionality to Web browsers on the fly, allowing the creation of complex Web pages. A scripting language designed to offer greater support for objects than other such languages. v A scripting language for MathWorks' Matlab computing ‘environment, Matlab is designed for numerical computing tasks, such as engineering or scientific simulations. ‘Source: http://spectrum.ieee.org/static/interactive-the-top-programming-languages-2015 PEM cmcieruie cacnkar eu |e: Ifyou are a little confused with where to begin, let us give you our recommendation, Based on a survey of 18,665 users of lifehacker.com, the following order was highly recommended for learning programming, building your confidence and for the usability of the languages. Just learning Python, will put you WAY AHEAD of the curve! Try one and see the opportunities it can open le: Python, C, C++, Java, JavaScript, Ruby le: What it is: Python is a general purpose language that first appeared in the 1990°s. This language was designed to be highly readable making it very easy for beginners, Despite its relatively small learning curve, it still packs the power do very cool stuff like scientific computing, web development and 3D rendering. = Why you should learn it: You'd want to leam Python if you're looking to jump straight into programming with relative ease, Unlike lower level languages such as C ot Java, Python can be picked up ata rather fast pace. This makes Python an extremely beginner friendly language. | Applications and exampl Instagram, YouTube, and Reddit are all examples of what Python is capable of. Because these applications have become so big, many more technologies are now involved, however Python played a major role in starting these sites. |e: Job titles/companies that need such programmers: Because Python is useful in many different situations; there are jobs available in just about every market. Titles such as Data Analyst, Network Security Developer, Web Application Developer and IT Auditor are common. Companies such as Google and YouTube are always on the hunt for top notch Python programmers. Source: hitp:/www.topprogramminglanguages.com Je Learning to think like a computer programmer is a good end in itself, since the processes used in computer programming combine some of the best features of mathematics, engineering, and natural science. Js The best coders go through several phases on their programming journey: 1. The “I know nothing” phase . Everything is new, nothing is easy. 2. The “it’s starting to make sense” phase You've written a few programs and are making fewer mistakes. 3. The “I'm invincible” phase Your confidence matches your competence. No challenge seems too difficult 4, The “I know nothing” phase, part I! The sudden realization that development is infinitely more complex and you begin to doubt your own abilities. 5. The “I know a bit and that’s OK” phase ‘You have decent coding skills but recognize your limitations and can find solutions to most problems (even if that means hiring another developer), Pe ee eel te Re oe er ie om clelaeretal | low-level language is a programming language that is d called machine language or assembly language. igned to be easy for a computer to execute; alsé [2° It is high-level if the program must be processed before it can run, and low-level if the computer can execute it without additional processing. Python is a high level language but must be interpreted into machine code (binary) before it can be executed Je: A program written in high level languages cannot be understood by the processor of a computer. Thus translator (such as Interpreters/Compilers) are needed to convert the programs in high level languages to the understood by the computer (Machine languages). 90g 20068 wBoeim merOai SGet Eom ce DSeC Snax (computer program) Sosa omamad eFh9 on om 7S w. SAE! Que ODEO sBocim meat Ost Gan C4 BBECdD LdOGIZO e489 OD wUB aetGm mwOd eBObaanw HE agen (qbo Eomum oo eOugme Oe) SBomo wots UBDSDm EDan oD. J The original program is called the Source Code (Source Program) which means a program, stored in a file, in a high-level language before being compiled or interpreted and the translated program is called Object Code (Object Program) which means the output of the compiler after it translates the program. B80am _2edaned Jd Bem Borg emia (Source Program) eceset wet§m wed oBOSana me 8Ou5 Dedq oxime (Object Program) eews seston CAB. |< There are three techniques for language translation. tails SBOEDD OSeO¢ Qua LOS. lz An Assembler creates object by translating Assembly instruction mnemonics into machine language. Ben8Hb - ¢.008HE (Assembly) macO=t Gac cg OOO evtg mw Cveda (instructions) DS H8ddnne md_ ced. [_Sowee Progam _]}—[iiggeinblagg] ———>[_Objee rogram | = A Compiler translates all statements completely written in high-level languages into machine language instructions before program execution. le In this case, the high-level program is called the source Syntax Errors code and the translated program is called the object code or the executable. Once a program is compiled, you can execute it repeatedly without further translation. mBenewa - gwve 2000 wousOGet (High level languages) Gam c¢ eosin QQUODe assim 880 o86, Bag Dosis (statements) aaty mes Coede (instructions) 200 a&_Sesoust © oBOSSne 269 C08. @8e Interpreter OED OB eBoOes a (fast) |<: An Interpreter translates cach statement written in high-level languages into machine language instructions one at a time during the program execution x Itreads a high-level program and executes it, meaning that it does what the program says. | It processes the program a little at a time, alternately reading lines and performing computations. gBd Bamema - ne 00008 mudGai (High level languages) Gem e¢ SBoaim DAxOvoat BarvtOm Or Edged & 0600 Om A,Ga Ont dat DoriSu ang mow Cuede AND SBdbas mdy 6108. od Q& meus NE OYAsONend oxi DusiGas’ cSdSane m6 Guslow moB. Errors/Results |e: Combination of use of compiler and interpreter as follows pon galeder qimdad BOerqine i ghd Eamams an eBodaw oem © op oF CAB: |e: Many modern languages (JAVA, Python, ...) use both processes in different operating system int or platforms (Windows, Linux, Fedora, etc.). JAVA, Python 08 edxed nBzn sBocie wows Compiler ew Interpreter azn oS0bmm gOuide © ocn¢ ods 85d eSewg® oddS enc GgeeOc (Windows, Linux, Fedora 8,8 /'platform independently) Bustos H800 Bandas 008. |< These languages first compile source code into a lower level language, called byte code and then interpret the byte code with program called a virtual machine. Byte Code is an intermediate language between source code and object code. Orga Oat HEY O ENE D068 meal ADO dm® ABO oxtne HOD LBdinns md, 68 bd Bomame O6et SarsiOm m6 ena sboGm 8 9 Dedduxt 400 vIOIaNs mdB. ABO enine 2m Geng eats m Ded ontne qnoog Odeo, |e: Python uses both processes, but because of the way programmers interact with it, itis usually considered an interpreted language. 089 §a0E dOxidu © GartOm Om cost mmo, |oecdnast semg CdD emde nd, gbo Bomam mada oce meste8. |: There are two ways to use the Python interpreter: shell mode (interactive mode) and program mode (script mode). in shell mode, you type Python expressions into the Python shell, and the interpreter immediately shows the result. [~ Comparison of Compiler and Interpreter shown below table. One wdae Description Compiler | pBegoo Interpreter | q&O Bemama ‘Works on. the complete program at once. It takes | program works line-by-line. It takes one: ‘BeomoBei0.s | the entire program as input beginning of | statement at a time as input while program are the execution. executing. 0,Oudun Gurs'Om 500 ond sOghG | Oswn edGeast eds Hmm On . Dalen © oat dos coax | emdQd mem cod. Saonioe ad eons cd a8. Intermediate | Generates object code / machine code _| Dose not generate object code/machine code code avin estnust tone 6. | wot§a ostaast dome ened. qndeg oxtna Execute Faster Slower speed statements. 2808n o | Sxteons o. gama Sacto | 880 ‘Memory Take more memory, because entire | Interpreted programs are more memory usages ‘object code has to reside in memory. _| efficient, because does not generate object Somed weybes Oem © ded | code. Da OGD Bf OH He GO eam ado Oowuee object code oma dnnw arBendet waBe0 OB md Bes ef Oom Gos md mdE toaBim den toowy Running ‘Compile one and run any time, doesn’t | Interpreted programs are interpreted line-by- aoOanee need to be compiled every time. | line every time they are run. ex doe Compile md a, 208 | bd Brname edGoust ed&s Gus'Oa DOadun Gastow me mS He 28 | 2m Ber ado Fastom On «19 59 © 8d © Compile s¢ ga omed. e8dinne me ga ed. Error Reported after entire program is checked | Error is reported as soon as the first error is reporting for syntactical and other errors encountered. Rest of the program will not be (68 abn aide an cD eels 68m S3ee | checked until the existing error is removed. 889 24g cats Odan 258. SEG celus HG Dey tiat ociuc Dati mdm ead 68 ees HOCR min onal OQsdnest cess camded Sra erm mB. Debugging “More difficult to debug Debugging is easy because interpreter stops 0,08 BD,68 B80] ociw Horndess BIO OO quwys 2. and reports errors as it encounters them. egeadt an moe 8d o8dinm GandGe Dad 8 ods Bim B69 Sm ode Baomies B89 0 ong o. Run Doesn’t allow a program to run until itis | Runs the program from first line and stops: completely _| completely error-free. execution only if it encounters an error. ndgdmeaste | abqbccust & cele A628 > ons’ | edeas wG On onal veg edEod BO Gaolos 59 Oadvn Gusiom me om Gu. | 7.Oudon Gusto mE ms a. Efficient More efficient but difficult to debug. | Less efficient but easier to debug. moSeisOm6 | embamOmd 0,8 gost ode Ao,c2 | mbamOmd gf Post ode A008 AO B89 quog o. ong o. ‘Used languages | C, C++, COBOL BASIC, Visual Basic, JAVA, Python, Ruby, PHP, Perl, MATLAB, LISP (EPs Race Moncey Moe Koon) [= The single most important skill for a computer programmer is problem solving. Problem solving means the ability to formulate problems, think creatively about solutions, and express a solution clearly * and accurately. As it turns out, the process of learning to program is an excellent opportunity to practice, problem-solving skills. There are four step of the problem solving. 1) Analyzing the Problem @Ogo Odegema 458 2) Develop an Algorithm GOQO OED HGemOo® em! axHO 3) Developing / Writing a Computer Program / Coding Obesum @SegAaa/n00bO20 4) Check the Solution toe ea Boge cca 658 ERM Rudarcukkoes Nese | Analyzing the problem in terms of input, process and output. mon, Bad08 av yBon vgm oABal oOgd Bdoce mu 489 By oma. RR eu an) ke eee noes Je: Suggests a solution for the problem that analyzed in the first stage. The method that is used to solve the problem is called the algorithm. An algorithm is a step by step list of instructions that if followed exactly will solve the problem under consideration which can be represented in two ways. og Dako® veg quod 8 Bolodeeia mdm Ce QIGHS Hk wEw EQwONE Ddm _eEdGa| qea:858 eg wEZOE. Ome oOGOu' Hak sem qQone mdm HaOo Doobes gaBEodE: Bubedst Badd Agowe G59 gCemBsdad ece wesedm end o©s sum quteDm qand| ocd Biome me mS 0. 1. Textually Glo mada PseudoCode Omd exo 2. Graphically — x0®@ @arda Flow Chart = ax88 GOS |e Pseudo code is a sequence of written statements of an algorithm prepared by using a restricted and well- defined vocabulary of terms. Pseudo code (derived from pseudo and code) is a shorthand way of describing a computer program rather than use the specific syntax of a computer language, a more general wording is used. Using Pseudo code, it is easier for a non-programmer to understand the general working of the program. combat 280 qsdo wy8, BOraGn 00m H2E0s mim om0 amd adm y¢ooBs®am eq 65a] gman gngdasl Ome estos ce mgst03. qdemindar! ow mule On om seun mwOSat ode O gaBo mB 0. ed qwOO oes] mdm mE BQ mwOsiod gainbonast agm HOD SOgSesi emo. Boum |eecaast ow] Beeld cdaus 68 goods Ogwa eD|OO ade wwrdHat quid Omd eaina ewds qoOi emia] eee mEsed. c8u Som B@eCdmam emOD emengd YO ¢ oUgedst exig,Gon MB wdc DExt Baw cied. Je: Some word are used commonly in pseudo code / Oxses ext>De eemgod mB Os O05: BEGIN, START, WHILE, ENDWHILE, | DISPLAY, PRINT, AVERAGE, END, STOP, REPEAT, WRITE, SET, COUNT, IF, THEN, UNTIL, LOOP, CALCULATE, FIND, SHOW, ELSE, ENDIF, «| INPUT, OUTPUT, ADD, SUM, OPEN, CLOSE Bd8mG, game, | cbena, Océoo, dan 868, 5388, mene, e8e00, | 858, omaa, mes 6x88, Bown 608, E80 [es A flowchart is a diagrammatic/graphical/visual representation of an algorithm that illustrates the sequence of operations to be performed to get the solution of a problem. BELO MOGNM Supa Co OHO sqm, qteminum Ban gagoad Bon mE gn mada, en BEedst jude conta O63 qual f ada o1@2 dona ece westod. 2 Flowcharts are generally drawn in the early stages of formulating computer solutions. Flowcharts facilitate communication between programmers and business people. OG adr! mormreas eBocm Bugdd 00d ghaod 8 AUOrKa DID FDS oO DoECam«» tou) Dwrmba ydocw Gnd exiHodym DOgy aouagine 53, Je: These flowcharts play a vital role in the programming of a problem and are quite helpful in understanding the logic of complicated and lengthy problems. Once the flowchart is drawn, it becomes easy to write the program in any high level language. Often we see how flowcharts are helpful in explaining the program to others. Hence, it is correct to say that a flowchart is a must for the better documentation of a complex program. A programmer prefers to draw a flowchart prior to writing a computer program. gut gad O88 O- qyBat o-Bies OQadVOral orbGmo GOLD md OYHSO Comd OD. J2° The flowchart is drawn according to defined rules and using standard flowchart symbols prescribed by the American National Standard Institute, Inc. Few of the commonly used symbols defined by the standard are tabled below. Terminators Cae ees / po (GS) Input / Output ee / 98Q0 ee §moo Decision Som . Flow Line eee 2G COO Connector a82ddDa © |e: To write effective computer programs a programmer needs (o develop the ability to trace the execution . of a computer program. Tracing involves “becoming the computer” and following the flow of execution through a sample program run, recording the state of all variables and any output the program generates afler each instruction is executed. Trace yourself the following sample problem. OeH8 oBocsm OOsIst GOO mB, HeeCdmesgd LnGD O.Ovduma GeormBdOo otnra| wie (tracing) mBawd Ode m5 OBS gOox oO. 23, “sBoawmea 800 oc edEss” sw GarciOn| 5e® ocr mB/qQBEode CnOoa BdSzt, BBs Hak O.Oudvow oat ont cveda Hurxtom 64 qdmmed %, Bag 8 Bdexaxted sxfdust an coogme On ySpnus! Odmomdcel wemedna. QA BGst © own galed> Hujk goede ndmaebdne wdatn. Problem: a flow chart, write a pseudo code and the Python code to print the integer numbers from 1 to 5 and print “Good Bye!” finally. GWOQO: 1 BO 5 gw HH HSC adm Goes md cerned “Good Bye!” ecw Pewa SBC cen O80 Bons mE 8d G_|KS Od oalna 90 BEDE oxinw Garin NEXT counter Print “Good Bye!” End |e: Tracing can be a bit tedious and error prone (that’s why we get computers to do this stuff in the first place!), but itis an essential skill for a programmer to have. From a trace we can learn a lot about the way our code works. FEMS eke oan uc bce heroes) |2 Main aim at this stage is to write a program in a programming language to carry out the steps in the algorithm developed in the previous stage. Today, a large number of programming languages are available for implementing algorithms. C, C"", C#, Python, PHP, VB, Ruby, Java, Pascal, Matlab and Fortran are few examples for such languages. The process of writing a program in some programming language to implement an algorithm is termed as “Coding SBocim gqendeant og, Bal0® QUD gimdad O.IEE BEE COO mg GemBne ge» HOC?) eBoesw mmO0Bat Bla/odociman ME wae. 46 UD 50 e8 eam HIOraa wd GS vB0-cm woUey dene o-omdal qu Gnd GD: maHO maw Oca HESS EO) ® C, C™, C#, Python, PHP, Visual Basic, Ruby, Java, Pascal, Matlab and Fortran m&s ©8. e898 e@ad cSomm ONudusindae ends] B®edan g2ud ece ogalda ca. Ce Ro trol esd ead aoncs “he deneaceneto asad |e: Testing the computer program while identifying and removing the bugs in the program and execute the program on the input data in the final stage poeddns Garson md8at 0,68 oger cOD w Jd QDs! md, gato Oo HO,SLO Goo mH dew ghaod 2 Bs omed, |e: Use your problem solving skills to ask: is it the right problem to solve?” “qe gana ¢ Bags xed?” Hear NBEO, Bed HIG Baked oAndsd mo wdvin. Flow Control structures allow you to control the flow of your program's execution. Any algorithm can be constructed by using three different flow control structures. BLeddnas Guxtom On 69 66 ocr ww ens HBO MBO orem Ogw GA CEB. B® RdeorBo0ast quand OB ge a9 ae Oyo mOdeadl emd me mS a. |e If left unchecked by control-flow statements, a program's logic will flow through statements from left to right and from top to bottom, IE Dg gama AC exw COAOsles! |, eB seus! |VeCdus Deo BO enwdsi, que BO ee0et (from left to right and from top to bottom) ec 66 coed Gaston ob. | While some very simple programs can be written with only this unidirectional flow, and while some flow| can be controlled by using operators to regulate precedence of operations, most of the power and utility’ of any programming language comes from its ability to change statement order with structures and loops. 9m Bde Q8edam da tmnd mea oes Ga GA Dd, 28Nd BOECA wbO 9YdD00 qm) adder mineust mene mE MH oD. cdend YC Qoedan mHoest qed Emr.9 |oeCca| wombat Gen ce DIETING Coed Garston S08 enSEode, edad $89 sew von qudoda| ED yD ARGO mBm omes. "A simple definition of sequence is that it is a set of instruction that are in order, one instruction after the other, once one instruction has been executed. All actions aligned with the same indent. The actions are performed in the sequence (top to bottom) that they are written. Brush teeth > Wash face > Comb hair > Smile in mirror. }2:. In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability. 2.4 IF-THEN-END IF ‘The Boolean expression after the if statement is called the condition. If it is true, then all the indented statements get executed. What happens if the condition is false, nothing happens, and the program continues on to the next statement. 2,2 IF-THEN-ELSE-END IF S It is frequently the case that you want one thing to happen when a condition it true, and something else to happen when it is false. For that we have the if else statement. © Bach statement inside the if block of an if else statement is executed in order if the Boolean expression evaluates to True. The entire block of statements is skipped if the Boolean expression evaluates to False, and instead all the statements under the else clause are executed. 2.3 Nested/Chained IF (Multiple IF conditions) © Sometimes there are more than two possibilities and we need more than two branches. One way to express a computation like that is a chained/nested conditional. © One conditional can also be nested within another. Again, exactly one branch will be executed. There is no limit of the number of else if statements but only a single (and optional) final else statement is allowed and it must be the last branch in the statement, $ Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch executes. and the statement ends. | Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that computers do well and people do poorly. Repeated execution of a set of statements is called iteration. 3.1 FOR-NEXT -5 The for statement is a compound statement consisting of a header and a body. The for loop processes each item in a sequence. Each item in turn is (re-)assigned to the loop variable, and the body of the loop is executed. A for loop executes an known number of times. Use a for loop if you know, before you start looping, the maximum number of times that you'll need to execute the body. This ease definite iteration — we have some definite bounds for what is needed. & The loop variable is created when the for statement runs, so you do not need to create the variable before then. Each iteration assigns the loop variable to the next element in the sequence, and then executes the statements in the body. The statement finishes when the last element in the sequence is reached. Running through all the items in a sequence is called traversing the sequence, or traversal. 3.2 DO WHILE/WHILE-END WHILE /LOOP ] & Like the branching statements and the for loop, the while statement is a compound statement consisting of a header and a body SA while loop executes an unknown number of times, as long at the Boolean expression is true. If you are required to repeat some computation until some condition fs met, and.you ‘cannot calculate in advance when this will happen, you'll need a while loop. This case is called indefinite iteration - we're not sure how many iterations we'll need - we cannot even establish an upper bound! 4S The body of the loop should change the value of one or more variables so that eventually the condition becomes false and the loop terminates. Otherwise the loop will repeat forever, which is called an infinite loop. 3.3 REPEAT-UNTIL S This loop is similar to the WHILE loop except that the test is performed at the bottom of the loop instead of at the top. Two keywords, REPEAT and UNTIL are used. S The "sequence" in this type of loop is always performed at least once, because the test is performed after the sequence is executed. Generally, at the conclusion of each iteration, the condition is evaluated, and the loop repeats if the condition is false. The loop terminates when the condition becomes true. |e: The WHILE structure executes the instructions sequence as long as the condition is satisfied, while the REPEAT-UNTIL structure executes the instructions sequence as long as the condition is not satisfied. In other words, the REPEAT-UNTIL structure iterates until the condition becomes true | The WHILE structure checks the condition before cach iteration while the REPEAT-UNTIL structure checks the condition after each iteration. The main distinction between the two structures resides in the fact that, in the REPEAT-UNTIL structure, the instfuctions sequence is executed at least once, without regards to the value of the condition. This distinction is clearly highlighted by the location of the condition at the end of the structure, as opposed to the WHILE structure in which the condition is located at the entry point of the structure. La LA SS) LUM hr 5 |e Use of standard Flow Chart symbols on the following example: Input the number of integers required as M Input the first integer as N cat IS Draw a flow chart, write a pseudo code and the Python code to read a radius of a circle from user and. to print the circumference and area of the circle. /Oaciaam q6a Ha D8 obDa s Obedeo cso * 808 wen ox88 nomad me, 00 ences Omd edna 8 oBod eine ada. Sequence Conirol Structure a 2x22x1/7 area=22x 72/7 Print circumference, area Circumference is 44.0 area = 22 * rt*2°/ 7 Area is 154.00 print ("Circumference is", circumference) print ("Area is %.2£" %area) IS Draw a flow chart, write a pseudo code and the Python code to read length of the two adjacent sides ofthe Right triangle from user and to print the hypotenuse and area of the triangle. mageni” Senin ema oe semD EO Ga) 8 Oden oxcod Ew wy OWWOES QcHow ASO BED Ors DOOD are 00 GH Omd enios a0 oBaed ecioo Eadie. Input the base of a triangle as B Hypotenuse = VH? + B? Area=BxH/2 Print “Hypotenuse of the triangle”, Hypotenuse Print “Area of the triangle is", Area hypotenuse area = b*h/2 print ("Hypotenuse of the triangle is %.2f" % hypotenuse) print ("Area of the triangle is %.2f" tarea) Area of the triangle is 6.00 4.2 Selection Control Structures TEE a Tae) — Condition between IF and THEN IF THEN“ Statement(s) <——}—4 ENDIF | Otherwise the flow of execution continues 10 IE Marks > 50 THEN These statement(s) execute |@ Draw aflow chart, write a pseudo code and the Python code to read the marks of a subject from student and to print the grade as “Pass” if marks is greater than 50. Bexoqed Becom ent SOO Eat 500 HH 08 “Pass” seo Qesna B68 mem a8 dood Re, DO Gace Omd eddae 20 Bod eine ode. Drachman mee aroenker ‘#TP-THEN-ENDIF m=int (input ("Enter Marks: ")) if m> 50: print Pass") Condition must render a Boolean value (either TRUE or FALSE) IF TH Statement(s) <——t ELSE Statement(s) <——+ ENDIF | IE Marks > 50 THEN ‘~—} > Print “Pass” ELSE y——}-> Print “Fail” ENDIF ‘These statement(s) run when condition renders TRUE These statement(s) run when condition renders FALSE © Draw a flow chart, write a pseudo code and the Python code to read the marks of a subject of a student and to print the grade as “Pass” if marks is greater than 50 and otherwise “Fail” Geraned Beam ERG SOO ONe 50 Oc O8 “Pass” eqD ¢ Ded axtia® “Fail” ego Gcso 850 GE© oxBS DOoad ae 00 GacO Omd ecdoe a» oBad sina Eada. Peeteke ear ‘#1F-THEN-ELSE-ENDIF No mint (input ("Enter Marks: ")) Print “Fail” Se SU print ("Pass") else: print ("Fail") |: Nested if condition is used to make decisions when more than one condition exists in the given situation: + Nested if structure consists set of If Then ... End If structures. One conditional can also be nested within another. earstedS dmmd 0D: VHD qOdcOm & B55 HS qr If Then ... End If Ogo S8sex ease) OS® Bg emed. ZO. owa quiede nested qumdud Bay C128. le Wecanhaveanif...e1if...else statement inside another if...e1if...e1se statement This is called nesting in computer programming. In fact, any number of these statements can be nested inside one another. Indentation is the only way to figure out the level of nesting. This can get confusing, so must be avoided if we can, If Then Ifm < 40 Then Statement(s) 2 Else G="Weak If Then Else Statement(s) Else Ifm<50 Then If Then G=“Good” Statement(s) its Else o If Then Ifm<75 Then ie Statement(s) G="Very Good” \o s Else Bee a G="“Excellent” tatement(s) End If End if EndIf EndIf Endif . End If End If © In the following program, we input a number check if the number is positive or negative or zero and display an appropriate message. This time we use nested if 280 Brdadeed go BBS ened mda mddOo sons Ox om} sas oo} Dog 88 eno acre OOH EaNG G50 semQ. 68 qOdds6 & nested if MBM mE ord a. Garner M-=“Positive” Endif s Print “Number is”, M- End. ",M. ee een eet ener eee print the grade according the following conditions. Benoned Seacn 608) queda omededs jo ‘soe ee ao aoe 30 2238 od eins B68 mgm oS + 00-39 > Weak/d8e8 + 40-59 > = Good /esne® "60-74 > Very Good/ 9m eme8 e015 > — Excellent/®8808 Flo Eeeterrerre 60<40 OR ‘60>100 * 75<40 oR 75100 * |75 < 40 *|75 < 60 ¥|75 < 75 ® 150<40-OR 150>100 ¥ ero Grae elif m< 7! Grade = "Very Good" else: # range is 75-100 Grade = "Excellent" print ("Grade is %s" %Grade) 4.3 Iteration/Repetition Control Structures start TO end [STEP step} ‘Computer FOR counter FOR counter = 1 TO 5 Computer statement(s) Print “Computer” Computer m Computer NEXT counter NEXT counter Conntten |e: Repeats a group of statements a specified number of times. 83d cm quien £0 gmon Quad gndmdee oD Part ‘Description counter | Numeric variable used as a loop counter which is the control variable for the loop. It is required in the For statement. For loop sca S89 agen counter BOCs erg OBO gersOar oD. ‘start Tnifial value of counter. Required. Numeric expression. counter BOcne agin edastOm ASC md2um ous gaxdar ed. end Final value of counter. Required. Numeric expression. Counter Besa mews edmtOm Sc cdast eoast qasdan od. step ‘Amount counter is changed each time through the loop. Ifnot specified, step defaults to one. The step argument can be either positive or negative godmdese Om 60 counter 6 gow oboe! ob. step squat © em n® oat om OS eO8zF counter Bene 08 cos obs 95 oF. © Positive or 0 > counter <= end step qoa Om BScos ont gars Oates! n® counter BWqueaB gow gdust gawd BOs QO ood Bs @D. © Negative > counter >= end step qo mes HSeas Oster! n& counter HOeuead qos eOesst goo OB Bane end WO od. ‘statemeni(s) | One or more statements between For and Next that are executed the specified number of times. For eo Next gad a8 gma ome ons SGcas aquet m6 gH quinn 0:5 aims csOdn ©. _ |© Draw a flow chart, write a pseudo code and the Python code to print the integer numbers from I to 5 and print “Good Bye!” finally. 180 5 ESO) a SBE GoOm Bema 26 FOmeed “Good Bye!” eee Bowe G68 og oxb8 edeed qe 50 gaden Omd eins oo Saad edioo Goda. “print (c) print ("Good Bye!") # out of for loop ear ear ee eae) aie! Ne DIOR TON eT es user and to print the maximum number of them. - FO] GES GOD SHoad SOM Haren © mom Beira G58 sew axG8 nOowd owe, 50 qyceo Bad eddoo an OBnd eddoo Gaeia. Hand Tracing Table Print “The largest number is”, Max End nuke # Finding Max Max =n” print ("The largest number is %d" %Max) # Output Max ‘These statement(s) DO WHILE execute when condition | 0 Computer renders TRUE. | | DO WHILEn<5 Computer Statement(s) <————++# fcondition is FALSE, *}—— Print “Computer” Computer i ' =n+1 ‘Computer ENDW: it skips all the statement(s) | us “cae inside th | | ENDWHILE ‘Computer [ESREZ PRAT © These statemen(s) | [ERB | are executed at least once, | | n= 0 Oo then check the condition; }| Ho loop can execute, while} li 5 3 * Statemeni(e) <————}4 Nana enden TRUE. Tht oo ‘ Ifcondition is FALSE, eae LOOP WHILE < > os condition terminate the loop. __} | LOOP WHILE n<5 |© Draw a flow chart, write a pseudo code and the Python code to print the integer numbers from 1 to 5 and print “Good Bye!” finally: 180 5 EXO) gO BB@ mods Besa md gamed “Good Bye!” e@o Gotra G68 oem aS edsad que 00 aad OM saino oo oBnd exinc Basa. mo an End le print (n) ores n=n+i # counter variable print ("Good Bye!") # out of loop print ("Good Bye!") [Sie statements ition> |{ execute while condition ||" =0 Computer, DO UNTIL |; "tenders FALSE. || DO UNTIL n=5 Computer Statement(s) <——6 Ifthe condition is TRUE, 4+—> Print “Computer” Computer’ it skips all the statement(s) n=n+1 Computer LOOP inside the loop. LOOP ‘Computer [SEAT SSESELOA These statement(s) are executed at least once, ! | n = 0 REPEAT : ane fies ances ames |] EPEAT etre Statemeni(s) ——t csration renders PALSE.¢] > Print “Computer” Computer UNTIL ee ROR eee ee | terminate the loop. | UNTIL n=5 Computer Computer and print “Good Bye!” finally. edad ace 50 QCD OMS exons aw oBad exine Base. pridt(n) nenti n=ntl print ("Good Bye! © Draw a flow chart, write a pseudo code and the Python code to print the integer numbers from 1 to 5 180 5 edO> GeO GB som Acta m6 GOme~ed “Good Bye!” sew Gets G58 wEm axGB PLUSmin cnc mn # counter variable ¥ out of loop

You might also like