Page 262 - CTS - CSA TP - Volume 2
P. 262

COMPUTER SOFTWARE APPLICATION - CITS




           while c <= n:  # Specifying the condition of the loop
               # Beginning the code block
               summation = c**2 + summation

               c = c + 1  # Incrementing the counter
           # Print the final sum
           print(“The sum of squares is”, summation)
           Explanation:

           1  n = int(input(“Enter the limit: “)): Takes user input to set the upper limit for the loop. The int() function is used to
              convert the input to an integer.
           2  summation = 0: Initializes a variable summation to 0. This variable will store the sum of squares.
           3  c = 1: Initializes a counter variable c with the value 1.

           4  while c <= n:: The while loop continues as long as c is less than or equal to the specified limit.
           5  summation = c**2 + summation: Calculates the square of c and adds it to the current value of summation.
           6  c = c + 1: Increments the value of c by 1 in each iteration of the loop.
           7  After the loop, print(“The sum of squares is”, summation): Prints the final sum of squares.
           This program is a straightforward example of using a while loop to iteratively calculate the sum of squares.

           Output:









           Related Exercises:
           Develop the following Python programs using while loop
           1  Display Sum of digits of a number and its reverse
           2  Print the cube of all numbers from 1 to a given number

           3  Factorial of a number
           4  Display the Fibonacci series upto ‘n’
           5  Write a program to display all prime numbers within a range
           Python For Loop

           TASK 1: Python For Loop in Python String
           Code:
           # Iterating over a String
           print(“String Iteration”)
           s = input(“Enter the String: “)

           foriin s:
               print(i)
           Explanation:
           This code uses a for loop to iterate over a string and print each character on a new line. The loop assigns each
           character to the variable i and continues until all characters in the string have been processed.




                                                           247
                              CITS : IT & ITES - Computer Software Application - Exercise 126
   257   258   259   260   261   262   263   264   265   266   267