Monday, September 9, 2013

OOP Concepts

Posted by Unknown On 9:27 AM No comments

OOP Concepts

Paradigm-: It means organizing principle of a program. It is an approach to programming.
Procedural ParadigmIn procedural programming paradigm, the emphasis is on doing things i.e., the procedure or the algorithm. The data takes the back seat in procedural programming paradigm. Also, this paradigm does not model real world well.
Object Oriented programmingThe object oriented programming paradigm models the real world well and overcomes the shortcomings of procedural paradigm. It views a problem in terms of objects and thus emphasizes on both procedures as well as data.
The following are the basic concepts used in object-oriented programming.
Object-: An object is an identifiable entity with some characteristics and behavior.
Class-: A class represents a group of objects that share common properties, behavior and relationships.
Data Abstraction-: Abstraction refers to act of representing essential features without including the background details or explanations.
Encapsulation-: The wrapping up of data and associated functions into a single unit is known as Encapsulation. Encapsulation implements data abstraction.
Modularity-: Modularity is the property of a system that has been decomposed into a set of cohesive and loosely coupled modules.
Inheritance-: It is the capability of one class of things to inherit capabilities or properties from another class.
Base and sub classes-: The class whose properties are inherited is called base class (or superclass) and the class that inherits the properties is known as derived class(or subclass).
Derived Class :- The class, which inherits from other classes is called derived class or Subclass.
Polymorphism-: It is the ability for a message or data to be processed in more than one form. Polymorphism is a property by which the same message can be sent to objects of several different classes. Polymorphism is implemented in C++ through virtual functions and overloading- function overloading and operator overloading.
Advantages of Object oriented programming.
Software complexity can be easily managed
Object-oriented systems can be easily upgraded 
It is quite easy to partition the work in a project based on object
class enforce data-hiding, abstraction & encapsulation
A class groups its members into three sections : private, protected, and public. The private and protected members remain hidden from outside world. Thus through private and protected members, a class enforces data-hiding.
The outside world is given only the essential and necessary information through public members, rest of the things remain hidden, which is nothing but abstraction. Abstraction means representation of essential features without including the background details and explanation.

Structure

Posted by Unknown On 9:26 AM No comments

Structure

A structure is a collection of variable which can be same or different types. You can refer to a structure as a single variable, and to its parts as members of that variable by using the dot (.) operator.  The power of structures lies in the fact that once defined, the structure name becomes a user-defined data type and may be used the same way as other built-in data types, such as int, double, char.
struct STUDENT
{
        int rollno, age;
        char name[80];
        float marks;
} ; 

int main()
{
       // declare two variables of the new type
       STUDENT s1, s3;
       //accessing of data members
       cin>>s1.rollno>>s1.age>>s1.name>>s1.marks;
       cout<<s1.rollno<<s1.age<<s1.name<<s1.marks;
       //initialization of structure variable
       STUDENT s2 = {100,17,”Aniket”,92};
       cout<<s2.rollno<<s2.age<<s2.name<<s2.marks;
       //structure variable in assignment statement
       s3=s2;
       cout<<s3.rollno<<s3.age<<s3.name<<s3.marks;
       return 0; 
}


Defining a structure

When dealing with the students in a school, many variables of different types are needed.  It may be necessary to keep track of name,  age, Rollno, and marks point for example. struct STUDENT
{
        int rollno, age;
        char name[80];
        float marks;
};
 
STUDENT  is called the structure tag, and is your brand new data type, like int, double or char.

rollno, name, age, and marks are structure members.

Declaring Variables of Type struct

The most efficient method of dealing with structure variables is to define the structure globally.  This tells "the whole world", namely main and any functions in the program, that a new data type exists.  To declare a structure globally, place itBEFORE void main().  The structure variables can then be defined locally in main, for example…
struct STUDENT
{
        int rollno, age;
        char name[80];
        float marks;
}; 

int main()
{
       // declare two variables of the new type
       STUDENT s1, s3;
       ………
       ………
       return 0; 
}

Alternate method of declaring variables of type struct:
struct STUDENT
{
        int rollno, age;
        char name[80];
        float marks;
} s1, s3;

Accessing of data members

The accessing of data members is done by using the following format:
structure variable.member name
for example cin>>s1.rollno>>s1.age>>s1.name>>s1.marks;

Initialization of structure variable

