Skip to content Skip to sidebar Skip to footer

Using a Loop, Write a Program That Reads in Exactly 10 Integers and Outputs the Sum. C++

xviii. For Loops

By Bernd Klein. Last modified: 27 Feb 2022.

Introduction

Like the while loop the for loop is a programming language argument, i.due east. an iteration argument, which allows a code block to be repeated a certain number of times.

There are hardly any programming languages without for loops, but the for loop exists in many different flavours, i.e. both the syntax and the semantics differs from one programming language to some other.

Different kinds of for loops:

  • Count-controlled for loop (3-expression for loop)

    This is by far the well-nigh common type. This statement is the one used by C. The header of this kind of for loop consists of a 3-parameter loop control expression. Generally it has the class: for (A; Z; I) A is the initialisation part, Z determines a termination expression and I is the counting expression, where the loop variable is incremented or dcremented. An example of this kind of loop is the for-loop of the programming language C: for (i=0; i <= north; i++) This kind of for loop is not implemented in Python!

  • Numeric Ranges

    This kind of for loop is a simplification of the previous kind. It's a counting or enumerating loop. Starting with a start value and counting upwards to an end value, like for i = 1 to 100 Python doesn't utilize this either.

  • Vectorized for loops

    They behave every bit if all iterations are executed in parallel. That is, for example, all expressions on the right side of consignment statements get evaluated before the assignments.

  • Iterator-based for loop

    Finally, we come to the one used past Python. This kind of for loop iterates over an enumeration of a gear up of items. Information technology is commonly characterized by the utilize of an implicit or explicit iterator. In each iteration step a loop variable is set to a value in a sequence or other data collection. This kind of for loop is known in most Unix and Linux shells and it is the one which is implemented in Python.

Syntax of the For Loop

Ring as a Symbol of the for loop

As nosotros mentioned earlier, the Python for loop is an iterator based for loop. It steps through the items of lists, tuples, strings, the keys of dictionaries and other iterables. The Python for loop starts with the keyword "for" followed past an arbitrary variable name, which will hold the values of the following sequence object, which is stepped through. The general syntax looks similar this:

for in : else:

The items of the sequence object are assigned i later on the other to the loop variable; to be precise the variable points to the items. For each item the loop body is executed.

Example of a simple for loop in Python:

              languages              =              [              "C"              ,              "C++"              ,              "Perl"              ,              "Python"              ]              for              linguistic communication              in              languages              :              print              (              linguistic communication              )            

OUTPUT:

Can of Spam

The else block is special; while Perl developer are familiar with information technology, it's an unknown concept to C and C++ programmers. Semantically, it works exactly as the optional else of a while loop. Information technology will be executed only if the loop hasn't been "broken" past a pause statement. So it will only be executed, subsequently all the items of the sequence in the header take been used.

If a suspension statement has to be executed in the plan flow of the for loop, the loop will be exited and the program menstruum will continue with the commencement statement following the for loop, if there is any at all. Usually suspension statements are wrapped into conditional statements, e.yard.

              edibles              =              [              "bacon"              ,              "spam"              ,              "eggs"              ,              "nuts"              ]              for              food              in              edibles              :              if              food              ==              "spam"              :              print              (              "No more spam please!"              )              break              print              (              "Corking, delicious "              +              food              )              else              :              print              (              "I am so glad: No spam!"              )              print              (              "Finally, I finished stuffing myself"              )            

OUTPUT:

Nifty, succulent bacon No more spam please! Finally, I finished stuffing myself            

Removing "spam" from our list of edibles, nosotros will gain the post-obit output:

$ python for.py  Keen, delicious bacon Keen, delicious eggs Great, succulent nuts I am so glad: No spam! Finally, I finished stuffing myself $        

Maybe, our cloy with spam is non so high that we want to stop consuming the other food. Now, this calls the proceed statement into play . In the following petty script, we utilise the continue argument to go along with our list of edibles, when we have encountered a spam particular. So keep prevents us from eating spam!

              edibles              =              [              "bacon"              ,              "spam"              ,              "eggs"              ,              "nuts"              ]              for              food              in              edibles              :              if              food              ==              "spam"              :              print              (              "No more spam please!"              )              proceed              print              (              "Great, succulent "              +              food              )              print              (              "Finally, I finished stuffing myself"              )            

OUTPUT:

Neat, delicious salary No more than spam please! Great, delicious eggs Great, delicious nuts Finally, I finished stuffing myself            

The range() Function

The built-in function range() is the right part to iterate over a sequence of numbers. It generates an iterator of arithmetic progressions: Instance:

OUTPUT:

This result is not cocky-explanatory. Information technology is an object which is capable of producing the numbers from 0 to four. We tin can utilize it in a for loop and you will see what is meant by this:

              for              i              in              range              (              5              ):              print              (              i              )            

OUTPUT:

range(n) generates an iterator to progress the integer numbers starting with 0 and ending with (n -one). To produce the listing with these numbers, we have to cast range() with the listing(), as nosotros exercise in the following example.

OUTPUT:

[0, ane, 2, 3, four, v, six, vii, eight, 9]

range() can also be called with two arguments:

range(begin, end)

The above phone call produces the list iterator of numbers starting with begin (inclusive) and ending with one less than the number end.

