Thursday, June 23, 2011

C- Maths Function!


We already seen some string built-in-function. All programming languages having certain amount of built-in-function, which written as subroutine or function to solve a certain requirement, while writing a program you can, call these functions by sending arguments that required or without any arguments. It is not that we cannot solve these by writing our own routine but these functions will save your time and space. Built-in-functions come in different types depending upon data types – Numeric, Date, String, Database etc. Numeric or math function to solve a mathematics routine like square root, power and others. Many math functions in C, the return value is float or double type but you can take help of explicit type casting to get it in integer. In C or C++, you have to include "math.h". but for min() and max() in C you require "stdlib.h" or often "complex.h"

Note : Num - is the Integer numeric argument and Fnum is floating point arguments that you have to pass. For larger values, declare the variable as double.


abs() - abs (a macro) gets the absolute value of an integer, All of these routines return the absolute value of their argument.
 
Declaration:   int abs(int x);

 Return Value:    An integer in the range 0 to 32,767;
  
 /* Example: abs */

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

void main()
 {
          int num = -456;
          clrscr();
          printf("Number: %d  absolute value: %d\n", number, abs(num));
          getch();
 }

Output :
Number: -456 absolute value: 456; / * Example: pow()  eithout built-in */




ceil() / floor() - ceil finds the smallest integer not < x. floor finds the largest integer not > x. ceil round up the given value where floor round down the same.
Return Value: Both ceil and floor return the integer.

/* Example: ceil() / floor() example */

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

 void main()
  {
          float num = 123.54,fl,cl;
          cl = ceil(num);
          fl = floor(num);     
          clrscr();
          printf("Original Number     %5.2f\n", num);
          printf("Number after ceil :  %5.2f\n", cl);
          printf("Number after floor :  %5.2f\n", fl);
          num=-123.54;
          printf("\nOriginal Number     %5.2f\n", num);
          printf("Number after ceil %5.2f\n", cl);
          printf("Number after floor %5.2f\n", fl);
          getch();
  }


Output :

Original Number     123.54
Number after ceil :  124.00
Number after floor :  123.00

Original Number     -123.54
Number after ceil -123.00
Number after floor -124.00


cos() / sin() / tan() -  Cosine, sine, and tangent functions. cos compute the cosine of the input value. sin the sine of the input value and tan calculate the tangent of the input value

 Declaration:   Real:     cos(x);sin(x);tan(x);
 Remarks:  Angles are specified in radians.

 Return Value:   On success, cos  return the cosine of the input value (in the range -1 to 1).  sin and sinl return the sine of the input value (in the range -1 to 1).  tan returns the tangent of x, sin(x)/cos(x).


/* Example: cos/sine/tan example */

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

 void main()
  {
            int ang;
            float rad,sn,cs,tn;
            clrscr();
            printf("\nEnter an angle : ");
            scanf("%d",&ang);
            rad=ang*3.1415/180.0;
            sn=sin(rad);
            cs=cos(rad);
            tn=tan(rad);
            printf("\nAngle : %d", ang);
            printf("\nRadian : %8.5f", rad);
            printf("\nSine : %5.2f", sn);
            printf("\nCos : %5.2f", cs);
            printf("\nTan : %5.2f", tn);
            getch();
  }



Output:

Enter an angle : 45

Angle : 45
Radian :  0.78537
Sine :  0.71
Cos :  0.71
Tan :  1.00


exp() -  exp calculates e to the xth power. exp calculates the exponential function e**x.
 
 Declaration: float exp(float x);

Return Value:  On success, exp returns e**x


 /* Example: exp() */

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

 void main()
   {
          float result;
          float x = 2.0;
          clrscr();
          result = exp(x);
          printf("'e' raised to the power \ of %f (e ^ %f) = %f\n", x, x, result);
          getch();
  }


Output :

'e' raised to the power  of 2.000000 (e ^ 2.000000) = 7.389056



fmod() -  Calculates x modulo y, the remainder of x/y. To find remainder of two real value.

 Declaration:  fmod(float x, float y);

/* Example: fmod() */
 #include <conio.h>
 #include <stdio.h>
 #include <math.h>

 void main()
   {
          double x = 5.0, y = 2.0;
          double result;
          clrscr();
          result = fmod(x,y);
          printf("The remainder of (%lf / %lf) is %lf\n", x, y, result);
          getch();
    }


Output :

The remainder of (5.000000 / 2.000000) is 1.000000

modf () - splits double into integer and fraction parts.  modf breaks the double x into two parts: the integer and the fraction. It stores the integer in ipart and returns the fraction.

 Declaration: modf(double x, double *ipart);


