Copyright © Programs ++
Design by Dzignine
Wednesday, 22 August 2012

Basic OOP program

Object Oriented Programming or OOP is an approach to programming(in general) that is based on the view of treating each entity or element as an object, in such a way that each object is unaware of the existence of other objects. Before going further, let me lay out some basic details for you.

CLASS -  Many of you must have the definition of class as : "a class is the collection of data members of same or different type, grouped under a common name". Well this is actually a very trivial definition of class. A class serves as a blueprint for building something. Simply put, it is a layout that describes where everything should be put together. In programming
terminology, a class is a way of binding the data describing an entity and its associated functions together.

Now i can go on and on, about classes and object, why the use of classes, data abstraction and so on, but all that you can find in any textbook. Let us jump to the practical implementation of OOP.

The article follows a program that demonstrates the use of classes and objects. Before i get into the nitty gritty of it all, please understand that you need to focus on the concept , not the
technical details. The "TECH DETAILS" will come with time and practice. Focus must be on understanding the concept. So let's begin :

The following program creates a class "MarkSheet" with a single member variable "marks" of type int(a.k.a integer). Now the class also has two PUBLIC member functions, a setter function and a corresponding getter function. Getter and Setter functions are not some SPECIAL functions, they are just named that way, sort of a trend. The job of a "getter" function is to return
the value of a variable of the class and the job of a "setter" function is to SET the value of a variable of the class.

For e.g : here is a demo setter function

void setDAY(int x) // sets the value of 'day' with the value contained by 'x'
{
     day = x;
}

Similarly, e.g : here is a demo getter function

int getDay() // 'gets' or returns the value of the variable 'day'
{
     return day;
}

The class has the following setter and getter functions :
1 - setMarks() // sets the marks of the student
2 - getMarks() // gets or returns the marks of the student

In the main() function, two objects,name objA and objB are declared that represent object of student A and B respectively. The program then prompts the user to enter the values
of the marks of students A and B. The marks are set by using the setMarks() setter function. After that, the marks are displayed by calling the getMarks() getter function.

Note : Please do not get into the details of using 'this'. Just understand that 'this' acts as a pointer to the current object. To get more details on the use of 'this' in OOPS, please refer
the FAQ.

// C++ program to demonstrate the concept of Object Oriented Programming Structure(OOPS)

#include<iostream>

using namespace std;

class MarkSheet
{
     int marks;

     public :

     void setMarks(int marks) // setter function
     {
          this->marks = marks;
     }

     int getMarks() // getter function
     {
          return this->marks;
     }

}; // end of class MarkSheet

int main()
{
     MarkSheet objA; // object A of class MarkSheet
     MarkSheet objB; // object B of class MarkSheet
     int temp;

     // propmts the user to enter the marks of student A
     cout<<" Enter the marks of student A : ";
     cin>>temp;
     objA.setMarks(temp); // uses the setter function to set the marks of student A

     // propmts user to enter the marks of student B
     cout<<" Enter the marks of student B : ";
     cin>>temp;
     objB.setMarks(temp); // uses the setter function to set the marks of student B

     cout<<"\n ---------- Marks of A and B are as follows ------------ \n";
     cout<<" Marks of student A : "<<objA.getMarks(); // displays the marks of student A
     cout<<"\n Marks of student B : "<<objB.getMarks(); // displays the marks of student B
     return 0;
}// end of main


Please do comment if you don't understand any part or want to know more or just want to say thanks. I love programming and love to teach my friends. Your suggestions and appreciation will make this blog much better.

------ OUTPUT ----- 


Tuesday, 22 May 2012

Use of string iterator in C++

The following program computes the length of the string using the string iterator

// Program to demonstrate the use of string iterator
#include <iostream>
#include <string>

int main()
{
     using namespace std;
     int counter=0;
     string str("welcome to programsplusplus");
     // declares the string iterator
     string::iterator it;
     for (it=str.begin(); it<str.end(); it++)
     {
          // displays each character that the iterator points to
          counter++;
          cout<<" "<<*it;
     }
     cout<<"\n"<<"Total length of the string : "<<counter;

     return 0;
} // end of main
------OUTPUT------

Please do comment if you don't understand any part or want to know more or just want to say thanks. I love programming and love to teach my friends. Your suggestions and appreciation will make this blog much better.
Monday, 21 May 2012

Methods to initialize string in C++

