CHAPTER 4

Looping Techniques

Various computer applications need ‘repeated’ execution of some set of ‘computational statements’ again and again. For example, different terms of the Fibonacci series are computed by repeatedly adding the values of two immediate preceding terms. The sum of a series expansion involves the repeated generation of next terms and adding it to the previous sum, the salary of all the employees of an organization is computed using the same set of rules again and again. At an university level examination students results are computed using the same set of rules again and again, and so on. There are such innumerable number of applications where one will be repeatedly or iteratively executing a certain set of statements again and again. As a result almost all the computer languages provide facilities, in the form of language constructs, using which repeated executions can be carried out easily. In C, the for, while, and dowhile constructs are used for repeated execution of required set of statements for required number of times. These language constructs are generally called loop control structures. This chapter discusses few examples that employ these structures.

4.1 SUM OF FIRST N NATURAL NUMBERS

Here, the problem is to find the sum of the series 1 + 2 + 3 + 4 + 5 + 6 + 7 ……+ n.

The Method

This is one of the simplest examples one comes across to compute the sum of a series. It is simple because, the first term is 1 and each of the next terms are obtained by incrementing the previous term by 1 (i.e. by adding 1 to the previous term). A variable sum is used to hold the entire sum of the series. A variable like ‘i’ is used as a counter which counts from 1 to n in steps of 1. The value of this counter (i.e. variable) is added to sum at each step using a relation like sum = sum + i. The only input to this program is ‘n', the value of number of terms. The flowchart for this method is given below.

C-Tips

In this example repeated execution of certain statements is achieved using the while loop structure. The general structure of the while structure is shown below.

while (logical expression)
{
     statements in the
     while loop
}

images

When the control comes across a while, the logical expression is evaluated first. As long as the result of the evaluation of the logical expression is TRUE, statements in the while block are repeatedly executed. Once the evaluation of the logical expression results in FALSE, the control comes out of the while loop.

Flowchart

images

The Program

/* Finding the sum of first n natural numbers */

#include<conio.h<       /* Including header file */
#include<stdio.h>

main()
{
   int n, i = 1, sum=0;  /* Initializing i to one and sum to zero */
   clrscr();
   printf(“

Enter value of n
”);
   scanf(“%d”, &n);
   printf(“n = %d
”,n);

    /* Repeat while i is less than or equal to n */
    while (i <= n)
    {

        sum = sum + i;             /* Adding i to sum */
        i = i + 1 ;                /* Incrementing i by 1 */
    }

    printf(“
Sum of first %d natural numbers is %d
”, n, sum) ;
}

Note: It may be observed that the variable sum and i are initialized during type declaration itself. The C language permits this. A variable like i based on the value of which the loop is executed is called a loop control variable.

4.2 SUM OF THE SQUARES OF ALL INTEGERS FROM 1 TO N

Here, the problem is to find the sum of the series 12 + 22 + 32 + 42 + 52 + 62 + 72 ……+ n2.

The Method

The procedure here is exactly similar to the one used in example 4.1. The only difference being, the square of the next term is added to the current sum. Of course, the loop control variable ‘i’ itself is being used as the next term. Note that though the value of ‘i’ is being squared, we are not altering its value. Yes, it is important to note that we can use the value of any loop control variable but its value should not be manipulated.

C-Tips

In this example also the while loop structure, discussed in the previous example, is used. Notice that we have used a statement like sum+ = i * i. This statement is equivalent to sum = sum + i * i. An assignment statement of the form sum += i * i is called the shorthand assignment statement. Also, we have used a statement like ++i; which is equivalent to i = i + 1. In C, ++ is known as the increment operator.

Flow Chart

images

The Program

/* To find the sum of the squares of all integers from 1 to n */
#include<conio.h>                   /* Including header file */
#include<stdio.h>
main()
{
      int n, i = 1, sum=0;   /* Initializing i to 1 and sum to 0 */ 
      clrscr();
      printf (“

Enter value of n
” ) ;
      scanf(“%d”, &n) ;
      printf(“n = %d
”,n);

      while (i <= n) /* Repeat while i is less than or equal to n */

      {
         sum += i * i;            /* Adding i to sum */
         ++i;                     /* Incrementing i by 1 */
      }
 
     printf(“
Sum of squares of numbers from 1 to %d is %d
”, n, sum);
}

