Docstoc

Programming in Turbo C

Document Sample
Programming in Turbo C Powered By Docstoc
					                                       Programming in C

DEFINITION OF A COMPUTER
         A computer is a fast electronic calculating machine that accepts
input information, processes it according to a list of internally stored
instructions called a program, and produces the resultant output
information.

DEFINITION OF AN ALGORITHM
•A sequence of well-understood steps that one takes to do something.
•A set of instructions for a person to follow in order to accomplish a certain
         task.
•A sequence of instructions that tell how to solve a particular problem.

Examples:
        1.        directions for going to a certain place
        2.        baking a chocolate cake
        3.        computing income tax
        4.        searching for a name in a telephone directory
CHARACTERISTICS OF AN ALGORITHM

1. Specify each step or instruction exactly.
      There must be no ambiguity.
      The instructions must be clear.
2. There must be a finite number of steps.
      The algorithm must terminate.
      There must be a stopping point.
3. There must be an output.
      The algorithm must produce the correct result.
                TYPES OF PROGRAMMING LANGUAGES:


1.     Machine Language
       The natural or primitive language that the computer actually
understands. This programming language consists of 0‟s and 1‟s which
makes programming very difficult.

        Sample machine language program to add 5 and 3 (using the
Intel 486 processor instruction set):
                         10111000
                         00000101
                         00000000
                         10111011
                         00000011
                         00000000
                         00010001
                         11011000
2.     Assembly Language
         A programming language that uses “abbreviations” or mnemonics
in place of binary patterns in order to make the task of programming
easier. Mnemonics are designed to be easy to remember and are a
significant improvement over binary digits.
         An assembly language program has to be converted to machine
language before a computer can execute it. An assembler is a special
program that translates assembly language mnemonics into machine
language.
         Sample assembly language program to add 5 and 3 (using the
Intel 486 processor instruction set):

                       MOV AX, 05
                       MOV BX, 03
                       ADC AX, BX

NOTE: Both machine and         assembly    languages   are   low-level
programming languages.
3.      High-Level Language
         A programming language that uses english-like commands or
instructions. High-level languages are the easiest to use and contains many
complicated or advanced instructions.
         A high-level language has to be converted to machine language
before a computer can execute it. A compiler is a special program that
translates high-level language instructions into machine language.
         Examples of High-level Languages:
         1.       FORTRAN (FORmula TRANslation)
         2.       COBOL (COmmon Business-Oriented Language)
         3.       BASIC (Beginner‟s All-purpose Symbolic Instruction Code)
         4.       Pascal

Sample BASIC program to add 5 and 3:

                         LET A = 5
                         LET B = 3
                         LET C = A + B
    COMPARISON BETWEEN LOW-LEVEL AND HIGH-LEVEL
                                     LANGUAGES

      High-level languages are easier to understand and
use while low-level languages are difficult.

      Low-level languages are more efficient (programs
written in low-level languages are better in terms of
speed and hardware utilization) than high-level
languages.

TRADE-OFF : EASE OF USE VS. EFFICIENCY
             (having one sacrifices the other)
                      WHAT KIND OF A LANGUAGE IS C?

        C is a “middle-level” language.
        C-language is easier to use compared to machine or assembly
language and it is more efficient than other high-level languages.

OTHER FEATURES OF C

        C is very portable. It is easy to transfer (with little or no
modifications) a C program written for one type of machine to another
machine.

         C is a structured language.     The distinguishing feature of a
structured language is compartmentalization of code and data

          This is the ability of a language to section off and hide from the rest
of the program all information and instructions necessary to perform a
specific task.

         A C program consists of one or more functions.         A function is a
subroutine or subprogram that performs a certain task.
THE PROGRAMMING PROCESS
  1. Specify the task
  2. Find an algorithm for its solution
  3. Code the algorithm in C
  4. Test the solution
A SIMPLE C PROGRAM
The following program prints the phrase “Introduction to
   C-Language” on the screen:

             #include <stdio.h>
             main ()
             {
             printf (“Introduction to C-Language\n”);
             }
The important parts of the program above are:
1. #include <stdio.h>
   This is a preprocessor directive (or compiler directive). All
   preprocessor directives start with a # symbol. This particular
   directive tells the compiler to include or to insert a copy of the
   header file stdio.h at this point of the program. The stdio.h file
   (standard input-output) tells C how to perform or execute input
   and output functions.

