Documents
Resources
Learning Center
Upload
Plans & pricing Sign in
Sign Out

97382-3036-Convert-UPPERCASE-CHARACTERS-Into-lowercase-characters

VIEWS: 19 PAGES: 67

									                                                   1



Convert UPPERCASE CHARACTERS Into lowercase characters



// Following example, converts UPPERCASE characters in a string to lower case string
# include <iostream.h> // Header file for input output streams
# include <string.h> // Header file for string related functions such as strlen()

// Here is the function declaration "StrToLwr" for converting upper case characters in a string to
lower case characters. The function takes two arguments. Both are char type pointers. First one is
the actual string passed to it for conversion. The second argument will send the result back to the
calling program. The function will convert only UPPERCASE CHARACTERS to lowercase characters.
Every other character will remain as it is
void StrToLwr(char* mainstring, char *output)
{
int Len = strlen(mainstring); // Len will contain the length of the passed string.
for(int i = 0; i < Len; i++) // Now we will move from the 0th character in the string till its length
and we will check if its a UPPERCASE character and then change it to lowercase characters.
{
if( (int)mainstring[i] < 65) // If the ASCII code of the character i.e. integer value of the character
is less than 65, then copy the character as it is into the result string. It means that the character is
not in the range of upper case characters
output[i] = mainstring[i];
if( (int)mainstring[i] >= 65 && (int)mainstring[i] <= 90) // If the ASCII code of the character i.e.
integer value of the character is between 65 and 90, then its a UPPERCASE CHARACTER and let's
convert it into the lowercase. By adding 32 in the ASCII number of the character, the character
will be converted to lowercase. Such as, the ASCII code of UPPERCASE A is 65 and the ASCII code
of lowercase a is 97. If we add 32 to UPPERCASE A, its ASCII code will become 97 and the
character is changed from UPPERCASE to lowercase
output[i] = (char)mainstring[i] + 32;
if( (int)mainstring[i] >= 97 && (int)mainstring[i] <= 122) // If the ASCII code of the character i.e.
integer value of the character is between 92 and 122, then copy the character as it is into the
result string. It means that the character is not in the range of upper case characters. This is the
range for lowercase characters
output[i] = (char)mainstring[i];
if( (int)mainstring[i] > 122) // If the ASCII code of the character i.e. integer value of the character
is greater than 122, then copy the character as it is into the result string. It means that the
character is not in the range of upper case characters. This range contains the graphical ASCII
characters.
output[i] = mainstring[i];
}
output[i] = '\0'; // Null terminating the string to show the end of the string
}

// Here is the main program which will be using the C_File function
void main()
{
char arr1[21]="PRAsHANT"; // String to be converted
char arr2[21]; // Result will be stored here
StrToLwr(arr1,arr2); // Calling the function
cout<<arr2; // Display the result
} // End of main function
                                                  2

Reading and Writing a Class Object


Since the class objects are the central elements of C++ programming, so the language support
features for writing to and reading from the disk files object directly. The binary input and output
functions read() and write() are designed to do the given task.

#include< fstream.h>
#include< iomanip.h>
#include< conio.h>
class detail
{
char name[10];
int code;
float cost;
public:
void readdata(void);
void writedata(void);
};
void detail:: readdata(void)//read from keyboard
{
cout<<"\nEnter name: ";
cin>>name;
cout<<"\nEnter code: ";
cin>>code;
cout<<"\nEnter cost: ";
cin>>cost;
}
void detail::writedata(void)//formatted display on the screen
{
cout<< setiosflags(ios::left)<< setw(10)<< name
<< setiosflags(ios::right)<< setw(10)<< code
<< setprecision(2)<< setw(10)<< cost
<< endl;
}
main()
{
clrscr();
detail item[3];//Declare array of3 objects
fstream file; //Input and Output file
file.open("details.dat",ios::in,ios::out);
cout<<" Enter Details For Three Items \n";
for(inti=0;i<3;i++)
{
item[i].readdata();
file.write((char*) &item[i],sizeof(item[i]));
}
file.seekg(0);//reset to start
cout<< "\nOUTPUT\n\n";
for(i=0;i<3;i++)
{
file.read((char*) &item[i], sizeof(item[i]));
item[i].writedata();
}
file.close();
}




The output of the program ::
                                                  3

Enter   name:xyz
Enter   code:121
Enter   cost:500
Enter   name:mmm
Enter   code:222
Enter   cost:600
Enter   name:nnn
Enter   code:333
Enter   cost:400

OUTPUT

xyz 121 500
mmm 222 600
nnn 333 400




Pointer and Integer Arrays



If an integer variable occupies four bytes of memory, then each element of an integer array would
also occupy four bytes. If the pointer is assigned the address of the starting element of an integer
array. If the value in the pointer is incremented by one, the pointer will point to the next element
of the array.

#include<iostream.h>
int main()
{
         int numarr[] = { 10, 20, 30, 40, 50);
         int *ptr = numarr;
         cout << *ptr       <<endl;                       //Displays 10
         cout << *(ptr + 1) <<endl;                        //Displays 20
         ptr++;
         cout << *ptr       <<endl;                       //Displays 20
         cout << *(ptr - 1) <<endl;                       //Displays 10
         ptr--;
         cout << *ptr        <<endl;                      //Displays 10
         cout << sizeof(numarr)<<endl;                    //Displays 20 _ The Number of Bytes
Occupied By numarr
         cout << sizeof(ptr) <<endl;                      //Displays 4
         return 0
}




Output:   10 20
            20 10
            10 20      4




Comparing Strings in C++



The strcmp() function compares the two strings supplied as its parameters and returns its integer
value. To use of this function the file cstring needs to be included. If the first string argument is
less than the second,strcmp() returns a value less than zero. If the first argument is equal to the
second,strcmp() returns a value equal to zero. If the first argument is greater than the second,
the function returns a value greater than zero.
                                                 4

#include <iostream>
#include <cstring>
int main()
{
     char str[] = "ABCD";
     char str[] = "ABCD";
     cout<< endl << strcmp(str1,str2);        //OUTPUT Is 0 Since Both Strings Are Identical

char str[] = "ABCD";
     char str[] = "ABC";
     cout<< endl << strcmp(str3,str4);        //OUTPUT Is 68 Since ASCII Code for 'D' Is 68 and
The Fourth Character In
                                              str4 Is NULL, Hence 68 - 0 = 68
     char str[] = "ABCD";
    char str[] = "abcd";
    cout<< endl << strcmp(str5,str6);         //OUTPUT Is -32 Since ASCII Code FOR 'A' IS 97
And That Of 'A' Is
                                               65,Hence 65 - 97 = -32

char str[] = "abcd";
     char str[] = "ABCD";
     cout<< endl << strcmp(str7,str8);        //OUTPUT Is 32 Since ASCII Code FOR 'A' IS 97 And
That Of 'A' Is
                                               65,Hence 97 - 65 = 32

return 0;

}




Output: 0
             68
            -32
             32


Using new and delete Operators


C++ offers programmers a means to create variables dynamically using new operator. The new
operator determines the type of receiving pointer and converts its return value appropriately.
Memory is allocated. To release the memory allocated,C++ uses delete operator.
The new operator, when used with the pointer to a data type, allocates memory for the item and
assigns the address of that memory to the pointer. The delete operator does the reverse, it de-
allocates the memory allocated to the variable. The C++ new operator is used to allocate memory
from the heap. The advantage of the new operator is that it offers safety in terms of type and size.
Whereas malloc only takes one argument, the desired size in bytes. The argument to the new
operator identifies the type of the variable to create, which ensures that the user is getting
memory of the intended size and type. When no longer needed, memory that is allocated with new
should be deallocated with delete.

#include <iostream>
int main()
{
     char *name;                   //Declare a pointer
     name = new char[31];            //Allocates 31 bytes memory for the object
     cout<< "Enter name : " << endl; //Will be displayed on the screen
                                                     5


     cin >> name;
     cout << name <<;
     delete [] name;                     //Destroys the object by de-allocating the memory
     return 0;
}


Convert All Whitespaces Into a Single Space



The following code can be used to convert all whitespaces in a string to a single space.
For ex., if a string contains "one guy is standing", will be converted to "one guy is standing".

// Here is the code.
#include <ctype.h> // for isspace() function
#include <conio.h> // for getch() function
#include <iostream.h> // for input-output stream functionalities
void lv(char *str) // Function to convert all whitespaces in a string to a single space.
{
char *ibuf, *obuf; // Declaring pointers to character
int i, cnt;
if (str)
          {
          ibuf = obuf = str; // Storing the value of str to obuf and str both.
          i = cnt = 0;
          while(*ibuf) // while there is some value in ibuf
          { // Loop to eliminate whitespaces...
          if(isspace(*ibuf) && cnt)
          ibuf++;
          else
                   {
                   if (!isspace(*ibuf)) // isspace will return a non-zero value if *ibuf is a space, tab,
                   newline, form feed, carriage return or vertical tab
                   cnt = 0;
                   else
                   {
                   *ibuf = ' ';
                   cnt = 1;
                   }
                   obuf[i++] = *ibuf++; // *ibuf++ increments the pointer to the next character in
                   ibuf and that particular character gets stored into obuf array
          }
          }
          obuf[i] = '\0'; // Storing NULL Termination character at the end
}
cout<<obuf<<endl; // Statement containing the final string values
}
void main()
{
lv("one guy is standing"); // Calling the function.
getch(); // Wait for a key press from the user.
}


Output:

one guy is standing
                                                6

Overloading Plus Operator


Function Overloading allows to have multiple functions with the same name. The compiler
identifies the function based on the parameters to the function. The concept of overloading a
function can be applied to operators as well. Most built-in data types have predefined operators
associated with them. For example, the C++ data type, int,together with the operators,+,-,*,and
/,provides support for mathematical operations using integers. To make a user-defined data type
as natural as a built-in data type, it must be associated with the appropriate set of operators.

Operator overloading refers to giving additional meaning to the normal C++ operators when they
are applied to ADTs only a predefined set of C++ operators can be overloaded. An operator can be
overloaded by defining a function for it. The function for the operator is declared by using the
operator keyword. There are some operators that cannot be overloaded like Member
Access(.),Pointer to member(.*),Scope resolution(::),Ternary(?:),Number of bytes in operand
(sizeof). There are some operators that should not be overloaded since they destroy the meaning
of the built-in operators like The AND logical operator(&&),The OR logical operator(||),The comma
operator(,).