/* Example: modf() */

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

 void main(void)
   {
          double f, i, num = 1000.567;
          clrscr();
          f = modf(num, &i);
          printf("The whole and fractional parts of  %lf are %lf and %lf\n",num, i, f);
          getch();
   }


Output :

The whole and fractional parts of 100000.570312 are 0.000000 and 0.570312


log() / log10() - Natural logarithm function, log10  = common logarithm function

 Return Value:   On success, log return the natural log of x, log10 the return log (base 10) of x

/* Example:  log()/log10() */

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

 void main()
  {
          float result;
          float x = 9.5672;
          clrscr();
          result = log(x);
          printf("\nNatural log :\n");
          printf("The natural log of %f is %f\n", x, result);
          x = 8.9023;
          result = log10(x);
          printf("\nLog base 10 :\n");
          printf("The natural log of %f is %f\n", x, result);
          getch();
  }

Output:

Natural log :
The natural log of 9.567200 is 2.258341

Log base 10 :
The natural log of 8.902300 is 0.949502



 pow() -  Power function calculate, x to the y (x**y)

 Declaration: pow(float x, float y);
                                     
 Return Value: On success, pow return the value  calculated, x**y.

/*  Example: pow() */

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

  void main(void)
    {
           float x = 2.0, y = 3.0;
          clrscr();
           printf("%lf raised to %f is %f\n", x, y, pow(x, y));
           getch();
   }


Output :
2.000000 raised to 3.000000 is 8.000000



sqrt() -  Calculates square root. sqrt calculates the positive square root of the input value.

 Declaration: sqrt(float x);

 / * Example: sqrt() */

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

  void main()
    {
          float x = 4.0, result;
          clrscr();
          result = sqrt(x);
          printf("The square root of  %f  is  %f\n", x, result);
          getch();
    }

Output :

The square root of  4.000000  is  2.000000



We can write our own subroutine for solving some of those maths function. I will put a few like pow(), sqrt(), sin() and abs for it.



/ * Example: sqrt()  without built-in */

#include<stdio.h>
#include<conio.h>
 void main()
  {
          float a,b,c=0.00001,prod,k;
          clrscr();
          printf("\nEnter the Value : ");
          scanf("%f",&k);
          a=k;
          prod=a*a;
          while(prod-k>=c)
               {

                        b=(a+(k/a))/2;
                        a=b;
                        prod =a*a;
               }
          printf("Square Root  Of  %f  is =  %f ",k,a);
          getch();
  }

Output :

Enter the Value : 15
Square Root  Of  15.000000  is =  3.872984



/ * Example: abs()  without built-in */

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

 void main()
  {
          float a,b;
          clrscr();
          printf("\nEnter the Value : ");
          scanf("%f",&a);
          b=a;
          if(b<0)
            {
                b=b*-1;
            }
          printf("Input Value %f and ab;ousute value is =  %f ",a,b);
          getch();
}

Output :

Enter the Value : -12
Input Value -12.000000 and ab;ousute value is =  12.000000

Enter the Value : 23
Input Value 23.000000 and ab;ousute value is =  23.000000


/ * Example: pow()  without built-in */

#include<stdio.h>
#include<conio.h>
 void main()
  {
          float x,y,s=1;
          int i;
          clrscr();
          printf("\nEnter X and Y for x^y : ");
          scanf("%f%f",&x,&y);
          for(i=1;i<=y;i++)
            {
                 s=s*x;
            }
          printf("%f ^ %f = %f ",x,y,s);
          getch();
 }

Output :

Enter X and Y for x^y : 2  4

2.000000 ^ 4.000000 = 16.000000



/ * Example: sin()  without built-in */

#include<stdio.h>
#include <math.h>
#include<conio.h>
 void main()
  {
          float rad,f=1,s;
          int ang,i;
          clrscr();
          printf("\nEnter an Angle : ");
          scanf("%d",&ang);
          rad=ang*3.1415/180.0;
          s=rad;
          for(i=3;i<=11;i+=2)
            {
                 f=f*i*(i-1)*(-1);
                 s=s+pow(rad,i)/f;
            }
          printf("Sine of %d angle = %f",ang,s);
          getch();
}


Output :

Enter an Angle : 90
Sine of 90 angle = 1.000000




Thursday, June 16, 2011

Handy Notes for C



History : `C' programming language invented by  Kernighan & Ritchie way back 1972, basically called as `B' language.


