Loading...

Messages

Proposals

Stuck in your homework and missing deadline? Get urgent help in $10/Page with 24 hours deadline

Get Urgent Writing Help In Your Essays, Assignments, Homeworks, Dissertation, Thesis Or Coursework & Achieve A+ Grades.

Privacy Guaranteed - 100% Plagiarism Free Writing - Free Turnitin Report - Professional And Experienced Writers - 24/7 Online Support

Nested for loop flowchart example

18/11/2021 Client: muhammad11 Deadline: 2 Day

Loop statements

IV. Nested Statements

We have already seen examples where one conditional statement is nested inside another. In this section, we will consider more examples of nested statements. Two of the most common examples are nested for statements and conditional statements nested inside while loops. Other combinations of nested statements also arise in practice, but if you master the two we consider here, you will be able to deal with whatever life throws at you!

A. Nested for Loops

Nested for loops occur in processing multidimensional arrays. The typical structure of such loops is shown below. If you trace this code, you will get a good idea of how nested loops work. We have deliberately kept things simple. The inner loop's body has just one statement (the output statement), and the only statement in the body of the outer loop is the inner for statement. No braces are therefore necessary in the body of either loop.

For i = 0 step 1 to 4 //outer(i)loop For j = 1 step 2 to 6 //inner(j)loop Output i, j End for //inner(j)loop End for //outer(i)loop

Trace through the code in the following example to see how nested for loops are executed.

Points to note:

· The inner loop will be executed completely (i.e., as many iterations as required) for each single iteration of the outer loop. In the example above, the inner loop executes three times ( j = 1, 3, 5). The values taken by i in the outer loop are 0, 1, 2, 3, and 4. But for each of these values of i, the inner loop executes three times. Thus the total number of lines in the output will be

5 * 3 = 15

The sequence of numbers that are output will show the values of i and j at each step.

· It is necessary to ensure that the two loops use different loop indices. What would happen if the inner loop also used i as the index ?

Here is a somewhat more complicated example that illustrates the use of nested for loops. Suppose you are asked to write a program that prints the following output:

1

1 2

1 2 3

1 2 3 4

1 2 3 4 5

How would you do this task? Naturally, we reject the obvious solution , which does not use any loops! You should stop here and try to do this problem on your own (give yourself plenty of time) before reading further. Then look at our solution to the problem using nested for loops .

Exercise: Before you go on, do this code analysis exercise involving nested for loops .

B. Nested Conditional Inside Loop

As an example of synthesizing code that will have a conditional statement inside a while loop, we will write a program that mimics tie breakers in tennis. If both players have won six games apiece in a set, a tie-breaker set may be played. The first player to score seven or more points, while also leading by two or more points, wins the tie-breaker set.

We will assume that the players are called A and B. Because a program can't play real tennis (yet!), you, the user, will simply tell the program who won the next point.

We solve this problem by talking our way through to the solution. Click on the Next button in the example below to see how we arrive at the final solution in a sequence of logical steps where each step builds on work done in the previous step. What we write in the first few steps is not proper pseudocode—we are slowly feeling our way to the final solution, and it is okay to be imprecise during the intermediate steps—but the final product should be precise!

https://umuc.equella.ecollege.com/file/6ceaae77-7100-45ad-bb64-de4d87f024da/1/CMIS102-1302.zip/Modules/M3-Module_3/resources/3-17%282%29/images/code1.png

https://umuc.equella.ecollege.com/file/6ceaae77-7100-45ad-bb64-de4d87f024da/1/CMIS102-1302.zip/Modules/M3-Module_3/resources/3-17%282%29/images/expl1.png

Check out the code by supplying various sequences of points won by A and B in the interactive example below. As the saying goes, the proof of the pudding is in the eating…

Exercise: Before you go on, do this code analysis exercise involving the while loop

III. Loop Statements
In programming (and in cooking!), we must often repeat certain actions until a desired condition is achieved ("stir the mixture until a smooth consistency is obtained"). To address this need, "looping statements" were created. The name arises from the flow charts of these statements, which show a loop indicating that one must go back and perform the same sequence of operations until something happens that allows one to stop.