Initialization is done at the time of declaration of a variable. For example 
STUDENT s2 = {100,17,”Aniket”,92};
Structure variable in assignment statement
s3=s2; 
The statement assigns the value of each member of s2 to the corresponding member of s3. Note that one structure variable can be assigned to another only when they are of the same structure type, otherwise complier will give an error.

Nested structure (Structure within structure)

It is possible to use a structure to define another structure. This is called nesting of structure. Consider the following program
struct DAY
{
     int month, date, year;
};

struct STUDENT
{
        int rollno, age;
        char name[80];
        day date_of_birth;
        float marks;
};

typedef

It is used to define new data type for an existing data type. It provides and alternative name for standard data type. It is used for self documenting the code by allowing descriptive name for the standard data type.

The general format is:
typedef existing datatype new datatype
for example: 
typedef float real;
Now, in a program one can use datatype real instead of float.
Therefore, the following statement is valid: 
real amount;

Enumerated data type

The enum specifier defines the set of names  which are stored internally as integer constant. The first name was given the integer value 0, the second value 1 and so on.

for example: 
enum months{jan, feb, mar, apr, may} ;
It has the following features:
  • It is user defined.
  • It works if you know in advance a finite list of values that a data type can take.
  • The list cannot be input by the user or output on the screen.

#define preprocessor directive

The #define preprocessor allows to define symbolic names and constants e.g.#define pi 3.14159 
This statement will translate every occurrence of PI in the program to 3.14159

Macros

Macros are built on the #define preprocessor. Normally a macro would look like:#define square(x) x*x 
Its arguments substituted for replacement text, when the macro is expanded.

Two Dimensional Array

Posted by Unknown On 9:22 AM 1 comment

Two Dimensional Array

It is a collection of data elements of same data type arranged in rows and columns (that is, in two dimensions).

Declaration of Two-Dimensional Array

Type arrayName[numberOfRows][numberOfColumn];
For example, int Sales[3][5];

Initialization of Two-Dimensional Array

An two-dimensional array can be initialized along with declaration. For two-dimensional array initialization, elements of each row are enclosed within curly braces and separated
by commas. All rows are enclosed within curly braces. int A[4][3] = {{22, 23, 10},
              {15, 25, 13},
              {20, 74, 67},
              {11, 18, 14}};

Referring to Array Elements

To access the elements of a two-dimensional array, we need a pair of indices: one for
the row position and one for the column position. The format is as simple as:
name[rowIndex][columnIndex]

Examples: cout<<A[1][2];      //print an array element
A[1][2]=13;         // assign value to an array element
cin>>A[1][2];       //input element

Using Loop to input an Two-Dimensional Array from user

int mat[3][5], row, col ;
for (row = 0; row < 3; row++)
  for (col = 0; col < 5; col++)
    cin >> mat[row][col];

Arrays as Parameters

Two-dimensional arrays can be passed as parameters to a function, and they are passed by reference. When declaring a two-dimensional array as a formal parameter, we can omit the size of the first dimension, but not the second; that is, we must specify the number of columns. For example:     void print(int A[][3],int N, int M) In order to pass to this function an array declared as:    int arr[4][3]; we need to write a call like this:    print(arr);
Here is a complete example: 
#include <iostream.h>
void print(int A[][3],int N, int M)
{
  for (R = 0; R < N; R++)
    for (C = 0; C < M; C++)
       cin >> A[R][C];
}
int main ()
{
  int arr[4][3] ={{12, 29, 11},
                  {25, 25, 13},
                  {24, 64, 67},
                  {11, 18, 14}};
  print(arr,4,3);
  return 0;
}

Function to read the array A

void Read(int A[][20], int N, int M)
{
  for(int R=0;R<N;R++)
    for(int C=0;C<M;C++)
    {
      cout<<"(R<<','<<")?";
      cin>>A[R][C];
     }
}

Function to display content of a two dimensional array A

void Display(int A[][20],int N, int M)
{
  for(int R=0;R<N;R++)
  {
     for(int C=0;C<M;C++)
        cout<<setw(10)<<A[R][C];
     cout<<endl;
   }
}

Function to find the sum of two dimensional arrays A and B

void Addition(int A[][20], int B[][20],int N, int M)
{
  for(int R=0;R<N;R++)
    for(int C=0;C<M;C++)
      C[R][C]=A[R][C]+B[R][C];
}

Function to multiply two dimensional arrays A and B of order NxL and LxM

