Wednesday 30 January 2013

C++ Programming Operator Overloading

The meaning of operators are already defined and fixed for basic types like: int, float, double etc in C++ language. For example: If you want to add two integers then, + operator is used. But, for user-defined types(like: objects), you can define the meaning of operator, i.e, you can redefine the way that operator works. For example: If there are two objects of a class that contain string as its data member, you can use + operator to concatenate two strings. Suppose, instead of strings if that class contains integer data member, then you can use + operator to add integers. This feature in C++ programming that allows programmer to redefine the meaning of operator when they operate on class objects is known as operator overloading.

Why Operator overloading is used in C++ programming?

You can write any C++ program without the knowledge of operator overloading. But, operator operating are profoundly used by programmer to make a program clearer. For example: you can replace the code like: calculation = add(mult(a,b),div(a,b)); with calculation = a*b+a/b; which is more readable and easy to understand.

How to overload operators in C++ programming?

To overload a operator, a operator function is defined inside a class as:
Operator function inside class in C++ programming
The return type comes first which is followed by keyword operator, followed by operator sign,i.e., the operator you want to overload like: +, <, ++ etc. and finally the arguments is passed. Then, inside the body of you want perform the task you want when this operator function is called.
This operator function is called when, the operator(sign) operates on the object of that class class_name.

Example of operator overloading in C++ Programming


/* Simple example to demonstrate the working of operator overloading*/
#include <iostream>
using namespace std;
class temp
{
   private:
      int count;
   public:
       temp():count(5){  }
       void operator ++() { 
        count=count+1; 
       }
       void Display() { cout<<"Count: "<<count; }
};
int main()
{
    temp t;
    ++t;        /* operator function void operator ++() is called */
    t.Display();
    return 0;
}
Output

Count: 6
Explanation
In this program, a operator function void operator ++ () is defined(inside class temp), which is invoked when ++ operator operates on the object of type temp. This function will increase the value of count by 1.

Things to remember while using Operator overloading in C++ language

  1. Operator overloading cannot be used to change the way operator works on built-in types. Operator overloading only allows to redefine the meaning of operator for user-defined types.
  2. There are two operators assignment operator(=) and address operator(&) which does not need to be overloaded. Because these two operators are already overloaded in C++ library. For example: If obj1 and obj2 are two objects of same class then, you can use code obj1=obj2; without overloading = operator. This code will copy the contents object of obj2 to obj1. Similarly, you can use address operator directly without overloading which will return the address of object in memory.
  3. Operator overloading cannot change the precedence of operators and associativity of operators. But, if you want to change the order of evaluation, parenthesis should be used.
  4. Not all operators in C++ language can be overloaded. The operators that cannot be overloaded in C++ are ::(scope resolution), .(member selection), .*(member selection through pointer to function) and ?:(ternary operator).

Following best practice while using operator overloading

Operator overloading allows programmer to define operator the way they want but, there is a pitfall if operator overloading is not used properly. In above example, you have seen ++ operator operates on object to increase the value of count by 1. But, the value is increased by 1 because, we have used the code:
void operator ++() { 
        count=count+1; 
       }
If the code below was used instead, then the value of count will be decreased by 100 if ++ operates on object.
void operator ++() { 
        count=count-100; 
       }
But, it does not make any sense to decrease count by 100 when ++ operator is used. Instead of making code readable this makes code obscure and confusing. And, it is the job of the programmer to use operator overloading properly and in consistent manner.
Again, the above example is increase count by 1 is not complete. This program is incomplete in sense that, you cannot use code like:
t1=++t
It is because the return type of operator function is void. It is generally better to make operator work in similar way it works with basic types if possible.
Here, are the examples of operator overloading on different types of operators in C++ language in best possible ways:

This is not all in Operator Overloading... I will upload some more stuff on it very soon..

Sunday 27 January 2013

Passing Objects and Returning Object from Function in C++

In C++ programming, objects can be passed to function in similar way as variables and structures.

Procedure to Pass Object to Function

Passing Object to function in C++ Programming

Example to Pass Object to Function

C++ program to add two complex numbers by passing objects to function.