Note: Like in the previous example, here also some of the variables are initialized during declaration itself. Also observe the use of shorthand assignment statement and increment operator.

4.3 FACTORIAL OF A GIVEN INTEGER

The factorial of a given integer n is given by the product 1 × 2 × 3 × 4 × 5 × 6 × 7 × …. × (n − 1) × n.

The Method

It may be observed that this is also a type of series made up of many terms like 1, 2, 3, …… etc. Therefore this problem is handled in a similar manner to that of summation of series examples. It may be noted that in summation problems the initial value of the variable sum must be equal to zero (0). But in this case, since successive multiplications are used, the initial value of the variable that holds the factorial value, say prod, must be 1. A loop control variable like i itself is used for counting as well as the next term. A statement of the type prod = prod * i is used to get the required factorial. Note that, as already mentioned, i is being used as new term which is nothing but a loop control variable and automatically gets incremented under the control of the loop control structure used.

The process of generating the next term and multiplying with the current product is repeated till the next term exceeds the value of ‘n’.

Note: Though it has been mentioned that a statement like term = term + 1 is used to generate the next term, it is not necessary to use such a statement exclusively. Instead, the same can be managed using the loop control variable itself as it starts from 1 and runs upto and equal to n in steps of 1. In general only values of loop control variable, can be used, but should not be altered.

C-Tips

In this example the repeated execution of the required statement has been carried out using the for control structure of C. The general format of this loop control structure is given below.

for ( exp1 ; exp2 ; exp3 )
{
       for block
       statements
}

Here exp1 is an expression used to hold the initial value of a variable, the value of which is incremented or decremented in the expression exp3. The exp2 is generally a logical expression. As long as this logical expression exp2 is TRUE, the statements in the for block are executed. Once exp2 becomes FALSE control goes out of the for loop. The behavior of the for statement can be pictorially shown in a flow diagram as follows.

images

Flowchart

images

The Program

/* To find the factorial of a given integer */

#include<stdio.h>
#include<conio.h>

main()
{
       long n, i,prod=1;
      clrscr();
    
      printf (“Input the value of n 
”) ;
      scanf(“%ld”,&n);
  for(i=1;i<=n;++i)
  {
      prod = prod * i;
  }
  printf(“
The value of %ld factorial is : %ld 
”,n,prod);
}

Note: As the factorial of an integer might result in a large integer value, the variable prod which finally holds the value of the factorial is type declared as long. Therefore, while handling prod in i/o statements the format specifier %ld is used.

4.4 FINDING THE SUM OF ODD NUMBERS AND SUM OF EVEN NUMBERS FROM 1 TO N

The Method

Starting from 1, numbers 2, 3, 4 ……. upto n are generated by adding (i.e. incrementing) a 1 to the previous number. As a sort of convention let the first number be term the initial value of which is 1. The next number (which is also called term) is generated by adding a 1 to the previous term (i.e. term). In other words, the relation term = term + 1 is used.

At every step, after generating a new term (i.e. term) it is tested to find out whether it is odd or even. For this modulo division by 2 is used (as discussed in 3.3). If the number is even then it is used to find the evensum and if the number is odd it is used to find the oddsum. Infact, evensum and oddsum are two variables, which are intitally zero, and are specifically used for storing the required sum. The above procedure is repeated as long as the number (i.e. the term) is less than or equal to n. In other words, the above procedure is repeatedly done while the number (or term) is less than or equal to n. Given below is the pictorial representation, i.e. the flowchart, of the above process.

Flowchart

images

C-Tips

The while loop control structure, already explained in 4.1, is used for the repeated execution of the required statements.

The Program

/*Finding the sum of odd numbers and sum of even numbers from 1 to n */

#include<stdio.h>
#include<conio.h>

main()
{
    int n,evensum=0, oddsum=0, i=1;
    /*Initializing evensum and oddsum to zero and i to 1 */
    clrscr();
    printf (“Enter value of n
” ) ;
    scanf(“%d”, &n);
    printf(“
n = %d
”, n) ;

    while (i<=n)  /*Repeat while i is less than or equal to n*/
    {
    /*If the remainder after dividing number by 2 is zero then it is
     even, add to evensum*/

     if(i%2==0)
        evensum += i;
     else

    /*If the remainder after dividing number by 2 is non zero then it
     is odd, add to oddsum*/
          oddsum += i ;

     ++i;                      /*Increment i by 1*/
    }

    printf (“
Sum of odd numbers from 1 to %d is %d
”, n, oddsum) ;
    printf(“
Sum of even numbers from 1 to %d is %d
”, n, evensum);
}

