Monday, January 1, 2018

Iterative statements in C++ and Python (Part 2)

for loop iterative statements

Executing set of statements using for iterative statement in C++ and Python is quite different.

First, lets look how C++ implement iterative method using the for method. In C++, for loop is better suites for situations where number of iterations are known.

Syntax

for (initialization : condition : modifier )
{
      statement 1;
      statement 2;
            ...
}

The initialization, condition, and modifier do not need to be placed inside the brackets.

Example

for (int a=0 ; a<=10 ; a++)
{
      cout<<a<<" x2 = "<<a*2<<endl;
}

or

int a = 0;
for ( ; a<=10 ; )
{
      cout<<a<<" x2 = "<<a*2<<endl; 
      a++;

}

In Python, for loop can be used in various ways as shown in the following examples

Syntax

for variable in sequence:
      statement 1
      statement 2
            ...

example 1

for num in range (1,10)
      print num

This will print number 1,2,3,4,5,6,7,8,9
The range function use the following syntax : range (start, end, step).
 
for num in range (2,10,2)
      print num

output
2
4
6
8


example 2

for letter in 'Monday':
    print 'letter value : ', letter

output
letter value : M
letter value : o
letter value : n
letter value : d
letter value : a
letter value : y


example 3

weekdays = ['Monday','Tuesday','Wednesday','Thursday','Friday']
for name in weekdays:
    print 'weekday - ',name

output
weekday - Monday
weekday - Tuesday
weekday - Wednesday
weekday - Thursday
weekday - Friday

example 4
for m in range(2,15):
    a = 0
    for n in range (1, m/2+1):
        if m%n == 0:
            a = a+1
    if a==1:
        print 'prime number - ',m


output
prime number -  2
prime number -  3
prime number -  5
prime number -  7
prime number -  11
prime number -  13


No comments:

Post a Comment

Iterative statements in C++ and Python (Part 2)

for loop iterative statements Executing set of statements using for iterative statement in C++ and Python is quite different. First, l...