#include <iostream>
using namespace std;
class Complex
{
    private:
       int real;
       int imag;
    public:
       Complex(): real(0), imag(0) { }
       void Read()
        {
           cout<<"Enter real and imaginary number respectively:"<<endl;
           cin>>real>>imag;
        }
        void Add(Complex comp1,Complex comp2)
        {
            real=comp1.real+comp2.real; 
 
            /* Here, real represents the real data of object 
            c3 because this function is called using code c3.add(c1,c2); */
 
            imag=comp1.imag+comp2.imag; 
 
            /* Here, imag represents the imag data of obect c3 because
             this function is called using code c3.add(c1,c2); */
        }
        void Display()
        {
            cout<<"Sum="<<real<<"+"<<imag<<"i";
        }
};
int main()
{
    Complex c1,c2,c3;
    c1.Read();
    c2.Read();
    c3.Add(c1,c2);
    c3.Display();
    return 0;
}
Output

Enter real and imaginary number respectively:
12
3
Enter real and imaginary number respectively:
2
6
Sum=14+9i

Returning Object from Function

The syntax and procedure to return object is similar to that of returning structure from function.
Returning Object from function in C++ Programming

Example to Return Object from Function

This program is the modification of above program displays exactly same output as above. But, in this program, object is return from function to perform this task.

#include <iostream>
using namespace std;
class Complex
{
    private:
       int real;
       int imag;
    public:
       Complex(): real(0), imag(0) { }
       void Read()
        {
           cout<<"Enter real and imaginary number respectively:"<<endl;
           cin>>real>>imag;
        }
        Complex Add(Complex comp2)
        {
            Complex temp;
            temp.real=real+comp2.real;
            /* Here, real represents the real data of object 
            c1 because this function is called using code c1.Add(c2) */
            temp.imag=imag+comp2.imag;
            /* Here, imag represents the imag data of object 
            c1 because this function is called using code c1.Add(c2) */
            return temp;
        }
        void Display()
        {
            cout<<"Sum="<<real<<"+"<<imag<<"i";
        }
};
int main()
{
    Complex c1,c2,c3;
    c1.Read();
    c2.Read();
    c3=c1.Add(c2);
    c3.Display();
    return 0;
} 

Saturday 26 January 2013

Destructors in C++

In my last post, I have discussed about Constructors.
Today we will discuss about Destructors.
But before that look at Memory Management.

Memory Management

* Repeatedly creating objects will eat up memory, especially if the object stores vectors or arrays in  
   its private variables.
* Running out of memory may cause your program to crash.
* Sometimes if you run a program many times, it will start to crash.
* It would be nice to have a way to remove objects that we no longer need, so that we can free up memory

Automatic Self-Destruct

When we create a local variable for a function, the memory blocks it used are deallocated. This saves memory.
void fun () 
{
     double a; 
     int b[10];  
     string c;
}

* A
ll variables are destroyed when the program ends.  
* But dynamic arrays are not automatically destroyed. YOU control the memory blocks.
* So clear any dynamic memory when you are done with it.  
  Clean up after yourself!
 void fun() 
 {
       int a* = new int[10];
       delete[] a;
 }

* But what if our function creates a local variable that is a class?
 void fun() 
 {
       MyClass c;
 }

* If the class only uses primitive data types (int, double, char) and built-in classes (string, vector),
   then the compiler will figure out how to destroy it.
* If the class uses dynamic memory (pointers), then it will NOT be destroyed automatically.
* You should write a destructor for the class.

Destructors

* A class destructor frees up the memory taken up by the private variables of the class.
* The standard C++ convention is to call the destructor function:
  ~ClassName( );
* Even the built-in C++ classes follow this standard.
  string s = "Millenium Falcon";         //Let string be a class
  s.~string( );                      //Now s="" (blank)

  vector v(1000);              //Let vector is a class
  v.~vector( );  
              //Clears 1000 memory blocks.

Note that variables v and s still exist, they're just reset to blank.
 cout << s << v.size( );

 Example:
  A trivial class Test that uses dynamic memory. The default constructor creates a dynamic array
 with 100,000 memory blocks.
 class Test 
 {
      public:
           Test();
      private:
           int* p;
 };
 Test::Test() 
 {
      p = new int[100000];
  }

 * The test class has a dynamic array as a private variable. So we should define a destructor 
    ~Test();