We have one loop statement (the for statement) when the number of iterations is known in advance ("rinse your hair with water three times"). The other (the while statement) is used when this number is not known in advance ("stir until smooth").

Mastering the hows and whys of the while and for loops is an absolute necessity for all students of programming.

A. The while Loop
The diagram below will help you to understand the different components of a while loop. Be sure to trace through both the true and false paths to see how it is executed.

Points to note:
· If the loop test fails at the very beginning, none of the statements in the loop body will ever be executed. Thus, we can say that a while loop executes 0 or more times.

· The only way to break out of the loop is if the Boolean expression evaluates to false.

The while loop shown above will be written in C++ or Java as follows (we assume the Boolean expression is i <= 10):

while ( i <= 10 ) { ... }

Note that there is no End while marker, and that there is no semicolon after the closing parenthesis.

We will use Euclid's Algorithm for the greatest common divisor (GCD) of two positive integers to showcase a while loop. Of course, Euclid did not state his algorithm in exactly the terms we use below—his algorithm was couched in terms of lengths of line segments. His algorithm appears in Book 7, proposition 2 of The Elements.

The algorithm is mathematically sophisticated, and it is not obvious how or why it works, but at this level you do not have to understand the algorithm. However, you should be able to trace through it.

Notice how we have used blocks inside the if-then and the while statements. Also notice that if x is >= y initially, the if-then statement will not execute.

Now trace through the algorithm in the following example, using the values we suggest. Then try some input values of your own.

Infinite Loops
Recall that the only way to break out of a while loop is if the Boolean expression evaluates to false. If the expression never evaluates to false, then one is stuck in an infinite (i.e., never-ending) loop!

There are an infinite number of ways in which to create infinite loops using the while statement. Look at each of the following examples of infinite loops and try to understand why the loop will not terminate. Then look at our answer to confirm if your reasoning was correct.

While (true) { … anything here… } End while

i = 0 j = 0 While (i == 0) j = j + i End while

i = 0 j = 0 While (i == 0) j = i i = i + 1 i = j End while

Answer

Answer

Answer

Code Synthesis Using the while Statement
To demonstrate your mastery of the while statement, we invite you to write pseudocode to solve the problem described in detail under the "Description" tab in the interactive activity below. The problem involves determining the number of males and number of females indicated in an input string of symbols.

As in previous interactive programs, you will develop your algorithm, using pseudocode, in five phases. The tabs on the top of the interactive diagram will carefully guide you through these five phases.

Description

Test Plan

Code

Execute

Answer

The program must accept a sequence of characters typed by the user. The characters can be m, M, f, F, 0. The first two stand for "male," while the next two stand for "female" (we allow bot upper and lower case). The user types 0 in order to stop the input process. After the user has finished input (by typing 0), the program must determine the number of females and the number of males. The value '0' that was used to terminate input is called a sentinel value for obvious reasons.

B. The for Loop (a counter-controlled loop)
Study the diagram in the example below to understand all the components of a for loop and trace both the true and false paths to see how it is executed. It will help to remember that the words for, step, and to are all keywords, whereas counter is a variable. initial_value, increment, and limit_value can be either plain integers or even arithmetic expressions (involving variables) that evaluate to integers.

The for loop is used when we know in advance the number of iterations. A typical use of for loops is to process arrays whose dimensions are known in advance (we will study arrays in module 5).

Points to note:
· If the test condition fails initially, all the statements in the loop are skipped (study the flow chart).

· The variable counter used in the loop is sometimes called a loop index. It is usually a variable of type int.

· The index variable is incremented by the same amount each time.

· If the initial value is larger than the final value and a negative increment is used, the loop works as a "down counter."

· It is extremely important to realize that the action of updating the value of the index variable (just before the next iteration) is not a part of the actual loop body!! It is an automatic action that the compiler attends to. The programmer should not be writing any code to update the value of the counter (we discuss this concept below).

· Do not change any of the components—the loop index, the initial value, the increment, or the limit_value—of the for loop within the loop body.