#include <iostream.h>                                     //Including the header file
class Number
{
private:
        int number;
public:
        Number(int = 0);                                 //Constructor
                                                        /*Operators*/
       Number operator +(int);                          //Operator cannot have default arguments
       Number operator +(const Number &);
       void display();                                 //Function
};
Number : : Number(int num)
{
        number = num;
}
Number Number : : operator +(int RHS)
{
        Number temp;
        temp.number = number + RHS;
        return temp;
}
void Number : : display()
{
        cout << number << endl;
}
int main()
{
        Number num1(100);
        Number num2(200);
        Number num3=num1;
        Number tot;
        tot = num1 + 50;
        tot.disply();                                //Displays 150
        tot = num1 + num2;
        tot.display();                               //Displays 300
        num3.display();                             //Displays 100
        return 0;
}
                                                 7

Output: 150

         300

         100




Sequence of Constructor and Destructor

The following program demonstrates the sequence of calling the constructor, destructor and
overloaded new and delete operator function

#include< iostream.h>
#include< conio.h>
#include< stdlib.h>
#include< string.h>
#include< new.h>
class emp
{
char name[20];
int age;
float sal;
public:
//Opertor overloading for new opertor
void * operator new (size_t bytes);
// Opertor overloading for delete
void operator delete(void *k);
emp();
~emp();
};
char pool[sizeof(emp)];
emp::emp()
{ cout<<endl<<"Reached constructor";
}
emp::~emp()
{ cout<<endl<<"Reached destructor";
}
void *emp::operator new(size_t sz)
{
cout<<endl<<"Reached emp:: new";
return pool;
}
void emp::operator delete(void *q)
{
cout<<endl<<"Reached employee:: delete";
}
void main()
{
clrscr();
emp *e;
e=new emp;
delete e;
}

The new function may not access any of the class's members because no memory exists for them
until new allocates it and because the constructor function has not yet performed any other class-
specific initializations. Similarly because the delete operator may not have access to the class
member.
                                                8

The output of the given program::

Reached   emp:: new
Reached   constructor
Reached   destructor
Reached   employee:: delete




Capture Arrow Keys

// The following example shows you how to detect and capture Arrow Keys in DOS. Infact, this will
just show how a person might use the arrow keys in DOS.

#include <iostream.h> // Header file for stream input and output such as cout and cin
#include <conio.h> //Header file for kbhit() , getch() functions

// Let's define the macros for arrow keys.
const char CKEYUP = 72; // Up Arrorw key
const char CKEYLEFT = 75; // Left Arrow key
const char CKEYRIGHT = 77; // Right Arrow key
const char CKEYDOWN = 80; // Down Arrow key

void main() // Our main function
{
char Arr = 0;
Arr = kbhit(); // keeps processing commands while you hit.
while(Arr !=27) // 27 is the ASCII code for ESCAPE key. When you will press ESCAPE key, the
program will quit you out.
{
Arr = getch(); // getch() retrieves the char and wait for it to be pressed
switch(Arr) // Let's check the value of Arr variable
        {
        case CKEYUP:
        cout<<" UP ARROW KEY PRESSED!! ";
        break; // break will take you out of the switch loop
        case CKEYDOWN:
        cout<<" DOWN ARROW KEY PRESSED!! ";
        break;
        case CKEYLEFT:
        cout<<" LEFT ARROW KEY PRESSED!! ";
        break;
        case CKEYRIGHT:
        cout<<" RIGHT ARROW KEY PRESSED!! ";
        break;
} // switch loop ends
} // while loop ends
} // main function ends




Declaring Functions

A function is a set of statements that perform a specific task. In C++,functions must be defined
outside any other enclosing block where a block is delimited by braces '{ }'.There are certain
terms associated with functions like Function declaration(which introduces the function in the
program), Function definition(which contains the function code),Function call(used to execute the
function), Function parameters(the data that is passed to function before it starts
execution),Function returntype,Calling function, Called function.

#include <iostream.h>                                     //Including the header file
void acceptdata();
                                               9

void displaydata();
/* Define Variables Outside All Functions, Since More Than One Function Needs To Access Them */
char mobileNo[11];
char name[26];
char dateOfBirth[9];

/* Definition Of The main() Function */
int main()
{
   acceptdata();    //Function Call
   displaydata(); //Function Call
   return 0
}
void acceptdata()
{
/* Accept Data from The User */
   cout << endl << "Please enter customer details" << endl;
   cout << "Mobile phone number: ";
   cin >> mobileNo;
   cin.ignore();
   cout << endl << "Name: ";
   cin.getline(name,25);
   cout << endl << "Date of birth: ";
   cin >> dateOfBirth;
   cin.ignore();
}
void displaydata()
{
/* Display Data */
   cout << endl << endl << "The details of the customer are:" << endl;
   cout << "Mobile phone number: ";
   cout << mobileNo << endl;
   cout << Name: ";
   cout << name << endl;
   cout << "Date of Birth: ";
   cout << dateOfBirth << endl;
   return;
}




Output:
Mobile phone number: 9810127011
Name: Michael
Date of Birth: 10/8/1971
                                                  10

Virtual Base Class

Virtual functions ensure that the code that manipulate objects of a base type can manipulate
without changing derived-type objects as well. Virtual functions should always be called using
either pointer or a reference.If we try to do so using an object a phenomenon called object slicing
takes place.

#include< iostream.h>
#include< conio.h>
class base
{
int i;
public:
base(int m)
{
i=m;
}
virtual void fun1()
{
cout<< endl<< i;
}
};
class derived: public base
{
int j;
public:
derived(int m,int n): base(m)
{
j=n;
}
void fun1()
{
base:: fun1();
cout<< endl<< j;
}
};
void main()
{
clrscr();
base b(15);
derived d(20,25);
base *ptr1=&b;
//calls the virtual function
ptr1->fun1();
base *ptr2=&d;
//calls the virtual function
ptr2->fun1();
base &ref1=b;
// Calls the virtual function
ref1.fun1();
base &ref2=d;
ref2.fun1();
/* Object slicing means if an object of a derived class is assigned to base portion of the object.It
slices off the derived portion of the object.Hence when we make call b.fun1() only the member
fuction in the base class gets called. */
b=d;< /FONT>//Object sliced b.fun1(); }




The output of the program ::
                                                11

15
15
20
25
15
20
25
20




Simple File Input/Output With fstream



The following code example shows a simple file Input/Output with fstream

# include <iostream.h> // Header file for input output streams
# include <fstream.h> // Declares the stream classes for file input and output
# include <conio.h> // Header file for getch() function

void main()
{
// first lets output some data to a file
ofstream fout("filename.txt"); // ofstream class provides input operations on files i.e. using the
object of ofstream, you can write something in a file. Here we are calling the argument constructor
of ofstream by creating an object fout and providing the filename we want to write into to it.
fout << "data" << endl; // Storing data into fout i.e. into the file it is pointing to
fout.close(); // close function closes a file handle

char data[15]; // Lets declare an array to get the data from the same file
ifstream fin("filename.txt"); // ifstream class provides output operations on files i.e. using the
object of ifstream, you can read something from a file. Here we are again calling the argument
constructor of ifstream by creating an object fin and providing the filename we want to read from.
fin >> data; // Get the data from the file into our variable.
fin.close(); // close the file handle
cout << "data read from file: " << data << endl;
         getch(); // Wait for a key press from the user.
}




Output:

date read from file : data
                                                  12

Program for counting the Number of characters in the string or sentence

In the program below we count the number characters in the sentence or string without
counting the spaces between them.

#include< iostream.h> //Header file for Console Input and Console Output
#include< conio.h> //Header file for clrscr()
#include< stdio.h> //Header file for gets()

main()
{
clrscr(); //It clears the screen
char * str; //pointer declaration for holding the string;
inti=0,space=0;
cout<<"Enter the String :: ";
gets(str); //holds the string until a new line character is pressed.
while(str[i]!='\0') //Checks for the new line character to terminate the string
  {
  i++;
  if(str[i]==' ')
  space++;
  } //End of while loop
cout<<"The number of character in the string are :: "<< i++ -space;
} //End of main()


The output of the program::

Enter the string:: Hello how are you
The number of character in the string are :: 14




Working with multiple files( File streams)

The program segment opens two files and inserts the data in the files,and then opens the two files
simultaneously and reads the input from them one by one;

#include< fstream.h>
#include< stdlib.h> // for exit() function
#include< conio.h>
main()
{
clrscr();
const int SIZE=80;
char line[SIZE];
ofstream fout; // create output stream
fout.open("EmpCode");// connect EmpCode to it
fout<<"E0001\n";
fout<<"E0002\n";
fout<<"E0003";
fout.close(); // disconnect "EmpCode"
fout.open("Salary");// Connect to salary
fout<<"15000\n";
fout<<"25000\n";
                                                  13

fout<<"22000";
fout.close();
ifstream fin1,fin2; //creating two input streams
fin1.open("EmpCode"); //connect EmpCode to fin1
fin2.open("Salary"); // connect Salary to fin2
for(inti=0;i<=10;i++)
{
if(fin1.eof()!=0)
{
cout<<"Exit from EmpCode\n";
exit(1);
}
fin1.getline(line, SIZE);
cout<<"Salary of Emp :: "<< line;
if(fin2.eof()!=0)
{
cout<<"Exit from Salary \n";
exit(1);
}
fin2.getline(line,SIZE);
cout<<"\t"<<line<<"\n";
}
}




The output of the program ::

Salary of Emp :: E0001 15000
Salary of Emp :: E0002 20000
Salary of Emp :: E0003 22000
Exit from EmpCode




Program for finding if the string is palindrome or not

This program checks for the string or sentence, whether it is a Palindrome or not

#include<   iostream.h>
#include<   conio.h>
#include<   stdio.h>
#include<   string.h>
#include<   alloc.h> //Header file for free()

main()
{
clrscr();
char *str, *reverse; //Variable declaration for string and its reverse;
inti=0,j=0;
cout<<"Enter the string:: ";
str=new char[100]; //memory allocation for str;
reverse=new char[100]; //memory allocation for reverse;
gets(str);
while(str[i]!='\0') // This loop move the cursor at the end of the string
{
i++;
}
i--;
while(i>=0) //Loop for reversing the string
{
                                               14

reverse[j]=str[i];
j++;
i--;
}
reverse[j]='\0';
cout<<"The reverse of string is::"<< reverse<< endl; //Displaying the reverse string;
if(strcmp(str,reverse)==0) //Comparing the string and its reverse
cout<<"The given string is Palindrome";
else
cout<<"The string is not Palindrome";
free(str);
free(reverse);
}

The output of programe will be as follows::


Output:

Enter the string:: malylam madam malylam
The reverse of string is::malylam madam malylam
The string is Palindrome
                                                 15

Linear Search

This is the simplest technique to find out an element in an unsorted list. In this technique the
value of the key is compared with the first element of the list,if match is found then the search is
terminated. Otherwise next element from the list is fetched and compared with the key and this
process is continued till the key is found or list is completely exhausted.

#include< iostream.h>
#include< conio.h>
#include< stdlib.h>
int search;
int flag;
int input(int *,int,int);
void linear_search(int *,int, int);
void display(int *,int);
void main()
{
clrscr();
int number,key, list[200];
number=input(list,number,key);
key=search;
cout<<"\n Entered list as follows: \n";
display(list,number);
linear_search(list,number,key);
cout<<"\nIn the following list\n";
display(list,number);
}
//Defination of function
void linear_search(int l[],int n, int element)
{
int k;
flag=1;
for(k=0;k< n;k++)
{
if(l[k]==element)
{
cout<<"\nSearch is successful \n";
cout<<"\n Element : "<<element<<" Found at Location: "<< k+1;
> flag=0;
}
}
if(flag)
cout<<"\nSearch is unsuccessful";
}
void display(int list[],int n)
{
int i;
for(i=0;i< n;i++)
{
cout<<list[i]<<"\t";
}
}
input(int list[], int number,int key)
{
int i;
number=20;
key =30;
cout<<"Number of elements in the list:: "<< number;
for(i=0;i<20;i++)
{
list[i]=rand()%100;
}
cout<<"\nElement to be searched:: "<< key;
                                 16

search=key;
return number;
}




The output of the program ::

Number of elements in the list:: 20
Element to be searched:: 30
Entered list is as follows:
46 30 82 90 56 17 95 15 48 26
4 58 71 79 92 60 12 21 63 47
Search is successful
Element:30 found AT Location: 2
In the following list
46 30 82 90 56 17 95 15 48 26
4 58 71 79 92 60 12 21 63 47
                                                  17


Binary Search

Binary search works for sorted lists and is very efficient searching technique. It is used to find the
location of given element or record in a list. Other information associated with the element can
also be fetched if required. To find the location of a file in the computer directory one can use this
searching technique.

In the given program let low represent lower limit of the list, high upper and mid is average of low
and high. We comapre the middle element with key to be searched.If the value of middle element
is greater than key, then key will exists in lower half of the list,take high= mid-1and find new
value of mid.This process continues until the entire list exhausted or key is searched. < /FONT>

#include< iostream.h>
#include< conio.h>
int binary_search(int array[],int value,int size)
{
int found =0;
inthigh=size,low=0,mid;
mid=(high+low)/2;
cout<<"\n\nLooking for "<< value<< endl;
while((!found) && (high>=low))
{
cout<<"Low "<< low<<" Mid "<<mid<<" High "<< high<< endl;
if (value==array[mid])
found=1;
else if(value< array[mid])
high=mid-1;
else low=mid+1;
mid=(high+low)/2;
}
return((found)?mid: -1);
}
void main(void)
{
clrscr();
int array[100],i;
for(i=0;i<100;i++)
array[i]=i+20;
cout<<"Result of search "<< binary_search(array,15,100)<< endl;
cout<<"Result of search "<< binary_search(array,23,100)<< endl;
}




The output of the program ::

Looking for 15
Low 0 Mid 50 High 100
Low 0 Mid 24 High 49
Low 0 Mid 11 High 23
Low 0 Mid 5 High 10
Low 0 Mid 2 High 4
Low 0 Mid 0 High 1
Result of search -1


Looking for 23
Low 0 Mid 50 High 100
Low 0 Mid 24 High 49
Low 0 Mid 11 High 23
Low 0 Mid 5 High 10
Low 0 Mid 2 High 4
                     18

Low 3 Mid 3 High 4
Result of search 3
                                                   19

Fibonacci Series

This program calls the function fibo_number() recursively

#include< iostream.h>
#include< conio.h>
long fibo_number(int );
/* Defination of the function fibonacci number generator */
long fibo_number(int n)
{
int r;
if((n==1)||(n==0))
return 0;
else
if(n==2)
return 1;
else
return(fibo_number(n-1)+ fibo_number(n-2));
}
/* main function */
main()
{
int n;
int i=0;
cout<<endl<<" Input the number for fibonacci series, you want to generate:";
cin>> n;
cout<<"\n Fibonacci Series is as follows: \n";
while(i< n)
{
++i;
cout<<" "<< fibo_number(i));
}
}




