CHAPTER 2

Basic Techniques

Undoubtedly, present day computers are very powerful tools, which are being used to solve a variety of problems of varying complexities. Yet they cannot solve any problem by themselves however trivial the problem may be. It is the responsibility of the computer user to provide all necessary information to the computers for it to work for us. For example, even to add just two numbers the user has to provide the necessary procedure (in the form of a program) as well as supply (input) the necessary data values and get the results (output) of the addition out of the machine. This chapter discusses few very straightforward examples by studying which the reader gets acquainted with the tricks of reading in (i.e. input operation) the data values, performing very simple computations and to getting out(i.e. output operation) the computed results.

2.1 SUM OF TWO GIVEN NUMBERS

The Method

Let the two given numbers be a and b. Also, let both these numbers be integers. These two numbers are first read in (i.e. input). Then the sum is computed using a statement like sum = a + b. Observe that after actually computing the sum, the answer is stored in a variable called sum. As the required result is in sum, the value of sum is finally printed out or displayed (i.e. output).

C-Tips

In C the function scanf() is used to input values of data items like a and b. The function printf() is used to output the computed results. As such functions are available as predefined or library functions on a file called <stdio.h>, this file must be included in the beginning. Such inclusions are made using statements called preprocessor directives. Here #include is used as preprocessor directive. It is a good practice to clear the display screen before the results of a presently running program is displayed on the screen. The C function clrscr () is used for this clearing purpose. This function is available on a file called <conio.h> which also must be included in the beginning. Files like <stdio.h> and <conio.h> which are included in the beginning, something like a heading, are called header files. Files with names having .h extension are generally identified as header files. Brief explanations about the program or some specific statement are provided using statements called comment statements. In C, comment statements are written with a /* pair in the beginning and a */ pair at the end of the statement. Since integers are handled by the scanf () and printf() functions the format specifier %d is used. It may be observed that there will be a control string with both these scanf() and printf() functions. This string will be within a pair of double quote marks (“). A produces a new line.

Flowchat

images

The Program

/* Program to find the sum of two given numbers */
#include<conio.h>                   /* Including header file */
#include<stdio.h>

main()
{
        int a,b,sum;                /* Declaration of variables */
        clrscr();
       /* A message is displayed on the monitor indicating the action
           to be taken by the user */
       printf(“

Enter two numbers
”) ;
       /* The input statement follows */
        scanf(“%d%d”,&a,&b);
        /* The output statement follows */
        printf (“ 
 a = %d	 b = %d
”, a, b) ;
        sum= a+b;                   /* Computing the sum */
       printf (“sum = %d
”, sum) ; /* Printing the sum */
}

Note: It is a good programming practice to echo i.e. to display, the values of the data items as and when they are input. An input statement like scanf() silently expects the values of the data items to be input. Therefore it is recommended to include statements which display the action to be taken by the user just prior to input statements.

2.2 SWAPPING THE CONTENTS OF TWO VARIABLES

Swapping of two variables means exchanging the values of two variables. For example, let a and b be two given variables with the values 5 and 10 stored in them respectively, as shown in the figures, below.

images

After swapping the value of a will be 10 and the value of b will be 5, as shown in the figures, below

images

The Method

In order to exchange the values of a and b, first a copy of A is made and stored in a temporary location (temp). Then the value of b is copied on to A. Finally, the contents of temp is copied on to the variable b. These operations are illustrated in the following diagram where 1, 2 and 3 indicate the order in which the operations are performed.

images

C-Tips

As already mentioned the function scanf() is used to input data items. The function printf() is used to output results as well as any other values. The function clrscr() is used to clear the screen. Here also, the files <stdio.h> and <conio.h> are included in the beginning. A produces a tab (usually 5 blanks) in the output.

Flowchart

images

The Program


/* Program to swap the contents of two variables */

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

main()
{
       int a,b,temp;              /* Declaration of variables */
      clrscr(); 
      printf(“

Enter two numbers
”);
      /*The input statement follows*/
      scanf(“%d%d”,&a,&b);
      /*The output statement follows*/
      printf (“
 a = %d	 b = %d
”, a, b) ;
      temp = a;
      a = b;
      b = temp;                 /* Swapping contents of a and b */
      printf (“After swapping 
 a = %d 	 b = %d
”, a, b) ;
}

2.3 SIMPLE INTEREST CALCULATION

The Method

The formula used to calculate simple interest is si = ( p r t )/100

where p is the principal,

r is the rate of interest and

t is the time period.

Obviously, the values of p, r and t are input and the total interest for the given period is computed and output. The process involved is shown in the adjoining flowchart.

Care should be taken to avoid integer division while evaluating expressions like si = (p * t * r )/100.

Flowchart

images

C-Tips

The values of the variables like p, r and t are input using the input function scanf() statement. The result computed i.e. the value of si in this case is output using the output function printf(). These functions i.e., the scanf() and printf() are available on a C file named <stdio.h>. Here also <stdio.h> and <conio.h> files are included in the beginning. The format specifier %f is used to handle float type data items.

The Program

/* Program for simple interest calculation */

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

main()
{
        float p, r, t, si ;         /* Declaring variables */
       clrscr();
       printf(“

Enter principal, rate of interest and time
           


”);
       scanf (“%f%f%f”, &p, &r, &t);
       /* Entering principal, rate of interest and time */
       printf (“
Principal = %f	Rate of interest = %.2f	Time =
            %.2f
”,p,r,t);
       si=(p*r*t)/100;            /* Computing simple interest */
       printf(“

Simple Interest = %.2f
”,si);
}

2.4 COMPUTING THE AREA OF A CIRCLE GIVEN ITS RADIUS

The Method

