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.
Tuesday, 17 April 2012

Reverse of an integer in C++

The modulus operator (%) is widely used in many programming languages, especially in C/C++. It returns the remainder. For e.g 10%2 returns 0 as the remainder that we get when dividing 10 by 2 is 0.

One use of this operator is used for finding the reverse of an integer. Simply divide the integer by 10 and use the modulus operator to store
the remainder. The following programs demonstrates the above concept.
 
// Program to find out the reverse of an integer

#include <iostream>

int main()
{
     unsigned int x;
     // prompts the user to enter an integer
     std::cout<<" Enter the number : ";
     std::cin>>x;
     std::cout<<" The reverse of "<<x<<" is : ";
     while ( x != 0)
     {
          std::cout<<x%10;
          x = x/10;
     }
     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.
Wednesday, 4 April 2012

Sophie Germain Prime Numbers in C++

Prime numbers are those numbers that are only divisible by 1 and themselves. Sophie geramin prime numbers are a special category of prime numbers.
By definition, a prime number, say 'p', is a sophie germain prime number if p is prime and 2p+1 is also prime. For e.g 23 is a sophie germain prime because
23 is prime and 23*2 + 1 = 47 is also prime.

For those who do not know how to check whether a number is prime or not, please read my post : Checking PRIME numbers in C++.

Now generating sophie germain primes, is actually quite a simple task. We need just need to check the following :
1 - p is prime
2 - 2p+1 is prime
3 - print p if both cases 1 and 2 turn out to be true.

The following program generates sophie germain primes upto the limit specified by the user. Please have a look at the source code to have a better
understanding of how the program works. Please leave a comment if you want to ask something or just want to say hi .

// Program to generate sophie germain prime numbers

#include <iostream>

bool checkPrime(int number)
{
     bool flag = true;
     if ( number == 2 ) // checks if 2 is entered(as 2 is a prime number )
     {
      //    std::cout<<" The number is PRIME !!! ";
          return true; // terminates the program is two is enterd, as there is no need for further checking
     }

     else // divides the number with value from 2 to (number-1)
     {
          for (int i=2; i<number; i++)
          {
               // if it is divisible than values smaller than number-1 it is non - prime
               if ( number%i == 0)
                    flag = false;
          }
     }
     return flag; // returns either true or false as the result

}

int main()
{
     int max,i = 2;
     // prompts the user to enter the max numbers to generate
     std::cout<<" Enter the max. numbers to generate : ";
     std::cin>>max;
     int counter = 1;

     while ( counter <= max) // run until the limit is reached
     {
          if ( checkPrime(i) == true ) // initial check to see if p is prime
          {
               if ( checkPrime((2*i) + 1) == true ) // secondary check to see if 2p+1 is prime
               {
                    std::cout<<" "<<i; // displays the number if it turns out to be a sophie germain prime
                    counter++;
               }
          }
          i++;
     } // end of while
     std::cout<<"\n End of program !! ";
     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.   

------ Related Posts ------
1 : For more information on sophie germain primes , please visit : http://en.wikipedia.org/wiki/Sophie_Germain_prime
3 : Generating Prime numbers in C++ : http://programsplusplus.blogspot.in/2012/03/numbers-can-become-quite-huge-mess-when.html
Tuesday, 3 April 2012

Constructer initialization

Initializing variables while writing a program is one of the most basic routines that a programmer does while writing the code. Normally it is done using the assignment operator '=' and initializing the variable.
E.g 

int x = 5;

// this initializes the value of x with 5

But i found out that it could also be done this way,

int x(5); // this initializes the variable with the value 5

This is called constructor initialization, though it is not widely used, I thought it would be a good idea to know.
Initializing the variable using this method has no advantage, so its not necessary. Just remember that it can also be done this way.
Monday, 2 April 2012

Binary to Decimal conversion in C++

My previous post was based on converting a decimal number into its binary equivalent. Contrary to that, the program given below converts binary numbers into their decimal equivalents. That is, it converts binary numbers such as 1000 into its corresponding decimal equivalent i.e 8.

Now for those who are not familiar with the concept of binary numbers, please read the following post : decimal to binary conversion.
Now, the method works like this. Just traverse the binary number step by step, starting from 0 to n-1, where n is the most significant bit(MSB) ,
multiply them with 2 with raising powers and add the sum together. E.g to convert 1000(which is binary equivalent of 8), just do the following

1 0 0 0 ==> going from right to left  

0 x 2^0 = 0
0 x 2^1 = 0;
0 x 2^2 = 0;
1 x 2^3 = 8;
now add them together i.e 0+0+0+8 = 8; this the decimal equivalent of 1000. Please read the program below to have a better understanding how the concept
work. Note : The program works only for 16-bit binary numbers(non-floating) or less. Leave a comment if anything is not clear. You are bound to receive a reply.

// Program to convert binary to its decimal equivalent

#include <iostream>
#include <math.h>

int main()
{
     int x;
     int i=0,sum = 0;
     // prompts the user to input a 16-bit binary number
     std::cout<<" Enter the binary number (16-bit) : ";
     std::cin>>x;

     while ( i != 16 ) // runs 16 times
     {
          sum += (x%10) * pow(2,i);
          x = x/10;
          i++;
     }
     std::cout<<"\n The decimal equivalent is : "<<sum;
     return 0;
}

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

 ------ Programming Advice and Tips ------

1 : Note : The above program only accepts 16-bit binary numbers as inputs. This limit can be increased by increasing the number of loop executions by
changing the value in the while loop from 16 to say 32. (be sure it is a valid number which is a factor of 2 ).

2 : This program is the most basic method to do this type of conversion. However, there are a number of algorithms to do the same, so just GOOGLE out some
of them. Try it out, there are a variety of programs that do the same conversion in different ways.


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.

------ Related Posts ------ 

1 : Decimal to binary conversion (v1.0) : http://programsplusplus.blogspot.in/2012/04/my-apologies-to-my-readers-for-posting.html  
2 : Decimal to binart conversion (v2.0) : http://programsplusplus.blogspot.in/2012/04/decimal-to-binary-conversion-program.html 
Sunday, 1 April 2012

Decimal to Binary conversion program (v2.0)

The program I posted in my previous post could only convert whole decimal numbers into binary. Meaning it could not convert decimal numbers like 2.34 into its binary equivalent. This is the updated version of that program, and this one is capable of converting any decimal number into its binary equivalent.

Pleas read the post : Decimal to binary conversion , if you are new to this concept.

// Program to convert decimal to binary ( version 2.0 )

#include <iostream>

void convert_integer(int arr[],int x) // function to convert the integer part to binary
{
     int i=0;
     while ( x != 0 ) // until x is fully divided, leaving only 1
     {
          arr[i] = x%2; // store the remainder in the array
          x = x/2;
          i++;
     }
     /*since arrays are passed by refernce, hence any changes in the parameter array will
        result in change in the array passed as the argument */

} // end of function

void convert_float(int arr[],double x) // function to convert the floating part into binary
{
     int i=0;
     do
     {
          x = x * 2;
          if ( x > 1 )
          {
               arr[i] = (int)x;
               x = x - (int)x;
          }
          else
          arr[i] = (int)x;
          i++;
     }while ( x != 1 && i != 8);

}// end of function

int main()
{
     double value;
     int arr1[8] = {0,0,0,0,0,0,0,0}; // for integral part
     int arr2[8] = {0,0,0,0,0,0,0,0}; // for floating part
     std::cout<<" Enter a number to convert : ";
     std::cin>>value;
     convert_integer(arr1,(int)value);
     double temp = value - (int)value;
     convert_float(arr2,temp);

     std::cout<<" \n The binary output (8-bit ) is : ";

     for (int i=7; i>=0; i--) // displays the LHS of the binary number
          std::cout<<arr1[i]<<" ";

     std::cout<<" . "; // adds the decimal(point) between the numbers

     for (int i=0; i<8; i++) // displays the RHS of the binary number
          std::cout<<arr2[i]<<" ";

     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.

------ Related Posts ------