void Multiply(int A[][20], int B[][20], int C[][20],int N, int L, int M)
{
  for(int R=0;R<N;R++)
   for(int C=0;C<M;C++)
   {
      C[R][C]=0;
      for(int T=0;T<L;T++)
        C[R][C]+=A[R][T]*B[T][C];
    }
}

Function to find & display sum of rows & sum of cols. of a 2 dim. array A

void SumRowCol(int A[][20], int N, int M)
{
  for(int R=0;R<N;R++)
  {
     int SumR=0;
     for(int C=0;C<M;C++)
       SumR+=A[R][C];
     cout<<"Row("<<R<<")="<<SumR<<endl;
   } 
  for(int R=0;R<N;R++)
  {
    int SumR=0;
    for(int C=0;C<M;C++)
      SumR+=A[R][C];
    cout<<"Row("<<R<<")="<<SumR<<endl;
   }
}

Function to find sum of diagonal elements of a square matrix A

void Diagonal(int A[][20], int N, int &Rdiag, int &LDiag)
{
  for(int I=0,Rdiag=0;I<N;I++)
    Rdiag+=A[I][I];
  for(int I=0,Ldiag=0;I<N;I++)
    Ldiag+=A[N-I-1][I];
}

Function to find out transpose of a two dimensional array A


void Transpose(int A[][20], int B[][20],int N, int M)
{
  for(int R=0;R<N;R++)
    for(int C=0;C<M;C++)
       B[R][C]=A[C][R];
}

string in c++

Posted by Unknown On 9:18 AM No comments

C-STRINGS (Character Arrays)

STRING: It is an array of type char.

Syntax for declaration

char <array/string name> [max. number of characters to be stored +1];
The number of elements that can be stored in a string is always n-1, if the size of the array specified is n. This is because 1 byte is reserved for the NULL character '\0' i.e. backslash zero. A string is always terminated with the NULL character.
Example: char str[80]; In the above example, str can be used to store a string with 79 characters.

Initializing a string

A string can be initialized to a constant value when it is declared.
char str[ ] = "Good";     Or char str[]={'G','o','o','d','\0'};
Here. 'G' will be stored in str[0], 'o' in str[1] and so on.
Note: When the value is assigned to the complete string at once, the computer automatically inserts the NULL character at the end of the string. But, if it is done character by character, then we have to insert it at the end of the string.

Reading strings with/without embedded blanks

To read a string without blanks cin can be used cin>>str; To read a string with blanks cin.getline() or gets() can be used. cin.getline(str,80);    -Or- gets(str);

Printing strings

cout and puts() can be used to print a string. cout<<str:    Or
puts(str);
Note: For gets( ) and puts(), the header file stdio.h has to be included. puts() can be used to display only strings. It takes a line feed after printing the string.
cin
gets()
It can be used to take input of a value of any data type.It can be used to take input of a string.
It takes the white space i.e. a blank, a tab, or a new line character as a string terminator.It does not take the white space i.e. a blank, a tab, or a new line character, as a string terminator.
It requires header file iostream.hIt requires the header file stdio.h
Example:
char S[80];
cout<<"Enter a string:”;
cin>>S;
Example:
char S[80];
cout<<"Enter a string:";
gets(S);

cout
puts()
It can be used to display the value of any data type.It can be used to display the value of a string.
It does not take a line feed after displaying the string.It takes a line feed after displaying the string.
It requires the header file iostream.hIt requires the header file stdio.h
Example:
char S[80]="Computers";
cout<<S<<S; 

Output:
ComputersComputers
Example:
char S[80]="Computers";
puts(S);
puts(S); 

Output:
Computers
Computers

Counting the number of characters in a string and printing it backwards

#include<iostream.h>
#include<stdio.h>
int main( )
{
  char str[80];
  cout<<"Enter a string:";
  gets(str);
  for(int l=0; str[l]!='\0';l++);  //Loop to find length
    cout<<"The length of the string is : "<<l<<endl ;
  for(int i=l-1;i>=0;i--)    //Loop to display the string backwards
    cout<<str[i];
  return 0; 

}

Function to count the number of words in a string

void count(char S[])
{
  int words=0;
  for(int i=0;S[i]!='\0';i++)
  {
    if (S[i]==' ')
      words++;                   //Checking for spaces
  }
  cout<<"The number of words="<<words+1<<endl;
}

Function to find the length of a string