The output of the program ::

Input the number for fibonacci series, you want to generate:12

Fibonacci Series is as follows:
0 1 1 2 3 5 8 13 21 34 55 89



Reverse an Integer Value

Its easy to reverse a given string such as reverse of "NIT" is "TIN". But its a little difficult process
when you are converting an integer value stored in an integer variable. The following example
shows how to accomplish this.
# include <iostream.h> // Let's include header file for screen input and output
# include <conio.h> // For getch() function
void revfunction(int num); // Declaration of function which will perform the actual reverse of
number. The function accepts an integer as an argument and then it reverse the number and
displays it.
                                                 20

void main() // Our main function, programs starting point
{
int nnum;
cout <<"this program will give the inverse of any number:"<<"\t";
cin>>nnum; // Accept the number from the user i.e. via keyboard
revfunction(nnum); // Calling the function with the number passed to it.
cout<<"\n"<<"Press a Key..."<<"\t";
getch();
}
void revfunction(int num)
{
int p=1,f,i;
while (p!=0)
{
// Lets take an example if the number if 132 then,
p=num/10; // it will store 13 into p
f=p*10; // f will contain 130
i=num-f; // i will have 132-130 i.e. 2 i.e. the last number of the value
num=p; // lets store the remaining part of the value into num for more caluclations till p is not
equal to 0
cout<<i; // display the last number extracted. Then with 13, the program will do the same
calculation and extract the last number from it and this is how it reverse an integer value.
}
}


Working with Pointers

// The following example illustrates some of the basic operations with pointers. This program will
help you in understanding the pointers and the functionalities of pointers. Pointers store the
address of another variable and it provides another path to work with variables

# include <iostream.h> // Header file for stream input-output such as cout, cin

void main() // Our main program starts here
{
int v=25, u=50; // Declaring two variables of int type, and storing some value into them
int *p, *q; // Declaration of two pointers. * is the operator used for declaring a pointer

p = &v;          // Now p points to v. This statement means that we are storing the address of
variable v into pointer p. & operator is Address-Of operator
cout << v << endl; // Here we are displaying the value of variable v using v only, like we normally
do in programs
cout << *p << endl; // Here we are showing the value of the address pointed to by pointer p. *
operator is known as dereferencing/indirection operator) which returns an alias or nickname of the
variable its operand point to. Here we are displaying the value of variable v using *p, as * is
indirecting the reference to the variable v because p holds the address of v. This way we can
display the value of a variable using a pointer
                                                          21

*p = 50;        // Now v = 50. As stated above, * is dereferencing operator and here we are
storing some value into *p. Infact we are indirecting the value to the address the pointer p points
to and thus the value of variable v will get change. This way we can change the value of a variable
using a pointer
cout << v << endl; // Displaying v's value
cout << *p << endl; // Dispaying v's value through a pointer

q = p;           // Now q points to v. We can make two or more pointers to point to same memory
location. Like here, we are storing the value of p into q. As we know that value of p is the memory
address of variable v, so here q will also points to v
cout << *p << endl; // Displaying v's value using pointer p
cout << *q << endl; // Displaying v's value using pointer v

q = &u; // Now q points to u. This shows that once pointed to a memory address, a pointer can
change its pointer location to another variable i.e. a pointer can start pointing to another variable
*p = 25;        // Here we are indirectly storing 25 into v
*q = *p;        // This statement is storing the value of memory address pointed by p in the
memory address pointed to by q. So, this statement is same as u = v
cout << v << endl; // Display the value of v
cout << u << endl; // Display the value of u
}

Output:

25

25

50

50

50

50

25

25



Drawing A Rectangle

// The following program shows how to draw a rectangle using graphical functionalities of C++
using the header file graphics.h

# include <graphics.h> // Header file for graphical functions
# include <iostream.h> // Header file for stream input-output such as cout, cin
#include <conio.h> // For getch()
void main()
{
int left, top, right, bottom; // Variables for storing coordinates of rectangle
/* request auto detection */
int graphdriver = DETECT, graphmode; // Variables to be passed to intigraph function. DETECT will request autodetection
initgraph(&graphdriver,&graphmode,""); // Initializing the graphics driver. To start the graphics
system, first you have to call the initgraph() function and it will load the graphics system and store
the system into graphmode. /* initialize graphics and local variables */
                                                22

// Let's set the left, top, right and bottom co-ordinates of rectangle
left = getmaxx() / 2 - 50; // getmaxx() returns the maximum screen relative x value for the
current graphics driver and mode
top = getmaxy() / 2 - 50; // getmaxx() returns the maximum screen relative x value for the
current graphics driver and mode
right = getmaxx() / 2 + 50;
bottom = getmaxy() / 2 + 50;
/* Here is the function used for drawing a rectangle */
rectangle(left,top,right,bottom);

getch(); // Wait for a key press
closegraph(); // It deallocates all the memory allocated by graphics system
}
Marquee Effect of a String

The following program shows an example of how you can achieve a cool Marquee effect, as seen
on news channels. It is same as the marquee effect on HTML pages, as it show the characters
moving towards left from right.
# include <conio.h> // For gotoxy() function
# include <string.h> // For strlen() function
# include <iostream.h> // For input output stream functionalities

void main(void) // This is our main function, starting point of program
{
int N=1;
char p;
char m[]={"- A cool marquee effect. Programmed in C++ Language - "};
intc=(strlen(m))-1,a=0,i,b=c; // We are storing the length of our string into c and then storing the
value of c into b.
while(a<131) // Loop till a<131. When a will be greater than or equal to 0, it will exit from the
loop
{ // Looping to display marquee effect
p=m[0]; // Storing the first character of the string into p
m[0]=m[c];
m[c]=p;
gotoxy(7,12); //it will put the current cursor at the specified position
for(i=1;i<=b;i++)
cout<<m[i];
for(i=0;i<N;i++){ } // Blank loop
c--;
if(c<1) // If c is less than 1 , then start it from the starting
{
c=b;
a++;
        if(a==100) N=51500;
}
}
}
                                                   23


Check if File Exists or Not

// Following is an example of File Exist Algorithm andthe function will check to see if a file exist in
the computer or not. If it doesnt it will return -1, if it exists it will return 0.
# include <iostream.h> // Header file for input output streams
# include <fstream.h> // Declares the stream classes for file input and output