Data Type : A variable is a symbolic name for a computer memory location, while declaring a variable the programmer must declare the type of data or information to be stored in a variable and the size of memory it is going to occupy.  Primitive data types are those are not composed, it also known as fundamental data types.
1.      Integers : Integers are whole numbers with a machine dependent range of values. A good programming language as to support the programmer by giving a control on a range of numbers and storage space. C has 3 classes of integer storage namely short int, int and long int. All of these data types have signed and unsigned forms. A short int requires half the space than normal integer values. Unsigned numbers are always positive and consume all the bits for the magnitude of the number. The long and unsigned integers are used to declare a longer range of values.
2.      Characters : A single character can be defined as a defined as a character type of data. Characters are usually stored in 8 bits of internal storage. The qualifier signed or unsigned can be explicitly applied to char. While unsigned characters have values between 0 and 255, signed characters have values from –128 to 127.
3.      Floating point – Floating point number represents a real number with 6 digits precision. Floating-point numbers are denoted by the keyword float. When the accuracy of the floating-point number is insufficient, we can use the double to define the number. The double is same as float but with longer precision. To extend the precision further we can use long double, which consumes 80 bits of memory space.
All C Compilers accept the following fundamental data types

1.
  Integer
  int
2.
  Character
  char
3.
  Floating Point
  float
4.
  Double precision floating point
  double
5.
  Void
  void

Size and Range of Data Types on 16 bit machine.

 Type
SIZE (Bits)
Range
 Char or Signed Char
8
-128 to 127
 Unsigned Char
8
0 to 255
 int or Signed int
16
-32768 to 32767
  Unsigned int
16
  0 to 65535
  Short int or Signed short int
8
  -128 to 127
  Unsigned short int
8
  0 to 255
  long int or signed long int
32
  -2147483648 to 2147483647
  Unsigned long int
32
  0 to 4294967295  
  float
32
  3.4 e-38 to 3.4 e+38
  double
64
  1.7e-308 to 1.7e+308
  long double
80
  3.4 e-4932 to 3.4 e+4932


Constant or Literals– A data item does not change during execution of a program is called a constant or literals. Constant or literals can be numeric – Integer (int) type or fractional (float or double), character or string. e.g. 200, “hello”, 45.0F, 444.4545, TRUE, FALSE
Identifiers or variables– Symbolic names used for various data items in programs known as identifiers. Identifiers also can be defined as user defined name given to memory boxed to store data or information.
Rules for naming identifiers.
1. Must start with an alphabet.
2. A numeric digit allowed.
3. No space or symbols are allowed except an underscore.
4. No keyword can be use as identifiers.
Volatile Variable : A volatile variable is the one whose values may be changed at any time by some external sources.
Example:
   volatile int num;
The value of data may be altered by some external factor, even if it does not appear on the left hand side of the assignment statement. When we declare a variable as volatile the compiler will examine the value of the variable each time it is encountered to see if an external factor has changed the value.
User defined type declaration : In C language a user can define an identifier that represents an existing data type. The user defined datatype identifier can later be used to declare variables. The general syntax is
Example:
   typedef int Integer;
   typedef float Fpoint;

Here Integer symbolizes int and Fpoint symbolizes float. They can be later used to declare variables as follows:

Example:
  Integer age;
  Fpoint Saray,tax;
  enum identifier {value1, value2 …. };

The identifier is a user defined enumerated datatype which can be used to declare variables that have one of the values enclosed within the braces. After the definition we can declare variables to be of this ‘new’ type as below.

Example:
   enum col {RED,BLUE,GREEN,..};
   enum day CR,CG;
   CR =RED;
   CG = GREEN;
Declaring Variable as Constant
The values of some variable may be required to remain constant through-out the program. We can do this by using the qualifier const at the time of initialization.

Example:
  const int val = 20;
  const value = 30;

Defining a Symbolic Constant using #define directive A symbolic constant value can be defined as a preprocessor statement and used in the program as any other constant value.

Example:
  # define [valid variable name] value
  # define MAX 100
  # define pi  3.14159

These values may appear anywhere in the program, but must come before it is referenced in the program. It is a standard practice to place them at the beginning of the program.

Declaration of Storage Class
Variables in C have not only the data type but also storage class that provides information about their location and visibility. The storage class divides the portion of the program within which the variables are recognized.
auto : It is a local variable known only to the function in which it is declared. Auto is the default storage class.
static : Local variable which exists and retains its value even after the control is transferred to the calling function.
extern : Global variable known to all functions in the file
register : Social variables, which are stored in the register.
Storage Class
Storage
Default Initial Value
Scope
Life
Automatic (syntax: auto) (All data types)
Memory
Unpredictable Garbage value
Local to the block in which the variable is defined
Till the control remains within the block in which it is defined
Register (syntax: register) (Only integers)
CPU Registers
Unpredictable Garbage value
Local to the block in which the variable is defined
Till the control remains within the block in which it is defined
Static
(syntax: static) (All data types)
Memory
Zero
Local to the block in which the variable is defined
Value of the variable persists between different function calls
External (syntax: extern) (All data types)
Memory
Zero
Global
As long as the program's execution does not come to an end