* Otherwise every Test we create will continue to eat up memory. This could result in disastrous            situations. like
 void fun () 
{
        int main() 
        {
              Test t; 
              for (int i=0; i<10000; i++)
                    return; 
              fun();
        } return 0;
}

The destructor is actually quite easy.
Test::~Test() 
{
        delete[] ; //Deletes all blocks in array
}

Automatic Self-Destruct
* When a function ends, we don't want its local variables using up memory.
* Primitive data types (int, char, double) are automatically deleted at the end of a routine.
* If a class is equipped with a destructor ~ClassName(); , the object is destroyed automatically when    it goes out of scope, like at the end of a function.
void my_fun (vector v1) 
{
      vector v2 = v1;
      int x = 3;
      return;
 }

* Note v1 is passed by value, so a local copy is created just for the function. The second vector v2 is    a local variable.
* Both v1 and v2 are automatically destroyed when the function ends if there is a  
 ~vector( );(And there is!)
* Destructors also called at end of main routine. This is why it's important to call destructor.
   ~class_name();

This is about destructors...

Thursday 24 January 2013

Understanding Copy Constructor

Copy Constructor

To create an object from an existing object requires a special type of constructor, called a copy constructor. It allocates memory but copies the POD (Plain Old Data) values from another object of the same class. It has one parameter, a reference to an existing object.
Like a default constructor, one is supplied by the compiler if there is a need for one and you haven't supplied it. If the object being copied is POD then no problems, i.e. no references, virtual functions or other complexities which affects how the data is stored in the object.
E.g. a pointer to non-const data owned by the object will be cloned and when the original object is destroyed it will release ownership of the pointer. So will destroying the new object. Freeing an object twice is a bad thing that can lead to unexpected crashes. So if you have non POD in your object then you must write a copy constructor and take care of the copying. For POD you can let the compiler do the hard work!
This example of a class containing POD shows a copy constructor being used.


 #include <iostream>
 
 using namespace std;
 
 struct example 
 {
     int rd; 
     example(example & ref) 
     {
         cout << "Copy Constructor called" << endl;
         rd = ref.rd;
     }
 
     example() : rd(0) 
     {
     }
 };
 
 int main() 
 {
     example s;
     s.rd =9;
     example s2=s;
     cout << s2.rd << endl;
     return 0;
 }
 

The previous page used a struct instead of a class. The two are identical except members in a struct have public access by default whereas class members are private by default.


 #include <iostream>
 #include <string>
 
 using namespace std;
 
 class demo 
 {
 
       int pd;
       string id;
    public:
       demo(demo & ref) 
       {
           cout << "Copy Constructor called" << endl;
           this->pd = ref.pd ;
           this->id = "Copy Constructed";
       }
 
       demo(string name) 
       {
           pd = 1;
           id=name;
           cout << "Constructor for " << id << endl;
       };
 
       ~demo() 
       {
           cout << "Destructor called "<< endl;
       }
 };
 
 int main() 
 {
   demo s("First");
   demo s2=s; //copy constructor called
   return 0;
 }
 
This example shows a class SomeData containing an int member pd. A copy constructor is provided to create a new instance of this pointer and then copy the original value into it. The id  is provided by the normal constructor but is just set to a nominal value in the copy constructor.
As we have allocated memory in the various constructors, it is vital that the memory is released when the object is destroyed so don't forget the destructor in that case.

Wednesday 23 January 2013

Constructors in C++

C++ Constructor

Constructors are the special type of member function that initializes the object automatically when it is created. Compiler identifies that the given member function is a constructor by its name and return type. Constructor has same name as that of class and it does not have any return type.

Constructors are Basically of 3 types:-
1. Default Constructor: Constructor which does not take any arguments. And used to Initialize object data members with default values given by the programmer (say 0).
Syntax:
       class_name object_name; 
2. Parametrized Constructor: Constructors which takes arguments that can be helpful in initializing data members of class with these arguments..
Syntax:
       class_name object_name(argument1,argument2, ...); 
3. Copy Constructor: Constructors which are used to initialize object with the another object of same class. It Uses Reference Variables.
Syntax:
       class_name object_name(object);
 Note:
1. if a class contains parametrized constructor then its a mandatory to have a default constructor also.
2. copy constructor is need not be defined in class because it is already built when class is created. But it is a good programming practice to introduce copy constructor while making a class.
3. if default constructor is not defined in class then compiler itself provide a default constructor which initializes the data members with garbage value.