// Various methods to initialize strings in C++

#include <iostream>
#include <string>

using namespace std;

int main()
{
     string s0("welcome to programsplusplus");
     string s1(s0);
     std::cout<<s1;

     string s2(s0,8,3);
     std::cout<<"\n"<<s2;

     string s4("hello world",4);
     std::cout<<"\n"<<s4;

     string s5(10,'x');
     std::cout<<"\n"<<s5;

     string s6(10,42);
     std::cout<<"\n"<<s6;

     string s7(s0.begin(),s0.begin()+5);
     std::cout<<"\n"<<s7;

     return 0;
}
------ OUTPUT------

Please do comment if you don't understand any part or want to know more or just want to say thanks. I love programming and love to teach my friends. Your suggestions and appreciation will make this blog much better.
Sunday, 20 May 2012

C++ implementation of linked list

// C++ implementation of a linked list

#include <iostream>

struct Node // declares the node structure
{
     int info;
     Node *next;
}*start,*ptr,*newptr;

Node *new_list(int x) // creates a new list
{
     ptr = new Node;
     ptr->info = x;
     ptr->next = NULL;
     return ptr;
}

void insert_beg(Node *np) // inserts an element in list
{
     if ( start == NULL )
          start = np;
     else
     {
          Node *save = new Node;
          save = start;
          start = np;
          np->next = save;
     }
}

void display(Node *np) // displays the list
{
     while ( np != NULL )
     {
          std::cout<<np->info<<" -> ";
          np = np->next;
     }
}

int main()
{
     int item,choice;
     do
     {
          std::cout<<" \n1 : Create a new list ";
          std::cout<<" \n2 : Insert at beginning ";
          std::cout<<" \n3 : Display List ";
          std::cout<<" \n4 : Exit\n ";
          std::cout<<"\n Enter your choide : ";
          std::cin>>choice;

          switch(choice)
          {
               case 1 :
                    std::cout<<" \nEnter some value : ";
                    std::cin>>item;
                    start = new_list(item);
                    std::cout<<" List created !!! ";
                    break;
               case 2 :
                    std::cout<<" Enter an item to insert : ";
                    std::cin>>item;
                    newptr = new Node;
                    newptr->info = item;
                    newptr->next = NULL;
                    insert_beg(newptr);
                    break;
               case 3 :
                    std::cout<<" The list is as follows : \n";
                    display(start);
                    break;
          } // end of switch

     }while ( choice != 4 ); // end of do while
     return 0;
}// end of main
------OUTPUT------

Please do comment if you don't understand any part or want to know more or just want to say thanks. I love programming and love to teach my friends. Your suggestions and appreciation will make this blog much better.


Friday, 4 May 2012

Namespace example in C++

// Program to demonstrate the use of namespaces

#include <iostream>

namespace other // defines a namesapce
{
          int sum(int,int); // function prototype
}

// function sum() that belong to the other namespace which returns the sum of two //integers
int other :: sum(int x,int y)
{     return x+y;
}
/* another function sum() that does not belong to the namespace 'other' and returns the
   difference of two integers passed as arguments */
int sum(int x,int y)
{   return x-y;
}
 
int main()
{
    int a,b;
    // prompts the user to enter two integer values a and b
    std::cout<<" Enter the value of a : ";
    std::cin>>a;
    std::cout<<" Enter the value of b : ";
    std::cin>>b;
    // calls the function declared under the 'other' namespace
    // notice the other:: is used to call this function
    std::cout<<"\n Sum() function of 'other' namespace : "<<other::sum(a,b);
    // normal sum() function that actually computes the difference of a and b
    std::cout<<"\n Normal Sum() function : "<<sum(a,b);
    return 0;
}// end of main
------ OUTPUT ------








 

Please do comment if you don't understand any part or want to know more or just want to say thanks. I love programming and love to teach my friends. Your suggestions and appreciation will make this blog much better.


Saturday, 28 April 2012

C++ program to display current date and time

This program is about printing the date and time using C++. The C library contains the time.h header that deals with time and dates. Before heading further, i would like to mention a new type of variable of the type time. It is the time_t type, which is a variable of time and is used to store time related information when dealing with time functions included in the time.h header file.

It is declared as follows :

time_t seconds; // this declares a variable of the type time_t

Please note that it is not a fundamental data type;