Note: Here, observe that the loop control variable i is used both as the present term and the next term.

4.5 GENERATION OF REQUIRED NUMBER OF TERMS OF THE FIBONACCI SEQUENCE

The Fibonacci sequence is the sequence of integers which will be as shown below.

0, 1 , 1, 2, 3 , 5 , 8 , 13 , 21 , 34 , ...........

The Method

By carefully inspecting the above sequence one can see that the third term can be obtained by adding the first and second terms. The fourth term can be obtained by adding the second and the third terms. The fifth term can be obtained by adding the third and fourth terms and so on.

Let term1 and term2 be the first and second terms, to begin with. The third term is obtained using the relation term=term1 + term2. For generating the fourth term, term2 is made as term1, the term (i.e. third term which was generated in the recent past) is made as term2 and the relation term = term1 + term2 is again used. This term will be the fourth term. The fifth term is generated by making term2 as term1, the term (i.e. fourth term which was generated in the recent past) is made as term2 and once again using the relation term = term1 + term2. This procedure is totally repeated n times for generating n terms. Each term is output as and when generated. As two values are assumed in the beginning, total number of terms actually displayed will be (n+2).

Flowchart

images

C-Tips

While generating the required number of terms in the sequence, one should remember that first two terms are taken as known and n terms are generated. Therefore, the loop control variable i may vary from 0 to less than n. Note that, here, i is used only for the counting purpose. The repeated execution of the required statement is achieved using the for loop control structure. This structure has been already explained in Section 4.3.

The Program

/* Generation of required number of terms of the Fibonacci sequence
*/

#include<stdio.h>
#include<conio.h>

main()
{
    int n, term1 = 0, term2 = 1, term, i;
    /*Initializing first and second numbers to 0 and 1 respectively */
    clrscr();
    printf (“Enter the value of n, the number of terms to be
                                           generated
”);
    scanf(“%d”, &n);
    printf(“
n = %d
”, n) ;
    printf(“
First %d Fibonacci numbers are :
”, n+2) ;

    /* Printing first and second number */
    printf(“
%d
%d”, term1, term2);

    /* Repeating for n times since already two numbers are printed */

    for ( i=0; i>n ; ++i)
    {
        term = term1 + term2;
       printf(“
%d”,term);
        term1=term2; 
        term2=term;
    }
}

4.6 FINDING THE GCD AND LCM OF GIVEN NUMBERS

The Method

The GCD is obtained using the Euclid's principle. In this method, the first number (num1) is divided by the second number (num2). If the remainder is zero, num2 will be the required GCD. If the remainder is non zero, the division process is repeated until the remainder becomes zero by making num2 as num1 and the remainder (rem) as num2.

The LCM is computed using the relation

LCM = (numl * num2) / GCD

C-Tips

The while loop control structure, introduced in Section 4.1 is used for repeated execution. The values of given numbers are saved in two variables, say for example in n1 and n2, as they are required for LCM computation as well as for printing out the result.

Flowchart

images

The Program

/* Finding the GCD and LCM of given numbers */

#include<conio.h>         /* Including header file */
#include<stdio.h>
main()
{
    int num1, num2, rem=0, n1, n2;
    clrscr();
    printf (“
Program to find the GCD and LCM of 2 integer numbers”) ;
    printf(“

Enter two non zero integer numbers
”);
                       /* Reading two non zero numbers */
    scanf(“%d%d”, &num1, &num2);
    printf(“
num1 = %d	 num2 = %d
”,num1, num2);
    /* Keeping num1 and num2 in temporary variables to print it later
*/

    n1 = num1;
    n2 = num2 ;
    rem = num1 % num2 ;       /* Computing remainder */

    while(rem!=0)              /* Repeat while remainder is not zero */
    {
        num1=num2;             /* Store second number in first number */
        num2=rem;              /* Store remainder in second number */
        rem =num1%num2;        /* Compute remainder */
    }

    printf (“
GCD of %d and %d = %d
”, n1, n2 , num2 ) ;
                             /* Computing and printing lcm */
   printf ( “
LCM of %d and %d = %d
”, n1, n2 , (n1*n2 )/num2 ) ;
}