2. main ()
   main() is the name of a function. Every C program has a main()
   function where execution begins. The parentheses following main
   indicate that it is a function. All function names have a ().

3. { and }
   The left brace indicates the start of a function while a right brace
   denotes the end of a function. In other word, braces group
   statements or instructions together.
4. printf()
   printf() is one of the several built-in functions of C that programmers can
   use in their programs. This purpose of this function is to print something
   on the computer screen. C has a large collection or library of built-in
   functions. The stdio.h file contains information needed in executing this
   function.

5. “Introduction to C-Language\n”
   A string constant in C is a series of characters surrounded by double
   quotes. This string is an argument to the function printf(). In other
   words, it tells the printf() function what to print on the computer screen.
   The two characters \n at the end of the string (read “backslash n”)
   represents a single character called newline. It is a nonprinting character
   that tells C to advance the cursor on the screen to a new line.

   Arguments are values that are passed to a function at the time it is called.
   Some functions may have several arguments (commas separate multiple
   arguments). However, there are some functions that do not require
   arguments (like the main() function).
6.   printf (“Introduction to C-Language\n”);

     This statement calls the function printf() with a single argument,
     namely, the string:
         “Introduction to C-Language\n”
     Notice that this line ends with a semicolon. All statements in C end with
     a semicolon.
                            More on printf () function

       The printf() function prints its arguments continuously across
the computer screen. The newline character causes the cursor to
move to a new line.

       The following program gives the same result as in the previous
program:

                       #include <stdio.h>
                       main ()
                       {
                       printf (“Introduction to ”);
                       printf ( “C-Language\n”);
                       }
The following program segment will print the string Introduction to
and the string C-Language on separate lines:

               printf (“Introduction to\n”);
               printf ( “C-Language\n”);
                               or
               printf (“Introduction to\n C-Language\n”);
 VARIABLES, EXPRESSIONS, AND ASSIGNMENT

         In any programming language, variables store values. Different
kinds of variables are necessary to store different kinds of data.
Therefore, it is important to specify the type of each variable.

        Sample program:

                #include <stdio.h>
                main()
                {
                int gross, net, cost;
                gross = 100;
                cost = 10;
                net = gross - cost;
                printf(“If the gross income is %d\n”, gross);
                printf(“ and the cost of materials is %d,\n”, cost);
                printf(“ then the net income is %d.\n”, net);
                }
