Page 165 - CA_Blue( J )_Class10
P. 165

Program 4    To input a number and print the sum of the following series using do-while loop:
                               s= 1 + (1x2) + (1x2x3) + (1x2x3x….xn)

                   1   import java.util.*;
                   2   class series

                   3       {
                   4           public static void main()

                   5           {
                   6               Scanner sc= new Scanner(System.in);

                   7               int n,s=0,p=1,i;
                   8               System.out.print("Enter a number : ");

                   9               n=sc.nextInt();
                  10               i=1;

                  11               do
                  12               {

                  13                   p=p*i;
                  14                   s=s+p;
                  15                   i=i+1;

                  16               }

                  17               while(i<=n);
                  18               System.out.println("Result : "+s);
                  19           }

                  20       }

                 You will get the following output:


















                     8.7 INTERCONVERSION BETWEEN DIFFERENT TYPES OF LOOPS
                 Coding always allows flexibility in choosing the type of loop. We select the loops according to the ease of logic of the
                 coding. We can also convert any type of loop to another loop just by changing the place of the parts of the loops.







                                                                                                                       163
                                                                                              Iterative constructs in Java  163
   160   161   162   163   164   165   166   167   168   169   170