Instance variable - Instance variables are any variables that are defined in a constructor function and that are copied into each object instance of that constructor. All object instances have their own copies of instance variables. The significance of an instance variable is that every object instantiated from that class contains its own copy of all instance variables.
Global Variable - A variable whose value can be accessed and modified by any statement in an application, and not merely within a single routine in which it is defined. Variables declared just in side the class known as global variable.
class testing
 {
     int a, b; //global variable
  }
 Local Variable - A variable that is accessible only within a function or procedure. Other procedures or functions cannot access this variable's data. Use global variables to share data across many procedures and functions, or private variables to share data with the functions you call.


Keyword – Reserved words that convey meaning to the computer. Used to write programming syntax. A programming syntax or statement should have at least one keyword. e.g. class, int, if, for.
Statements: Statements consist of tokens, expressions, and other statements. A statement that forms a component of another statement is called the “body” of the enclosing statement. Each statement type given by the following syntax is discussed in this chapter.
Compound Statements (Blocks) - A compound statement consists of zero or more statements enclosed in curly braces ({ }). A compound statement can be used anywhere a statement is expected. Compound statements are commonly called “blocks.”


Operators -An operator is a symbol or letter, which makes the computer perform specific operation in a programming statement.
arithmetic operator - Operators that perform numeric calculations known as arithmetic operators are: + (addition), – (subtraction), * (multiplication), / (division) and % (modulus).
Relational operator - An operator that manipulates numeric and other values to produce a logical result. The relational operators are &lt;, &gt;,= =, &lt;=, &gt;=, and !=.
Unary operator - The unary assignment operators, use two operand instead of one, for the increment (++) and decrement (– –) operators. Its also call increment/decrement operator. a++, a--, a+=10.
Ternary Operator – Can be used to replace certain of if – else-if statement. Its require three operands to work on. It represent by the ? and : symbols. Expression1?Expression2:Expression3 e.g. tax = salary&gt;10000?salary*0.05 : 0; (if variable salary stored more than 10000 then tax variable will calculated 5% of salary otherwise tax will be).
Logical Operator - An operator that produces a logical result (true or false); sometimes called a Boolean operator. The logical operators are used for expression grouping, NOT or ! (negation), AND (Creates a Boolean behavior that represents the logical AND of the given behaviors. The behavior's value is true when both b1 and b2 are true; otherwise, it is false. OR (Creates a Boolean behavior that represents the logical OR of the given behaviors. The behavior's value is true when either b1 or b2 are true; otherwise it is false).
Binary Operator - This operator do the binary operations between two or more variables. Also known as bits operator. The bitwise operators perform bitwise-AND (&), bitwise-exclusive-OR (^), and bitwise-inclusive-OR () operations. E.g. 101 & 100 = 100 (Multiplication). 101 ! 100 = 101 (Addition). 101 ^ 100 = 001(If one bit is 0 and the other bit is 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0). Right shift &gt;&gt; Left shift &lt;&lt; (The value of a right-shift expression e1 &gt;&gt; e2 is e1 / 2e2, and the value of a left-shift expression e1 &lt;&lt; e2 is e1 * 2e2).


Function Call by value - When a simple type passed to a method, as a copy of the argument is being made and passed to the function is known as call by value, any changes made to the parameter inside the function do not affect the original. A functions parameter list also known as signature.
void test()
  {
      int a=10,b=20;
      int s=sum(a, b);
  }
Function call by reference - When an object is passed as an argument to a method it is passed by reference. A reference to an argument is passed as parameter, the value of the argument is not passed. This method is called call by reference.
struct testing 
    {
        int a, b;
     }*test;

void tester(struct *t)
 {
      printf("%d %d ",t-&gt;a,t-&gt;b);
 }
void main() // main function
  {
      tester(test);
  }
Pure function - Pure function or accessor methods return information to the caller about a state of an object without changing the state.
Impure function - Impure function or mutator methods return information to the caller about a state of an object by changing the state.
actual parameter - The actual value that is passed into the method by a caller. Actual arguments (those supplied by the caller) are evaluated. Caller – sum(a, b)
formal parameter - The identifier used in a method to stand for the value that is passed into the method by a caller. Receiver – int sum(int x, int y)