The important parts of the program above are:
1.      # include <stdio.h>
        main()
        {
        int gross, net, cost;

          The first line within the body of function main() is the declaration.
This is the part of the program that declares where all variables of the
function main(). This program has three integer variables. The variable
names are gross, net, and cost. Integer variables can have integer values
(whole numbers). Like all statements, declarations end with a semicolon.

          A variable name or identifier, consists of a sequence of letters,
digits, and underscores, but may not begin with a digit. Programmers should
choose identifiers that reflect their use in the program.

          C is case sensitive (uppercase letters are different from lowercase
letters). Therefore, the variable name gross is different from Gross.
2.      gross = 100;
        cost = 10;
        net = gross - cost;

        These are assignment statements.

         The value of the expression on the right side of the equal sign
(=) is assigned to the variable on the left side. The equal sign is the
basic assignment operator in C.
3.      printf(“If the gross income is %d\n”, gross);

        This particular printf() statement has two arguments:

                “If the gross income is %d\n”   and             gross

        The first argument of a printf() statement is always the
control string. The control string in this example contains a
conversion or format specification %d. The format %d causes the
value of the expression or variable in the second argument (the
variable gross) to be printed in the format of a decimal integer. The
remaining printf() statements are similar to this one.
In general, C programs follow the form:

                        preprocessing directives
                        main()
                        {
                        declarations
                        statements
                        }

        At the top of the file are the preprocessing directives such as
#include lines.

       In the body of main() the declarations must come before the
statements. The declarations tell the compiler what kind of data
each variable can store. After declaring all the variables, they can
assume values and can be used in expressions.
                        SOME C ARITHMETIC OPERATORS

1. Addition (+)
   Example:             sum = num1 + num2;

2. Subtraction (-)
   Example:             diff = num – 10

3. Multiplication (*)
   Example:             product = 20 * num

4. Division (/)
   Example:             quotient = num / 43

5. Modulus (%) - yields the remainder of a division process
   Example:             rem = 5 % 2
                          the variable rem will be equal to 1
                                               BASIC C DATA TYPES

1.        int
          Variables of type int can hold integer quantities that do not require
fractional components such as 0, 12, 135, and -24. int variables can usually hold
integer numbers between -32,768 to 32,767. Typical memory requirement is 2
bytes.

2.        float
          Variables of type float are for numbers with a fractional component
(floating-point numbers) or for numbers with very large values such as 12.34, -
0.5, 9,456,776, and 87.45 x 1023. float variables can usually hold real numbers
between 3.4 x 10-38 to 3.4 x 1038. Typical memory requirement is 4 bytes.
3.       double
         Variables of type double are similar to float variables but can hold a
wider range of numbers. double variables can have numbers whose values range
from 1.7 x 10-308 to 1.7 x 10308. Typical memory requirement is8 bytes.

4.       char
         Variables of type char hold 8-bit ASCII characters such as „A‟, „B‟, „C‟, or
any other 8-bit quantity. Typical memory requirement is 1 bytes.
        MORE ON THE CONVERSION OR FORMAT
                               SPECIFIERS
Some of the conversion specifiers of C are:

• %c    for char variables or constants

• %d for int variables or constants

• %f    for float variables or constants

• %lf for double variables or constants

• %e similar to %f except that the output is in scientific notation

• %g    same as %f or %e whichever is      shorter
                                  SAMPLE PROGRAMS

1. # include <stdio.h>
   main()
   {
   char sample;
   sample = „M‟;
   printf (“The letter is %c.”, sample);
   }
       The output of this program is:
                     The letter is M.
2. #include <stdio.h>
   main()
   {
   float x, y, sum;
   x = 1.5;
   y = 2.0;
   sum = x + y;
   printf(“The sum of x and y is %f.\n”, sum);
   }

The output of this program is: The sum of x and y is
  3.500000.
3. #include <stdio.h>
   main()
   {
   int num1, num2;
   num1 = 5;
   num2 = 3;
   printf (“The product of 5 times 3 is %d.”, num1 *
   num2);
   }

The output of this program is: The product of 5 times 3 is
  15.
4. #include <stdio.h>
   main()
   {
   int a, b;
   float answer;
   a = 10;
   b = 2;
   answer = a / b;
   printf (“%d divided by %d is %f.”, a, b, answer);
   }

The output of the program is: 10 divided by 2 is 5.000000.
OTHER FEATURES OF THE printf() FUNCTION

When printf() prints its arguments, the place where it is printed is its
field and the number of characters in its field is the field width. The
field width is specified in a format as an integer occurring between the %
and the conversion character.

                 Example:
                 printf (“%c%3c%7c\n”, „A‟, „B‟, „C‟);

                 The output of this will be:
                 ABC

                                          space

         There are two spaces between A and B since the second
character has a field width of 3 (the two spaces plus the character „B‟
itself. There are 6 spaces between „B‟ and „C‟ since the third character
has a field width of 7 (the six spaces plus the character „C‟ itself).
In printing floating-point values, C allows the programmer to control
the precision (the number of decimal places to the right of the
decimal point) as well as the field width. In the format of the form
%m.nf the field width is m and the precision is n. The programmer
may opt to specify either the field width or the precision only.

        Example:
               printf (“%.1f %.2f %.3f\n”, 1.0, 2.0, 3.0);
               printf (“%7.1f%7.2f%7.3f\n”, 4.0, 5.0, 6.0);

        The output of this will be:
               1.02.003.000
               4.05.006.000
                    INITIALIZATION OF VARIABLES

A program may place initial values in variables upon their
declaration.

      Example:
      The program:
            #include <stdio.h>
            main()
            {
            int x = 10, y = 20;
            printf (“x is %d and y is %d, x, y);
            }
is equivalent to:

             #include <stdio.h>
             main()
             {
             int x, y;
             x = 10;
             y = 20;
             printf (“x is %d and y is %d, x, y);
             }
                                   THE scanf() FUNCTION

        The purpose of the scanf() function is to input data to a
program. If printf() is for printing formatted output, then scanf() is
for reading formatted input.
                Example:
                scanf(“%d”, &num);

         This statement causes the program to pause and wait for the
user to input data at the keyboard. Once the user types in a number,
that number is then stored or placed in variable num.

        The format %d in this example causes the program to
interpret the input characters as a decimal integer.

        The ampersand symbol (&) should always be present right
before the name of the variable where the input data is to be stored.
  SAMPLE PROGRAMS USING THE scanf() FUNCTION


1. Program to convert dollars to pesos
   #include <stdio.h>
   main()
   {
   float dollars, pesos;
   printf (“Enter the no. of dollars you want to convert : “);
   scanf (“%f”, &dollars);
   pesos = dollars * 26.95;
   printf (“\n\n$ %.2f is equal to %.2f pesos.”, dollars, pesos);
   }

   Sample Output:
   Enter the no. of dollars you want to convert : 3.55
   $ 3.55 is equal to 95.67 pesos.
2. Program to compute the area of a circle
   #include <stdio.h>
   main()
   {
   float radius, area, pi = 3.14;
   printf (“Enter the radius of the circle: “);
   scanf (“%f”, &radius);
   area = pi * radius * radius;
   printf (“\n\nThe area of the circle is %.2f.”, area);
   }

   Sample Output:
   Enter the radius of the circle: 2.0
   The area of the circle is 12.56.
3. Program to prompt the user to enter his initials and age
   #include <stdio.h>
   main()
   {
   char first, middle, last;
   int age;
   printf (“Enter your three initials and age: “);
   scanf (“%c%c%c%d”, &first, &middle, &last, &age);
   printf (“\n\nGreetings %c.%c.%c. Next year your age will
                 be %d.”, first, middle, last, age + 1);
   }

  Sample Output:
  Enter your three initials and age: MMA21
  Greetings M.M.A. Next year your age will be 22.
 SYMBOLIC CONSTANTS (THE #define DIRECTIVE)


        The purpose of the #define directive is to define an identifier
and a value that will be substituted for the identifier each time it is
encountered.
        The general form of this directive is:
                #define identifier value
        Example:
                #include <stdio.h>
                #define PI       3.1416
                main()
                {
                float radius, area;
                printf (“Enter the radius of the circle: “);
                scanf (“%f”, &radius);
                area = PI * radius * radius;
                printf (“\n\nThe area of the circle is %.2f.”, area);
                }
As a general rule, identifiers for symbolic constants are always in uppercase
letters to distinguish them from regular variables.

Example:
        The gravitational attractive force between two bodies of mass m1
and m2 separated by distance d is given by:
                                F = G m1 m2

                                        d2

                  where G is the universal gravitational constant:

                               G = 6.673 x 10-8 cm3/g sec2

         Write a C program that will read in the mass of two objects and the
distance between them and will then output the gravitational force between
them.
Solution:
# include <stdio.h>
#define GRAVITY 6.673e-8
main()
{
  float mass1, mass2, distance, force;
  printf ("Enter the mass of the first object > ");
  scanf ("%f", &mass1);
  printf ("Enter the mass of the second object > ");
  scanf ("%f", &mass2);
  printf ("Enter the distance between the two > ");
  scanf ("%f", &distance);
  force = GRAVITY * mass1 * mass2 / (distance * distance);
  printf ("\n\nThe Gravitational Attractive Force between the two objects is
%e.",
  force);
}
                  C-LANGUAGE CHARACTER SET

 Among the characters that a programmer can use are
  the following:
  lowercase letters :     a     b      c     ...   z
  uppercase letters :     A     B      C     ...   Z
  digits            :     0     1      2     ...   9
  other characters :      * / = ( ) { } < > „ “! @#
  $                       %&_|^~\.           ,;:?
  white space characters such as blank, newline, and tab

 These characters are collected by the compiler into
  syntactic units called tokens.
                                   MORE ON IDENTIFIERS

         C-Language defines the names that are used to reference
variables, functions, labels, and various other user-defined objects as
identifiers.
         An identifier can vary from one to several characters. The
first character must always be a letter or an underscore ( _ ) with
subsequent characters being letters, numbers, or underscores.
                 Sample valid identifiers:
                         tax_rate
                         final_grade
                         _counter
                 Sample invalid identifiers:
                         1st_data
                         high+low
                         last*temperature
         Remember that C is case sensitive (uppercase letters are
different from lowercase letters). Therefore, the identifier Tax_rate
is different from tax_rate.
       The following are examples of keywords in C that should
never be used as identifiers:

       auto           double         int            struct
       break          else           long           switch
       case           enum           register       typedef
       char           extern         return         union
       const          float          short          unsigned
       continue       for            signed         void
       default        goto           sizeof         volatile
       do             if             static         while
         C will only recognize a certain number of characters in
identifiers. The exact number depends on the computer system being
used.
         Example:

         Turbo C running on an IBM PC or compatible will recognize the
first 32 characters of an identifier. This means that if two identifiers
are identical in the first 32 characters but different in subsequent
characters, Turbo C will not be able to tell them apart. The variable
names
                 this_is_a_very_long_variable_name
                                  and
                 this_is_a_very_long_variable_name_1

                are the same as far as Turbo C is concerned.
                                    MORE ON OPERATORS

1.The Increment Operator (++)

      The increment operator (++) is a unary operator that
increments the contents of a variable by 1. For example, the
statement

                          ++ age;

        increments the contents of the variable age by 1. If age
= 5, then ++age will make age = 6. In other words, ++age is the
same as age = age + 1.

       The ++ operator can also be in the postfix notation.
This means that age ++ will also have the same effect as ++age.
2.The Decrement Operator (--)

       The decrement operator (--) is a unary operator
that decrements the contents of a variable by 1. In other
words, --age or age-- is the same age = age - 1.

NOTE: Both the increment and decrement operators are
not applicable to constants or ordinary expressions. For
example, --8 and ++(a + b) are not allowed.
       DIFFERENCE BETWEEN POSTFIX AND PREFIX NOTATIONS OF THE
                         INCREMENT AND DECREMENT OPERATORS


      The postfix and prefix notations of the increment
and decrement operators differ when used in expressions.
      Examples:
      a = ++age;
       Assume age = 5. After execution of this statement,
a = 6 and age = 6. In other words, the value of age is
incremented first and then its value is assigned to
variable a.
       a = age++;
       Assume age = 5. After execution of this statement,
a = 5 and age = 6. In other words, the value of age is
assigned first to variable a and then its value is
incremented.
Sample Program:
#include <stdio.h>
main()
{
int a, b, c, d;
c = 1;
d = 1;
a = ++c;
b = d++;
printf (“The value of a is %d and the value of c is %d.\n”, a, c);
printf (“The value of b is %d and the value of d is %d.\n”, b, d);
}

The output of the program is:
  The value of a is 2 and the value of c is 2.
       The value of b is 1 and the value of d is 2.
   PRECEDENCE AND ASSOCIATIVITY OF OPERATORS



        As in algebra, the arithmetic operators (+, -, *, /, and %) in C
follow rules in precedence and associativity. These rules determine
how evaluation of expressions should take place.

        The following summarizes the rules of precedence and
associativity:

          Operators                              Associativity

    ( ) ++ (postfix) -- (postfix)                left to right
 + (unary) - (unary) ++ (prefix) -- (prefix)     right to left
        *     /     %                            left to right
            + -                                            left to right
       = +=     -= *= /= etc.                    right to left
In the table, all operators in the same line have equal
precedence with respect to each other, but have higher
precedence than all operators that occur on the lines
below them. The associativity rule for all operators on a
given line appears on the right side of the table.
         EXAMPLES ON EXPRESSION EVALUATION


1.       2 * 5 + 5 * 3 + 4 * 10

     =   10 + 5 * 3 + 4 * 10
     =   10 + 15 + 4 * 10
     =   10 + 15 + 40
     =   25 + 40
     =   65
2.       -8*5/4*2

     =   - 40 / 4 * 2
     =   - 10 * 2
     =   - 20
3.       4%2+3-4*5

     =   0+3-4*5
     =   0 + 3 - 20
     =   - 17
4.       x * y - z / 2 where x = 5, y = 4 and z = 12

     =   5 * 4 - 12 /2
     =   20 - 12 / 2
     =   20 - 6
     =   14
5.       7 - - a * ++b    where a = 2 and b = 4

     =   7 - (-2) * ++b
     =   7 - (-2) * (5)
     =   7 - (-10)
     =   7 + 10
     =   17
6.     ++u * v - w --               where u = 1, v = 2, and
     w=3
     =   ++u * v - 3
     =   2*v-3
     =   2*2-3
     =   4-3
     =   1

     NOTE:      In the case of w--, the value of w will be
     used in the evaluation of the expression first before it
     is decremented. But in the case of ++u, the value of u
     was incremented first before being used in the
     expression.
                                          PARENTHESES

       Parentheses change the rules of precedence and
associativity. Expressions in parentheses have the highest
precedence.

      Examples:
      1.   5+3*4+2
      =    5 + 12 + 2 =          17 + 2   =   19

      2.     5 + 3 * (4 + 2)
      =      5+3*6          =    5 + 18   =   23

      3.     (5 + 3) * (4 + 2)
      =      8 * (4 + 2)    =    8*6      =   48
    PERFORMING ARITHMETIC OPERATIONS ON DIFFERENT DATA
                                                TYPES


        Any variable whose value is computed from at least one
floating-point operand should generally be a floating-point variable.
        Example:
                x = 3.5 + 2
                        Variable x should be of type float or double.
                y = 2.7 * z

        Variable y should be of type float or double regardless on the
type of variable z.

         Any variable whose value is computed from at least one
division operation should be a floating-point variable.
         Example:
                 x = y/z
                        Variable x should be of type float.
                              INTRICACIES OF DIVISION

        Division between two integers yields either an integer or a
floating-point number.
                Examples:
                       y = 10 / 2 = 5 (integer)
                       y = 11 / 2 = 5.5 (floating-point)

        In C, the division of two integers always results in an integer.
The value obtained will be truncated, or rounded down to the largest
whole number less than the result.
                Examples:
                         y = 11 / 2 = 5
                         y = 10 / 3 = 3
                         y = 5/2 = 2

        In C, the division between a floating-point number and an
integer always results in a floating-point number.
SAMPLE PROGRAMS
1. #include <stdio.h>
   main()
   {
   float a;
   a = 5/2;
   printf ("The value of a is %d.", a);
   }
   The output of this program is:
       The value of a is 0.
2. #include <stdio.h>
   main()
   {
   int a;
   a = 5/2;
   printf ("The value of a is %d.", a);
   }
   The output of this program is:
        The value of a is 2.
3. #include <stdio.h>
   main()
   {
   int a;
   a = 5/2;
   printf ("The value of a is %f.", a);
   }
   This program will not run (although it will compile).
   The following error message will appear:
        printf: floating point formats not linked
        Abnormal program termination
4. #include <stdio.h>
   main()
   {
   float a;
   a = 5/2;
   printf ("The value of a is %f.", a);
   }
   The output of this program is:
       The value of a is 2.000000.
                     THE ASSIGNMENT OPERATOR

        Unlike other programming languages, C treats the equal
sign (=) as an operator. Its precedence is lower than the other
operators that were discussed so far and its associativity is
from right to left.
                Examples:
                1.     The program segment:
                               a = 1;
                               b = 2;
                               c = a + b;
                       is equivalent to:
                               c = (a = 1) + (b = 2);
                2.     The expression:
                               a = b = c = 0;
                       evaluates to:
                               a = (b = (c = 0));
                      THE COMBINED OPERATORS

It is a very common assignment to add one variable to another.
         Example:
                      x = x + y

gets the value of x and y, add them together, then store the
result in x.

       A combined operator offers a shortcut for these kinds of
expressions.
             x=x+y                 x += y
             x=x-y                 x -= y
             x=x*y                 x *= y
             x=x/y                 x /= y
             x=x%y                 x %= y
5. #include <stdio.h>
   main()
   {
   float a;
   a = 5.0/2;
   printf ("The value of a is %f.", a);
   }
   The output of this program is:
       The value of a is 2.500000.

				
DOCUMENT INFO
Shared By:
Categories:
Stats:
views:18979
posted:12/4/2009
language:English
pages:63
Description: Programming C at iAcademy