// Following function takes the filename as the argument and then it checks for if the file exists or
not in the computer. If the file exists, the function will return 0, else it will return -1.
int C_File(char *FileName)
{
ifstream FileL; // ifstream class provides output operations on files i.e. using the object of ifstream,
you can read something from a file
FileL.open(FileName); // Using the open function of ifstream class through its object to open the
file
if(!FileL) // If there's an error opening the file using open function, the FileL object will contain
nothing and this staetment is checking if FileL object contains anything or not
{
FileL.close(); // Close the opened stream from the memory using close function of ifstream class
return -1; // Return -1 value to the calling program i.e. main() in our case. This means that the
file doesnt exists
}
else
{
FileL.close(); // Close the opened stream from the memory using close function of ifstream class
return 0; // Return 0 to the calling program i.e. main() in our case. This means that file exists
}
}

// Here is the main program which will be using the C_File function
void main()
{
int ret; // Declaring an integer variable to capture the return value of C_File function
ret=C_File("C:\abc.txt"); // Calling the function and passing file name to it. The function will
return the value into ret.
if(ret==0) // If ret is 0, means the file exists
cout<<"\nFile Exists";
else // If its not 0, means the file doesnt exists
cout<<"\nFile not exists";
} // End of main function



Using Graphics

// The following example shows you how you can display a string in Dos Graphics Mode. Here you
will get to know about graphical functionalities in C/C++ in graphics.h.
                                                 24

# include <graphics.h> // Header file for graphical functions
# include <iostream.h> // Header file for stream input-output such as cout, cin
# include <conio.h> // Header file for getch()

void main()
{
char *string = new char[25]; // Pointer to a char type array of 25 characters
int graphdriver = DETECT, graphmode; // Variables to be passed to intigraph function. DETECT will
request autodetection
initgraph(&graphdriver,&graphmode,""); // Initializing the graphics driver. To start the graphics
system, first you have to call the initgraph() function and it will load the graphics system and store
the system into graphmode.

cout<<"Enter a string: "; // Output the string on screen
cin>>string; // Takes input from the user
cleardevice(); // Clear the graphics screen. This function should be used when working with
graphics in C/C++ instead of using clrscr() function
outtext(string); // This function displays the string on the graphics screen. When graphics screen
has been initialized, then instead of using cout, you should use outtext() function to display the
string in graphical mode
delete string; // Released the memory occupied by string variable
}

Operator overloading for Matrix Multiplication

The program opens with a structure that contains a two - dimensional array.It is necessary to
create this structure since after performing addition and subtraction the structure can be
conveniently returned and assigned to another structure variable. To keep the array size general
two consts MAXROW and MAXCOL have been used to indicate the number of rows and columns in
the matrix.

#include< iostream.h>
#include< conio.h>
#include< iomanip.h> //header file for setw()
//macro declaration in program MAXROW will be replaced by 3 and MAXCOL also by 3
constintMAXROW=3,MAXCOL=3;

struct matrix
{
int arr[MAXROW][MAXCOL];// Double dimensional array
};
matrix operator * (matrix a,matrix b); //Operator overloding

// function declaration for printing matrix
void matprint(matrix p);

void main()
{
clrscr();
                                                 25

// Declaring matrix values
matrix a={ 1,2,3,
4,5,6,
7,8,9
};
matrix b={ 1,2,3,
4,5,6,
7,8,9
};

matrix c,d;
//overloaded operator will be called
c=a*b;
//display the matrix
matprint(c);
}
//overloaded operator defination for matrix Multiplication

matrix operator *(matrix a, matrix b)
{
matrix c;
int i, j,k;
for(i=0;i< MAXROW;i++)
{
for(j=0;j< MAXCOL;j++)
{
c.arr[i][j]=0;
for(k=0;k< MAXCOL;k++)
c.arr[i][j]+=a.arr[i][j]*b.arr[i][j];
}
}
return c;
}

//displaying matrix
void matprint(matrix p)
{
int i,j;
cout<< endl<< endl;
for(i=0;i< MAXROW;i++)
{ cout<< endl;
for(j=0;j< MAXCOL;j++)
cout<< setw(5)<< p.arr[i][j];
}
}




The output of the programe will be ::
                                                26

3   12      27
48  75      108
147 192     243




Multiple Inheritance

When a class can be derived from more than one base class. This is called Multiple Inheritance.
The example given below illustrates a company that markets both hardware and software. We
create a base class item that stores the title of the item and its price. Suppose we have another
base class sales that holds an array of three floats so that it can record the sale in rupees of a
perticular item for the last three months. Now we derive two classes hwitem(Hardware Item) and
switem(Software Item) from both item and sales. Each class has its own getdata() and
displaydata() functions to input and output data respectively.

#include< iostream.h>
#include< conio.h>
// Base Class declaration

class item
{
private:
char title[20];
float price;
public:
//Function for accepting the value
void getdata()
{
cout<<endl<<"Enter Title and Price ::";
>cin>>title>>price;
}

//function for displaying the value

void displaydata()
{
cout<<endl<<"Title and Price ::";
>cout<< title<<"\t"<< price;
}
};

// Second Base class declaration
class sales
{
private:
float salesfig[3];
public:
//Function for accepting the value
void getdata()
{
                                              27


cout<<endl<<"Enter sales figure for three months ::";
> for(inti=0;i<3;i++)
cin>> salesfig[i];
}

//function for displaying the value
void displaydata()
{
cout<<endl<<"Sales figure for three months ::";
> for(inti=0;i<3;i++)
cout<<salesfig[i]<<"\t";
>}
};

// A class drived from two base classes

class hwitem : private item,private sales
{
private:
char category[10];
char oem[10];
public:
//derived class getdata()
void getdata()
{
//base class getdata
item:: getdata();
cout<<endl<<"Enter category and Oem ::";
>cin>>category>>oem;
// base class getdata
sales::getdata();
}

//derived class function
void displaydata()
{
// base class displaydata

item:: displaydata();
cout<<endl<<"Category and Oem ::";
>cout<< category<<"\t"<< oem;
// base class displaydata
sales::displaydata();
}
};
                                              28

// Another class derived fro two base class
class switem:private item, private sales
{
private:
char category[10];
char os[10];
public:
void getdata()
{
item::getdata();
cout<<endl<<"Enter the Category and Os ::";
>cin>>category>>os;
sales::getdata();
}
void displaydata()
{
item::displaydata();
cout<<endl<<"Category and Os ::";
cout<< category<<"\t"<< os;
sales::displaydata();
}
};
void main()
{
clrscr();
// declaring the objects of derived class
hwitem h1,h2;
h1.getdata();
h1.displaydata();
h2.getdata();
h2.displaydata();
// declaring the objects of derived class
switem s1,s2;
s1.getdata();
s1.displaydata();
s2.getdata();
s2.displaydata();
}




The output of the programe will be ::

Enter Title and Price ::ABC 200
Enter Category and Oem ::ZZZ yyy
Enter sales figure for three months :: 2200 3300 4400
Title and Price ::ABC 200
Category and Oem ::ZZZ yyy
Sales figure for three months ::2200 3300 4400
Enter Title and price ------------
                                               29

Implementing constructor and destructor

This program describes the flow of constructor and destructor

#include< iostream.h>
#include< conio.h>
#include< stdio.h>
class student
{
private:
char *name;
char *sub;
int marks;
public:
student()//constructor( same name as class)
{
cout<<"Inside the constructor"<< endl;
// allocate the space in the memory.
name=new char[20];
sub=new char[20];
}
void input();
void output();
~student()//destructor(same name with tilde)
{
cout<< endl<<"Inside the distructor"<< endl;
//frees the allocated space
delete name;
delete sub;
}
};
main()
{
clrscr();
student st;
st.input();
st.output();
}
void student::input()
{
cout<<"Enter the name:: ";
gets(name);
cout<<endl<<"Enter the Subject:: ";
gets(sub);
cout<<endl<<"Enter the marks:: ";
cin>>marks;
}
                                                30

void student::output()
{
cout<<"Name:: "<< name<< endl;
cout<<"Subject:: "<< sub<< endl;
cout<<"Marks:: "<< marks;
}




The output of the program:

Inside the constructor
Enter the name:: Vikas
Enter the Subject:: Electronics
Enter the marks:: 92
Name:: Vikas
Subject:: Electronics
Marks:: 92




Overloading Assignment Operator and Copy constructor

The operator = () function in our program returns a value by creating a temporary rect object and
initialising it using the two arguments constructor. The value returned is a copy of the object of
which the overloaded = operator is a member. Cop constructor takes one argument,an object of
type rect,passed by reference. < /FONT >

#include< iostream.h>
#include< conio.h>
class rect
{
int area;
float len,width;
public:
rect()
{
}
rect(float ll,float wd)
{
len=ll;
width=wd;
area=ll*wd;
}
//Overloading the = operator
rect operator =(rect &r)
{
cout<<endl<<"Assignment operator invoked";
> area=r.area;
len=r.len;
width=r.width;
return rect(len,width);
}
                                             31

//copy constructor
rect(rect &r)
{
cout<<endl<<"Copy constructor invoked";
> len=r.len;
width=r.width;
area=r.len*r.width;
}
void display()
{
cout<< endl<<endl<<"Area= "<< area;
>cout<< endl<< endl<<"Length= "<< len;
> cout<< endl<<endl<<"Width= "<< width;
}
};
void main()
{
clrscr();
rect r1(4.5,10);
rect r2;
r2=r1;
//Copy constructor invoked
rect r3=r1;
r1.display();
r2.display();
r3.display();
}




The output of the program ::

Assignment operator invoked
Copy constructor invoked
Area=45
Length=4.5
Width=10
Area=45
Length=4.5
Width=10
Area=45
Length=4.5
Width=10




Overloading Unary Operators (prefix)

Example of unary operators are the increment and decrement operators ++ and --, program below
will demonistrate overloaded unary operator for class called list.
                                                  32

#include< iostream.h>
#include< conio.h>
class list
{
int count;
public:
//constructor for initializing the variable count to 0
list()
{
count=0;
}
//parametrized constructor for initializing the variable count
list(int i)
{
count=i;
}
// operator ++ overloaded
void operator ++()
{
++count;
}
//Function for displaying the value of count
void showdata()
{
cout<< count;
}
};
void main()
{
clrscr();
list l;
cout<< endl<<"C= ";
l.showdata();
//calling the overloaded operator
++l;
cout<<endl<<"C = ";
l.showdata();
}

The output of the program ::

C=0
C=1




Overloading Unary Operators (postfix)

Example of unary operators are the increment and decrement operators ++ and --, program below
will demonistrate overloaded unary operator for class called list.
                                                  33

#include< iostream.h>
#include< conio.h>
class list
{
int count;
public:
//constructor for initializing the variable count to 0
list()
{
count=0;
}
//parametrized constructor for initializing the variable count
list(int i)
{
count=i;
}
// operator ++ overloaded
list operator ++()
{
return list(++count);
}
//Operator ++ for postfix
list operator ++(int)
{
return list(count++);
}
//Function for displaying the value of count
void showdata()
{
cout<< count;
}
};
void main()
{
clrscr();
list l,k,m,o;
//prefix increment
m=++l;
cout<< endl<<"l= ";
l.showdata();
cout<<endl<<"e = ";
m.showdata();
//Postfix increment
o=k++;
cout<<endl<<"k = ";
k.showdata();
cout<<endl<<"o = ";
o.showdata();
}
                                                 34