From the examples you will be more comfortable with Constructors.
..... ... .....   
class temporary
{
       private: 
          int x;
          float y;
       public:
          temporary(): x(5), y(5.5)        /* default Constructor  */
          {  
                     /* Body of constructor */
          }
          /* Remaining Body of Class*/ 
}
int main()
{
        temporary t1;
        .... ... ....
        return 0;
}            
Working of Constructor
In the above pseudo code, temporary() is a constructor. When the object of class temporary is created, constructor is called automatically and x is initialized to 5 and y is initialized to 5.5 automatically.
You can also initialize data member inside the constructor's function body as below. But, this method is not preferred.
temporary(){
   x=5;
   y=5.5;
}
/* This method is not preferred. */

Use of Constructor in C++

Suppose you are working on 100's of objects and the default value of a data member is 0. Initializing all objects manually will be very tedious. Instead, you can define a constructor which initializes that data member to 0. Then all you have to do is define object and constructor will initialize object automatically. These types of situation arises frequently while handling array of objects. Also, if you want to execute some codes immediately after object is created, you can place that code inside the body of constructor.
Ex: if u create a class for student, then the attributes can be name,roll no, marks, percentage, DOB etc. and if you created a physical instance of this class (i.e object) it will use garbage value unless it gets initialized. 

Constructor Example

/*Source Code to demonstrate the working of constructor in C++ Programming */
/* This program calculates the area of a rectangle and  displays it. */ 
 
#include <iostream>
using namespace std;
class Area
{
    private:
       int length;
       int breadth;

    public:
       Area(): length(5), breadth(2)  /* default Constructor */
       { 
       } 
       void GetLength()  
       { 
           cout<<"Enter length and breadth respectively: "; 
           cin>>length>>breadth;  
       }
       int AreaCalculation()  
       {   
           return (length*breadth);   
       }
       void DisplayArea(int temp)
       {
           cout<<"Area: "<<temp;
       }
};
int main()
{
    Area A1,A2(5,10);
    int temp;
    A1.GetLength();
    temp=A1.AreaCalculation();
    A1.DisplayArea(temp);
    cout<<endl<<"Default Area when value is not taken from user"<<endl;
    temp=A2.AreaCalculation();
    A2.DisplayArea(temp);
    return 0;
}

Explanation
In this program, a class of name Area is created to calculate the area of a rectangle. There are two data members length and breadth. A constructor is defined which initializes length to 5 and breadth to 2. And, we have three additional member functions GetLength(), AreaCalculation() and DisplayArea() to get length from user, calculate the area and display the area respectively.
When, objects A1 and A2 are created then, the length and breadth of both objects are initialized to 5 and 2 respectively because of the constructor. Then the member function GetLength() is invoked which takes the value of length and breadth from user for object A1. Then, the area for the object A1 is calculated and stored in variable temp by calling AreaCalculation() function. And finally, the area of object A1 is displayed. For object A2, no data is asked from the user. So, the value of length will be 5 and breadth will be 2. Then, the area for A2 is calculated and displayed which is 10.

Output
Enter length and breadth respectively: 6
7
Area: 42
Default Area when value is not taken from user
Area: 10

Constructor Overloading

Constructor can be overloaded in similar way as function overloading. Overloaded constructors have same name(name of the class) but different number of argument passed. Depending upon the number and type of argument passed, specific constructor is called. Since, constructor are called when object is created. Argument to the constructor also should be passed while creating object. Here is the modification of above program to demonstrate the working of overloaded constructors.
 
/* Source Code to demonstrate the working of overloaded constructors */
#include <iostream>
using namespace std;
class Area
{
    private:
       int length;
       int breadth;

