Friday, April 12, 2013

C-Programming Example


/**** Program to Find Sum and Average of Three Real Numbers ****/
#include <stdio.h>
main()
{
float a, b, c, sum, avg;
printf("\nEnter value of three numbers: ");
scanf("%f %f %f", &a, &b, &c);
sum = a + b + c;
avg = sum / 3;
printf("\nSum = %.2f", sum);
printf("\nAverage = %.2f", avg);
getch();
}



Simple program to show how children get out of control if not monitored by the parent.
#include <stdio.h>
main (int argc, char *argv[])
  { int pid ;
     char *args[2] ;
     printf("Ready to FORK\n") ;
     pid =  fork() ;
     if (pid ==0)
        { printf("I AM THE CHILD!!\n") ;
          args[0] = "./a.out" ;
          args[1] = NULL ;
          execv("./a.out", args) ;
          printf("OPPSSSS\n") ;
        }
   else
        printf("I AM THE PARENT!!!\n") ;
   //wait(NULL) ;
}

Monday, April 8, 2013

C-Programming



What is C?
A language written by Brian Kernighan and Dennis Ritchie. This was to be the language that UNIX was written in to become the first "portable" language.
Why use C?
Mainly because it produces code that runs nearly as fast as code written in assembly language. Some examples of the use of C might be:
        Operating Systems
        Language Compilers
        Assemblers
        Text Editors
        Print Spoolers
        Network Drivers
        Modern Programs
        Data Bases
        Language Interpreters
        Utilities
      A computer program is set of instructions, written in any of the computer languages, as a step by step solution of problems.
      Programming is the process of planning, designing, writing, testing and maintaining these procedures or programs according to user need.
History of C
      In 1972 Dennis Ritchie at Bell Labs writes C and in 1978 the publication of The C Programming Language by Kernighan & Ritchie caused a revolution in the computing world
      In 1983, the American National Standards Institute (ANSI) established a committee to provide a modern, comprehensive definition of C. The resulting definition, the ANSI standard, or "ANSI C", was completed late 1988.
      Why C Still Useful?
      C provides:
      Efficiency, high performance and high quality s/ws
      flexibility and power
      many high-level and low-level operations à middle level
      Stability and small size code
      Provide functionality through rich set of function libraries
      Gateway for other professional languages like C à C++ à Java
      C is used:
      System software Compilers, Editors, embedded systems
      data compression, graphics and computational geometry, utility programs
      databases, operating systems, device drivers, system level routines
      there are zillions of lines of C legacy code
      Also used in application programs
Characteristics of C
  1. C is a Middle Level/Intermediate Language
      Directly access the memory through pointer for manipulation.
      Supports high-level programming language syntax.
      It has the capability to access the system's low level functions
2.      C is a Case Sensitive Language
      The commands in ‘C’ are written in lowercase.
      The variables written in C in upper case letters have different meaning than the variables used in lower case letters.
3.      C is a Structured Programming Language
      It divides the programs in small module to perform a specific task.
      Through this approach one can have accurate, error free code.
      Each module can have – sequence, selection or iterative statements.
4. C is Portable Language:
       C programs are run on different environment.
      E.g. if u have written a C program in windows 95, then it can be executed in UNIX without any or little modification
5.  C is a Extendible:
      Enhance our program with new code.
      That means a user can write numbers of functions, subprograms according to the requirement.
 Description:   This program prints the greeting “Hello, World!”   */
           #include  <stdio.h>
           int main ( void )
           {
                printf ( “Hello, World!\n” ) ;
                return 0 ;
           }
Comment:
      A comment is descriptive text used to help a reader of the program understand its content.
      All comments must begin with the characters  /*  and end with the characters  */
      These are called comment delimiters.
      The program header comment always comes first.
      Text surrounded by /* and */ is ignored by computer.
      Used to describe program
        Preprocessor directives
      Lines that begin with a “ # ” are called preprocessor directives (commands).
      It tells the computer to load contents of a certain header file.
      For Example:
                        #include <stdio.h>
                        #include <stdlib.h>
                        #include <string.h>
      The #include directives “paste” the contents of the files stdio.h, stdlib.h and string.h into your source code, at the very place where the directives appear.
      These files contain information about some library functions used in the program:
        stdio stands for “standard I/O”,
        stdlib stands for “standard library”,
        string.h includes useful string manipulation functions
The Function Body
      A left brace (curly bracket)
                                    --  {  --
                                    begins the body of every function.
      A corresponding right brace
                                    --  }  --
                                    ends the function body.
The main (  ) function
      main ( ) is always the first function called in a program execution.
      Every program must have a function called main.
            -           Here program execution begins.
      Void indicates that the function takes no arguments.
            -           “void” means nothing.
      The reserved word “int” indicates that main( ) returns an integer value.
      The parentheses following the reserved word “main” indicate that it is a function.
      Braces { and } indicate a block.
      The bodies of all functions must be contained in braces