Comment - A comment is a remark from programmer to explain some aspect of the code to who is reading the source code. Comments can be anything including or excluding programming syntax as compiler ignore it. a) Single line comments - Comments followed the // symbols
b) Multiline Comments – The are used for comments spread over many line. They begin with /* and end with */.


printf() - Print formatted output to the standard output stream. A format specification, which consists of optional and required fields. Each field of the format specification is a single character or a number signifying a particular format option. The simplest format specification contains only the percent sign and a type character : %d – Integer, %f – Float, %u – Unsigned, %c – Character, %s – String. %3d – Integer 3 digit long. %5.2f – 1 whole no, one decimal point and 2 decimal places( 99.99). %30s – Right align. %-30s – Left align. Some of escape character - \n – new line. \t – 8 space tab.
Scanf() - Read formatted data from the standard input stream. The scanf function reads data from the standard input stream and writes the data into the variable given by argument. Each argument must be a pointer to a variable (address) of a type that corresponds to a type specifier in format(see printf) .


If – else if – else - The if keyword is used to execute a statement or block of statements when its associated expression evaluates to true. An if statement may also have an alternative else if or else clause. If the expression defined by the if statement evaluates to false, then control transfers to the statement (or block of statements) following the else if or else keyword. If the expression defined by the if statement evaluates to true, then control transfers to the first statement following the if keyword. Multiple conditional expression can be written in if or else if statement separated by logical operator but there is no expression written in else.
if ( num < 1000 )       //when num is below 1000
     t=10;
else if ( num <5000)    // When num is equal or over 1000 but below 5000
    t=100;
else
    t=1000