    public:
       Area(): length(5), breadth(2)   // Constructor without no argument
       { }        
       Area(int l, int b): length(l), breadth(b)  // Constructor with two argument
       { }  
       void GetLength()
       {
           cout<<"Enter length and breadth respectively: ";
           cin>>length>>breadth;
       }
       int AreaCalculation()  
       { 
           return (length*breadth); 
       }
       void DisplayArea(int temp)
       {
           cout<<"Area: "<<temp<<endl;
       }
};
int main()
{
    Area A1,A2(2,1);
    int temp;
    cout<<"Default Area when no argument is passed."<<endl;
    temp=A1.AreaCalculation();
    A1.DisplayArea(temp);
    cout<<"Area when (2,1) is passed as arguement."<<endl;
    temp=A2.AreaCalculation();
    A2.DisplayArea(temp);
    return 0;
}
Explanation of Overloaded Constructors
For object A1, no argument is passed. Thus, the constructor with no argument is invoked which initializes length to 5 and breadth to 2. Hence, the area of object A1 will be 10. For object A2, 2 and 1 is passed as argument. Thus, the constructor with two argument is called which initializes length to l(2 in this case) and breadth to b(1 in this case.). Hence the area of object A2 will be 2.
Output
Default Area when no argument is passed.
Area: 10
Area when (2,1) is passed as arguement.
Area: 2

Default Copy Constructor

A object can be initialized with another object of same type. Let us suppose the above program. If you want to initialize a object A3 so that it contains same value as A2. Then, this can be performed as:
....
int main() {
   Area A1,A2(2,1);
   Area A3(A2);     /* Copies the content of A2 to A3 */
     OR, 
   Area A3=A2;      /* Copies the content of A2 to A3 */  
}
You might think, you may need some constructor to perform this task. But, no additional constructor is needed. It is because this constructor is already built into all classes.

if you have any Doubt then Leave comment. Your doubt will be resolved in next 24 hours.

Tuesday 22 January 2013

Object and Class in C++

C++ Class

A class is the collection of related data and function under a single name. A C++ program can have any number of classes. When related data and functions are kept under a class, it helps to visualize the complex problem efficiently and effectively.


Datas and function inside class in C++

A Class is a blueprint for objects
When a class is defined, no memory is allocated. You can imagine like a datatype.
int var;
The above code specifies var is a variable of type integer; int is used for specifying variable var is of integer type. Similarly, class are also just the specification for objects and object bears the property of that class.

 

Defining the Class in C++

Class is defined in C++ programming using keyword class followed by identifier(name of class). Body of class is defined inside curly brackets an terminated by semicolon at the end in similar way as structure.
class class_name
{
   // some data
   // some functions
};

Example of Class in C++

class temp
{
      private:
         int data1;
         float data2;  
      public:  
         void func1()
         {
              data1=2; 
         } 
         float func2()
         { 
              data2=3.5;
              retrun data;
         }
};
 
Explanation for above program:
As mentioned, definition of class starts with keyword class followed by name of class(temp) in this case. The body of that class is inside the curly brackets and terminated by semicolon at the end. There are two keywords: private and public mentioned inside the body of class.

 

Keywords: private and public

Keyword private makes data and functions private and keyword public makes data and functions public. Private data and functions are accessible inside that class only whereas, public data and functions are accessible both inside and outside the class. This feature in OOP is known as data hiding. If programmer mistakenly tries to access private data outside the class, compiler shows error which prevents the misuse of data. Generally, data are private and functions are public.

C++ Objects

When class is defined, only specification for the object is defined. Object has same relationship to class as variable has with the data type. Objects can be defined in similary way as structure is defined.

Syntax to Define Object in C++

class_name variable name; 
For the above defined class temp, objects for that class can be defined as:
temp obj1,obj2;
Here, two objects (obj1 and obj2) of temp class are defined.

Data member and Member functions

The data within the class is known as data member. The function defined within the class is known as member function. These two technical terms are frequently used in explaining OOP. In the above class temp, data1 and data2 are data members and func1() and func2() are member functions.

Accessing Data Members and Member functions

Data members and member functions can be accessed in similar way the member of structure is accessed using member operator(.). For the class and object defined above, func1() for object obj2 can be called using code:
obj2.func1();
Similarly, the data member can be accessed as:
object_name.data_member;
Note: You cannot access the data member of the above class temp because both data members are private so it cannot be accessed outside that class.

 

Illustration for above theory of object and Class in C++ 

 /* Program to illustrate working of Objects and Class in C++ Programming */ #include <iostream> using namespace std; class temp { private: int data1; float data2; public: void int_data(int d)

       {
          data1=d;
          cout<<"Number: "<<data1;
       }
       float float_data()
       {
           cout<<"\nEnter data: ";
           cin>>data2;
           return data2;
       }
};
 