The printf(  ) function
printf( “Prog. In C is easy. %s \n", input );
      printf( ) is a library function declared in <stdio.h>
      Syntax:
                                    printf( FormatString, Expr, Expr...)
      Format String: String of text to print.
      Format String has placeholders to show where to put the values.
      Placeholders:     %s (print as string),
                                                       %c (print as char),
                                                       %d (print as integer),
                                                       %f (print as floating-point)
      \n indicates a new line character
Expr: Values to print
printf (“Hello, World!\n”) ;
      All statements in C end with a semi colon(;).
      Entire line is called a statement.
      printf() prints the text/string of characters within double quotes (“ ”).
      Escape character (\) indicates that printf( ) should do something out of the ordinary.
      return 0 ;
      Because function main () returns an integer value, there must be a statement that indicates what this value is.
      The statement return 0 indicates that main () returns a value of zero to the operating system.
      A value of 0 indicates that the program successfully terminated execution

C Syntax and Program Structure:
/* A first C Program*/
#include <stdio.h>
void main()
{
     printf("Hello World \n");
}
Line 1: #include <stdio.h>
      As part of compilation, the C compiler runs a program called the C preprocessor. The preprocessor is able to add and remove code from your source file.
      In this case, the directive #include tells the preprocessor to include code from the file stdio.h.
      This file contains declarations for functions that the program needs to use. A declaration for the printf function is in this file.
Line 2: void main ()
      This statement declares the main function.
      A C program can contain many functions but must always have one main function.
      A function is a self-contained module of code that can accomplish some task.
      Functions are examined later.
      The "void" specifies the return type of main. In this case, nothing is returned to the operating system.
Line 3: {
      This opening bracket denotes the start of the program.
Line 4: printf("Hello World From About\n");
      Printf is a function from a standard C library that is used to print strings to the standard output, normally your screen.
      The compiler links code from these standard libraries to the code you have written to produce the final executable.
      The "\n" is a special format modifier that tells the printf to put a line feed at the end of the line.
      If there were another printf in this program, its string would print on the next line.
Line 5: }
           This closing bracket denotes the end of the program.
Escape Sequence:
      \n                  new line
      \t                  tab
      \r                  carriage return
      \a                  alert
      \\                  backslash
      \”                  double quote
Anatomy of a C Program
program header comment
           preprocessor directives (if any)
           int main ( void )
           {
                statement (s);
                return 0 ;
           }
C Character Set:
      The C language consists of:
  1. Alphabets: A to Z (Upper case) , a to z (lower case)
      2.   Digits: 0 to 9
      3. Special Symbols:   !  *   :   &   (   )   =    #    [   ]  {   }    <   >      +   -   ?       ^   ~    ;    |    /    .    ~
Identifiers
      Identifier is the name given to various program elements.
      These are user defined names that consists of alphabets, digits and underscore,
      Both uppercase & lowercase letters are permitted but they cannot be used interchangeably.
            e.g.    and   both are different variables.
Rules for constructing an identifier:
  1. First letter must be a character.
  2. It should not start with a digit.
  3. Special characters are not allowed.
  4. The name of the identifier is so chosen that its usage & meaning becomes clear.
  5. The name of the identifier should not be same as the keyword.
Constants:
      A constant is a quantity which does not change its value during execution of the program.
      The syntax for constant declaration is:
Variable:
      Variables are memory locations in computer memory to hold different types of data.
      It may vary during the program execution.
      The syntax of variable declaration is:
                        <datatype> <variable name>;
            -           here ‘datatype’ is the type value stored in variable ‘varname’
Keyword
      These are the reserved words in C.
      They have a fixed meaning.
      The keywords are always written in lowercase.
      There are 32 keywords in C.
      For example:- Auto, Break, If, Else, For, Goto, Return, Static, Union, Default, Switch, Case, Do, While, Continue, Int, Struct, Char, Float, Long, Enum, Extern, Double, Short, Void, Const,  ………….. ……..more
Data Types
      C programming language which has the ability to divide the data into different types.
      The ‘type’ of a variable determines what kind of values it may take on.
      Data type of an object determines the set of value it can have & what operations can be performed on it.
Integer Data Type
      The integer data type holds the integer value.
      The integer number is stores in short int, int and long int.
      For Example
                  int x;                   //integer variable
                  int y = 454;         //integer constant
                  short int x1;       //short integer variable
                  long int y1;        //long integer variable
Character Data Type
      The character data type hold a single character.
      It is declared by the Keyword ‘char’.
      I/O conversion must be performed using %c conversion code.
      For Example:-
                  char x1=‘h’;         // character constant
                  char x2;                // character variable

Floating Point
      The floating point data type provides the means to store & manipulate numbers with fractional points & a very large range of sizes.
      The floating point number are stores in float, double and long double.
      For Example
         float x = 2.88;                 //floating point constant
         float y;                            //floating point variable
         double x1=9.8778;   //floating point constant
Array Data Type
      An array is a collection of identical data objects which are stored in consecutive memory locations.
      The objects are called elements of the array and are numbered consecutively 0, 1, 2, 3, 4.....
      These numbers are called Index values of the array
      These numbers locate the elements position within the array.
      An array is used to perform the operations on a collection of similar data items.
      The syntax of an array is
                        <data type> <array name>[size];
-           Data type specifies the data type of array.
-           Array name tells the name of array.
-          Size tells the number of elements in the array.
      Example of Array
                                    int X[6];
-          It contains the array of integer data type having the name “X”  that holds the six elements from 0 to 5.
      Each have different integer value in it.
      All the data elements are stored in contiguous memory locations.

Structure Data Type
      The Structure is a group of different data items in a single unit.
           Syntax of Structure:                       Example
                   struct <struct name>                  struct student
                  {                                                     {
                 member 1;                                     char name[20];
                member 2;                                      int rollno;
                 …………..                                          float marks;
                 } ;                                                    } ;
Union Data Type
      The Union is same as a Structure in C language.
      The difference is only in the memory allocation.
      The syntax of Union is
                 Union <struct name>
                                    {
                                    member 1;
                                    member 2;
                                    …………..
                                    } ;
String Data Type
      The string is a group of characters.
      It also called an array of characters.
      It is a sequence of characters.
      The syntax of String is
                                    char string name [size];
      For Example
                                    char a [10];
Operators
      An operator is a function which is applied to values to give a result.
      An operand is a symbol that operates on a certain data type.
Arithmetic Operator
This operator perform arithmetic operations like addition, subtraction, multiplication &so on
Operator
Meaning
+
Addition
-
Subtraction
*
Multiplication
/
Division
%
Module

Relational Operator
      Relational operators are used to compare their first operand to second operand to test the validity of their relationship.
Operators
Meaning
Example
<
Less than
x < 5
>
Greater than
x > 2
<=
Less than equal to
x <= 4
>=
Greater than equal to
x >= 4
==
Equal to
x == 4
!=
Not equal to
x != 5

Logical Operator
Operators
Meaning
&&
Logical AND
||
Logically OR
!
Logically NOT

Bitwise Operator:
Operators
Meaning
&
Bitwise AND
|
Bitwise OR
^
Bitwise XOR
>>
Bitwise right shift
<<
Bitwise left shift
-
One’s component

Conditional Operator (?):
      It is used to carry out conditional operations.
      It can be used in place of if – else.
      Syntax is:
                        expr1? expr2: expr3
                             Condition
      E.g.      x =  (y>12) ? 2 : 400
      If y>12 holds true, the value 2 is assigned to variable x. else value 400 is assigned to variable x.
Assignment Operator:
      It is used to assign the result of an expression to a variable.
      The most commonly used assignment operator is “=”
      Syntax is:         identifier = expression
      E.g.      x = 5, means the value 5 is assigned to variable ‘x’.
      x = y, in this expression the value of ‘y’ is assigned to variable ‘x’ i.e. the value of variable on RHS is assigned to a variable on LHS.
Expressions
      An expression represents a single data item such as a number or a character.
      The expression may consist of a single entity such as a constant, variable, an array or reference to a function.
      Expression can also represent logical condition that is either true or false.
      E.g.      C = A+ B
                                    X = = Y
                                    i = i+1

Statements
      A statement causes the computer to carry out some action.
      There are three different classes of statements:
  1. Expression Statement: It consist of an expression followed by a semicolon (;)
         e.g.   a = 5;         /*assignment type statement*/
                           c = a+b;        /*assignment type statement*/
                           ++i;               /*increment type statement*/
                           printf(“Area= %f”, area); /*function to be evaluated*/
                            ;                   /*Does nothing. Only a semicolon*/
  1. Compound Statement: It consist of several individual statements in it enclosed within a pair of braces { }.
      It provides a capability for embedding statements within another statement.
            e.g.      {           pi = 3.142;
                                                circumference = 2 * pi *radius;
                                                area = pi *radius *radius;                   }
      Above compound statement consist of three assignment type expression statement, though it is considered in a single entity within the program in which it appears.
3. Control Statements: These are used to create special program features like logical tests, loops & branches.
      E.g.      while (count < =n)       {
               printf(“x= ”);
               scanf(“%f”, &x);
                Sum + = x;
               ++ count;                              }
      The compound statement will continue to be executed as long as the value of count does not exceed the value of ‘n’.
      Count increases in value during each pass through the loop.