For & While Loops
For & While Loops
5. Reverse a String
• Theory: Strings can be reversed by iterating backward
using range(len(string)-1, -1, -1).
• Steps:
1. Input a string.
2. Use a loop to iterate backward.
3. Append characters to a new string.
7. Transpose a Matrix
• Theory: Transposing a matrix means swapping its rows and
columns.
• Steps:
1. Input the Matrix:
• Accept a 2D list representing the matrix.
2. Initialize a Result Matrix:
• Create an empty matrix of appropriate size.
3. Use Nested Loops to Rearrange Elements:
• Outer loop iterates through rows.
• Inner loop iterates through columns to swap
elements (result[j][i] = matrix[i][j]).
4. Output the Transposed Matrix:
• Print the result.
6. Reverse a String
• Theory: Reverse a string by iterating backward.
• Steps:
1. Initialize an empty result string.
2. Use while i >= 0 (where i is the index of the last
character).
3. Append each character to the result.
7. Find the Smallest Divisor of a Number
• Theory: Find the smallest number greater than 1 that
divides the given number.
• Steps:
1. Initialize i = 2.
2. Use while i <= num and check if num % i == 0.
3. Print i and break.