/* The last two lines of the output show the result of the statement
o=k++; here k is incremented to 1,but o is assigned the value of k before
it is incremented, so o contains the value 0;
*/



The output of the program ::

l=1
e=1
k=1
o=0




Virtual Function

Here the class base contains a single virtual function disp1().The derived class redefines disp1()
and adds another virtual function called disp2().The compiler would pass the calls to disp1(), but it
would report an error for the call
ptr2->disp2();

#include< iostream.h>
#include< conio.h>
class base
{
int i;
public:
//virtual function of base class
virtual void disp1()
{
cout<<endl<<"In base class";
}
};
class derived:public base
{
public:
// function of derived class
void disp1()
{
cout<<endl<<"In derived class";
}
virtual void disp2()
{
cout<< endl<<"In derived->disp2()";
}
};
void main()
{
clrscr();
base *ptr1,*ptr2;
base p;
derived d;
                                                 35

ptr1=&p;
ptr2=&d;
ptr1->disp1();
ptr2->disp1();
//In this case compiler is working only with base class object.
//ptr2->disp2();// Error disp2()n is not a member of base.
}




The output of the program :In base class
In derived class




Virtual Base Class

Consider the situation where there is one base class and two classes derived from it,say
child1,child2.Suppose we derive a class gchild from child1 and child2. Now if a member function of
gchild class wants to access data or function in the base class.Since child1 and child2 are derived
from base, so each inherits a copy ofbase. This copy is referred to as a subobject.Each subobject
contains its own copy of base's data. So when data gchild refers to the data in the base class,
which of the two copies will it access? This is an ambiguous situation for the compiler, hence it
gives an error. To get rid of this ambiguity, we make child1 and child2 as virtual base.

#include< iostream.h>
#include< conio.h>
class base
{
protected:
int data;
public:
base()
{
data=10;
}
};
class child1:virtual public base
{
};
//Using the keyword virtual in the two base classes causes them to share a single
// subobject of the base class, which eliminates the ambiguity.
class child2:virtual public base
{
};
class gchild:public child1,public child2
{
public:
int getdata()
{
return data;
}
};
                                                 36

void main()
{
clrscr();
gchild obj;
int num;
num=obj.getdata();
cout<< num;
}




The output of the program ::10

BUBBLE SORT

It is a very simple sorting technique.However,this sorting technique is not efficient in comparison
to other sorting techniques. But for smaller lists this sorting technique works fine. Suppose we sort
the elements in descending order, the bubble sort loops through the elements in the list comparing
the adjacent element and moves the largest element to the top of the list.