int length(char S[ ])
{
  for(int i=0;S[i]!='\0';i++);
     return i;
}

Function to copy the contents of string S2 to S1

void copy(char S1[ ], char S2[ ])
{
   for(int i=0;S2[i]!='\0';i++)
      S1[i]=S2[i];
   S1[i]='\0';
}

Function to concatenate the contents of string S2 to S1

void concat(char S1[ ], char S2[ ])
{
   for(int l=0;S1[l]!='\0';l++);
     for(int i=0;S2[i]!='\0';i++)
         S1[l++]=S2[i];
     S1[l]='\0';
}

Function to compare strings STR1 to STR2. The function returns a value>0 if //STR1>STR2, a value<0 if STR1<STR2, and value 0 if STR1=STR2

int compare(char STR1[ ],char STR2[])
{
  for(int I=0;STR1[I]==STR2[I] && STR1[I]!='\0'&&STR2[I]!='\0'; I++);
     return STR1[I]-STR2[I];
}

To reverse the contents of string S and store it in string Rev

void Reverse(char S[], char Rev[])
{
   for(int C1=0; S[C1]!='\0'; C1++);
      C1--;
   for(int C2=0;C1>=0;C2++,C1--)
      Rev[C2]=S[C1];
   Rev[C2]='\0';
}

Function to check whether a string S is a palindrome or not

int Palin(char S[])
{
   for(int L=0;S[L]!='\0';L++);    //To find length
      for(int C=0;(C<L/2) && (S[C]==S[L-C-1]);C++);
         return (C==L/2)?1:0; //Returns 1 if Palindrome else 0
}

Function to change the case of string S to uppercase

void Upper(char S[])
{
   for(int i=0;S[i]!='\0';i++)
      S[i] = (S[i]>='a' && S[i]<='z')?(S[i]-32):S[i];
}

Function to change the case of string S to lower case

void Lower(char S[])
{
   for(int i=0;S[i]!='\0';i++)
       S[i] = (S[i]>='A' && S[i]<='Z')?(S[i]+32):S[i];
}

Function to extract n characters from left side of the string and store it in a different string. Example: 4 characters from ENVIRONMENT=ENVI

int SLeft(char S[ ], int n, char result[ ])
{
   for(int l=0;S[l]!='\0';l++);
     if(n<=I)    //characters extracted should be <=length
     {
        for(int i=0;i<n;i++)
            result[i]=S[i];
        result[i]='\0';
        return 1;
     }
     else
        return 0;
}

Function to extract n characters from right side of the string and store it in a different string. Example: 4 characters from ENVIRONMENT=MENT

int SRight(char S[ ], int n, char result[ ])
{
   for(int l=0;S[l]!='\0';l++);
     if(n<=I)     //characters extracted should be <=length
     {
        for(int j=0;i=l-n;S[i]!=’/0’;i++,j++)
            result[j]=S[i];
        result[j]='\0';
        return 1;
     }
     else
        return 0;
}

Function to extract n characters from specified location loc of the string and store it in a different  string. Example: 4 characters from third location in string ENVIRONMENT= VIRO


int substring(char S[ ], int n, int loc, char result[ ])
{
  for(int l=0;S[l]!='\0';l++);
     if(n<=I)      //characters extracted should be <=length
     {
        for(int j=0;i=l-n;S[i]!=’/0’;i++,j++)
           result[j]=S[i];
        result[j]='\0';
        return 1;
     }
     else
        return 0;
}

Sunday, September 8, 2013

ARRAY

Posted by Unknown On 9:56 AM 1 comment

Array

An array is a collection of data elements of same data type. It is described by a single name and each element of an array is referenced by using array name and its subscript no.

Initialization of One Dimensional Array

An array can be initialized along with declaration. For array initialization it is required to place the elements separated by commas enclosed within braces. int A[5] = {11,2,23,4,15}; It is possible to leave the array size open. The compiler will count the array size. int B[] = {6,7,8,9,15,12};

Referring to Array Elements

In any point of a program in which an array is visible, we can access the value of any of its elements individually as if it was a normal variable, thus being able to both read and modify its value. The format is as simple as:
name[index]

Examples: 
cout<<age[4];      //print an array element
age[4]=55;         // assign value to an array element
cin>>age[4];       //input element 4

Using Loop to input an Array from user

int age [10], i ;
for (i=0 ; i<10; i++)
{
  cin>>age[i];
}

Arrays as Parameters