Note: Observe that the required LCM is computed within an output statement itself. Yes, this is permitted in C. Only problem with this type of computation is that, if LCM is required for any other purposes it has to be recalculated.

4.7 SUM OF ALL THE DIGITS OF A GIVEN INTEGER NUMBER

Given an integer number, say 4567, the problem here is to find the sum of the individual digits of the given number. That is, we have to find the sum of the digits 7, 6, 5 and 4.

The Method

Let a variable called sum is used to store the determined sum. The digit in the unit's position is extracted using modulo 10 division (as discussed in Section 2.6) and added to the sum. After extracting the unit's digit, the number gets reduced. The above process of extracting the unit's digit and summing up is repeated till the given number becomes zero. The underlying principle can be well understood by going through the following illustration.

Illustration The numbers 1, 2, 3 on the lines are in the order in which the operations are performed. These set of operations are repeatedly done as long as i.e. while the number is not equal to zero.

images

Flowchart

images

The Program

/* To find the sum of all the digits of a given integer number */

#include < stdio.h>
#include<conio.h>
void main()
{
     int num, rem, sum = 0;
    clrscr();
    printf(“Enter a number
”);
    scanf(“%d”,&num);
    while ( num ! = 0 )
        {
          rem = num % 10 ;
          sum = sum + rem;
          num = num / 10 ;
        }
        printf(“The sum of the digits of a given number is %d ”,sum);

}

4.8 REVERSING A NUMBER AND TO CHECK WHETHER IT IS A PALINDROME OR NOT

A number (in fact any string) is said to be a palindrome, if it and its reverse are the same. For example, 23132 is a palindrome, as it is same when it is read from right to left as well as from left to right.

The Method

The procedure involved here is to extract the least significant digit (the right most) of the given number and making it as current least significant digit of the reversed number. After getting the least significant digit, the remaining digits of the given number are taken as the number for the next step. In the next step, once again the least significant digit of the number is extracted and appended to the reversed number, as its new least significant digit, pushing the earlier least significant digit to one decimal place up. This procedure is repeated till the number becomes zero.

Modulo 10 division is used to extract the least significant digit, i.e. the digit at unit's position, from the number (Section 2.6). Integer division by 10 is used to get the modified number for the next step, i.e. next iteration. In the first step, the reverse number is obtained by assigning the first least significant digit to the reversed number. Afterwards, the digits extracted by the number are added to the reversed number as its new least significant digit using the relation

reversednumber = reversednumber * 10 + digit

Actually, multiplying by 10 makes room for the digit to be added to the reversed number at the proper position, i.e. the unit's digit position.

C-Tips

The while loop control structure discussed in Section 4.1 is used for repeated execution. As in Section 2.6 modulo division is done using the % operator. Equality of two numbers is tested using the = = operator.

Given below is an illustration of the above process, as well as the corresponding flowchart.

The numbers on the arc indicate the order in which the operations are performed. The above set of operations are repeatedly done as long as, i.e. while the number is not equal to 0 (Zero).

images

Flowchart

images

The Program

/* Reversing a number and to check whether it is a palindrome or not
*/

#include<conio.h>  /* Including header file */
#include<stdio.h>
main()
{
   int num,r_num,digit,n;
   clrscr();
   printf(“

Enter an integer number
”);
   scanf(“%d”, &num);
   n=num;           /*Keep the value of num in n for later use*/
   r_num=0;
   printf(“
number = %d	”, num) ;
   while ( num != 0)         /* Repeat while num is not zero */
   {
      digit = num % 10;
             /* Obtain the remainder by dividing number by 10,
                so that last digit is obtained */
      r_num = r_num * 10 + digit;
              /* r_num is multiplied by 10 and added to digit*/
      num = num/10;   /* Dividing number by 10 to get quotient */
   }
   printf (“
The reverse of the given number %d is %d 

”, n, r_num) ;
   if(n==r_num)
                 /* If number and reverse are same then
                 it is palindrome otherwise not */
   printf (“reverse = %d, given number %d is a palindrome
” ,
   r_num, n);
   else
   printf(“reverse = %d, given number %d is not a palindrome
”, 
     r_num,n);
}