Now, to print the date and time, we need to store it first. This task is done with the time() function, that calculates the time and stores it in a variable of type time_t. The value that is calculated is a long numeric value. To print the date and time in a more readable and user friendly format, the ctime() function is used which converts the date and time into a string for display purposes.

The program below demonstrates the use of time() and ctime() functions to display time and date. It also displays the time elapsed from 1st January 1970 till now. For more information, please e-mail me or leave a comment.

// Program to print current date and time using C++

#include <iostream>
#include <ctime>

int main()
{
     time_t sec;
     // creates and instance of the time variable time_t
     time(&sec);
     std::cout<<" Current Date and time : "<<ctime(&sec);
     std::cout<<"\n Time elapsed from 1st January 1970 --> "<<sec<<" seconds ";
     std::cout<<"\n Time elapsed from 1st January 1970 --> "<<sec/3600<<" hours ";
     std::cout<<"\n Time elapsed from 1st January 1970 --> "<<(sec/3600)/24<<" days ";
     std::cout<<"\n Time elapsed from 1st January 1970 --> "<<((sec/3600)/24)/7<<" weeks ";
     std::cout<<"\n Time elapsed form 1st Jaunary 1970 --> "<<((sec/3600)/24)/365<<" years ";
     std::cout<<"\n Time elapsed from 1st January 1970 --> "<<(float)(((sec/3600)/24)/365)/10<<" decades \n";
     return 0;
} // end of main
------ OUTPUT ------









Please do comment if you don't understand any part or want to know more or just want to say thanks. I love programming and love to teach my friends. Your suggestions and appreciation will make this blog much better.


Friday, 20 April 2012

Matrix Multiplication in C++

Matrix multiplication is one of the most basic programs I learned when i was in my 12th standard. Its really simple, simply multiply the rows
of the 1st matrix with the columns of the 2nd matrix and add them up. This will generate the resultant matrix.

The following code demonstrates how it is done. Read it, its quite simple. Still if you encounter any problems or have any other query, please
leave a comment or email me. Any suggestions are also welcome
// Program to multiply two matrices

#include <iostream>

int main()
{
     int arr1[20][20],arr2[10][10];
     int result[20][20];
     int m,n;
     int i,j;
     // prompts the user to enter the rows and columns of the matrix
     std::cout<<" Enter the number of rows (m) : ";
     std::cin>>m;
     std::cout<<" Enter the number of columns (n) : ";
     std::cin>>n;
     std::cout<<" \n Enter the elements of the 1st matrix \n ";

     for (i=0; i<m; i++)
     {
          for (j=0; j<n; j++)
          {
               std::cout<<" Element "<<i<<" : "<<j<<" --> ";
               std::cin>>arr1[i][j];
          }
     }

     std::cout<<"\n Enter the elements of the 2nd matrix : \n ";
     for (i=0; i<m; i++)
     {
          for (j=0; j<n; j++)
          {
               std::cout<<" Element "<<i<<" : "<<j<<" --> ";
               std::cin>>arr2[i][j];
          }
     }

     //------------ display matrics -----------------------

     std::cout<<"\n 1st matrix \n ";
     for (i=0; i<m; i++)
     {
          for (j=0; j<n; j++)
          {
               std::cout<<" "<<arr1[i][j];
          }
          std::cout<<"\n";
     }

     std::cout<<"\n 2nd matrix \n ";
     for (i=0; i<m; i++)
     {
          for (j=0; j<n;j++)
          {
               std::cout<<" "<<arr2[i][j];
          }
          std::cout<<"\n";
     }
    std::cout<<" \n Resultatn matrix \n";
    int k=0;
     // multiplies the two matrices together
     for(i=0;i< m;i++)
     {
          for(j=0;j< n;j++)
          {
               result[i][j] = 0;
          for(k=0;k< m;k++)
          {
               result[i][j] = result[i][j] + arr1[i][k] * arr2[k][j];
          }
          } // end of j sub loop
     } // end of i main loop

     // displays the resultant matrix

     for (i=0; i<m; i++)
     {
          for (j=0; j<n; j++)
          {
               std::cout<<result[i][j]<<"  ";
          }
          std::cout<<"\n \n";
     }
     return 0;
} // end of main

------ OUTPUT ------
 

















 



Please do comment if you don't understand any part or want to know more or just want to say thanks. I love programming and love to teach my friends. Your suggestions and appreciation will make this blog much better.