At some moment we may need to pass an array to a function as a parameter. In C++ it is not possible to pass a complete block of memory by value as a parameter to a function, but we are allowed to pass its address.
For example, the following function:     void print(int A[]) accepts a parameter of type "array of int" called A.
In order to pass to this function an array declared as:    int arr[20]; we need to write a call like this:   print(arr);
Here is a complete example: 
#include <iostream.h>
void print(int A[], int length)
{
  for (int n=0; n<length; n++)
    cout << A[n] << " ";
  cout << "\n";
}
int main ()
{
  int arr[] = {5, 10, 15};
  print(arr,3);
  return 0;
}

Basic Operation On One Dimensional Array

Function to traverse the array A

void display(int A[], int n)
{
       cout<<"The elements of the array are:\n";
       for(int i=0;i<n;i++)
              cout<<A[i];
}

Function to Read elements of the array A

void Input(int A[], int n)
{ 
      cout<<"Enter the elements:";
      for(int i=0;i<n;i++)
            cin>>A[i];
}

Function to Search for an element from A by Linear Search

int Lsearch(int A[], int n, int Data)
{
      int I; 
      for(I=0; I<n; I++)
      {
            if(A[I]==Data)
            {
                  cout<<"Data Found at : "<<I;
                  return;
            }
      }
      cout<<"Data Not Found in the array"<<endl;
}

Function to Search for an element from Array A by Binary Search

int BsearchAsc(int A[], int n, int data)
{
       int Mid,Lbound=0,Ubound=n-1,Found=0;
       while((Lbound<=Ubound) && !(Found))
       {
              Mid=(Lbound+Ubound)/2;        //Searching The Item
              if(data>A[Mid])
                     Lbound=Mid+1;
              else if(data<A[Mid])
                     Ubound=Mid-1;
              else
                     Found++;
       }
       if(Found)
              return(Mid+1);        //returning 1ocation, if present
       else
              return(-1);        //returning -1,if not present
}

Function to Sort the array A by Bubble Sort

void BSort(int A[], int n)
{
    int I,J,Temp;
    for(I=0;I<n-1;I++) //sorting
   {
       for(J=0;J<(n-1-I);J++)
            if(A[J]>A[J+1])
           {
               Temp=A[J]; //swapping
               A[J]=A[J+1];
               A[J+1]=Temp;
           }
    }
}

Function to Sort the array ARR by Insertion Sort

void ISort(int A[], int n)
{
       int I,J,Temp;
       for(I=1;I<n;I++) //sorting
       {
           Temp=A[I];
           J=I-1;
           while((Temp<A[J]) && (J>=0))
           {
               A[J+1]=A[J];
               J--;
           }
           A[J+1]=Temp;
       }
}

Function to Sort the array by Selection Sort

void SSort(int A[], int n)
{
    int I,J,Temp,Small;
    for(I=0;I<n-1;I++)
    {
         Small=I;
         for(J=I+1;J<n;J++) //finding the smallest element
         if(A[J]<A[Small])
              Small=J;
         if(Small!=I)
        {
            Temp=A[I]; //Swapping
            A[I]=A[Small];
            A[Small]=Temp;
        }
     }
}

Function to merge A and B arrays of lenghts N and M

void Merge(int A[], int B[], int C[], int N, int M, int &K)
{
      int I=0, J=0;
      K=0;             //Initialisation of counters for A, B, and C
      while (I<N && J<M)
      {
            if (A[I]<B[J])
                  C[K++]=A[I++];
            else if (A[I]>B[J])
                  C[K++]=B[J++];
            else
            {
                  C[K++]=A[I++];
                  J++;
            }
      }
      for (int T=I;T<N;T++)
            C[K++]=A[T];
      for (T=J;T<M;T++)
            C[K++]=B[T];
}

some more about function

Posted by Unknown On 5:58 AM No comments

Global Variable And Local Variable

Local Variable : a variable declared within the body of a function will be evaluated only within the function. The portion of the program in which a variable is retained in memory is known as the scope of the variable. The scope of the local variable is a function where it is defined. A variable may be local to function or compound statement.
Global Variable : a variable that is declared outside any function is known as a global variable. The scope of such a variable extends till the end of the program. these variables are available to all functions which follow their declaration. So it should be defined at the beginning, before any function is defined.

Variables and storage Class