Here is a simple example of a for loop that reads in an input number n and evaluates the sum of the first n numbers: 1 + 2 + 3 + … + n.

/* Pseudocode to sum 1 + 2 + ... + n */

Input n

Set sum = 0

//no braces used since the loop body is just 1 statement For i = 1 step 1 to n Set sum = sum + i End for

Output sum

Here, the loop index variable is called i, initial_value is 0, the increment is 1, and limit_value is n. Note that the loop body contains a statement of the form sum = sum + i (i.e., add the current value of i to the current value of sum, and place the result in sum). It is important to ensure that the variable sum is initialized correctly, so that the additions are performed correctly.

The for statement shown above would be written in C++ or Java as follows:

for (i = 1 ; i <= n ; i = i + 1) sum = sum + i ;

You should trace through the code in the following example using the values of n we suggest: 1, 4, and the special case of 0.

Points to note:
· In pseudocode, the initial, increment, and final values are simply stated as values, whereas in C++ or Java, they are written as complete expressions separated by semicolons.

· Note the semicolon at the end of the entire for statement.

· In pseudocode, the limit value is written last, whereas in C++ or Java, the expression that increments the counter appears last.

· In C++ or Java, i++ is a shorthand for i = i + 1, and the shorthand notation is widely used.

Test your skills in using for loops on the following pseudocode programming problem described in detail under the "Description" tab in the interactive activity below. Your task is to write a program that finds the sum of a sequence of numbers (floats). The user will first specify a number (integer) that specifies how many floats will be given, and the remaining inputs will specify the floats that need to be added together.

While doing this exercise, note that the loop body has more than one statement, which is why we have used braces.

You will develop your algorithm, using pseudocode, in five phases. The tabs on the top of the interactive diagram will carefully guide you through these five phases.

Description

Test Plan

Code

Execute

Answer

Test your skills in using for loops on the following psuedocode programming problem. Your task is to write a program that finds the sum of a sequence of numbers (floats). You will first specify a number (integer >= 0) that specifies how many floats will be given, and the remaining inputs will specify the floats (positive or negative) that need to be added together.

Homework is Completed By:

Writer Writer Name Amount Client Comments & Rating
Instant Homework Helper

ONLINE

Instant Homework Helper

$36

She helped me in last minute in a very reasonable price. She is a lifesaver, I got A+ grade in my homework, I will surely hire her again for my next assignments, Thumbs Up!

Order & Get This Solution Within 3 Hours in $25/Page

Custom Original Solution And Get A+ Grades

  • 100% Plagiarism Free
  • Proper APA/MLA/Harvard Referencing
  • Delivery in 3 Hours After Placing Order
  • Free Turnitin Report
  • Unlimited Revisions
  • Privacy Guaranteed

Order & Get This Solution Within 6 Hours in $20/Page

Custom Original Solution And Get A+ Grades

  • 100% Plagiarism Free
  • Proper APA/MLA/Harvard Referencing
  • Delivery in 6 Hours After Placing Order
  • Free Turnitin Report
  • Unlimited Revisions
  • Privacy Guaranteed

Order & Get This Solution Within 12 Hours in $15/Page

Custom Original Solution And Get A+ Grades

  • 100% Plagiarism Free
  • Proper APA/MLA/Harvard Referencing
  • Delivery in 12 Hours After Placing Order
  • Free Turnitin Report
  • Unlimited Revisions
  • Privacy Guaranteed

6 writers have sent their proposals to do this homework:

Academic Master
Top Rated Expert
A Grade Exams
Smart Tutor
High Quality Assignments
Writing Factory
Writer Writer Name Offer Chat
Academic Master

ONLINE

Academic Master

I will provide you with the well organized and well research papers from different primary and secondary sources will write the content that will support your points.

$22 Chat With Writer
Top Rated Expert

ONLINE

Top Rated Expert

This project is my strength and I can fulfill your requirements properly within your given deadline. I always give plagiarism-free work to my clients at very competitive prices.

$32 Chat With Writer
A Grade Exams

ONLINE

A Grade Exams