int main()
{
      temp obj1, obj2;
      obj1.int_data(12);
      cout<<"You entered "<<obj2.float_data();
      return 0;
}
 
Output: 
Number: 12
Enter data: 12.43
You entered: 12.43

Explanation of Program

In this program, two data members data1 and data2 and two member function int_data() and float_data() are defined under temp class. Two objects obj1 and obj2 of that class are declared. Function int_data() for the obj1 is executed using code obj1.int_data(12);, which sets 12 to the data1 of object obj1. Then, function float_data() for the object obj2 is executed which takes data from user; stores it in data2 of obj2 and returns it to the calling function.
Note: In this program, data2 for object obj1 and data1 for object obj2 is not used and contains garbage value.


Data member according to Object in C++.

Defining Member Function Outside the Class
A large program may contain many member functions. For the clarity of the code, member functions can be defined outside the class. To do so, member function should be declared inside the class(function prototype should be inside the class). Then, the function definition can be defined using scope resolution operator ::. Learn more about defining member function outside the class.

Saturday 19 January 2013

Preprocessor Directives in C

Preprocessor extends the power of C programming language. Line that begin with # are called preprocessing directives.

Use of #include

Let us consider very common preprocessing directive as below:
#include <stdio.h>
Here, "stdio.h" is a header file and the preprocessor replace the above line with the contents of header file.

Use of #define

Preprocessing directive #define has two forms. The first form is:
#define identifier token_string
token_string part is optional but, are used almost every time in program.

Example of #define

#define c 299792458 /*speed of light in m/s */
The token string in above line 2299792458 is replaced in every occurance of symbolic constant c.
C Program to find area of a cricle. [Area of circle=πr2]
#include <stdio.h>
#define PI 3.1415
int main(){
    int radius;
    float area;
    printf("Enter the radius: ");
    scanf("%d",&radius);
    area=PI*radius*radius;
    printf("Area=%.2f",area);
    return 0;
}
Output
Enter the radius: 3 
Area=28.27

Syntactic Sugar

Syntactic sugar is the alteration of programming syntax according to the will of programmer. For example:
#define LT <
Every time the program encounters LT, it will be replaced by <.
Second form of preprocessing directive with #define is:

Macros with argument

Preprocessing directive #define can be used to write macro definitions with parameters as well in the form below:
#define identifier(identifier 1,.....identifier n) token_string
Again, the token string is optional but, are used in almost every case. Let us consider an example of macro definition with argument.
#define area(r) (3.1415*r*r)
Here, the argument passed is r. Every time the program encounters area(argument), it will be replace by (3.1415*argument*argument). Suppose, we passed (r1+5) as argument then, it expands as below:
area(r1+5) expands to (3.1415*(r1+5)(r1+5))
C Program to find area of a circle, passing arguments to macros. [Area of circle=πr2]
#include <stdio.h>
#define PI 3.1415
#define area(r) (PI*r*r)
int main(){
    int radius;
    float area;
    printf("Enter the radius: ");
    scanf("%d",&radius);
    area=area(radius);
    printf("Area=%.2f",area);
    return 0;
}

Predefined Macros in C language

Predefined macro Value
__DATE__ String containing the current date
__FILE__ String containing the file name
__LINE__ Integer representing the current line number
__STDC__ If follows ANSI standard C, then value is a nonzero integer
__TIME__ String containing the current date.

How to use predefined Macros?

C Program to find the current time
#include <stdio.h>
int main(){
   printf("Current time: %s",__TIME__);   //calculate the current time
}
Output
Current time: 19:54:39

Friday 18 January 2013

Enumeration Datatype in C

Enumeration type allows programmer to define their own data type . Keyword enum is used to defined enumerated data type.

enum type_name{ value1, value2,...,valueN };
 
Here, type_name is the name of enumerated data type or tag. And value1, value2,....,valueN are values of type type_name.

By default, value1 will be equal to 0, value2 will be 1 and so on but, the programmer can change the default value as below:

enum cards{
    club=0;
    diamonds=10;
    hearts=20;
    spades=3;
};

Declaration of enumerated variable

Above code defines the type of the data but, no any variable is created. Variable of type enum can be created as:

