Iterative Programs (For, While, Nested Loop)

Iterative Programs (For, While, Nested Loop)

The next topic is the For Loop. The for loop in Python is used to iterate over a sequence (like a list, tuple, dictionary, set, or string) or other iterable objects. This loop allows us to execute a block of code multiple times based on the length of the sequence or specified range.

Below are 10 programs that demonstrate different uses of the For Loop in Python.


For Loop Programs


1. Print Numbers from 1 to 10

Description: This program uses a for loop to print numbers from 1 to 10.

# Program to print numbers from 1 to 10

for i in range(1, 11):
    print(i)

2. Print Even Numbers within a Range

Description: Prints even numbers between 1 and 20 using a for loop with a step of 2.

# Program to print even numbers from 1 to 20

for i in range(2, 21, 2):
    print(i)

3. Calculate the Sum of First N Natural Numbers

Description: This program calculates the sum of the first n natural numbers.

# Program to calculate the sum of first n natural numbers

n = int(input("Enter a number: "))
sum_n = 0
for i in range(1, n + 1):
    sum_n += i
print("Sum of first", n, "natural numbers is:", sum_n)

4. Display Multiplication Table

Description: Displays the multiplication table of a number entered by the user.

# Program to display the multiplication table

num = int(input("Enter a number: "))
for i in range(1, 11):
    print(f"{num} x {i} = {num * i}")

5. Print Each Character of a String

Description: Iterates over each character of a string and prints it on a new line.

# Program to print each character of a string

text = input("Enter a string: ")
for char in text:
    print(char)

6. Find the Factorial of a Number

Description: Computes the factorial of a number using a for loop.

# Program to find the factorial of a number

num = int(input("Enter a number: "))
factorial = 1
for i in range(1, num + 1):
    factorial *= i
print("Factorial of", num, "is:", factorial)

7. Calculate the Sum of Elements in a List

Description: This program calculates the sum of elements in a list using a for loop.

# Program to calculate the sum of elements in a list

numbers = [10, 20, 30, 40, 50]
sum_numbers = 0
for num in numbers:
    sum_numbers += num
print("Sum of list elements:", sum_numbers)

8. Display Only Positive Numbers from a List

Description: Filters and displays only the positive numbers from a list of integers.

# Program to display only positive numbers from a list

numbers = [-10, 15, -30, 45, 0, 50]
for num in numbers:
    if num > 0:
        print(num)

9. Print Fibonacci Series up to N Terms

Description: Generates the Fibonacci series up to n terms.

# Program to print Fibonacci series up to n terms

n_terms = int(input("Enter the number of terms: "))
a, b = 0, 1
for i in range(n_terms):
    print(a, end=" ")
    a, b = b, a + b

10. Count Vowels in a String

Description: Counts and displays the number of vowels in a given string.

# Program to count vowels in a string

text = input("Enter a string: ")
vowels = "aeiouAEIOU"
count = 0
for char in text:
    if char in vowels:
        count += 1
print("Number of vowels:", count)

Explanation

Each For Loop program showcases different ways to use for loops to iterate over numbers, lists, and strings. The for loop structure is versatile and allows us to perform various operations based on the elements or indexes of the sequence, which makes it essential for performing repeated tasks.

See also  Nested Functions

The next topic is the While Loop. The while loop in Python repeatedly executes a block of code as long as the condition specified is True. This loop is useful when the number of iterations is not known beforehand, and we want the loop to continue until a certain condition is met.

Below are 10 programs that demonstrate different uses of the While Loop in Python.


While Loop Programs


1. Print Numbers from 1 to 10

Description: This program uses a while loop to print numbers from 1 to 10.

# Program to print numbers from 1 to 10 using while loop

i = 1
while i <= 10:
    print(i)
    i += 1

2. Sum of Natural Numbers

Description: Calculates the sum of first n natural numbers using a while loop.