I have done dissertations, thesis, reports related to these topics, and I cover all the CHAPTERS accordingly and provide proper updates on the project.

$34 Chat With Writer
Smart Tutor

ONLINE

Smart Tutor

I have written research reports, assignments, thesis, research proposals, and dissertations for different level students and on different subjects.

$30 Chat With Writer
High Quality Assignments

ONLINE

High Quality Assignments

As an experienced writer, I have extensive experience in business writing, report writing, business profile writing, writing business reports and business plans for my clients.

$36 Chat With Writer
Writing Factory

ONLINE

Writing Factory

I have worked on wide variety of research papers including; Analytical research paper, Argumentative research paper, Interpretative research, experimental research etc.

$24 Chat With Writer

Let our expert academic writers to help you in achieving a+ grades in your homework, assignment, quiz or exam.

Similar Homework Questions

Female chauvinist pigs ariel levy pdf - South coast powder coating - Field installation work package - Bullyinessay3 - Toward a new interior an anthology of interior design theory - Cockburn basketball sporting pulse - HRM 522 - Nccam nih gov health herbsataglance htm - Should schools allow students to use cell phones - Write ACCIDENT PREVENTION RECOMMENDATIONS for each case - Discussion - What is repricing gap - The art of the commonplace - Formal and informal letter writing exercises - Password checker online domain tools - For Aleena - Discussion 1: Measuring Consciousness - What are the two functions of saliva - Barn owl food chain - 4th generation ct scanner - Alliterative adjective name game - simulation in public policy - Social Work Paper and PowerPoint Presentation - What is the transaction code to display current a material - How to factorise monic quadratic trinomials - Airbag lab baking soda and vinegar - Unit 4 DB Leading Change Management - A view from the bridge conflict essay - Computer Specifications - Birmingham voluntary service council - How to calculate freezing point depression - Macbeth worksheets with answers pdf - Discussion: Developing a Research Hypothesis and Selecting a Sampling Method and Technique - 560 paper - A static planning budget is - Wgu c228 task 2 - Swinburne senior secondary college staff - Under armour strategic group map - Becoming human part 3 transcript - World Literature - Parts catcher m code fanuc - Highgate mental health centre - The first born jack davis analysis - Contract clause & intellectual property drafting paper - Lemond g force ut craigslist - Critical thinking 12th edition mcgraw hill - Mrs van daan fur coat - 10 pages - Electromagnetic induction physics lab report - American express customer experience case study - Meaning of dog day afternoon - A blue ocean type of offensive strategy - Factor each completely algebra 1 - Formal Languages and Automata Theory - Flexcoat brush on coating - Play activity for child development assignment - Business Law Term Paper - Isotopes are atoms of the same element with different - La camarera te sirvió el plato de pasta con mariscos - Is ross lynch's hair naturally blonde - Aerated concrete floor panels - Jeremy buendia ebook pdf - How to open smil file on mac - Computer organization assignment - Customer profitability and customer relationship management at rbc case analysis - Microeconomics case study supply and demand - Family Information Night Presentation and Communication Plan - Staged cyber attack reveals vulnerability in power grid - Paul hynes sr7 for sale - Finance - Nitrogen and hydrogen react to form ammonia - Lil wayne quote mirror - Dobroyd point public school - Information Governance discussion 1 - Freedom foods corn flakes woolworths - Second ionisation energy equation - Case study The Problems of Multitasking - Case study on od interventions - 1984 big brother is watching you - John dickinson letters from a farmer in pennsylvania - Care certificate standard 1 understand your role answers - SQL ( fund of data systems) - Marshall pediatrics nowcare huntington wv - Black copper oxide wash - Ati video case study type 1 diabetes - Why did the zoot suit riots happen - Wk 5, IOP/470: Developing Transnational Groups - Dl120 gen9 ilo port - Homework - Harbor freight planishing hammer discontinued - Failed to establish a backside connection in datapower - Martin scorsese and quentin tarantino - Bizzy bounce party rentals waldorf md - University of salford staff channel - Assignment - Policy legal - Walmart organizational chart - Stat Report - Food a fact of life explore food - Scorecard and dashboard formulation