switch - The switch keyword is used along with the keyword case, and sometimes the keyword default, to create a conditional statement. In a switch statement, the switch keyword is followed by an expression within parentheses. Once the expression has been evaluated, its value is compared against the label following each case statement within the switch statement body. When a label has the same value, the lines following that case statement are executed. An optional default label is included within the body of a switch statement when there is no guarantee that the labels provided by each case statement are the only values the switch expression may evaluate to.
switch(variable)
  {
     case 1 : printf(“Switch-case”); break;
    default : printf(“Not a Value”;
  }
The break keyword is also, at times, used within the body of a switch statement. Once the lines following a case statement have executed, the break statement is included to jump over the remaining body of the switch condition. Without a break statement, subsequent case statements would continue being evaluated, and eventually the default statement, if one were included, would execute.
Difference between if-else-if-else and switch
1.      switch-case - switch-case can only check of equality. switch only looks for match between the values of the expression with one of its case constant values.
2.      No two case constant can have identical values.
3.      Use of switch is more convenient than multiple nested if. When the case constant match with criteria given computer start from that point continue performing each case even its not satisfied the condition, so its required jump statement like break to jump from the table.
4.      Thus its run faster than if construct. In switch-case no floating point constant allowed.

1.      if-else-if-else - if can evaluate any type, if-else statement uses series of expression involving unrelated variables.
2.      No jump statement can be given for if statement.
3.      It check each condition even after it’s found its match, so it’s slower than switch-case.
4.      In if-else-if-else floating point constant can be used as a condition.


for - The for keyword is used to create a loop construct. An initialization section, an expression section, and an update section immediately follow the keyword. A semicolon separates each section, and all appear together within at least one set of parentheses. The initialization section allows the programmer to declare one or more local loop variables with initial values. The expression or final value section contains an expression that is evaluated to determine whether the loop should continue or how long it should continue. A true result allows the loop to continue; a false result allows control to transfer to the statement following the loop body. The update section allows to increment loop counters or perform other updates. Typically, the update section is used to increment or decrements whatever loop counters the programmer defines. e.g. for( int i = 0; i< 10; i++ )
while - The while keyword is used to create a loop construct. In a while loop, the expression in parentheses immediately following the keyword is evaluated, and if the result is true, the statements appearing within the loop body are executed. If multiple statements make up the body of the loop, they must be enclosed with curly braces. Once the loop body has executed, control transfers back to the top of the loop where the test is performed again, and the execution of the loop body is repeated until the value of the expression evaluates to false. While is a entry centered loop as it check the condition and then perform the body. e.g. while(i++<10)
do-while - The do keyword is used as part of a do-while loop. Unlike the other, more commonly used loop constructs, a do/while loop expression is evaluated only after the block of code within its body has been executed. Thus, you are ensured that the code within the loop body is executed at least once, even if the expression tested causes the loop to end. . do-while is an exit centered loop as it does not check any condition but perform the body once and then check the condition. A semicolon is required after the condition (while) in a do/while loop.
 int i=1
  do
    {
         printf("Printing at least once";
         i++;
     } while ( i <= 10 );
while – do-while Difference
1.      while - while is entry centered loop.
2.      while check its condition and if satisfied then it performed the body else it comes out of the loop statement and proceeds further.

1.      do-while - do-while is a exit centered loop.
2.      do-while, start with do and does not check any condition when computer performed the loop body first time, but check the condition at the below, which given in while, so even condition is not satisfied.


Jump Statement – Jump statement used to transfer control to another part of the program. break, continue worked as jump statement.
break - Statement used to terminate the current loop or a sequence in switch statement. 
while(a<10)
 {
   if(a==5)
      break;
 }
continue – Used only in loop to terminate that particular process and transfer control to the loop conditional expression.
while(a<10)
  {
     if(a==5)
        continue;
}
break and continue Difference
1.      break can be used as a jump statement in any type of loops and switch-case.
2.      break jump directly out of the body of the loop or switch-case statement and follows the next statement onwards.

1.      continue can be used in loop but not in switch-case.
2.      continue transfer control to conditional expression not quite the loop.


Type Casting : Converting an expression of a given type into another type is known as type-casting. We have already seen some ways to type cast:
Implicit conversion : Implicit conversions do not require any operator. They are automatically performed when a value is copied to a compatible type. For example:
   short a=2000;
   int b;
   b=a;
Explicit conversion : Many conversions, specially those that imply a different interpretation of the value, require an explicit conversion. We have already seen two notations for explicit type conversion: functional and c-like casting:
  short a=2000;
  int b;
  b = (int) a;   // c-like cast notation
  b = int (a);   // functional notation


Array - An array is a group of same typed variables that are referenced by a common name. Arrays can be any typed and one or more dimensions. A particular element can be addressed by array name and index of the array enclosed in third bracket ([]). Array can be declared with its initial values or can be defined with the size and can input the values latter. An array index start from 0 by default. int x[]={1,2,3,4}; int a[10];


structure – Structure is groups the variables in a single record. E.g. struct personal { char name[20], int age;}per, per1;
personal is struct type name and per / per1 are structure variables, name and age are the structure elements. Structure type and variables both are optional, but one of the two must appear. Structure type used to create multiple copies and can not be used directly where structure variable can be used directly like per.name.
Header Files - File containing predefined compile-time constants or functions. This can be inserted at any part of the program.


#include - Directive tells the preprocessor to treat the contents of a specified file as if those contents had appeared in the source program at the point where the directive appears. You can organize constant and macro definitions into include files and then use #include directives to add these definitions to any source file.


Function-like macros can take arguments, just like true functions. To define a macro that uses arguments, you insert parameters between the pair of parentheses in the macro definition that make the macro function-like. The parameters must be valid C identifiers, separated by commas and optionally whitespace.  
Example:
#define min(X, Y)  ((X) < (Y) ? (X) : (Y))
void main()
{
int X,Y,Z ;
X=10 ;
Y=20 ;
Z = min(a, b);    // invoking the macro
printf("\n Minimum of %d and %d = %d ",X,Y,Z);
}


Macro & Function

·            Macro consumes less time. When a function is called, arguments have to be passed to it, those arguments are accepted by corresponding dummy variables in the function, they are processed, and finally the function returns a value that is assigned to a variable (except for a void function). If a function is invoked a number of times, the times add up, and compilation is delayed. On the other hand, the macro expansion had already taken place and replaced each occurrence of the macro in the source code before the source code starts compiling, so it requires no additional time to execute.
·            Function consumes less memory. While a function replete with macros may look succinct on surface, prior to compilation, all the macro-presences are replaced by their corresponding macro expansions, which consumes considerable memory. On the other hand, even if a function is invoked 100 times, it still occupies the same space. Hence function is more amenable to less memory requirements.


<stdio.h> – Standard input output header file having following function –
gets() – Gets a string from stdin.
puts() – print the output to the stdout.
getchar() : accept a character with confirmation.
fopen() ,fclsoe(), fwrite(), fread(): open, close, write and read a data file. These function also part of header file - scanf(), printf(),fopen(), struct etc.


<conio.h> – Console input and output header file. Some of following function of this header file –
clrscr() : To clear the user screen.
getch() : Wait until a character pressed & without prompting on the screen continue further. Also used to input a character. e.g. getch() or a=getch().
getche() : Wait until a character pressed & with displaying it on the screen continue. Also used to input a character. e.g. getche() or a=getche()


<string.h>  – Provide different string function, such as :
strcat() : Concatenate two string. e.g. strcat(a,c).
strcmp() : Compare two string and return zero if true. x=strcmp(a,c).
strcmpi() : Compare two string, case intensive.
strcpy() : Copy source string to target. e.g. strcpy(target,source).
strlen() : To get the length of a string. e.g. x=strlen(c).
strlwr() : To convert a string to lowercase. e.g. strlwr(c).
strrev() : Reverse the character in a string. e.g. strrev(c).
strupr() : Convert a string to uppercase. strupr(c).


<math.h> - Used to provide function for mathematical operation -
log() : To get a natural log of a given no.
pow() : To execute the x^n. e.g. b=(x,3) will give x^3 answer
sin() : To get the sine of an angle. e.g. sin(ivar or fvar)
sqrt() : Find square root of a no.
tan() : To find tan of a angle.


<ctype.h> - Used to provide function for character input.
tolower() : To change a character to lowercase. eg._tolower(a)
toupper() : To change a character to uppercase. e.g. _toupper(a)
isascii(), islower(), isupper(), isalpha(), isdigit()– Used to check a character.


<stdlib.h>-Mainly used for data conversion
itoa() : To convert a integer to string. e.g. svar=itoa(ivar,10)
atof() : Convert a string to float. e.g. a=atof(b).
atoi() : Convert a string to int. e.g. a=atoi(b).


<proccess.h>
exit() :Terminates the current process.


Pointers : Pointers are special type of variables, which are concerned, with the memory address of other variables.  The use of pointers is much more frequent in C, than in any other languages and it is  use of pointers that has made c such a popular language. Pointers are used to store the address of a memory variable and using this we can manipulate the program to access memory address. Program that uses dynamic allocation cannot be done without pointers.
int *p;    //  Indicates the address stored in the variable 'p' is that of a int type variable.
char *ch;  // Indicates the address stored in the variable 'ch' is that of a char type variable.
int i;
p=&i;  // Thus another variable can be used to store the address of the pointer variable 'j'.  That variable will thus hold the address of 'j' i.e. will be a pointer to another pointer variable. 


Pointer Arithmetic A pointer to any variable type is an address in memory -- which is an integer address. A pointer is definitely NOT an integer.
The reason we associate a pointer to a data type is so that it knows how many bytes the data is stored in. When we increment a pointer we increase the pointer by one block memory. So for a character pointer ++ch_ptr adds 1 byte to the address. For an integer ++p adds 2 byte where  ++p adds 4 bytes to the address for float.


Reference operator (&)
The address that locates a variable within memory is what we call a reference to that variable. This reference to a variable can be obtained by preceding the identifier of a variable with an ampersand sign (&), known as reference operator, and which can be literally translated as "address of". For example:
int n=10,*p;
p = &n;

This would assign to ‘p’ the address of variable ‘n’, since when preceding the name of the variable ‘n’ with the reference operator (&).
Dereference operator (*)
Using a pointer we can directly access the value stored in the variable, which it points to. To do this, we simply have to precede the pointer's identifier with an asterisk (*), which acts as dereference operator and that can be literally translated to "value pointed by".
int n,*p=10;
n = *p;


Arrays of Pointers : Arrays of Pointers are a data representation that will cope efficiently and conveniently with variable length. To declare an array using dynamic allocation we need pointer for the purpose 
int *p, n=10,i
p=(int *)malloc(n*sizeof(int)); // converting the pointer to array

for(i=0;i<10;i++)
scanf(“%d”,&p[i]);


Dynamic Memory  allocation is a way to allocate memory blocks to a pointer and it can be done while execution the program. malloc() and calloc() can be use for this purpose. Since dynamic memory allocation uses library routines, it is not considered part of the language.
malloc() : malloc() allocates a block of size bytes from the memory heap. It allows a program to allocate memory explicitly as it's needed, and in the exact amounts needed. The heap is used for dynamic allocation of variable-sized blocks of memory. Many data structures, such as trees and lists, naturally employ heap memory allocation. All the space between the end of the data segment and the top of the program stack is available for use in the small data models, except for a small margin immediately before the top of the stack. This margin is intended to allow the application some room to make the stack larger, in addition to a small amount needed by DOS. In the large data models, all the space beyond the program stack to the end of available memory is available for the heap.
Return Value:
On success, malloc returns a pointer to the newly allocated block of memory.
On error (if not enough space exists for the new block), malloc returns null. The contents of the block are left unchanged.
If the argument size == 0, malloc returns null.


 calloc() - calloc provides access to the C memory heap, which is available for dynamic allocation of variable-sized blocks of memory. calloc allocates a block (nitems * size) bytes and clears it to 0. To allocate a block larger than 64K, use farcalloc.
calloc allocates a block (nitems * size) bytes and clears it to 0. To allocate a block larger than 64K, use farcalloc.
There are two differences. First, is in the number of arguments. Malloc() takes a single argument (memory required in bytes), while calloc() needs two arguments (number of variables to allocate memory, size in bytes of a single variable). Secondly, malloc() does not initialize the memory allocated, while calloc() initializes the allocated memory to ZERO.
Calloc(m, n) is essentially equivalent to p = malloc(m*n); memset(p, 0, m*n); The zero fill is all-bits-zero, and does not therefore guarantee useful null pointer values or floating-point zero values. 'Free' is useable to release the memory allocated by malloc or calloc.
Malloc(s), returns a pointer for enough storage for an object of s bytes. Calloc(n,s); returns a pointer for enough contiguous storage for n objects, each of s bytes. The storage is all initialized to zeros.
Difference Between malloc() and calloc()
calloc

malloc
calloc() needs two arguments (number of variables to allocate memory, size in bytes of a single variable). calloc takes two arguments, and calculates their product.
calloc() initializes the allocated memory to ZERO.
Simply, where as, Calloc(n,s); returns a pointer for enough contiguous storage for n objects, each of s bytes. The storage is all initialized to zeros
p=(int *)calloc( 40, sizeof(int))
malloc takes a single argument and allocates bytes of memory as per the argument taken during its invocation.
Secondly, malloc() does not initialize the memory allocated
Malloc(s); returns a pointer for enough storage for an object of s bytes
p=(int *)malloc( 40* sizeof(int));


FILE
What are Files?
Output of the programs that we had written are temporary so the results derived after running the programs are lost after execution.  C allows data to be stored permanently in a data file with the help of an extensive set of library functions for handling these data files.  Using these library functions data can be stored in a secondary storage device like a hard disk in the form of a data file, for later access.
Opening and Closing a Data file:
To store data in a file, the data needs to be transferred from the computer's memory to the data file in the storage media like the hard disk.  However the data that is output does not go directly to the disk when an output command is issued.  Instead it goes to a temporary storage area in memory called a buffer.  Even if the buffer is not full, the data in the buffer can be forcibly transferred to the file, if required.  How to do all these will be discussed later.
To access a data file, the following steps need to be followed:
1.                  Declaration of file pointer:  To transfer data in and out of the buffer, a link needs to be first created between the buffer and the operating system.  When a program creates a file, it first sets up a special structure in memory containing information that the computer and the program need, to input or output information from the file.  The structure contains the address of the file's buffer, which tells the computer where to find the information temporarily stored, to output to or input from the disk and keeps track of the number of characters remaining in the buffer and the position of the next character.  This special structure data type is indicated by the variable type FILE (all capital), already defined in the header file "stdio.h".  A pointer of the structure-data-type FILE is declared to finally create the buffer area.
FILE *fp -  pointer variable fp of type FILE declared, to be used to indicate beginning of the buffer.
2.                  Opening the file:  The next step after creating the file pointer is to open the data file.  This is achieved by associating or linking the file name of the data file with the buffer area, by the help of the FILE type pointer fp, declared above.  One more thing needs to be indicated i.e. whether the data file should be opened as read-only, write-only, or read-write both i.e. the mode of operation.  The function that is used to open a data file is fopen (). The general syntax for using the fopen () function is:
fp = fopen ("filename", "mode");
The function fopen () returns a pointer indicating the beginning of the buffer area associated with the file.  The filename and mode are strings that represent the name of the file and the manner in which it should be opened.  In case the file cannot be opened (due to misspelled name or any other error), the function returns a NULL pointer.
Modes available for fopen()

File Type
Description
Applicable To
"r"
Open an existing file for reading only.
Existing file
"w"
Open a new file for writing only.  This will overwrite any existing file with the same name.
New file
"a"
Open an existing file for appending (adding new information at the end of the file).  A new file gets created in case the file-name does not exist.
Existing/New
"r+"
Open an existing file for reading and writing.
Existing file
"w+"
Open a new file for reading and writing.  This will overwrite any existing file with the same name.
New file
"a+"
Open an existing file for reading and appending.  A new file gets created in case the file-name does not exist.
Existing/New

3.                  Closing the file:  Finally, after accessing the file it needs to be closed.  Closing the file ensures that all information in the file buffer is written to the file.  If a file is not closed, the end-of-file marker, indicating the end of a file, may not be properly inserted also.  Moreover, closing the file releases the file pointer, which can be used for another file.  A file is closed using the fclose () function as shown below:
fclose (fp) ;