The storage class of a variable determines which parts of a program can access it and how long it stays in existence. The storage class can be classified as automatic register static external
Automatic variable
All variables by default are auto i.e. the declarations int a and auto int a are equivalent. Auto variables retain their scope till the end of the function in which they are defined. An automatic variable is not created until the function in which it defined is called. When the function exits and control is returned to the calling program, the variables are destroyed and their values are lost. The name automatic is used because the variables are automatically created when a function is called and automatically destroyed when it returns.
Register variable 
A register declaration is an auto declaration. A register variable has all the characteristics of an auto variable. The difference is that register variable provides fast access as they are stored inside CPU registers rather than in memory.
Static variable
A static variable has the visibility of a local variable but the lifetime of an external variable. Thus it is visible only inside the function in which it is defined, but it remains in existence for the life of the program.
External variable 
A large program may be written by a number of persons in different files. A variable declared global in one file will not be available to a function in another file. Such a variable, if required by functions in both the files, should be declared global in one file and at the same time declared external in the second file.

Function Prototype

A function prototype declares the function name, its parameters, and its return type to the rest of the program. This is done before a function is declared. (In most cases at the beginning of a program.) To understand why function prototypes are useful, try the following program:
#include<iostream>
 using namespace std;
 int main()
 {
  int answer;
  answer = Add(3,3);
  cout << answer;
  return 0;
 }
 int Add(int A, int B)
 {
  return A + B;
 }



This program will not compile on most compilers. (On some compilers you have to set a compiler option before it gives a warning or error.) The compiler will give an error, something like: ” Add, identifier not found”. (As we said before the function must be known before it’s called).
To solve this problem you can make use of function prototypes. If you use prototypes, the compiler can find the function and the compiler will check the parameters list (for wrong type usage). Try the next example:
#include<iostream>
 using namespace std;
 int Add(int,int); //Function prototype
 int main()
 {
  int answer;
  answer = Add(3,3);
  cout << answer;
  return 0;
 }
 int Add(int A, int B)
 {
  return A + B;
 }
The compiler can now find the Add function. It will also check if correct types (int,int) are used. This program should compile without a problem.
So in the future use function prototypes for every function you declare. It will save you a lot of time.
now let us look at some more of functions:--
a program to find the area and volume of a circle
#include<iostream> #include<string> using namespace std; int getapositive() { int num; cout<<" enter a radius"; cin>>num; return num; } double area(int r) { return 3.14*r*r; } double volume(int r) { return 4/3.0*3.14*r*r*r; } int main() { int radius=getapositive(); double carea=area(radius); double cvolume=volume(radius); cout<<" the area of a circle is"<<carea<<endl; cout<<" the volume of the circle is"<<cvolume<<endl; return 0; }

C++ Using functions, function parameters

Posted by Unknown On 5:09 AM No comments

Library Function

