Page 439 - Cs_withBlue_J_C11_Flipbook
P. 439

Step 5:  If b > c then assign g = b, else assign g = c.
                 Step 6:  Print g.

                 Step 7:  Stop.
                                                                                                             2
                 Problem 2: Write an algorithm to find the roots of a quadratic equation. For any quadratic equation ax +bx+c=0 the
                 roots are calculated as:
                                 2
                          - b ± √b  - 4ac
                               2a
                 Step 1:  Start.

                 Step 2:  Accept coefficients in a, b and c.
                 Step 3:  Calculate discriminant d = sqrt (b × b - 4 × a × c).
                 Step 4:  If d < 0 then print “roots are imaginary”, go to Step 12.

                 Step 5:  If d = 0 then print roots are real and equal, go to Step 6, else go to Step 8.
                 Step 6:  Calculate r1 = -b / (2 x a).

                 Step 7:  Print “Roots are”, r1, go to Step 12.
                 Step 8:  Calculate first root r1= (-b + d) / (2 × a).
                 Step 9:  Calculate second root r2 = (-b - d) / (2 × a).

                 Step 10: Print “Roots are real and unequal”.
                 Step 11: Print r1 and r2.
                 Step 12: Stop.

                 Problem 3: Write an algorithm to check if a year is a leap year or not.
                 Step 1:  Start.

                 Step 2:  Accept year in variable y.
                 Step 3:  If y is divisible by 100 then Go to Step 4 else Go to Step 6.

                 Step 4:  If  y is divisible by 400, print “the year as leap year”, and Go to Step 8.
                 Step 5:  Print “the year” y “is not leap year”, and Go to Step 8.

                 Step 6:  If y is divisible by 4 then print “the year  is leap year”, and Go to Step 8.
                 Step 7:  Print year y is not leap year.

                 Step 8:  Stop.

                 14.5.2 Algorithms involving Decision and Iterative Statements
                 Problem 4: Write an algorithm to calculate and print the factorial of a number.
                 n! = 1 × 2 × 3 × 4 × ……… x n

                 Step 1:  Start.
                 Step 2:  Accept number n.
                 Step 3:  Initialise fact to 1.
                 Step 4:  Initialise i to 1.

                 Step 5:  Repeat Step 6 to Step 7 while i <= n.
                 Step 6:  Multiply fact by i and store the product in fact.


                                                                                                                       437
                                                                            Implementation of Algorithms to Solve Problems  437
   434   435   436   437   438   439   440   441   442   443   444