Case:

OUTPUT:

OUTPUT:

So far the increment of range() has been 1. Nosotros tin specify a different increment with a third statement. The increment is chosen the step. It can be both negative and positive, just non cypher:

          range(brainstorm,end, step)

Example with stride:

OUTPUT:

[4, ix, xiv, 19, 24, 29, 34, 39, 44, 49]

Information technology can be done backwards as well:

OUTPUT:

[42, 35, 28, 21, 14, 7, 0, -7]

The range() function is especially useful in combination with the for loop, as nosotros tin see in the following example. The range() part supplies the numbers from one to 100 for the for loop to calculate the sum of these numbers:

              due north              =              100              sum              =              0              for              counter              in              range              (              1              ,              due north              +              1              ):              sum              =              sum              +              counter              print              (              "Sum of 1 until                            %d              :                            %d              "              %              (              northward              ,              sum              ))            

OUTPUT:

Live Python grooming

instructor-led training course

Upcoming online Courses

Python Nuts for Beginners

07 Mar 2022 to 11 Mar 2022
sixteen May 2022 to twenty May 2022
29 Aug 2022 to 02 Sep 2022
17 Oct 2022 to 21 Oct 2022

Intensive Advanced Course

28 Mar 2022 to 01 April 2022
thirty May 2022 to 03 Jun 2022
29 Aug 2022 to 02 Sep 2022
17 October 2022 to 21 Oct 2022

Enrol here

Calculation of the Pythagorean Numbers

Pythagorean Theorem Proof

Generally, it is assumed that the Pythagorean theorem was discovered by Pythagoras that is why it has his name. Yet, there is a debate whether the Pythagorean theorem might accept been discovered earlier or by others independently. For the Pythagoreans, - a mystical move, based on mathematics, religion and philosophy, - the integer numbers satisfying the theorem were special numbers, which had been sacred to them.

These days Pythagorean numbers are non mystical anymore. Though to some pupils at school or other people, who are not on good terms with mathematics, they may still appear then.

So the definition is very simple: Iii integers satisfying a2+b2=c2 are chosen Pythagorean numbers.

The post-obit program calculates all pythagorean numbers less than a maximal number. Remark: We have to import the math module to be able to calculate the square root of a number.

            from            math            import            sqrt            north            =            int            (            input            (            "Maximal Number? "            ))            for            a            in            range            (            1            ,            n            +            one            ):            for            b            in            range            (            a            ,            n            ):            c_square            =            a            **            two            +            b            **            2            c            =            int            (            sqrt            (            c_square            ))            if            ((            c_square            -            c            **            2            )            ==            0            ):            print            (            a            ,            b            ,            c            )          

Iterating over Lists with range()

If you lot have to access the indices of a list, it doesn't seem to be a expert idea to use the for loop to iterate over the lists. We can access all the elements, but the index of an element is non available. However, at that place is a mode to access both the index of an chemical element and the chemical element itself. The solution lies in using range() in combination with the length function len():

              fibonacci              =              [              0              ,              1              ,              i              ,              2              ,              3              ,              5              ,              8              ,              13              ,              21              ]              for              i              in              range              (              len              (              fibonacci              )):              print              (              i              ,              fibonacci              [              i              ])              impress              ()            

OUTPUT:

0 0 i 1 2 1 3 2 4 3 five 5 6 viii 7 13 8 21            

Remark: If you apply len() to a list or a tuple, y'all get the number of elements of this sequence.

List iteration with Side Effects

If you loop over a list, information technology'southward best to avoid changing the listing in the loop body. Take a await at the post-obit instance:

              colours              =              [              "red"              ]              for              i              in              colours              :              if              i              ==              "blood-red"              :              colours              +=              [              "black"              ]              if              i              ==              "black"              :              colours              +=              [              "white"              ]              print              (              colours              )            

OUTPUT:

['cherry', 'black', 'white']            

To avoid these side furnishings, it's all-time to work on a copy by using the slicing operator, as tin be seen in the next example:

              colours              =              [              "red"              ]              for              i              in              colours              [:]:              if              i              ==              "ruby-red"              :              colours              +=              [              "black"              ]              if              i              ==              "black"              :              colours              +=              [              "white"              ]              print              (              colours              )            

OUTPUT:

We still might have washed something, nosotros shouldn't take washed. Nosotros inverse the list "colours", merely our change didn't have any effect on the loop. The elements to be looped remained the same during the iterations.

Live Python training

instructor-led training course

Upcoming online Courses

Python Basics for Beginners

07 Mar 2022 to 11 Mar 2022
sixteen May 2022 to 20 May 2022
29 Aug 2022 to 02 Sep 2022
17 Oct 2022 to 21 Oct 2022

Intensive Avant-garde Course

28 Mar 2022 to 01 Apr 2022
30 May 2022 to 03 Jun 2022
29 Aug 2022 to 02 Sep 2022
17 Oct 2022 to 21 Oct 2022

Enrol here

sizerfaidelper.blogspot.com

Source: https://python-course.eu/python-tutorial/for-loop.php

Post a Comment for "Using a Loop, Write a Program That Reads in Exactly 10 Integers and Outputs the Sum. C++"