# Include Directive
The # include directive instructs the compiler to read and include another file in the current file. The compiler compiles the entire code. A header file may be included in one of two ways.
include <iostream.h>
or
include "iostream.h"
The header file in angle brackets  means that file reside in standard include directory. The header file in double quotes means that file reside in current directory.
LIBRARY FUNCTION
C++ provides many built in functions that saves the programming time 
Mathematical Functions
Some of the important mathematical functions in header file math.h are 
FunctionMeaning
sin(x)Sine of an angle x (measured in radians)
cos(x)Cosine of an angle x (measured in radians)
tan(x)Tangent of an angle x (measured in radians)
asin(x)Sin-1 (x) where x (measured in radians)
acos(x)Cos-1 (x) where x (measured in radians)
exp(x)Exponential function of x (ex)
log(x)logarithm of x
log 10(x)Logarithm of number x to the base 10
sqrt(x)Square root of x
pow(x, y)x raised to the power y
abs(x)Absolute value of integer number x
fabs(x)Absolute value of real number x
Character Functions
All the character functions require ctype.h header file. The following table lists the function.
FunctionMeaning
isalpha(c)It returns True if C is an uppercase letter and False if c is lowercase.
isdigit(c)It returns True if c is a digit (0 through 9) otherwise False.
isalnum(c)It returns True if c is a digit from 0 through 9 or an alphabetic character (either uppercase or lowercase) otherwise False.
islower(c)It returns True if C is a lowercase letter otherwise False.
isupper(c)It returns True if C is an uppercase letter otherwise False.
toupper(c)It converts c to uppercase letter.
tolower(c)It converts c to lowercase letter.
String FunctionsThe string functions are present in the string.h header file. Some string functions are given below:
strlen(S)It gives the no. of characters including spaces present in a string S.
strcat(S1, S2)It concatenates the string S2 onto the end of the string S1. The string S1 must have enough locations to hold S2.
strcpy(S1, S2)It copies character string S2 to string S1. The S1 must have enough storage locations to hold S2.
strcmp((S1, S2)==0) 
strcmp((S1, S2)>0) 
strcmp((S1, S2) <0)
It compares S1 and S2 and finds out whether S1 equal to S2, S1 greater than S2 or S1 less than S2.
strcmpi((S1, S2)==0) 
strcmpi((S1, S2)>0) 
strcmpi((S1, S2) <0)
It compares S1 and S2 ignoring case and finds out whether S1 equal to S2, S1 greater than S2 or S1 less than S2.
strrev(s)It converts a string s into its reverse
strupr(s)It converts a string s into upper case
strlwr(s)It converts a string s into lower case
Console I/O functions
The following are the list of functions are in stdio.h
getchar()It returns a single character from a standard input device (keyboard). It takes no parameter and the returned value is the input character.
putchar()It takes one argument, which is the character to be sent to output device. It also returns this character as a result.
gets()It gets a string terminated by a newline character from the standard input stream stdin.
puts()It takes a string which is to be sent to output device.
General purpose standard library functions
The following are the list of functions are in stdlib.h
randomize()It initializes / seeds the random number generator with a random number
random(n)It generates a random number between o to n-1
atoi(s)It converts string s into a numerical representation.
itoa(n)It converts a number to a string
Some More Functions
The getch() and getche() functions
The general for of the getch() and getche() is
ch=getche();
ch1=getch();
ch and ch1 are the variables of type character. They take no argument and require the conio.h header file. On execution, the cursor blinks, the user must type a character and press enter key. The value of the character returned from getche() is assigned to ch. The getche() fuction echoes the character to the screen. Another function, getch(), is similar to getche() but does not echo character to the screen.
intro to functions

Most languages allow you to create functions of some sort. Functions are used to break up large programs into named sections.
You have already been using a function which is the main function. Functions are often used when the same piece of code has to run multiple times. In this case you can put this piece of code in a function and give that function a name.
When the piece of code is required you just have to call the function by its name. (So you only have to type the piece of code once).

Creating User-Defined Functions

Declare the function.

The declaration, called the FUNCTION PROTOTYPE, informs the compiler about the functions to be used in a program, the argument they take and the type of value they return.

Define the function.

The function definition tells the compiler what task the function will be performing. The function prototype and the function definition must be same on the return type, the name, and the parameters.  The only difference between the function prototype and the function header is a semicolon.
The function definition consists of the function header and its body.  The header is EXACTLY like the function prototype, EXCEPT that it contains NO terminating semicolon.
//Prototyping, defining and calling a function
#include <iostream.h>
void starline();         // prototype the function
int main()
{
     starline( );      // function call
     cout<< "\t\tBjarne Stroustrup\n";
     starline( );    // function call
     return 0;
}

// function definitionvoid starline()
{
     int count;         // declaring a LOCAL variable
     for(count = 1; count <=65; count++)
          cout<< "*";
     cout<<endl;
}


Argument To A Function

Sometimes the calling function supplies some values to the called function. These are known as parameters. The variables which supply the values to a calling function called actual parameters. The variable which receive the value from called statement are termed formal parameters.
Consider the following example that evaluates the area of a circle.
#include<iostream.h>
void area(float);
int main()
{
    float radius;
    cin>>radius;
    area(radius);
    return 0;
}
void area(float r)
{
    cout<< “the area of the circle is”<<3.14*r*r<<”\n”;
}

Here radius is called actual parameter and r is called formal parameter.

Return Type Of A Function

// Example program
#include <iostream.h>

int timesTwo(int num);   // function prototype
int main()
{
     int number, response;
     cout<<"Please enter a number:";
     cin>>number;
     response = timesTwo(number);  //function call
     cout<< "The answer is "<<response;
     return 0;
}
//timesTwo function
int timesTwo (int num)
{
     int answer;   //local variable
     answer = 2 * num;
     return (answer);
}

Calling Of A Function

the function can be called using either of the following methods:
i) call by value 
ii) call by reference

Call By Value