Note: Since the given number is directly manipulated, its value has to be saved for future usage. Hence it is saved in the variable n.

4.9 TO FIND OUT WHETHER A GIVEN INTEGER NUMBER IS PRIME OR NOT

A number n is said to be prime if and only if it is divisible by 1 and itself. In other words, n is not a prime number if it is divisible by any number in the range 2 to (n − 1).

The Method

The straightforward procedure is to check for the divisibility of the given number (n) by all numbers smaller than itself (except 1), i.e. by numbers : 2, 3, 4, 5,........(n − 1). Though one feel like to test for the divisibility of n by numbers 2, 3, 4, …. upto (n − 1), it is not necessary to do so. It is sufficient if divisibility is tested for numbers 2, 3, 4, … upto n / 2. This is because a number n is never divisible by a number greater than n/2. For example, 8 is NOT divisible by 5, 6, 7, all of which are greater than 8 / 2, i.e. 4. Similarly, 15 is NOT divisible by 8, 9, 10, 11, 12, 13 or 14, all of which are greater than 15 / 2, i.e. 7. (integer division).

Obviously testing for divisibility is done repeatedly under the control of a counted loop structure. Here the program control may come out of the loop normally after completing all the iterations or abnormally after a successful testing for division.

When the control comes out normally, the loop control variable will be greater than (n/2) and the given integer will be a prime number (as it was not divisible by any numbers in the range 2 to (n/2), rather 2 to (n − 1)). When the control comes out abnormally, the loop control variable will be less than or equal to (n/2) and the given integer will not be a prime number.

C-Tips

The counted loop control variable itself has been used as numbers less than n for the divisibility testing of n, i.e. the given number. As soon as the divisibility test succeeds, the control has to come out of the loop structure. In C this is achieved by using the break statement.

The general format of break is

break;

Execution of a break statement from within a for, while, do-while or switch block causes execution of that block to be immediately terminated. Further execution continue with the statement that immediately follows the loop or switch block.

Flowchart

images

The Program

/* To find out whether a given integer number is prime or not */

#include<stdio.h>
#include<conio.h>

main()
{
   int n,i;
   clrscr();
   printf(“
Enter an integer number 
”) ;
   scanf (“%d”, &n) ;    /* Reading a number*/
   printf (“Given number = %d
”, n) ;

   /* Initializing i to 2 (smallest factor other than one) and
   repeating for all values of i less than or equal to n/2 */

   for(i=2; i<=n/2; ++i)
   {
      /* Dividing number n by i,If remainder is zero it is not a prime */

      if ( n%i == 0)
      break;
   }

   /* To check whether all possible numbers are tested and none of
   them are factors */

   if ( i > n/2 )
      printf(“%d is prime
”, n) ;
   else
      printf (“%d is not a prime 
”, n) ;
}

4.10 PRIME NUMBERS BETWEEN 1 AND N

The Method

The definition of a prime number and how to find it have been already discussed (in the previous example). Using the same technique repeatedly for every number in the range 1 to N we can identify all the prime numbers in the required range. A counter, say pcount is used to count the number of prime numbers in the range as and when a prime number is identified. The underlying principle can be clearly understood by going through the following illustration.

Illustration Assume that we are interested in generating prime numbers in the range 1 to 5, both inclusive.

Since 1 is not considered as a prime number, we have to generate the numbers 2, 3, 4 and 5, and find out whether each one of these is a prime number or not. As each one of these numbers are to be considered to identify whether it is prime or not, we have to use the prime number identification procedure (discussed in Section 4.9) repeatedly. For this we can use the for loop structure with some loop control variable (say, j). Obviously j should acquire the values 2, 3, 4 and 5. Therefore j has to vary from 2 to 5 in steps of 1. The involved technique may be pictorially shown in a flowchart fragment as follows. The complete flowchart is also given.

images

Flowchart

images

The Program

/* Prime numbers between 1 and N */

