Copyright © Programs ++
Design by Dzignine
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 ------

Decimal to Binary Conversion Program

My apologies to my readers for posting after such a long time. Had been caught up in examinations...!!

Anyways, this is a simple program to convert decimal numbers to binary numbers. In computers , binary numbers form the base of everything. Even numbers like 10,3,5 etc are converted into long string of 0s and 1s. For e.g. the decimal number 8 is converted into 1000. The bigger the number, the more 0s and 1s it has. Hence it makes sense to have a useful program to convert decimal numbers to binary numbers.

The program given below does that particular task. It takes in a decimal whole number and converts it into its binary equivalent.
The conversion method is quite simple. Just divide the number by 2 recursively and store its remainder side by side. Here is how the program works :
Step 1 : The program prompts the user to enter a decimal number;
Step 2 : The number is divided by 2 and its remainder stored in an array.
Step 3 : The number itself is divided by 2.
Step 4 : The loop is run backwards, and this gives us the required binary equivalent.

Read the following code for a better understanding. 

// Program to convert decimal to binary (8-bit)

#include <iostream>

int main()
{
     int arr[8] = {0,0,0,0,0,0,0,0}; // for a 8 bit binary
     int x;
     std::cout<<" Enter the value to compute (integer only) : ";
     std::cin>>x;
     int i=0;
     while ( x != 0 )
     {
          arr[i] = x%2;
          x = x/2;
          i++;
     }
     std::cout<<" \n Binary Output (8-bit) : ";
     for (i=7; i>=0; i--)
          std::cout<<arr[i]<<" ";

     return 0;
} // end of main

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

1 : The above program generates an 8 bit binary number. If you want a higher bit binary number, suppose 16-bit, then simply increase the size of the array fro
8 to 16 and initialize it accordingly.
2 : Be careful during display of the binary equivalent, keep in mind that the array has to be traversed in a descending index order i.e backwards, otherwise you
will not get the proper result.
3 : You can use the above program to convert decimal numbers into other types of numbers ( for e.g octal(base 8), just divide the number by 8.)
4 : Contact me at  : programsplusplus@gmail.com for related queries or leave a comment....you are bound to receive an answer.

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.
-----