# Program to calculate the sum of first n natural numbers using while loop

n = int(input("Enter a number: "))
sum_n = 0
i = 1
while i <= n:
    sum_n += i
    i += 1
print("Sum of first", n, "natural numbers is:", sum_n)

3. Print Even Numbers Between 1 and 20

Description: Prints even numbers between 1 and 20 using a while loop.

# Program to print even numbers from 1 to 20 using while loop

i = 2
while i <= 20:
    print(i)
    i += 2

4. Reverse a Number

Description: Reverses a number entered by the user using a while loop.

# Program to reverse a number using while loop

num = int(input("Enter a number: "))
reverse = 0
while num > 0:
    digit = num % 10
    reverse = reverse * 10 + digit
    num = num // 10
print("Reversed number:", reverse)

5. Count Down from 10 to 1

Description: A countdown from 10 to 1 using a while loop.

# Program to count down from 10 to 1 using while loop

i = 10
while i > 0:
    print(i)
    i -= 1

6. Print Multiplication Table of a Number

Description: Prints the multiplication table of a number entered by the user.

# Program to print multiplication table using while loop

num = int(input("Enter a number: "))
i = 1
while i <= 10:
    print(f"{num} x {i} = {num * i}")
    i += 1

7. Check for Prime Number

Description: This program checks whether a number is prime using a while loop.

# Program to check if a number is prime using while loop

num = int(input("Enter a number: "))
i = 2
is_prime = True
while i <= num // 2:
    if num % i == 0:
        is_prime = False
        break
    i += 1
if is_prime and num > 1:
    print(f"{num} is a prime number.")
else:
    print(f"{num} is not a prime number.")

8. Factorial of a Number

Description: Calculates the factorial of a number using a while loop.

# Program to calculate factorial of a number using while loop

num = int(input("Enter a number: "))
factorial = 1
i = 1
while i <= num:
    factorial *= i
    i += 1
print(f"Factorial of {num} is {factorial}")

9. Find the Largest Number in a List

Description: Finds the largest number in a list using a while loop.

# Program to find the largest number in a list using while loop

numbers = [12, 54, 23, 89, 45, 77]
largest = numbers[0]
i = 1
while i < len(numbers):
    if numbers[i] > largest:
        largest = numbers[i]
    i += 1
print("The largest number in the list is:", largest)

10. Guessing Game

Description: Implements a simple number guessing game where the user has to guess a random number.

# Program to implement a guessing game using while loop

import random

number_to_guess = random.randint(1, 100)
guess = None
attempts = 0

while guess != number_to_guess:
    guess = int(input("Guess a number between 1 and 100: "))
    attempts += 1
    if guess < number_to_guess:
        print("Too low! Try again.")
    elif guess > number_to_guess:
        print("Too high! Try again.")
    else:
        print(f"Congratulations! You've guessed the number in {attempts} attempts.")

Explanation

Each While Loop program demonstrates different use cases of the while loop. The while loop is ideal when we don’t know in advance how many times we need to repeat an operation and the loop continues as long as the specified condition remains True. These programs illustrate common scenarios such as counting, summing, reversing, and even implementing games.

See also  Pattern Programs

The next topic is Nested Loops. A nested loop is a loop inside another loop. The inner loop is executed completely for each iteration of the outer loop. Nested loops are commonly used when you have a multi-dimensional data structure, like a matrix or a table, and need to iterate over each element within that structure.

Below are 10 programs that demonstrate different uses of Nested Loops in Python.


Nested Loop Programs


1. Print a Pattern of Stars (Right-Angled Triangle)

Description: Prints a right-angled triangle pattern of stars using nested loops.

# Program to print a right-angled triangle pattern using nested loops

n = int(input("Enter the number of rows: "))
for i in range(1, n + 1):
    for j in range(i):
        print("*", end="")
    print()  # new line after each row

2. Print a Square Pattern of Stars

