0% found this document useful (0 votes)
2 views28 pages

Unit-1 Program Logic Development

The document covers the fundamentals of algorithms, including their definition, properties, and importance in problem-solving. It discusses algorithmic problems, flowcharting, and the analysis of algorithms, including efficiency and asymptotic notations. Additionally, it explains various time complexities and provides pseudo-code conventions for algorithm development.

Uploaded by

harshalthete12
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
2 views28 pages

Unit-1 Program Logic Development

The document covers the fundamentals of algorithms, including their definition, properties, and importance in problem-solving. It discusses algorithmic problems, flowcharting, and the analysis of algorithms, including efficiency and asymptotic notations. Additionally, it explains various time complexities and provides pseudo-code conventions for algorithm development.

Uploaded by

harshalthete12
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
NIT-I g a PROGRAM LOGIC DEVELOPMENT 1.1 Fundamentals of Algorithms : Notion of an algorithm. Pseudo-code conventions like assignment statements and basic control structures. 1.2. Algorithmic Problems : Develop fundamental algorithms to solve simple problems such as : (i) solve simple arithmetic expression, (i) find the greatest of three numbers, (i) determine whether a given number is even or odd, (iv) determine whether a given number is prime. 1.3 Flowchart : Flowchart, Symbols of flowchart, Guidelines for preparing Flowchart. * Practice Questions © We solve problems every day, often unaware of the process we are going through. «Ina leaming environment, we usually are given most of the information we need. ‘* A clear statement of the problem, the necessary input, and the required output. ‘© Inreal life, the process is not always so simple. © We often have to define the problem ourselves and then decide what information we have to work with and what the results should be. © As we understand and analyze a problem, we must come up with a solution normally known as algorithm. « Algorithm is a step-by-step procedure for solving a problem in a finite amount of time with a finite amount of data, © Although we work with algorithms all the time, most of our experience with them is in the context of following them. «In the problem-solving phase of computer programming, We will be designing algorithms, not following them. © This means we must be conscious of the strategies we use to solve problems in order to apply them to programming problems. Algorithmic Problem Solving : * The programmer begins the programming process by analyzing the problem, breaking it into manageable pieces, and developing a general solution for each piece called an algorithm. 71 y ra Program Logic Developmen in Comp. Engg. Sem. i ing nC (FY. Dp. Pogo i the pieces are collected together to form a program that ial the original Problem, PAN sGeibs va catia Ea description ofa logical sequence of actions applied to objects Rey te are all examples of algorithms that are not programs, re Satan using algorithms are efficiency, abstraction and reusability. Ma eects = of problems, like sorting, oocur often in computing. Efficient algorithms ° aaa sone problems considering the time and cost factor involved in each algorth, . iste Si ApoE provide devel of abstraction in solving problems ag many seemingly complicated problems can be distilled into simpler ones for which well known a gorithms ° Es we Sc 8 more complicated problem ina simpler light, we can think ofthe simpler problem as just an abstraction of the more complicated one, For example, imagine trying to find the shortest way to route a packet between two gateways in an internet. * Once we realize that this problem is just a vatation of the more general shortest path problem, we can solve it using the generalised approach, Reusability : Algorithms are often reusable in many different situations, Sins: many well-known algorithms ae the generalizations of more complicated Ohes, and since ‘any complicated problems can be distilled into simpler ones, an efficient means of. Simpler problems potentially lets us solve many complicated problems, Benefits of using Algorithms : * The use of algorithms provides a numberof benefits, * One ofthese benefits isin the development of the procedure itself, which involves identification of pi Processes, major desision pont, and variables necessary toe the problem, Developing an algorithm allows and even forces ®xamination of the solution process in a rations manner, Identification of the processes and more manageable size, : Prien tt onl Pe dificult or impossible to Solve in entity ean be approached as a series of small, solvable sub-problems, ° By using an algorithm, decision making becomes a more rational Process, * In addition to making the Process more rational, use of algorithm will make the process more efficient and more consistent, Efficiency is an inherent result ofthe analysis and specification Process, * An algorithm serves as a mnemonic device and helps ensure that vari b aot Ips ‘ariables or parts of the problem * Finally, separation of the procedure Steps facilitates division of labour and development of expertise. * A final benefit of the use ofan algorithm comes from the improvement it makes Possible, solving certain decision points Teduces the task into a series of smaller Steps of 1.1.4 Notion of Algorithm * An algorithm isin fat a method op *rstipe for obtaining a desired result. Se Tae) = Por © Analgorithm presumes : 3 . ‘i set % eect that abstracts the context of the solving problem. ._ A set of transformation relati i Cee ae 3, A set of expected results or final data that are obtained as result of applying the transformation relations over the initial data, passing through a sequence of intermediate information (results). Analgorithm has the following proprieties : 1, Generality : An algorithm doesn’t solve only a certain problem, but a generic class of problems of the same type; 2. Finitude : Final information is obtained from the initial one, passing through a finite number of transformation steps; 3. Uniqueness : The transformations and the order in which they are applied, are only (in a unique manner) determined by the algorithm’s rules. ‘Consequence : Whenever the same algorithm is applied to the same set of initial data, the same results are obtained. Algorithms Analysis : © Why algorithms analysis is useful for? Permits to specify in a predictive manner the algorithms’ behavior. ‘Analyzing different algorithms which solve the same problem, the proposed solutions can be compared and the skill and the experience of the developers can be ranked. Algorithms Analysis is based on some explicit assumptions : 1. The computing systems are considered as “conventional one program are assumed to be executed one at a time. 2. The total execution time of an algorithm is determined by summing the times of the indiv: ‘idual required instructions. In general, the analysis of an algorithm is achieved in two steps : 1, Thea priori analysis : > Presumes the assessment from temporal point of view of the used operations and their .” that means the instructions of relative cost. > Ina priori analysis, the result is a function (of some relevant parameters) Which bounds the algorithm’s computing time. 2. Thea posteriori testing supposes the following step’ }> Establishing a convenient number of sets of input data, behavior possibilities of the algorithm. > Executing the algorithm for each input set and collecting ‘actual statisties about algorithm’s consumption of time and space while itis executing, > Build the algorithm's profile - the precise amount of time and storage the algorithm ‘consumes. Constant of fastest growing term is insignificant : © Complexity theory is an Approximation theory. © We are not interested in exact time required by an algorithm to solve the problem. Which presumably cover all the wal _—_ a rogram Logic Development Programming in’C’ (FY. Dp. in Comp. Engg. Sem. I) is ‘ ymputer that + Rather we are interested in order of growth i.e. how much faster will algorithm run on comp is twice as fast? P * How much longer does it take to solve problem of double input size? TERE he wo * We can crudely estimate running time by T (n) © Cop *C Dae ree APVARO OPER ns as « function of n, Cop : running time of a single operation, C (n) : num function of n, Worst-case, Best-case, Average case efficiencies : * Algorithm efficiency depends on the input size n. * Forsome algorithms, efficiency depends on type of input. * We have best, worst and average case efficiencies. Mesetincer the basic operation wil be executed) for the worst case input of size n, ie, The algorithm runs the longest among all possible inputs of size n. efficiency : : ; 3} Besa as of times the basic operation will be executed) for the best case input of size n, ie, i fastest among all possible inputs of size n. : . Aer Average iia taken (number of times the basic operation will be executed) to solve all the possible instances (random) of the input. . Asymptotic Notations . * Asympiotic notation is @ way of comparing functions that ignores constant factors and small input sizes. * Itis order of growth of the running time of an algorithm, * Gives. simple characterization of the algorithm's efficiency, * Allows us to compare the relative performance of alternative algorithms, * The study of the asymptotic efficiency of algorithms means to use at input sizes large enough to ‘make only the order of growth of the running time relevant, “We are concemed with how the running time of an algorithm increases the size of the input increases without bound, * Usually an algorithm that is “asymptotically more efficient” will be the best choice for all but very ‘small inputs. * Three notations used to compare orders of growth of an algorithm’ Big Omegs-O notation ; > A function t (n) is said to be in Q (g(n)), Some constant multiple of g (n) for alll Some nonnegative integer no such that t(n) > cg(n) for all n> no, Big Theta-@ notation ; » A function t (n) is said to be in 6 (g (n)), denoted 1(n) € 8 (g (n)), ift (n) is bounded both above and below by some constant multiple of g (n) for all large n, ie,, if there exist some positive constant e1 and ¢2 and some nonnegative integer no, such that i ©2.8(n) n0. > Here is a list of classes of functions that are commonly encountered when analyzing algorithms. > The slower growing functions are listed first. c is some arbitrary constant. Notation name oa) constant O(log(n)) logarithmic ‘O((log(n)) ©) polylogarithmic On) linear O(n?) quadratic 0’) polynomial O(c") exponential Constant time : The following operations take constant time : + Assigning a value to some variable. + Inserting an element in an array. + Determining if a binary number is even or odd. + Retrieving element i from an array. + Retrieving a value from a hash table(dictionary) with a key. + They take constant time because they are “simple” statements. + Inthis case we say the statement time is O(1) int example = 1; Linear time : O(n) + The next loop executes N times, if we assume the statement inside the loop is O(1), then the total time for the loop is N*O(1), which equals O(N) also known as linear time : for (int i= 0; i heapsort > merge sort > Quick sort for(int = 0; i end if * The ease-of construct defines a multi-selection that is based on the value of an arithmetic expression, To clearly indicate which control branch is executed, we require that the branches are labelled with disjoint, constant-like values. Unlike in some programming languages, the control does not flow from one branch to another. A label others can be used to indicate the branch “any other value not mentioned’, Ifthe selection expression returns a truth valle, we prefer the if-then-else structure. 1: case expression of 2: constant0 tarement) Control branch for value constant0, 3: constant! ; statement 4s 5: others : default statement 6 end case 1Fnone of the branching labels match with the exy ‘pression, the control moves directly to the next statement following the case-of structure. Repetition : ¢ To iterate siatements, we introduce one definite loop structure and two indefinite loop structures. The definite loop is called for-do structure and itis used when the number of iteration cycles can be calculated before entering the loop body. a : 1° for iteration 2: statement 3:end for The iteration st: Variable v that Statement do 'atement has ‘Wo variants, First, it can represent an ‘enumeration by j in Y introducin, a ets values Sequentially from a Siven range Bejive fo. tlie. the initial ie *'8fand the final vatue iss), ra * Second, the iteration Statement can Tepresent a Sequential member Selection o vec . Ver a collection C all This loop Variant bounds ¥ once to each me lember of C in an Unspecified or Cannot be changed until the loop is finished, AS an example of the Aiference between these two for loops, sequence S of m values, * We denote the ith Problem is to defin lieu 50 fori 1. 3(n—1) do €c Display a is the largest number. Else Display c is the largest number. Else Ifb>c Display b is the largest number. Else Display c is the greatest number. Step 5: Stop 3. Write an algorithm to find all roots of a quadratic equation ax*+bx+c=0. Step 1: Start Step 2: Declare variables a, b, c, D, x1, x2, rp and ip; Step 3: Calculate discriminant D-—b2-4ac Step 4: If D>0 rl-(-b+YD)/2a 12(-b-YD)/2a Display rl and r2 as roots. Else Calculate real part and imaginary part 1pb/2a ip-\(-D)/2a Display rpti(ip) and rp-j(ip) as roots Step 5: Stop Write an algorithm to find the factorial of a number entered by user. Step 1: Start Step 2: Declare variables n,factorial and i. 2, = Progremming in ‘©’ (F.Y. Dip. in Comp. Engg. Sem.) 4-14 Program Logie Development Step 3: Initialize variables factorial—1 ic} Step 4: Read value ofn Step 5: Repeat the steps until i=n $.1: factorial—factorial*i 5 itl Step 6: Display factorial Step 7: Stop 5. Write an algorithm to check whether a number entered by user is prime or not. Step 1: Start Step 2: Declare variables n.i,flag. Step 3: Initialize variables flag—l ic? Step 4: Read n from user. Step 5: Repeat the steps until i<(n/2) 5.1 Ifremainder of n+i equals 0 flag—0 e Go to step 6 $.2icit] Step 6: If flag=0 Display n is not prime else Display n is prime Step 7: Stop : 6. Write an algorithm to find the Fibonacci series till term1000. Step 1: Start Step 2: Declare variables first_term,second_term and temp. Step 3: Initialize variables first_term--0 second_term—~I Step 4: Display first_term and second_term Step 5: Repeat the steps until second_terms1000 5.1: temp-second_term 5.2: second_termesecond_term+first term 5.3: first_term-—temp 5.4: Display second_term Step 6: Stop Algorithm is not the computer code. Algorithms are just the instructions which give clear idea to yo" idea to write the computer code, Programming in‘ (FY. Dp. Comp. Engg, Sem) 4-18 1.3 FLOWCHARTING ¢ A flowchart is a type of diagram (graphical or symbolic) that represents an algorithm or process, + Each step in the process is represented by a different symbol and contains short description of the process step. Program Logi * The flowchart symbols are linked together with arrows showing the process flow direction + A flowchart typically shows the flow of data in a process, detailing the operations/steps in a pictorial format which is easier to understand than reading it in a textual format + A flowchart describes what operations (and in what sequence) are required to solve a given problem, + A flowchart can be linked to the blueprint of a building. As we know, a designer draws a blueprint before starting construction on a building, Similarly, a programmer prefers to draw a flowchart prior to writing a computer program. + Flowcharts are a pictorial or graphical representation of a process. © The purpose of all flowcharts is to communicate how a process works or should work without any technical or group specific jargon, + Flowcharts are used in analyzing, designing, documenting or managing a process or program in various fields. © Flowcharts are generally drawn in the early stages of formulating computer solutions. * Flowcharts often facilitate communication between programmers and business people. © 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 © 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 igh level language. program. 1.3.1 Flowchart Symbols and Guidelines usually drawn using some standard symbols, however, some special symbols can also hhen required. rd symbols, which are frequently required for flowcharting many computer programs tor : An oval flowchart shape indicates the start or end of the process, usually containing “Start” or “End”. gular flowchart shape indicates a normal/generic process flow step, For example, “Add 1 to “M = M*F” or similar. Process ; wail ay A ai ang! a | y Programming in ‘© (FY. Dip. in Comp. Engg. Sem. fl) 1:16 Program Logic Development Decision : * A diamond flowchart shape indicates a branch in the process flow. This symbol is used when 2 decision needs to be made, commonly a Yes/No question or True/False test. & * A small, labelled, circular flowchart shape used to indicate a jump in the process flow. * Connectors are generally used in complex or multi-sheet diagrams. Connector Data: ‘= A parallelogram indicates data input or output (1/0) for a process. Examples: Get X from the use: Display X. Delay = . to indicate a delay or waitin the process for input from some other process. Arrow: _ Used to show the flow of control in a process. An arrow coming from one symbol and ending » another symbol represents that control passes to the symbol the arrow points to. — Working with Flowchart : Example : Draw the flowchart to calculate volume of cube. ing to our sample problem, we need to take in three items as input (length, width, and heis: we have the user's input, need to process it, fi a ne os hope pt. Programming iC’ (.Y. Dip. in Comp. Engg. Sem.) 4-17 Progen Ot * Now, since our processing is complete, we should display the output for the user. Get user input (length, width, height) Multiply length, | width, height 1.3.2 Pseudocode © The final step in analyzing our problem is to step from our flowchart to pseudocode. Pseudocode involves writing down all of the major steps you will use in the program as depicted in your flowchart. © This is similar to writing final statements in your programming language without needing to worry about program syntax, but retaining the flexibility of program design. * Like flowcharting, there are many elements to pseudocode design, only the most rudimentary are described here. Get used to get information from the user Display _used to display information for the user Compute _ perform an arithmetic operation + ° Standard arithmetic operators / O Store Store a piece of information for later use © Itis important to note that each time you compute a value that you will need later, itis necessary to store it even if you will need it right away. * Here is the pseudocode for our example, © Itmay be helpful to write out your pseudocode next to your flowchart, * Now, on your own, work through the three steps of decomposition, flowcharting, and pseudocode following example. ‘>? i Program Logic Developm. 1 In Comp. Engg. Sem.) aa ae id oranges. Oranges are Rs 10 each and lemons are Rs 1 pa 4 You have a store that sells lemons and or ea anges anal lemons he/she wants and outpuis the ton program should get from the user the numbers amount of money they owe you. Get user length, width, height input (length, bene aa width, height), length * width * height Store volume Display volume Multiply length, width, heig Display Result (volume) 1.3.3 Solving Problems with Solutions Requiring Selection i: * Upto this point, you have solved problems with solutions which were strictly linear in nature, sequential. / * ‘Another words, from the start 10 the end of your pseudocode (or flowchart), each line (or figure other yi ‘heflowchart) is executed once, in order. * However, this raises one important uestion : What happens if a problem Tequires a solution that ho alternate paths through the Pseudocode depending on the input? * How can make a particular line (or block) of pseudocode optional? Consider the following : * Write a program that wil) Accept as input from the user, an answer t0 the following question « |s raining? If is is raining, tell the user to 8etan umbrella, e Currently, we have not covered anything in problem Solving that can help us handle Conditions lik: Ifit is raining” * Fortunately, we ar¢ not left out in the cold and the rain; making, there is a Concept known as logical decision: mposition - When to use logical decision-making ; This relatively tri vial to identify when tou imply Put, wheney identify BUch situa: | You ean decipher sin 9 problem Statement, you first look for when this condit T cues. From these cues 4 lon tered ion is tue oe si the decision wilt be based on, and the actions that will be taken Programming in‘C’ (FY. Dip. in Comp. Engg. Sem.) 4.18 These cues may be obvious : [fit is raining, then tell user to get an umbrella Condition : If it is raining Action ; Tell the user to get an umbrella or they may be subtle. © Based on the temperature, either tell the user to bring a heavy jacket (colder than 32 degrees), light jacket (between 32 and $0 degrees), or no jacket at all. Condition : If the temperature is less than 32 degrees ‘Action : Tell user to bring a heavy jacket Condition : If the temperature is between 32 and 50 degrees Action ; Tell user to bring a light jacket Condition : If the temperature is greater than 50 degrees Action : Tell user not to bring any jacket ¢ Note, for the more subtle cues, look for cases; they are usually constructs that can be reworded into if statements. In the above problem statement, you have three cases : if temperature is less than 32 degrees, if itis between 32 and 50 degrees, and if it is above 50 degrees. It may be helpful to make a cursory sketch of all of the decisions you will need in your program before you go any further. For instance, an initial sketch of our sample problem yields the following Yes_____ Bring an umbrella Is it raining? No «Note : our program description did not tell us what to do ifthe user says it is not raining, therefore, ‘we do not put anything in the “No” branch of our decision. ‘After we have made cursory sketches of all of the decisions in our program, ‘move on to flowcharting. helpful as it helps the : © Drawing a flowchart for a program containing logical decisions is quite programmer see the “big picture” - how all of the decisions interact and affect each other, For decision-making, we have a brand new flowcharting tool, the diamond, “question” being asked goes inside the diamond. An arrow for we can immediately * Diamond (used for decisions). The each “answer” protrudes from the diamond, Mark each of these arrows with the appropriate “answer,” © The decision diamond in your flowchart should look very much like the rough sketch of your im '* The full flowchart for our example is below. ask user if itis raining: [roll user to get ‘an umbrella. curs if the user answers “no” to “is sketch, nothing of note 0c Note : Just Like in our rough to the actual implementation of th construct in our programming Most decisions will begin with the The general structure of a decision The pseudocode for our example is below, operative word if, as all decisions must be declarative statements. should make sense in your mind; if it is raining, get an umbrelle ‘matched with our flowchart for clarity. Ask user if itis The following isthe pseudocode tell the and flowchart for a modificati ‘ser to get an umbrella, Otherwise, say it is sunny, fication of our exanapte.s it ts rain: The extension of this in our flowchart is trivial, we simply do someth n\ ; 1 concept jomething with the “n° ‘The only change is in our e, f Pseudocode, we have added the else, or condition not true, case. If it is raining, tell user to get an umbrella... else tell the user that it is 5 junny. Programming in‘C"(F.Y. Dip. in Comp. Engg. Sem. I) 4:24 Program Lope Deel 's yoo Display “Get an umbretia” Display “itis sunny” ‘* Now, on your own, work through the three steps of decomposition, flowcharting, and pseudocode for the following example. Given 2 numbers, determine whether or not their sum is greater than 100. Conditions : ‘* Most programming languages provide the following relational operators (sometimes with slightly different syntax) to make mathematical comparisons between data within your conditions > greater than o less than >= greater than/equalto 9 <= less than/equal to = equal to I= not equal to ‘* Also, the following logical operators (or similar) are usually provided : && and || or ! not * Though the relational operations (>, >=, etc.) are self- explanatory, the and, or and not operations deserve a brief explanation. * Both and and or allow you to create compound conditions. And implies that a condition is true only ‘if all of its components are true. * Or implies that a condition evaluates to true if any of its components are true. ‘* Not reverses the truth value of a condition. This will be discussed in greater depth later * All conditions in computer programming must evaluate to a Yes/No (or True/False) question, * You cannot, for instance, have a condition which branches like this : 4, «197 Oe to drive ‘What is your age? <—1&- Better clear the road tine ta > 18. You are getting pretty od You cannot do that in a single condition in w program! . Computers only understand two things : 0 and |... true and false, , we can rewrite all conditions into a string of Yes/No questions. The Kbove'd can be {nto the following : " — . Programming in © (F.Y. Dip. in Comp. Engg. Sem.) 1-22 Program Logi Develop. What is your age" — Is Age < 167 M2 Is Age = 167 2 You are getting pretty old [yes |ves ‘Too young to drive Better clear the road Notice that the “> 16” case does not appeat in the conditional expression (if a number is not less tha; 16 and does not equal 16, it must be greater than 16) . Because of this obvious consequence, our flowchart and pseudocode do not have to explicitly sta: ‘the final case. * This is known as the default case. Again, a flowchart an its resulting pseudocode should be relatively easy to discern from the abc picture. ‘= Note the default case explained by the final ELSE in the pseudocode. If neither of the above if statements are true, the else is invoked by default. Furthermore, this if - chain is mutually exclusive. 1n other words, if one condition is true, none of the following conditions are tested. This is c from the flowchart, In the case where multiple conditions would be true, your flowchart would look much differe- Instead, you worked with aah a tc Programming in‘C(F.Y. Dip. n Comp. Engg. Sem.) ties ea «However, this simple execution (where the only deviati “path” is 7 hae. a Oats ss egg capella paras have covered thus far. ae ae Consider the following : © Write a small program that will display the numbers 1 - 10. Using the knowledge you current! possess, you would most likely write a program that uses individual lines of code that print out oa number. «The pseudocode for such an answer looks like this : Display 1 Display 2 Display 3 Display 4 Display 5 Display 6 Display 7 Display 8 Display 9 Display 10 «As far as code-length goes, programming such an application is indeed possible. However, what if the problem statement was modified thusly : Write a small program that will display the numbers 1 - 100. Ifyou had not guessed it before, you should know at this point that a good programmer would never vite (nor want to write!) an application made up of 100 lines, each saying display x. Indeed, there must be a way to avoid the repetition. Like any good tool, most programming languages provide us with a quick and easy way to solve such problems: iteration, also known as loops. Decomposition - Identifying the need for a loop. © Before we approach what the structure of a loop looks like, it is important to present the types of situations that you will encounter that will lend itself well to iteration. «Stated simply, one should use a loop at any point where you wish to repeat & process idea, or function. + For example, see if you can determine which of the following problems might be best solved using a Joop : 1. Solving the equation 2x? + x + 5 for all x between 5 and 10 2, Summing inputted integers until the user enters «1 rear, Your program computes the users 3, The user enters in the current year and then his/her birt y' age. Perform this task again if he or she wishes. «Trick Question! The answer is all of them. Let's briefly overview each problem to see why a loop would be necessary. Solve the equation 2x” +x +5 for all x between 5 and 10. a all a “Programming in ‘C'(F.Y. Dip. in Comp. Engg. Sem. i) 4:24 Program Logie Developme, - asl * This problem is very similar to the one we were approached with at the beginning of this section ; © Instead of writing the code which computes 2x? + x + $ six times (one for each of the followin x=5, 6, 7, 8, 9, 10), we can say repeat this equation for each of the values of x. Summing inputted integers until the user enters -1. * Without loops, this program is impossible : In essence, (wit infinite number of read statements all in a row to perform this task. ' * Instead, we notice that as long as the user has not entered —1, repeat the addition and read statement. © Remember, always look for indications that you will be repeating something. The user enters in the current year and then his/her birth year. Your program computes the user age. Perform this task again if he or she wishes. * This is a less intuitive use for loops. On the outside, it appears you are only performing ue task finding out the mumber of years the person has been living. However, you'll notice by reading «h problem statement carefully that, if the user chooses, you should run the program again. ‘© _Inessence, you will be repeating your entire program. In this case, the “something” that you will repeating is not a single statement or equation, but a large block of code. Flowcharting and Pseudocode : ‘© Loops are quite powerful : they allow us to do a massive amount of work with a minimal amount « programming. * Amazingly, there is no need to learn any additional structural tools in order to think about loops. * You have everything you need to know already at hand. If you are comfortable with logic: decision-making, iteration should be easy. ‘+ Let's create # flowchart for the problem A (Solve the equation 2x? + x + 5 for all x between 5 a". 10). * The first task is to step back from the problem and plan how you would like to attack it. * After you have devised this general plan of attack, you may proceed with the flowcharting 3 pseudocode. * Consider very carefully how you approach such a problem on a high-school mathematics exam. * Your program should take x and start it at 5, Next, substitute 5 for each value of x in the equativ (215) + (5) + 5) and then solve (answer = 60), take the next x, which is obviously 6 ($+ 1), Solve the equation for x = 6 and continue on. st value of x you will do this for is 10, wwe know how to approach the problem, let’s sketch it out, We will discuss the flowch." code in detail for this first example, different about this flowchart compared to others we have studied i ee pce execution path will lead you, not farther into the ‘program so (note that after you “add 1 to x” you proceed back to the decisio” hout loops) you would need to have a: Programming in‘ (F.Y. Dip. in Comp. Engg. Sem.) 4:25 Prope Logis When we hit the return statement in the pseudocode, we only repeat those lines that have been indented (note that we do not repeat “set x = 5”). Note that instead of an if statement, we are making a decision using the term while. In the pseudocode, while indicates that we will be repeating a certain chunk of code (that which is indented) until the condition (in this case “x <= 10") becomes false. Once this condition becomes false, we skip all of the indented code. In other words, when x = 11 we skip to the quit line. (sear ) Set x105 White x <= 10 Compute 2x° +x +5 Store answer Print answer Increment x Return to While Statement ‘Quit Compute 2x + x +5 1.3.5 Advantages of Using Flowcharts The benefits of flowcharts are as follows : Communication : Flowcharts are better way of communicating the logic of a system to all ‘concemed, Effective analysis : With the help of flowchart, problem can be analysed in more effective way 3. Proper documentation : Program flowcharts serve as a good program documentation, which is needed for various purposes. Efficient Coding : The flowcharts act as a guide or blueprint during the systems analysis and Program development phase. Proper Debugging : The flowchart helps in debugging process. 6. Efficient Program Maintenance : The maintenance of operating program becomes easy with the ne ke ga help of flowchart. It helps the programmer to put efforts more efficiently on that part. aad “Programming n'C’ (FY. Dip. n Comp. Engg. Sem.) 428 Program Logi Deveoye, f 1.3.6 Limitations of Using Flowcharts | ‘© Although a flowchart is a very useful tool, there are a few limitations in using flowcharts which ar. listed below : 1. Complex logic : Sometimes, the program logic is quite complicated. In that case, flowchar becomes complex and clumsy. 2. Alterations and Modifications : If alterations are required, the flowchart may require re-drawing completely. 3. Reproduction : As the flowchart symbols cannot be typed, reproduction of flowchart becomes problem. ! 4. The essentials of what is done can easily be lost in the technical details of how it is done. © Draw a flowchart to add two numbers entered by user. Declare variables num1, num2 and sum Read num1 and num2 sum

You might also like