#include<conio.h>        /* Including header file */
#include<stdio.h>
main()
{
  int n,i,j,pcount = 0;
  clrscr();

  printf(“
Enter the upper limit of the range.
”);
  printf (“(1 is assumed to be the lowerlimit of the range) 
” ) ;
  /* Reading upper limit */
  scanf(“%d”,&n);

  printf(“

Given range is 1 to %d
”, n) ;
  for(j=2; j<=n; ++j )      /* Repeat for all numbers from 2 to n */
  {
  /* Initializing i to 2 and repeating while i is less than or equal
  to j/2. To check whether this value of j is prime or not*/

  for(i=2; i <=j/2 ; ++i)
  /* Dividing number j by i. If remainder is zero j is not a prime */

     if ( j%i == 0)
           break;
  /* Whether all possible numbers are tested and none of them are
  factors */

  if ( i > j/2 )
  {
     printf (“%d	”, j) ; /* Then it must be prime */
     pcount++;               /* Counting number of prime numbers*/
  }
 }
     printf(“

Number of prime numbers in range 1 to %d is %d.
”,n,
              pcount);
}

4.11 SUM OF FIRST N TERMS IN THE EXPANSION OF SINE SERIES

The Method

The general procedure to find the sum of a series is to

  1. Find the nth term (Tn) and (n + 1)th term (Tn + 1) of the series.
  2. Find a general relationship between Tn and Tn+1.
  3. Generate the Tn+1 knowing the Tn.

Obviously, to begin with, the first term should be known. The second term is generated using the first term, the third term is generated using the second term, and the fourth term is generated using the third term and so on. It may be noted that this technique was not explicitly used in the earlier examples of series handling, i.e. in examples discussed in Sections 4.1, 4.2, 4.3. Since those series were trivial in nature and the reader could decide about the next term generating mechanism just by observation, this process was not required.

At every step, the sum is computed from the known generated terms. Thus the important step in solving this type of problem is to find a general relationship between the term to be generated and the previous term. Then this relation is executed repeatedly using one of the loop control structures available in the coding language. This process is stopped under the following situations:

  • (i) After required number of terms are generated and the sum is computed.
  • (ii) When the generated term does not significantly contribute to the sum. In other words, when the required accuracy is achieved.
  • (iii) Both the situations discussed under (i) and (ii) above are considered simultaneously and the program execution is stopped whenever either of the above two is satisfied first.

For example, consider the summation of the series

Sin (x) = x − x3/3! + x5/5! − x7/7! + ……

In the given series observe that

1st term = x, 2nd term = − x3/3!, 3rd term = x5/5!, and so on.

The nth term,

images obtained by inspection.

images also obtained by inspection.

images

Actually, the term on the right-hand side of the above expression corresponds to the present term and the term on the left-hand side corresponds to the next term.

C-Tips

The for loop control structure is used for the repeated generation of the terms and to compute the required sum. The value of sin(x) can be obtained straight away using the library function. This library function is available in the header file <math.h> and hence it is included in the beginning. images

Note: Normally the value of x will be given in degrees. The value to be used in the different terms of the expansion of a trigonometric series must be in radians. As such while handling a trigonometric series care should be taken to provide the value of x in radians. If necessary, the relation 180° = π radians may be used to carryout the necessary conversion.

Flowchart

images

The Program

/* Sum of first N terms in the expansion of Sine series */
#include<stdio.h>
#include<conio.h>
#include<math.h>
/*Including math.h header file to caculate*/
/*sin(x) value using library function */
main()
{
   int n, i ;
   /*Sum is initialized to zero, y is a temporary variable to hold x
   value in degrees*/
   float sum=0, term, x,y; clrscr();
   printf (“Enter the value of x and n
” ) ;
   /*Reading x in degrees and n number of terms*/
   scanf(“%f%d”, &x, &n) ;
   printf (“x = %f	 n = %d
”, x,n) ;

   y = x;                          /*Value of x is assigned to y */
   x = x*3 . 14/180 ;                  /*Converting x value to radians*/
   term = x;                       /*x value is assigned to term*/
  
 /*i is intialized to 1 and loop is repeated
   for i is less than or equal to n*/


   for(i=1; i<=n; ++i)
   {
       sum += term;          /*term is added to sum*/
       term *= -x*x/(2*i* (2*i+1)) ; /*Next term is calculated*/
    }
    printf (“Value of sin(%.0f) upto %d terms is %f 
”, y, n, sum) ;
    /*Calculating sin(x) value using lib function */
    printf(“Value of sin(%.0f) using library function=%f
”, y, Sin(x));

}