Description: Prints a square pattern of stars using nested loops.

# Program to print a square pattern using nested loops

n = int(input("Enter the size of the square: "))
for i in range(n):
    for j in range(n):
        print("*", end="")
    print()  # new line after each row

3. Multiplication Table Using Nested Loops

Description: Prints the multiplication table for numbers 1 to 10 using nested loops.

# Program to print multiplication table using nested loops

for i in range(1, 11):
    for j in range(1, 11):
        print(f"{i} x {j} = {i * j}")
    print()  # new line after each table

4. Print a Pyramid Pattern of Stars

Description: Prints a pyramid pattern of stars using nested loops.

# Program to print a pyramid pattern using nested loops

n = int(input("Enter the number of rows for the pyramid: "))
for i in range(1, n + 1):
    for j in range(n - i):
        print(" ", end="")  # spaces for alignment
    for k in range(2 * i - 1):
        print("*", end="")  # stars in the pyramid
    print()  # new line after each row

5. Print a Number Pattern

Description: Prints a number pattern where each row contains numbers from 1 to the row number.

# Program to print a number pattern using nested loops

n = int(input("Enter the number of rows: "))
for i in range(1, n + 1):
    for j in range(1, i + 1):
        print(j, end="")
    print()  # new line after each row

6. Create a Multiplication Table in a Matrix Form

Description: Prints a multiplication table in a matrix form using nested loops.

# Program to create a multiplication table in matrix form

n = int(input("Enter the size of the table: "))
for i in range(1, n + 1):
    for j in range(1, n + 1):
        print(f"{i * j:3}", end=" ")
    print()  # new line after each row

7. Print a Hollow Square Pattern

Description: Prints a hollow square pattern using nested loops.

# Program to print a hollow square pattern using nested loops

n = int(input("Enter the size of the square: "))
for i in range(n):
    for j in range(n):
        if i == 0 or i == n - 1 or j == 0 or j == n - 1:
            print("*", end="")
        else:
            print(" ", end="")
    print()  # new line after each row

8. Print Floyd’s Triangle

Description: Prints Floyd’s Triangle (a right-angle triangle filled with consecutive integers) using nested loops.

# Program to print Floyd's Triangle using nested loops

n = int(input("Enter the number of rows: "))
num = 1
for i in range(1, n + 1):
    for j in range(1, i + 1):
        print(num, end=" ")
        num += 1
    print()  # new line after each row

9. Sum of Matrix Elements

Description: Calculates the sum of all elements in a 2D matrix using nested loops.

# Program to find the sum of elements in a matrix using nested loops

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
sum_matrix = 0
for i in range(len(matrix)):
    for j in range(len(matrix[i])):
        sum_matrix += matrix[i][j]
print("Sum of matrix elements:", sum_matrix)

10. Print Diamond Pattern of Stars

Description: Prints a diamond pattern of stars using nested loops.

# Program to print diamond pattern using nested loops

n = int(input("Enter the number of rows for the upper half of the diamond: "))
# Upper half of the diamond
for i in range(1, n + 1):
    for j in range(n - i):
        print(" ", end="")  # spaces for alignment
    for k in range(2 * i - 1):
        print("*", end="")  # stars in the upper half
    print()  # new line after each row
# Lower half of the diamond
for i in range(n - 1, 0, -1):
    for j in range(n - i):
        print(" ", end="")  # spaces for alignment
    for k in range(2 * i - 1):
        print("*", end="")  # stars in the lower half
    print()  # new line after each row

Explanation

Each Nested Loop program demonstrates how to use loops inside loops to solve problems, print patterns, and manipulate data structures like matrices. Nested loops are essential for tasks like matrix traversal, generating complex patterns, or performing operations that require multiple levels of iteration.

See also  Why Python? The reasons why you should learn Python in 2024

Let me know if you’re ready to move on to the next topic, Pattern Programs!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
Contact Form Demo