Page 189 - Computer science 868 Class 12
P. 189

b.  Print whether the number n is a prime number or not.
                    int c=0;
                    for(int i=1; i<=n; i=i+1)
                    {
                    if(n%i==0)
                    {
                        c++;
                        }
                    }
                    if(c==2)
                        System.out.println(n+ " is a prime number");
                    else
                        System.out.println(n+ " is not a prime number");
                   The above example finds the number of factors of the number n and checks if the number of factors is 2 (which is
                   the condition of the prime number).

                 7.3.2 while Loop
                 Java ‘while’ loop executes a set of statements repeatedly for a certain number of time depending on the given condition.
                 As soon as the control statement does not match the condition, the loop terminates. It is known as an entry-controlled
                 loop as the condition is checked before the loop starts executing.
                 Syntax:
                    initialisation;
                    while(condition for testing)
                    {
                        // job performed by the body of the loop;
                             increment or decrement;
                    }
                 For example:

                 a.    int i=5;
                    while(i<=20)
                    {
                        System.out.println(i);
                        i=i+5;
                    }
                     The above example prints all the multiples of 5 up to 20.
                 b.    Print whether the number (n) is a prime number or not.
                    int c=0, i=1;
                    while(i<=n)
                    {
                        if(n%i==0)
                        {
                            c++;
                        }
                        i=i+1;
                        }
                        if(c==2)
                                  System.out.println(n+ " is a prime number");
                        else
                                  System.out.println(n+ " is not a prime number");


                                                                                                                       187
                                                                                                 Statements and Scope  187
   184   185   186   187   188   189   190   191   192   193   194