enum bool{
    false;
    true;
};
enum bool check;
 
Here, a variable check is declared which is of type enum bool.

Example of enumerated type

#include <stdio.h>
enum week 
{
 sunday, monday, tuesday, wednesday, thursday, friday, saturday 
};
 
int main()
{
    enum week today;
    today=wednesday;
    printf("%d day",today+1);
    return 0;
} 
 
Output
4 day
 
 
You can write any program in C language without the help of enumerations but, enumerations helps in writing clear codes and simplify programming.
 

Pascals Triangle

#include<stdio.h>

int main()
{
    int i,j,k,n,b;
    printf("Enter the number of rows= ");
    scanf("%d",&n);

    for(i=0;i<n;i++)
    {
       b=1;
       for(k=0;k<=n-i;k++)
        printf(" ");
       for(j=0;j<=i;j++)
          {
        if(i==0 || j==0)
            printf("1");
        else
              { b=b*(i-j+1)/j;
            printf("%3d",b);

              }
          }
     printf("\n\n");
       }
return 0;
}

Wednesday 16 January 2013

Expansion of e^x

#include<stdio.h>

int main()
{
  float x,term,sum;
  int cnt,n;
  printf("\t\t\t Expansion and sum of e^x\n\n");
  printf("Enter the value of x= ");
  scanf("%f",&x);
  printf("Enter the Power of x= ");
  scanf("%d",&n);
  printf("\nExpansion of %0.0f^%d is= ",x,n);
  for(cnt=1,term=1,sum=0;cnt<=n;cnt++)
    {
      if(cnt==1)
        printf("1");
      else
       {    sum=sum+term;
        term=term*x/cnt;
        printf("+ (%0.0f^%d)/%d!",x,cnt-1,cnt-1);
       }
    }
  printf("\nSum of the series is= %0.3f",sum);
return 0;
}

Wednesday 9 January 2013

Search substring in a String

#include<stdio.h>
#include<conio.h>
int main()
{
    char s1[20],s2[10]; int i,j,flag;
    printf("Search a string in another string..\n\n");
    printf("Enter the main string: ");
    gets(s1);
    printf("Enter the sub string: ");
    gets(s2);

    i=j=flag=0;
    while(s1[i]!=0)
    {
        if(s1[i]==s2[j])
        {
            while(s2[j]!=0 && s1[i+j]==s2[j])
            {
                j++;
            }
            if(s2[j]==0)
            {
                flag=1;
                break;
            }
            else
                j=0;
        }
     i++;
    }
    if(flag==1)
        printf("Found at no %d",i+1);
    else
        printf("Not found");
    return 0;
}

Wednesday 2 January 2013

Mini Scientific Calculator

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