In call by value method, the called function creates its own copies of original values sent to it. Any changes, that are made, occur on the function’s copy of values and are not reflected back to the calling function.

Call By Reference

In call be reference method, the called function accesses and works with the original values using their references. Any changes, that occur, take place on the original values are reflected back to the calling code.
Consider the following program which will swap the value of two variables.
using call by referenceusing call by value
#include<iostream.h>
void swap(int &, int &);
int main()
{
   int a=10,b=20;
   swap(a,b);
   cout<<a<<" "<<b;
   return 0; 
}
void swap(int &c, int &d)
{
   int t;
   t=c;
   c=d;
   d=t;
}
#include<iostream.h>
void swap(int , int );
int main()
{
   int a=10,b=20;
   swap(a,b);
   cout<<a<<" "<< b;
   return 0; 
}
void swap(int c, int d)
{
   int t;
   t=c;
   c=d;
   d=t;
}
output: 
20 10
output: 
10 20 

Function With Default Arguments

C++ allows to call a function without specifying all its arguments. In such cases, the function assigns a default value to a parameter which does not have a mathching arguments in the function call. Default values are specified when the function is declared. The complier knows from the prototype how many arguments a function uses for calling.
Example : 
float result(int marks1, int marks2, int marks3=75); 
a subsequent function call
average = result(60,70);
passes the value 60 to marks1, 70 to marks2 and lets the function use default value of 75 for marks3.
The function call 
average = result(60,70,80);
 
passes the value 80 to marks3.

Inline Function

Functions save memory space because all the calls to the function cause the same code to be executed. The functions body need not be duplicated in memory. When the complier sees a function call, it normally jumps to the function. At the end of the function. it normally jumps back to the statement following the call. 
While the sequence of events may save memory space, it takes some extra time. To save execution time in short functions, inline function is used. Each time there is a function call, the actual code from the function is inserted instead of a jump to the function. The inline function is used only for shorter code.
inline int cube(int r)
{
    return r*r*r;
}






lets see an example:::--

#include<iostream>
 using namespace std;

 void MyPrint()
 {
  cout << "Printing from a function.\n";
 }

 int main()
 {
  MyPrint();
  return 0;
        }
}
In the example above we declared a function with the name MyPrint. The only thing that this function does is to print the sentence “Printing from a function”. If we want to use the function we just have to call MyPrint() and the cout statement (in the function) will be executed. (Don’t forget to put the round brackets behind the function name when you call it or declare it).

Parameters and return

#include<iostream>
 using namespace std;

 int Add(int output1, int output2)
 {
  return output1 + output2;
 }

 int main()
 {
  int answer, input1, input2;

  cout << "Give a integer number:";
  cin >> input1;
  cout << "Give another integer number:";
  cin >> input2;

  answer = Add(input1,input2);

  cout << input1 << " + " << input2 << " = " << answer;
  return 0;
  }
The main() function starts with the declaration of three integers. Then the user can input two whole (integer) numbers. These numbers are used as input of function Add(). Input1 is stored in output1 and input2 is stored in output2. The function Add() will return the result of output1 + output2. The return value is stored in the integer answer. The number stored in answer is then printed onto the screen.

Void

If you don’t want to return a result from a function, you can use void return type instead of the int. So let’s take a look at an example of a function that will not return an integer:
#include<iostream>
using namespace std;


void Add(int input1, int input2);
int main()
{
int answer, input1, input2;

cout << "Give a integer number:";
cin >> input1;
cout << "Give another integer number:";
cin >> input2;

          Add(input1,input2);
return 0;
}
void Add(int input1,int input2)
{
int answer;
answer=input1+input2;
cout << input1 << " + " << input2 << " = " << answer;
        }
  •    Note: As you can see there is not an int before our_site() and there is not a return 0; statement in the function.

Global and local variables

A local variable is a variable that is declared inside a function. A global variable is a variable that is declared outside ALL functions. A local variable can only be used in the function where it is declared. A global variable can be used in all functions. See the following example:
#include<iostream>
 using namespace std;

 int A, B;

 int Add()
 {
  return A + B;
 }

 int main()
 {
  int answer;

  A = 2;
  B = 2;
  answer = Add();
  cout << A << " + " << B << " = " << answer;
  return 0;
 }
As you can see two global variables are declared, A and B. These variables can be used in main() and Add(). The local variable answer can only be used in main().
That’s all for this tutorial. In the next tutorial we will talk some more about functions