The relation used is area = πr2 where r is the radius of the circle. It may be observed that here the value of the radius ‘r’ is to be input. The value of π is 3.14. The process involved can be shown pictorially as in the following flowchart. It should be observed that π is a constant and cannot be used as it is. Its value has been used at the proper place.

C-Tips

In situations where a constant like π is to be used at many number of places, it will be defined as a symbolic constant and this symbolic constant will be used at the required places. Symbolic constants are defined in the beginning and are put in to use using the #define preprocessor directive. Since a character like π is not a valid C character, it is represented by some meaning full name like PI. Also it may be noted that names used to represent symbolic constants are conventionally written using uppercase alphabets.

Flowchat

images

The Program

/* Program to compute the area of a circle given its radius */

#include<stdio.h>
#include<conio.h>
#define PI 3.1428                 /*Using PI value as a symbolic
                                       constant*/
main()
{
     float r, area; /* Declaring variables */
     clrscr();
     printf(“

Enter radius of the Circle :”);
     scanf(“%f”, &r);   /* Entering radius of the circle */
     printf(“

Radius of the given Circle :%f
”, r);
     area = PI * r * r;          /* Computing area of the circle */
     printf(“

Area of the given Circle :%f
”, area);

2.5 COMPUTING THE AREA OF A TRIANGLE GIVEN ALL ITS SIDES

The Method

images

where a, b, c are the three sides of a triangle and ‘s’ is half of the perimeter of the triangle (s = (a + b + c )/2).

Flowchat

images

As the three sides a, b and c are given, they are first input. Then the half perimeter s is computed. Finally, the required area is computed and output. This process is shown pictorially in the adjoining flowchart.

C-Tips

As already mentioned both scanf() and printf() are available as predefined or library functions on a header file called <stdio.h> which is also included in the beginning itself. The function sqrt() is also available as a library function. While using the sqrt() function care should be taken to see that the argument is non-negative. In other words, the argument to the function sqrt() should not be negative. Since sqrt() function is available on the file <math.h> it is also included. Since one likes to clear the screen before results are displayed <conio.h> file is also included in the beginning.

The Program

/* Program to compute the area of a traingle given its sides */

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

main()
{
         float a,b,c,s,area;    /* Declaration of variables */
        clrscr();
        printf(“

Enter the three sides of the triangle
”);
        printf (“such that sum of any two sides is greater than the
           third side.

”);
        scanf(“%f%f%f”, &a, &b, &c);
        /* Entering three sides of the triangle such that sum of two
        sides should be greater than the third side */
        printf(“
Three sides of the triangle are
                         a=%f	b=%f	c=%f
”,a,b,c);
        s=(a+b+c)/2;             /* Computing value of s */

        area =sqrt(s*(s-a)*(s-b)*(s-c));
                    /* Computing area of the triangle*/
        printf(“

Area of the triangle is %f
”,area);
}

2.6 EXTRACTING THE UNIT'S DIGIT OF A GIVEN INTEGER NUMBER

The Method

If 43256 is the given number then 6 is the digit we are looking for. The problem here is to extract 6, the digit in the unit's position. Since the given number is in decimal number system (i.e. base 10 system) 10 is used to move the positions of the individual digits as illustrated below.

images

As seen from the above illustration when the given number is multiplied by 10, each digit moves to the left by one position. Therefore, the position value of each digit increases 10 times. A 0 (zero) gets appended to the number from RHS and the digit in the highest position goes out. When the given number is divided by 10, the position value of each digit reduces 10 times as each digit moves to the right by one position. The digit at the unit's position goes out as remainder and the size of the total number gets reduced by one digit.

In this case, we are interested in the digit that is going out when the given number is divided by 10. (i.e. the remainder). With many of the computer languages we can perform two types of divisions. The integer division and modulo division. When integer division is performed the result will be only the quotient. When the modulo division is performed the result will be only the remainder. Obviously, to get the unit's position digit we have to employ the ‘modulo 10’ division and trap the remainder by saving it in a variable. The complete procedure to extract the unit's digit may be shown diagrammatically as in the flowchart below.

C-Tips

In C there is an operator known as the Modulo divisor, %. When this operator is used modulo division takes place and the remainder of the division will be returned as the answer.

For example, 254% 10 returns 4 as the result. Observe that this is the remainder of the % division.

While handling larger integer numbers it is advised to use the data type long for the declaration of the corresponding variable. With long data type %ld is used as the format specifier.

Flowchart

images

The Program

/* Extracting the unit's digit of a given integer number */

#include<stdio.h>
main()
{
 long number ; int digit_req;
 clrscr();
printf(“Enter a number : 
”);
scanf(“%ld”,&number);
printf(“Given number = %ld
”, number);

/* The remainder in the following division operation is the unit's digit */

digit_req=number % 10;

printf(“The digit at the unit's position of the given number is: %d”,digit_req);
}

EXERCISES

  1. Draw a flowchart to convert the temperature given in degrees Fahrenheit to degrees Celsius, using the relation c = (5/9) x f − 32). Translate the flowchart into a C program.
  2. Given the radius of a sphere, it is required to compute its volume and area. Draw a flowchart for the same. Translate the same into a C program. Use the relations: Volume = (4 πr3)/3 and Area = 4 πr2.
  3. Develop an algorithm to evaluate the polynomial 3x3 − 5x2 + 6 for x = 2.55. Write a C program for the same.
  4. Given that the integer variables a, b and c have the values 8, 3 and − 5 assigned to them respectively and the float type variables x, y and z have the values 8.8, 3.5 and − 5.2 assigned to them respectively, draw a flowchart and hence write a C program to read in the values for the different variables, perform the following operations and output the results. Comment on the results.
    • (i) a*b/c
    • (ii) a% b
    • (iii)x/y
    • (iv) x%y
..................Content has been hidden....................

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