Note: When the value of a standard trigonometric function is found using its series expansion, it is customary to find the value of the function using library function also. This practice helps in comparing the results. In order to get the value using library function, the given value of x in degrees must be saved. Here, this has been accomplished by saving the value of x in y.

4.12 COMPUTING THE AREA OF CIRCLES GIVEN THEIR RADII

In all the examples discussed till now we are providing a set of data values and are getting the results. In a practical situation one might have more than one set of data values for which “required computations” are to be carried out once, for each data set. Thus the problem, here, is to compute areas of circles corresponding to different radius input interactively (i.e., input in response to the system's request).

The Method

In situations like this the program has to be run afresh for each and every set of data values. For example, let us assume that we have a set of data values each one corresponding to a radius. Also assume that we need to compute the area of circles corresponding to these radii. The general procedure could be

  1. Have a ‘program’ that computes the area of a circle given its radius (like the one presented in Section 2.4)
  2. The ‘program’ is run once with a value of the radius and the result is printed out.
  3. Allow the ‘program’ to interrogate the user regarding ‘whether he wants to re-run the program or not’. In other words, the program is allowed to find out whether there are some more data values (radii values, in this case) or not. Obviously there should be a facility in the program to ‘trap’ the user's response. The ‘program’ is ‘re-run’ or ‘terminated’ depending upon the user's response.

C-tips

Here, the program has to be run at least once. Also, depending on the number of data values, we might need to run the program repeatedly. Under such circumstances the use of do….while loop structure is recommended. The general format of the do….while is given below. When the system asks the user to continue processing or not, the user's response will be generally ‘y’ or ‘n', meaning yes or no respectively. Therefore a character type variable, say choice, is used to trap the user's response. Obviously the format specifier for handling this variable has to be %c.

do
{
    do-while
    block

}while(logical expression);

When the control comes across do it enters into the do…while block directly and executes all the statements in that block once. At the end it comes across the while statement and evaluates the adjoining logical expression. If the evaluation of the logical expression results in a YES or TRUE value, the control goes back and the do…while block will be executed once more. Otherwise, the control goes beyond the ‘while statement’ to the statement which immediately appears after the while statement. Following is the complete flowchart.

images

Flowchart

images

The Program

/* computing the area of circles given their radii */

#include<stdio.h>
#include<conio.h>
main()
{

   /*declaring the variables*/
   float r,area;
   char choice,
   /* clearimg the screen*/
   clrscr();

   do
   {
      /* accepting the radius*/
      printf ( “Input the value of a radius
” ) ;
      scanf(“%f“,&r);

      /* calculating the area of the circle*/
      area=3.142 * r * r;

      /* printing the radius and the area */
      printf(“	Radius = %5.2f	Area = %6.2f	
”,r,area);

      printf (“
Do you want to continue (y-YES, n - NO)
”) ;
      getchar();
      /*accepting the choice to continue or not*/
      scanf(“%c”,&choice);

     }     while(choice == ‘y’) ;
}

EXERCISES

  1. The first few numbers of a sequence are 1 3 4 7 11 18 29 47 ........ . Develop a flowchart to generate required number of terms of the sequence. Also implement the same using C.
  2. Develop a flowchart to multiply two given positive integers by the method of successive addition. {Hint: 4 × 3 = 4+ 4+ 4 : Adding three 4's}
  3. Develop a flowchart to count the number of digits in a given integer.
  4. The function cos(x) is expanded as cos(x) = 1 − x2/2! + x4/4! − x 6/6! + … Develop a flowchart to compute the sum of the above series expansion, correct up to four decimal places.
  5. Develop a flowchart to compute the sum of the exponential series: 1 + x/1! + x2/2! + x3/3! +… The summation has to be done for n terms as well as for a desired accuracy. However, the computation should stop whenever either of the condition is satisfied first.
  6. Develop a flowchart to find the sum of first n terms of the expansion of the sin(x) function for all values of x from 0° to 180° in steps of m0 and to tabulate the computed sums. Implement the same in C.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.157.197