int main()
{
    int n1,n2,opt,cnt;
    float ang,term,sum,p,r,t,si,ci,a;
    printf("A multifunction calculator\n\n");
do
   {
      clrscr();
      printf("\n\n\t\t     *******C A L C U L A T O R******\n");
      printf("\t\t\t__________________________\n\n");
      printf("\t\t\t1).  Addition\n");
      printf("\t\t\t2).  Subtraction\n");
      printf("\t\t\t3).  Multiplication\n");
      printf("\t\t\t4).  Division\n");
      printf("\t\t\t5).  Mod\n");
      printf("\t\t\t6).  Power\n");
      printf("\t\t\t7).  Square\n");
      printf("\t\t\t8).  Square Root\n");
      printf("\t\t\t9).  sin\n");
      printf("\t\t\t10). cos\n");
      printf("\t\t\t11). e^x\n");
      printf("\t\t\t12). Simple Interest\n");
      printf("\t\t\t13). Compound Interest\n");
      printf("\t\t\t14). Exit\n");
      printf("\t\t\t__________________________\n\n");
      printf("\t\t\tEnter your choice= ");
      scanf("%d",&opt);
      printf("\n");
    switch(opt)
    {
      case 1:
        printf("\t\t\tEnter the 1st number= ");
        scanf("%d",&n1);
        printf("\t\t\tEnter the 2nd number= ");
        scanf("%d",&n2);
        printf("\t\t\tTotal= %d",n1+n2);
        break;

      case 2:
        printf("\t\t\tEnter the 1st number= ");
        scanf("%d",&n1);
        printf("\t\t\tEnter the 2nd number= ");
        scanf("%d",&n2);
        printf("\t\t\tDifference= %d",n1-n2);
        break;

      case 3:
        printf("\t\t\tEnter the 1st number= ");
        scanf("%d",&n1);
        printf("\t\t\tEnter the 2nd number= ");
        scanf("%d",&n2);
        printf("\t\t\tMultiplication= %d",n1*n2);
        break;

      case 4:
        printf("\t\t\tEnter the 1st number= ");
        scanf("%d",&n1);
        printf("\t\t\tEnter the 2nd number= ");
        scanf("%d",&n2);
            if(n2==0)
            printf("\t\t\tERROR!! div by 0");
            else
            printf("\t\t\tDivison= %0.2f",(float)n1/n2);//type casting
        break;

      case 5:
        printf("\t\t\tEnter the 1st number= ");
        scanf("%d",&n1);
        printf("\t\t\tEnter the 2nd number= ");
        scanf("%d",&n2);
            if(n2==0)
            printf("\t\t\tERROR!! div by 0");
            else
            printf("\t\t\tMod= %d",n1%n2);
        break;

      case 6:
        printf("\t\t\tEnter the Base number= ");
        scanf("%d",&n1);
        printf("\t\t\tEnter the power number= ");
        scanf("%d",&n2);
        printf("\t\t\tPower= %ld",(long)pow(n1,n2));
        break;

      case 7:
        printf("\t\t\tEnter the no.= ");
        scanf("%d",&n1);
        printf("\t\t\tSquare= %ld",(long)n1*n1);
        break;

      case 8:
        printf("\t\t\tEnter the no.= ");
        scanf("%d",&n1);
        printf("\t\t\tSquare= %0.2f",(float)sqrt(n1));
        break;

      case 9:
        printf("\t\t\tEnter the angle of sin");
        scanf("%d",&n1);
        printf("\t\t\tHow many time to run :");
        scanf("%d",&n2);
        ang=3.142*n1/180;
        for(cnt=1,term=ang,sum=0;cnt<=2*n2-1;cnt+=2)
          {
            sum=sum+term;
            term=-term*ang*ang/((cnt+1)*(cnt+2));
          }
        printf("\t\t\tsin%d=%f",n1,sum);
        break;

      case 10:
        printf("\t\t\tEnter the angle of cos");
        scanf("%d",&n1);
        printf("\t\t\tHow many time to run :");
        scanf("%d",&n2);
        ang=3.142*n1/180;
        for(cnt=0,term=ang,sum=0;cnt<2*n2-1;cnt+=2)
          {
            sum=sum+term;
            term=-term*ang*ang/((cnt+1)*(cnt+2));
          }
        printf("\t\t\tcos%d=%f",n1,sum);
        break;

      case 11:
        printf("\t\t\tEnter the value of x= ");
        scanf("%d",&n1);
        printf("\t\t\tEnter the Power of x= ");
        scanf("%d",&n2);

        for(cnt=1,term=1,sum=0;cnt<=n2;cnt++)
            {
             if(cnt==1)
                printf("1");
             else
               {    sum=sum+term;
                term=term*n1/cnt;
                }
             }
        printf("\t\t\tSum of the series is= %0.3f",sum);
        break;

      case 12:
        printf("\t\t\tEnter Principle Amount:");
        scanf("%f",&p);
        printf("\t\t\tEnter Rate of Interest:");
        scanf("%f",&r);
        printf("\t\t\tEnter time in years:");
        scanf("%f",&t);
        si=p*r*t/100;
        printf("\t\t\tThe Simple Interest is Rs:%0.2f \n",si);
        break;

      case 13:
        printf("\t\t\tEnter Principle Amount:");
        scanf("%f",&p);
        printf("\t\t\tEnter Rate of Interest:");
        scanf("%f",&r);
        printf("\t\t\tEnter time in years:");
        scanf("%f",&t);
        r=r*0.01;
        a=p*pow(1+r,t);
        ci=a-p;
        printf("\t\t\tThe Compound Interest is Rs.%0.2f",ci);
        break;

      case 14:
        printf("\t\t\t\t\tBye!");
        break;

      default:
        printf("\t\t\t\INVALID CHOICE");
        break;
    }
   } while(opt!=14);
}