#include< iostream.h>
#include< conio.h>
#include< stdlib.h>
void bubble_sort(int array[],int size)
{
int temp,i,j;
for(i=0;i< size;i++)
for(j=0;j< size-i-1;j++)
if(array[j]< array[j+1])
{
temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}
void main(void)
{
clrscr();
int values[30],i;
cout<<"Unsorted list is as follows\n";
for(i=0;i<10;i++)
{
values[i]=rand()%100;
cout<<values[i]<<" ";
}
bubble_sort(values,10);
cout<<"\nSorted list is as follows\n";
for(i=0;i<10;i++)
cout<<values[i]<<" ";
}
                                                  37



The output of the program ::

Unsorted list is as follows
46 30 82 90 56 17                95   15    48   26
Sorted list is as follows
95 90 82 56 48 46                30   26    17   15




Insertion Sort

Insertion sort technique scans the list L from L[1] to L[n], inserting each into its proper position in
the previously sorted sub-list L[1],L[2],..... ....L[n-1].

#include< iostream.h>
#include< conio.h>

int key;
int insert(int*);
void display(int*, int);
int insert(int list[])
{
int i=0;
int j,k;
cout<<"element to be inserted break condition is -0 : ";
cin>>key;
cout<<"Selected element is "<< key;
while(key!=-0)
{
k=i-1;
while((key< list[k] &&(k>=0)))
{
list[k+1]=list[k];
--k;
}
// This statement is appending the elements.

list[k+1]=key;
cout<<"List after inserting an element";
for(j=0;j<=i;j++)
cout<<" "<< list[j];
cout<<" \nElement to be inserted break condition is -0 ::";
cin>>key;
cout<<"\nSelected Element is : "<< key;
i++;
}
return i;
}
void display(int list[],int n)
{
int j;
cout<<"\n Fianl sorted list is as follows :\n";
                                                  38

for(j=0;j< n;j++)
cout<<" "<< list[j];
}
void main()
{
clrscr();
int list[200];
int n;
n=insert(list);
display(list,n);
}


The output of the program ::

element to be inserted break condition is -0 : 12
Selected element is 12List after inserting an element 12
Element to be inserted break condition is -0::23

Selected Element is : 23List after inserting an element 12 23
Element to be inserted break condition is -0::2

Selected Element is : 2List after inserting an element 2 12 23
Element to be inserted break condition is -0::21

Selected Element is : 21List after inserting an element 2 12 21 23
Element to be inserted break condition is -0::31

Selected Element is : 31List after inserting an element 2 12 21 23 31
Element to be inserted break condition is -0::10

Selected Element is : 10List after inserting an element 2 10 12 21 23 31
Element to be inserted break condition is -0::0

Selected Element is : 0
Fianl sorted list is as follows :
2 10 12 21 23 31




QUICK SORT

Quick sort treats an array as a list of elements. When sort begins it selects the list's middle
element as the list pivot.The Sort then divides the list into two sub-lists one with elements that are
less than the list pivot and a second lists with the elements greater than or equal to the list pivot.
The sort then recursively invoke itself with both lists. Each time when the sort is invoked ,it further
divides the elements into smaller sub-lists.

#include< iostream.h>
#include< conio.h>
#include< stdlib.h>
                                                   39

void quick_sort(int array[],int first, int last)
{
int temp,low, high, pivot;
low=first;
high=last;
pivot=array[(first+last)/2];
do{
while(array[low]< pivot)
low++;
while(array[high]>pivot)
high--;
if(low<=high)
{
temp=array[low];
array[low++]=array[high];
array[high--]=temp;
}
} while(low<=high);
if(first< high)
quick_sort(array,first,high);
if(low< last)
quick_sort(array,low,last);
}
void main(void)
{
clrscr();
int values[100],i;
cout<<"\n Unsorted list is as follows \n";
for(i=0;i<20;i++)
{
values[i]=rand() %100;
cout<<" "<< values[i];
}
quick_sort(values,0,19);
cout<<"\nSorted list as follows \n";
for(i=0;i<20;i++)
cout<<" "<< values[i];
}




The output of the program ::

Unsorted list is as follows
46 30 82 90 56 17 95 15 48 26 4 58 71 79 92 60 12 21 63 47

Sorted list as follows
4 12 15 17 21 26 30 46 47 48 56 58 60 63 71 79 82 90 92 95
                                             40

BUBBLE SORT (String)

Bubble sort for Sorting The Strings

#include< iostream.h>
#include< conio.h>
#include< string.h>
#include< stdlib.h>
void bubble_sort(char *array[],int);
void display(char *list[], int);
void bubble_sort(char * array[], int size)
{
char *temp;
int i, j;
for(i=0;i< size;i++)
for(j=0;j< size-i-1;j++)
if(strcmp(array[j],array[j+1])>0)
{
temp=(char*) new char[sizeof(array[j])];
temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}

void display(char *list[],int n)
{
int i;
for(i=0;i< n;i++)
{
cout<< endl<< list[i];
}
}
void main(void)
{
clrscr();
char *list[100]={"MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY" };
cout<<"\nInput list is as follows: \n";
display(list,6);
bubble_sort(list,6);
cout<<"\nSorted list is as follows: \n";
display(list,6);
}




The output of the program ::

Input list is as follows:

MONDAY
TUESDAY
                                                 41

WEDNESDAY
THURSDAY
FRIDAY
SATURDAY

Sorted list is as follows:

FRIDAY
MONDAY
SATURDAY
THURSDAY
TUESDAY
WEDNESDAY




SELECTION SORT

The Selection sort starts from first element and searches the entire list until it finds the minimum
value.The sort places the minimum value in the first place,selects the second element and
searches for the second smallest element.The process continues until the complete list is sorted.

#include< stdlib.h>
#include< iostream.h>
#include< conio.h>
#define NUM_ITEMS 10
void selectionSort(int numbers[], int array_size);

int numbers[NUM_ITEMS];

int main()
{
clrscr();
int i;
//fill array with random integers
for (i = 0; i < NUM_ITEMS; i++)
numbers[i] = rand() %100;
//display the unsorted items
cout<<"Unsorted elements are::\n";
for (i = 0; i < NUM_ITEMS; i++)
cout<<" "<< numbers[i];
cout<< endl;
//perform selection sort on array
selectionSort(numbers, NUM_ITEMS);
cout<<"Sorted elements are::\n";
for (i = 0; i < NUM_ITEMS; i++)
cout<<" "<< numbers[i];
}
                                                    42

void selectionSort(int numbers[], int array_size)
{
int i, j;
int min, temp;
for (i = 0; i < array_size-1; i++)
{
min = i;
for (j = i+1; j < array_size; j++)
{
if (numbers[j] < numbers[min])
min = j;
}
temp = numbers[i];
numbers[i] = numbers[min];
numbers[min] = temp;
}
}




The output of the program ::

Unsorted elements are::
46 30 82 90 56 17 95 15 48 26

Sorted elements are::
15 17 26 30 46 48 56 82 90 95




SHELL SORT

The shell sort is named after ite developer "Donald Shell". The sort technique works by comparing
the list elements that are seperated by a specific distance, i.e , a gap until the elements compared
with the current gap are inorder. Two then divides gap and the process continues.When the gap is
reached to 0 and no changes are possible,the list is sorted. The shell sort is a "diminishing
increment sort", better known as a "comb sort" to the unwashed programming masses. The
algorithm makes multiple passes through the list, and each time sorts a number of equally sized
sets using the insertion sort. The size of the set to be sorted gets larger with each pass through
the list, until the set consists of the entire list. (Note that as the size of the set increases, the
number of sets to be sorted decreases.) This sets the insertion sort up for an almost-best case run
each iteration with a complexity that approaches O(n).

#include < stdlib.h>
#include < stdio.h>
#include< conio.h>
#include < iostream.h>
#define NUM_ITEMS 15

void shellSort(int numbers[], int array_size);
int numbers[NUM_ITEMS];
                                              43

int main()
{
clrscr();
int i;
//fill array with random integers
for (i = 0; i < NUM_ITEMS; i++)
numbers[i] = rand() %100;
cout<<"\nUnsorted list is as follows\n";
for (i = 0; i < NUM_ITEMS; i++)
cout<<" "<< numbers[i];
//perform shell sort on array
shellSort(numbers, NUM_ITEMS);
cout<<"\n\nSorted list is as follows:\n";
for (i = 0; i < NUM_ITEMS; i++)
cout<<" "<< numbers[i];
}
void shellSort(int numbers[], int array_size)
{
int i, j, increment, temp;
increment = 3;
while (increment > 0)
{
for (i= 0;i < array_size; i++)
{
j = i;
temp = numbers[i];
while ((j >= increment) && (numbers[j-increment] > temp))
{
numbers[j] = numbers[j - increment];
j = j - increment;
}
numbers[j] = temp;
}
if (increment/2 != 0)
increment = increment/2;
else if (increment == 1)
increment = 0;
else
increment = 1;
}
}




The output of the program ::

Unsorted list is as follows
46 30 82 90 56 17 95 15 48 26 4 58 71 79 92

Sorted list is as follows:
4 15 17 26 30 46 48 56 58 71 79 82 90 92 95
                                                  44

MEREGE SORT

The merge sort splits the list to be sorted into two equal halves, and places them in separate
arrays. Each array is recursively sorted, and then merged back together to form the final sorted
list. Like most recursive sorts, the merge sort has an algorithmic complexity of O(n log n).
Elementary implementations of the merge sort make use of three arrays - one for each half of the
data set and one to store the sorted list in. The below algorithm merges the arrays in-place, so
only two arrays are required. There are non-recursive versions of the merge sort, but they don't
yield any significant performance enhancement over the recursive algorithm on most machines.

#include < stdlib.h>
#include< iostream.h>
#include< conio.h>
#define NUM_ITEMS 10

// Function definations merge sort which calls m_sort for sorting
void mergeSort(int numbers[], int temp[], int array_size);
// Function defination for m_sort which splits the lists
void m_sort(int numbers[], int temp[], int left, int right);

//function defination for merging andsorting the lists
void merge(int numbers[], int temp[], int left, int mid, int right);
int numbers[NUM_ITEMS];
int temp[NUM_ITEMS];

int main()
{
int i;
//fill array with random integers
for (i = 0; i < NUM_ITEMS; i++)
numbers[i] = rand() %100;
cout<<"\n\n Unsorted elements are as follows::\n\n";
for (i = 0; i < NUM_ITEMS; i++)
cout<<" "<< numbers[i];
//perform merge sort on array
mergeSort(numbers, temp, NUM_ITEMS);
cout<<"\n\nSorted list is as follows\n\n";
for (i = 0; i < NUM_ITEMS; i++)
cout<<" "<< numbers[i];
}

// function defination
void mergeSort(int numbers[], int temp[], int array_size)
{
m_sort(numbers, temp, 0, array_size - 1);
}
                                                  45

// function defination for splitting the list
void m_sort(int numbers[], int temp[], int left, int right)
{
int mid;
if (right > left)
{
mid = (right + left) / 2;
m_sort(numbers, temp, left, mid);
m_sort(numbers, temp, mid+1, right);
merge(numbers, temp, left, mid+1, right);
}
}

// Function defination for sorting the list
void merge(int numbers[], int temp[], int left, int mid, int right)
{
int i, left_end, num_elements, tmp_pos;
left_end = mid - 1;
tmp_pos = left;
num_elements = right - left + 1;
while ((left <= left_end) && (mid < = right))
{
if (numbers[left] < = numbers[mid])
{
temp[tmp_pos] = numbers[left];
tmp_pos = tmp_pos + 1;
left = left +1;
}
else
{
temp[tmp_pos] = numbers[mid];
tmp_pos = tmp_pos + 1;
mid = mid + 1;
}
}
while (left < = left_end)
{
temp[tmp_pos] = numbers[left];
left = left + 1;
tmp_pos = tmp_pos + 1;
}
while(mid < = right)
{
temp[tmp_pos] = numbers[mid];
mid = mid + 1;
tmp_pos = tmp_pos + 1;
}
                                                  46

for (i= 0;i <= num_elements; i++)
{
numbers[right] = temp[right];
right = right - 1;
}
}




The output of the program :

Unsorted elements are as follows::
46 30 82 90 56 17 95 15 48 26

Sorted list is as follows
15 17 26 30 46 48 56 82 90 95




MEREGE SORT

The merge sort splits the list to be sorted into two equal halves, and places them in separate
arrays. Each array is recursively sorted, and then merged back together to form the final sorted
list. Like most recursive sorts, the merge sort has an algorithmic complexity of O(n log n).
Elementary implementations of the merge sort make use of three arrays - one for each half of the
data set and one to store the sorted list in. The below algorithm merges the arrays in-place, so
only two arrays are required. There are non-recursive versions of the merge sort, but they don't
yield any significant performance enhancement over the recursive algorithm on most machines.

#include < stdlib.h>
#include< iostream.h>
#include< conio.h>
#define NUM_ITEMS 10

// Function definations merge sort which calls m_sort for sorting
void mergeSort(int numbers[], int temp[], int array_size);
// Function defination for m_sort which splits the lists
void m_sort(int numbers[], int temp[], int left, int right);

//function defination for merging andsorting the lists
void merge(int numbers[], int temp[], int left, int mid, int right);
int numbers[NUM_ITEMS];
int temp[NUM_ITEMS];

int main()
{
int i;
//fill array with random integers
for (i = 0; i < NUM_ITEMS; i++)
numbers[i] = rand() %100;
cout<<"\n\n Unsorted elements are as follows::\n\n";
for (i = 0; i < NUM_ITEMS; i++)
cout<<" "<< numbers[i];
                                                  47

//perform merge sort on array
mergeSort(numbers, temp, NUM_ITEMS);
cout<<"\n\nSorted list is as follows\n\n";
for (i = 0; i < NUM_ITEMS; i++)
cout<<" "<< numbers[i];
}

// function defination
void mergeSort(int numbers[], int temp[], int array_size)
{
m_sort(numbers, temp, 0, array_size - 1);
}

// function defination for splitting the list
void m_sort(int numbers[], int temp[], int left, int right)
{
int mid;
if (right > left)
{
mid = (right + left) / 2;
m_sort(numbers, temp, left, mid);
m_sort(numbers, temp, mid+1, right);
merge(numbers, temp, left, mid+1, right);
}
}

// Function defination for sorting the list
void merge(int numbers[], int temp[], int left, int mid, int right)
{
int i, left_end, num_elements, tmp_pos;
left_end = mid - 1;
tmp_pos = left;
num_elements = right - left + 1;
while ((left <= left_end) && (mid < = right))
{
if (numbers[left] < = numbers[mid])
{
temp[tmp_pos] = numbers[left];
tmp_pos = tmp_pos + 1;
left = left +1;
}
else
{
temp[tmp_pos] = numbers[mid];
tmp_pos = tmp_pos + 1;
mid = mid + 1;
}
}
                                                  48

while (left < = left_end)
{
temp[tmp_pos] = numbers[left];
left = left + 1;
tmp_pos = tmp_pos + 1;
}
while(mid < = right)
{
temp[tmp_pos] = numbers[mid];
mid = mid + 1;
tmp_pos = tmp_pos + 1;
}
for (i= 0;i <= num_elements; i++)
{
numbers[right] = temp[right];
right = right - 1;
}
}




The output of the program :

Unsorted elements are as follows::
46 30 82 90 56 17 95 15 48 26

Sorted list is as follows
15 17 26 30 46 48 56 82 90 95




HEAP SORT

A heap is an ordered balanced binary tree in which the value of the node at the root of any sub
tree is less than ar equal to the value of either of its children. The heap sort works as it name
suggests - it begins by building a heap out of the data set, and then removing the largest item and
placing it at the end of the sorted array. After removing the largest item, it reconstructs the heap
and removes the largest remaining item and places it in the next open position from the end of the
sorted array. This is repeated until there are no items left in the heap and the sorted array is full.
Elementary implementations require two arrays - one to hold the heap and the other to hold the
sorted elements.

#include < stdlib.h>
#include < iostream.h>
#include < conio.h>
#define NUM_ITEMS 10

// Funstion declaration for building the heap
void heapSort(int numbers[], int array_size);
// Function decalration for palcing the data at the end of the sorted list
void siftDown(int numbers[], int root, int bottom);
int numbers[NUM_ITEMS];
                                                   49

int main()
{
clrscr();
int i;
//fill array with random integers
for (i = 0; i < NUM_ITEMS; i++)
numbers[i] = rand() %100 ;
cout<<"\n\nUnsorted elements are as follows::\n\n";
for (i = 0; i < NUM_ITEMS; i++)
cout<<" "<< numbers[i];
//perform heap sort on array
heapSort(numbers, NUM_ITEMS);
cout<<"\n\nSorted elements are as follows::\n\n";
for (i = 0; i < NUM_ITEMS; i++)
cout<<" "<< numbers[i];
}

//Function defination for building heap
void heapSort(int numbers[], int array_size)
{
int i, temp;
for (i = (array_size / 2)-1; i > = 0; i--)
siftDown(numbers, i, array_size);
for (i = array_size-1; i > = 1; i--)
{
temp = numbers[0];
numbers[0] = numbers[i];
numbers[i] = temp;
siftDown(numbers, 0, i-1);
}
}

// Function defination for shifting the data at the end of the sorted list
void siftDown(int numbers[], int root, int bottom)
{
int done, maxChild, temp;
done = 0;
while ((root*2 < = bottom) && (!done))
{
if (root*2 == bottom)
maxChild = root * 2;
else if (numbers[root * 2] > numbers[root * 2 + 1])
maxChild = root * 2;
else
maxChild = root * 2 + 1;
if (numbers[root] < numbers[maxChild])
{
                                                 50

temp = numbers[root];
numbers[root] = numbers[maxChild];
numbers[maxChild] = temp;
root = maxChild;
}
else
done = 1;
}
}




The output of the program ::

Unsorted elements are as follows::
46 30 82 90 56 17 95 15 48 26

Sorted elements are as follows::
15 17 26 30 46 48 56 82 90 95




Template

The essence of template is the instantiation of functions and classes themselves at runtime
according according to the requirements. This means that the programmer does not have to know
the exact utilization context at the coding stage. The end user of the class can create user-defined
classes at the time of implementation. The concept of template can be applied to classes below

#include< iostream.h>
#include< conio.h>

// template declaration
template< class type>
//function defination
type max(type a, type b)
{
returna>b? a:b;
}
int main()
{
clrscr();
cout<< "max('A','a') : "<< max('A','a')<< endl;
cout<< "max(30,40) : "<< max(30,40)<< endl;
cout<< "max(45.67f,12.32f) : "<< max(45.67F,12.32F)<< endl;
return 0;
}




The output of the program ::

max('A','a') : a

max(30,40) : 40

max(45.67f,12.32f) : 45.669998
                                                51



# PRAGMA Implementation

With #pragma, Turbo C++ can define whatever directives it desires without interfering with other
compilers that support #pragma. With the pragma we can call the function on the strtup or on exit
of main it also provides many other features. If the compiler doesn't recognize < directive name>,
it ignores the #pragma directive without an error or warning message. < /FONT>

//function defination for before main() and after main()

void before_main(void);
void after_main(void);

#pragma startup before_main //Include pragma directive before main
#pragma exit after_main //Include pragma directive after main
#include< iostream.h>
#include< conio.h>
#include< dos.h>
// for sleep()function
main()
{
cout<<" Hello we are inside main() \n";
cout<<" Exiting main()\n";
sleep(3);
}

// function defination
void before_main()
{
struct date d;
clrscr();
getdate(&d); // Initializing date structure for getting date
cout<<" Welcome to our program dated for year: "<< d.da_year;//display year
cout<<"\n Now we are exiting main()\n";
sleep(3); //stops the execution for 3 seconds
}
// Function defination for after main()
void after_main()
{
cout<<"\nMain has been exited :";
cout<<"Bye";
sleep(2);
}// The end of main()

The output of the program ::

Welcome to our program dated for year: 2002
Now we are exiting main()
Hello we are inside main()
Exiting main()
Main has been exited :Bye
                                                   52

Linked Lists

Linked list is a very common data structure often used to store similar data in memory. While the
elements of an array occupy contiguous memory locations, those of a linked list are not constraind
to be stored in adjacent locations.The individual elements are stored somewhere in memory. The
order is maintained by explicit links between them.

#include< iostream.h>
#include< conio.h>
#include< alloc.h>
// A user defined variable using struct for linked list
struct node
{
int data;
struct node *link;
};
main()
{
int delnum;
struct node *p;
p=NULL;//empty linked list

//Function declaration for adding the nodes to linked list
void append(struct node **,int);

//Function declaration for counting the nodes in the linked list
int count(struct node*);
//Function declaration for the displaying the nodes
void display(struct node *);
//Function declaration for deleting the nodes from the linked list
void deletes(struct node **,int);

// Adding the values to list
append(&p,1);
append(&p,2);
append(&p,3);
append(&p,4);
append(&p,5);
append(&p,12);
clrscr();
//counting the nodes in the list
cout<<"No of elements in the linked list = "<< count(p);
//Displaying the nodes
display(p);
cout<<"\n\n Enter the Element to be deleted :: ";
cin>>delnum;
// Deleting the node
deletes(&p,delnum);
display(p);
}
                                                53

// Display the contents of the Linked list
void display(struct node *q)
{
cout<<"\n\n Elements are as follows:: ";
//Traverse the entire linked list
while(q!=NULL)
{
cout<< q->data<<"->";
q=q->link;
}
}
//count the number of nodes present in the linked list
count(struct node *q)
{
int c=0;
//traverse the entire linked list
while(q!=NULL)
{
q=q->link;
c++;
}
return c;
}
//Adding the node at the end of a linked list
void append(struct node **q,int num)
{
struct node *temp,*r;
temp=*q;
if(*q==NULL)//If the list is empty, create first node
{
temp=(node*)malloc(sizeof(struct node));
temp->data=num;
temp->link=NULL;
*q=temp;
}
else
{
temp=*q;
// Goto last node
while(temp->link!=NULL)
temp=temp->link;
// Add node at the end
r=(node*) malloc(sizeof(struct node));
r->data=num;
r->link=NULL;
temp->link=r;
}
}
                                                    54

// Deletes the specified node from the list
void deletes(struct node **q,int num)
{
struct node *old, *temp;
temp=*q;
while(temp!=NULL)
{
if(temp->data==num)
{
// If node to be deleted is the first node in the linked list
if(temp==*q)
{
*q=temp->link;
//free the memory occupied by the node
free(temp);
return;
}
//delete the intermediate node in the linked list
else
{
old->link=temp->link;
free(temp);
return;
}
}
// Traverse the linked list till the last node is reached
else
old=temp; // Old points to the previous node
temp=temp->link;// go to the next node
}
cout<<"\n Element not found ";
}




The output of the program ::

No of elements in the linked list = 6

Elements areasfollows::1->2->3->4->5->12->

Enter the Element to be deleted :: 2

Elementsareasfollows::1->3->4->5->12->




Working with Constructors

/* Following program shows how to use various constructor types within a class*/
// A constructor is a special member function which is called as soon as the object of a class is
created or allocated some memory. Following example will describe the no-argument constructor
(default constructor) and argument constructor
                                                55

#include <iostream.h> // Header file for stream input-output such as cout,cin
class example { // Let's declare a class
// Here are the public methods. We are creating three constructors here for this class
public:
// Following is an example of the no-argument (default) constructor
example(void)
{
        cout<<"example default constructor"<<endl;
}

// A single-argument (conversion) constructor
example(int x)
{
        cout<<"example one argument constructor("<<x<<")"<<endl;
        }

}; // Class declaration ended
void main()
{
example a; // Creating an object of class example. This will call the default constructor
example*ap=new example; // Creating and allocating memory for example pointer. This will call
the default constructor too
delete ap; // Releasing the memory for ap pointer

        exampleb(2); // Creating an object of class example again, but this time we are passing
        one argument to the object i.e. it will call one argument constructor
        example*bp=new example(2); // Creating a pointer to class example and allocating
        memory to it and also passing one argument to it. It wil also call the argument constructor
delete bp; // Releasing the memory for bp pointer

}

Output:

example default constructor
example default constructor
example one argument constructor(2)
example one argument constructor(2)



Calling Functions and Using Loops

// Following example shows you how to create menu-driven program in C++. You will also get to
learn about if..else loops, switch..case loops and calling functions.
// The program is a menu-driven example, where a function call is made each time user selects
something. The program will show you a menu for a health club and will let you know the charges
for the membership according to some rules
                                                 56

#include <iostream.h> // Stream input output header file such as cin, cout

// Function Prototypes, Function Declarations. These functions will be called as per the user's
choice in the program
void a(int); // A function declaration which takes an integer type argument
void c(int); // A function declaration which takes an integer type argument
void s(int); // A function declaration which takes an integer type argument

void main() // Main program starts here
{
int choice, months; // choice is to get the user's input and months variable will store the value of
months which we will ask from the user
do
{ // Show the loop until user choose to quit the program
                cout << "\n\t\tHealth Club Membership Menu\n\n";
                cout << "1. Standard Adult Membership\n";
                cout << "2. Child Membership\n";
                cout << "3. Senior Citizen Membership\n";
                cout << "4. Quit the Program\n\n";
                cout << "Enter your choice: ";
                cin >> choice; // Get the input from the keyboard
                if (choice > 0 && choice < 4) // if choice is from the menu and user wishes to join
                for some membership, then we will ask for the number of months. && is AND
                operator which tells that both the conditions should be true in this conditional
                statement
                {
                         cout << "For how many months? ";
                         cin >> months; // get the input from the user
                }
                switch (choice) // Let's see what the user has selected
                {
                         case 1: a(months); // If user has selected 1, its a standard adult
                         membership, so we will call a(int) method here by passing the number of
                         months in it
                                          break;
                         case 2: c(months); // If user has selected 1, its a standard adult
                         membership, so we will call a(int) method here by passing the number of
                         months in it
                                          break;
                         case 3: s(months); // If user has selected 1, its a standard adult
                         membership, so we will call a(int) method here by passing the number of
                         months in it
                                          break;
                         case 4: cout << "Quitting the program.\n";
                                 break;
                         /* Statements under default will be executed when the value of choice
                         variable is not there in any case statement above...*/
                         default:cout << "Wrong Choce. The valid choices are 1-4. ";
                                                   57

                                 cout << "Please Try again!!\n";
                }
} while (choice != 4);
}

/* Here is the definition of function a. It uses an integer type parameter, mon, which holds the
number of months the membership should be calculated for. */
void a(int mon)
{
cout << "The total charges are Rs. ";
cout << (mon * 40.0) << endl;
}

/* Here is the definition of function c. It uses an integer type parameter, mon, which holds the
number of months the membership should be calculated for. */
void c(int mon)
{
cout << "The total charges are Rs. ";
cout << (mon * 20.0) << endl;
}

/* Here is the definition of function s. It uses an integer type parameter, mon, which holds the
number of months the membership should be calculated for. */
void s(int mon)
{
cout << "The total charges are Rs. ";
cout << (mon * 30.0) << endl;
}

Default argument in Function and call by reference

Functions in C++ have the ability to define default values for arguments that are not passed when
the function call is made.The default argument are given only in the function prototype and should
not be repeated in the function defination.Similarly during call by reference the original values are
effected and any change in there passing value will effect original one .

#include< iostream.h>
#include< conio.h>
//function declaration for default arguments
void boxarea(int len=20,int breadth= 15);< /FONT>
//function declaration for call by reference
void callbox(int &len,int &breadth);
main()
{
clrscr();
inta=20,b=10;
boxarea(12,13);//function call with two argument
boxarea(14);//function call with one argument and one will be default argument
boxarea();// function call with default argument
callbox(a,b);//function call for call by reference, it will interchange the value of a and b
cout<<"valueof a::"<< a << endl ;
                                                    58

cout<<"valueof b::"<< b << endl;
}
//function defination for area of box
void boxarea(int len,int breadth)
{
int area=len*breadth;
cout<<"Area of the box is::"<< area<< endl;
}
//function defination for call by reference.
void callbox(int &t, int &b)
{
int temp;
temp=t;
t=b;
b=temp;
}




The output of the programe will be ::
Area of the box is ::156
Area of the box is ::210
Area of the box is ::300
value of a::10
value of b::20




Local Variable Having Same Name as Global Variable

// The following example shows you that when a local variable has the same name as a global
variable, the function only sees the local variable

#include <iostream.h> // Header file for stream input/output such as cin, cout

// Function prototypes, Function Declarations
void delhi();
voidnyork(void);

/* Here is one global variable c with value 10 */
int c = 10;

void main()
{
cout << "There are " << c << " cakes in main.\n"; // In this statement, as there is no local
variable named c, it will look for it in the global variable list and thus it will show the value 10
delhi(); // Calling delhi function
nyork(); // Calling nyork function
cout << "Back in main, there are " << c << " cakes.\n"; // Here again, it will look for the variable
name c in the local variable list and as there is no local variable with that name, it will use the
global variable and will display the value 10
}
                                                    59


/* Here is the definition of function delhi. The local variable in this function for variable c is set to
100. c is the local variable of delhi function */
void delhi()
{
int c = 100;< /FONT > // Local variable declared with same name as global variable
cout << "There are " << c << " cakes in Delhi.\n"; // In this statement, as there is one local
variable named c is declared, it will use the same and thus it will show the value 100. So, local
variable has overrided the global variable
}

/* Here is the definition of function nyork. The local variable in this function for variable c is set to
50. c is the local variable of delhi function */
void nyork()
{
int c = 50;< /FONT > // Local variable declared with same name as global variable
cout << "There are " << c << " cakes in New York.\n"; // In this statement, as there is one local
variable named c is declared, it will use the same and thus it will show the value 100. So, local
variable has overrided the global variable
}


Output:

There are 10 cakes in main.

There are 100 cakes in Delhi.

There are 50 cakes in New York.

Back in main, there are 10 cakes.




Functions with Default Arguments

// The following example demonstrates the usage of default function arguments.
#include <iostream.h> // Header file for stream input/output such as cin, cout
// Here is the function prototype with default arguments
void makeRect(int = 10, int = 1); // This function ha two arguments and both are default
arguments. This means that if the function is not called with any argument, the default value for
the first argument will be 10 and default value for the second argument will be 1. The function is
used to make a rectangle filled of asterisks. First argument is the number of columns to be filled
and second argument is the number of rows the rectangle will be made of
// Starting of main program
void main()
{
makeRect(); // Here, we are calling the function with no arguments. This means that the rectangle
will be of 10 columns filled of asterisks having 1 row, because these are the default values for both
cout << endl;
makeRect(5); // Here, we are calling the function with one argument. This means that the
rectangle will be of 5 columns filled of asterisks having 1 row, because when we pass one
argument to this function, this value will be set as the value of the first argument. The second
argument is still not there, and so the default value i.e. 1 will be taken
cout << endl;
                                                 60

makeRect(7, 3); // Here, we have passed both the values i.e. row and column values to the
function and so the default values will not be taken. The rectangle here will be filled with 7
columns and 3 rows of asterisks.
}
/* Here is the definition of function makeRect. The default argument for cols is 10 and for rows is
1. This function displays a rectangle made of asterisks. */
void makeRect(int cols, int rows)
{
// We will be using nested loop. The outer loop controls the rows and the inner loop controls the
columns.
for (int down = 0; down < rows; down++)
{
                 for (int across = 0; across < cols; across++)
                          cout << "*";
                 cout << endl;
}
}

Output:

**********

*****

*******
*******
*******


All About Loops

Following program is a tutorial to teach basics of loops in C++.

#include <iostream.h>             //Needed to use the 'cin' and 'cout' statements
void main()      // Main function, void means that it has no 'return value at the bottom. Program
execution starts here.
{        // main function includes all information, this marks the beginning of the function
int i;   //Declare the variable 'i' as an integer (whole number)
// We'll do while loops first
i = 0; // Set a value for 'i' before you use it
while (i < 10) // Do the statements until 'i' is = 10
{        // Contains the statements for the while statement
                 i = i + 1;       // Adds one to the value of i. The statement 'i++;' also
                 accomplishes the same
                 cout << i << endl;         // Show i on the screen then end the current line
}        //Loop doesn't leave until 'i' is > 10
cout << endl; //Add a blank line to seperate the data on the screen.
                                                61

/*i now equals 11. Your screen will show
1
2
3
4
5
6
7
8
9
10*/


                 //We will now make a 'do while' loop
do       //The upper end of the loop
{        //Once again the start of the loop
                 i += 1;         // Another way to add one to 'i'. It works with any number ex. 'i
                 += 20;' works also
                 cout << i << endl;       //Show 'i' then end the line.
}        //End of the coding inside of the loop
while (i < 20); //The statements deciding how many time to loop. It will print 11 - 20.

//NOTE: 'do while' loops use a ';' after the while statement
/*The screen now also shows the numbers 11- 20 like this
11
12
13
14
15
16
17
18
19
20
*/
cout << '\n'; //Add a blank line to seperate the data on the screen. 'cout << endl;' also works

/*For loops are the easiest loops to use. */
for (i = 21; i <= 30; i++)       //while i between 20 and 30 add one per loop
{        //Begin of the loop statements
                 //No i++ statement is needed, the loop does that automatically
                 cout << i << endl;       //Show 'i' then end the line
}        //End of the loop statements
cout << endl; //Add a line for extra space
                                                62

/* The screen now shows the other data but it also shows 21-30
21
22
23
24
25
26
27
28
29
30
                 */
}       // This ends 'void main'

Operator Overloading

Operator overloading is one of the most fascinating features of C++. By overloading
operatorslike+,*,-,<=,>=,etc. Operator overloading teaches a normal C++ operator to act on
user- defined operand. In our case the operator + and - are thought to operate on a user -defined
data type complex.A complex number consists of a real and an imaginary part. So by overloading
+ and - operator we can perform addition and subtraction on the variables of complex data types

#include< iostream.h>
#include< conio.h>
// A structure is defined for holding two variables
struct complex
{
double real,imag;
};
// Function declaration for returning complex variables
complex complex_set(double r, double i);
//Function declaration for printing the values
void complex_print(complex c);
// Overloading + operator for two complex variables.
complex operator +(complex c1,complex c2);
// Overloading - operator for two complex variables.
complex operator -(complex c1, complex c2);
void main()
{
clrscr();
complex a,b,c,d;
a=complex_set(1.0,1.0);
b=complex_set(2.0,2.0) ;
//call the overloaded operator +
c=a+b;
//call the overloaded operator -
d=b+c-a;
//Display the value of c
cout<< endl<< "c=";
complex_print(c);
                                                63

//Display the value of d
cout<< endl<< "d=";
complex_print(d);
}
//Function defination for returning complex variables
complex complex_set(double r,double i)
{
complex temp;
temp.real=r;
temp.imag=i;
return temp;
}
// Function defination for displaying the value.
void complex_print(complex t)
{
cout<<"("<< t.real<<","<<t.imag<<")";
}
// Defination for the Overloaded operator +
complex operator +(complex c1, complex c2)
{
complex temp;
temp.real=c1.real+c2.real;
temp.imag=c1.imag+c2.imag;
return temp;
}
// Defination for the Overloaded operator -
complex operator -(complex c1,complex c2)
{
complex temp;
temp.real=c1.real-c2.real;
temp.imag=c1.imag-c2.imag;
return temp;
}




The output of the programe will be ::
c=(3,3)
d=(4,4)




Returning a Reference

We can also return a reference from a function. When a function returns a reference, the function
call can exist in any context where a reference can exist, including on the receiving side of an
assignment, The result is the variable returned by the function is assigned the value on the right
hand side of the = sign.

#include< iostream.h>
#include< conio.h>
// Declared structure emp
                                                 64

struct emp
{
  char name[15];
  int age;
  float salery;
};
// Initialized two global variables e1 and e2 to some values
emp e1={"Raj",22,12000.00};
emp e2={"Vikas",21,15000.00};

main()
{
  // Function declaration which returns reference of emp type.
  emp &fun();
  // Function call is written on the left handside of the assignment operator
  fun()=e2;
  cout<< endl<< e1.name<< endl<< e1.age<< endl<< e1.salery;
}

// Function defination
emp &fun()
{
  cout<< endl<< e1.name<< endl<< e1.age<< endl<< e1.salery;
  return e1;
}



The output of the programe will be ::

Raj
22
12000
Vikas
21
15000




Operator overloaded for matrix Addition and Subtraction

The program opens with a structure that contains a two - dimensional array.It is necessary to
create this structure since after performing addition and subtraction the structure can be
conveniently returned and assigned to another structure variable. To keep the array size general
two consts MAXROW and MAXCOL have been used to indicate the number of rows and columns in
the matrix.

#include< iostream.h>
#include< conio.h>
#include< iomanip.h>
//header file for setw() //macro declaration in program MAXROW will be replaced by 3 and
MAXCOL also by 3
constintMAXROW=3,MAXCOL=3;
                                                 65

struct matrix
{
int arr[MAXROW][MAXCOL];
// Double dimensional array
};
matrix operator + (matrix a,matrix b);
//OPerator overloding
matrix operator - (matrix a,matrix b);

// function declaration for printing matrix void matprint(matrix p);

void main()
{
clrscr();
// Declaring matrix values
matrix a={ 1,2,3,
4,5,6,
7,8,9
};
matrix b={ 1,2,3,
4,5,6,
7,8,9
};

matrix c,d;
//overloaded operator will be called
c=a+b;
d=a-b;
//display the matrix
matprint(c);
matprint(d);
}
//overloaded operator defination for matrix addition

matrix operator +(matrix a, matrix b)
{
matrix c;
int i, j;
for(i=0;i< MAXROW;i++)
{
for(j=0;j< MAXCOL;j++)
c.arr[i][j]=a.arr[i][j]+b.arr[i][j];
}
return c;
}
                                                  66

//overloaded operator defination for matrix subtraction
matrix operator - (matrix a,matrix b)
{
matrix c;
int i,j;
for(i=0;i< MAXROW;i++)
{ for(j=0;j< MAXCOL;j++)
> c.arr[i][j]=a.arr[i][j]-b.arr[i][j];
}
return c;
}

//displaying matrix
void matprint(matrix p)
{
int i,j;
cout<< endl<< endl;
for(i=0;i< MAXROW;i++)
{ cout<< endl;
for(j=0;j< MAXCOL;j++)
cout<< setw(5)<< p.arr[i][j];
}
}




The output of the programe will be ::

2 4 6
8 10 12
14 16 18

0   0   0
0   0   0
0   0   0




The this Pointer

The member functions of every object have access to a pointer named this , which points to the
object itself. When we call a member function, it comes into existence with the value of this set to
the address of the object for which it was called.Using this pointer any member function can find
out the address of the object of which it is a member.

#include< iostream.h>
#include< conio.h>
class test
{
private:
int i;
public:
//The function definition for setting the value
                                             67

void setdata(int a)
{
i=a;
//one way to set data cout<< endl<<"My object's address is "<< this<< endl;
this->i=a;//another way to set data
}
// The function defination for displaying the value
void showdata()
{
cout<< i; //oneway to display data
cout<< endl<<"My object address is"<< this<< endl;
cout<<this->i;//another way display data
}
};
void main()
{
clrscr();
test t;
t.setdata(10);
t.showdata();
}




The output of the programe will be :

My object address is 0*0012FF7
10
My object address is 0*0012FF7
10

								
To top