Friday 28 February 2014

Conversion of Binary Number to Decimal Number - C++ Program Source Code

Recently, I had shown the program to convert from decimal to binary. It is equally important that you know how to do the reverse process too! So let’s see how to do it manually first. Consider the binary number ‘1010’. To convert it to decimal, you must do the process shown:


 Code:
#include<iostream>
#include "math.h";
#include "conio.h";
using namespace std;

int main()
{
     int num,i,sum=0,a;
     cout<<"Enter the binary number : ";
     cin>>num;
     for(i=0;num!=0;i++)
     {
           a=num%10;
           sum=sum+a*pow(2,i);
           num=num/10;
     }
     cout<<"\nDecimal equivalent is : "<<sum;
     getch();
}

Working:

First, the binary number is input. Inside a for loop, a variable ‘a’ is defined as ‘num%10’, i.e., the last digit of the number. Now another variable ‘sum’ (initially 0) is changed to ‘sum + (a  * pow (2, i))’. Now num is changed again into sum/10, so that on the next run of the loop, the penultimate digit will go into the variable ‘a’. This process continues until num reduces to 0.
Consider the binary number 1010 as in the above figure.
1      1.  On the first run, a = num%10, i.e., a = 0. Sum changes to 0 + 0*20 = 0. ‘num’ is changed to 101.
2      2.  On the second run, a = 1. Sum changes to 0 + 1*21 = 2. ‘num’ is now 10.
3      3.  On the third, a = 0. Sum is 2 + 0 * 22 = 2. ‘num’ is now 1.
4      4.  On the forth, a = 1. Sum is 2 + 1 * 23 = 10. ‘num’ is hence reduced to 0 and the for          loop is terminated.
Now the variable ‘sum’ is successfully set to the decimal equivalent of the given number i.e., 10. At last, we just output the value of ‘sum’.

Sample output for the program is given below:



Here is the program to convert Decimal Number to Binary Number:

Conversion from Decimal Number to Binary Number - C++ Program Code

Happy Coding!
:)




Thursday 27 February 2014

Conversion from Decimal Number to Binary Number - C++ Program Code

So most of you out there know that computers does not use the normal number system, but another one called binary number system, which only has two digits (0 and 1) in it. That's why this program is important.
To understand this, you must know about the normal (manual) method of conversion. Here is a recap.

Consider the decimal number 7. To convert this you must divide the number by 2 repeatedly until the number reduces to 0. The binary equivalent is the remainders wrote in reverse order. Here is the process:


Now we just need to transfer this exact process into program. 

Code:
#include<iostream>
#include "conio.h";
using namespace std;

int main()
{
    int dec, bin[100],i=0,j;
    cout<<"Enter the decimal number : ";
    cin>>dec;
    do
    {
       bin[i]=dec%2;
       i++;
       dec = dec/2;
    }while(dec!=0);
       
    
    cout<<"\nThe binary equivalent is ";
    for(j=i-1;j>=0;j--)
    {
        cout<<bin[j];
    }
    getch();
    return 0;
}

Output:

Working:

The given decimal number is divided repeatedly by 2, and the remainders are stored in an array, and the array is printed in reverse order. Just like the real process! 

Here is the program to convert a binary number to decimal number:

Conversion of Binary Number to Decimal Number - C++ Program Source Code


Happy Coding!
:)




Wednesday 26 February 2014

A word for newer IDEs

The thing is, in newer IDEs like Dev C++ , the old  #include<iostream.h> and some other commands will not work. Although these newer ones uses more standardized version of C++, the older versions are still popular among schools and beginner programmers. This is why you gotta understand both. The headers like #include<iostream.h> in older IDEs change into #include<iostream> in newer ones. Also the headers like #include <conio.h> turns into #include "conio.h" . Another change is that the newer IDEs only support integer functions, so you must return some value. Here is a comparison of these kind of variations:

                                       
       
       Structural
      Differences           



Note that you must also include the line,

using namespace std;


under the header inclusion.

Example Program :

ODD OR EVEN
  • In Dev C++ (Typical newer IDE)

  • In Turbo C++ (Older IDE)



Monday 24 February 2014

Sum of harmonic series - C++ Program Source Code

The aim is to find the sum of the harmonic series with the limit 'n' specified by the user.
The harmonic series is as such:

Code:
//Please Comment, share, follow and visit often! :)
#include<iostream.h>
#include<conio.h>
void main()
{
    int i,n;
    double answer;
    cout<<"Enter 'n'\n";
    cin>>n;
    answer=0;
    if(n!=0)
    {
         for(i=1;i<=n;i++)
         {
            answer = answer + (1.0/i);
         }
         cout<<"Answer is "<<answer<<"\n";
    }
    else
    {
         cout<<"Answer not defined! :(\n";
    }
}


For newer IDEs, visit this page.
Working:

The program is remarkably simple. First we input 'n' from the user. A variable 'answer' is initialized with a value 0. Now inside a for loop, with limit 'n', we add '1/i' to the answer. This for loop runs n times, after which the variable answer will have the required value. Also, if the input number is 0, sum cannot be defined since series becomes 1/0, which is not defined. So the if-statement.
IF the input number is NOT 0, the increment process is done, else, an error message is displayed. 

Happy Coding!
:)

Sunday 23 February 2014

Transpose of a Matrix - C++ Program Source Code

Here is a program to find the transpose of a matrix. Here is an example for transposal of a matrix:

Example for a matrix transposal


Code:
#include<iostream.h>
#include<conio.h>
void main()
{
    int i,j,m,n,matrix[50][50],transpose[50][50];
    cout<<"Enter the order of the matrix\n";
    cin>>m>>n;
    cout<<"Enter the elements of the matrix \n";
    for(i=0;i<m;i++)
    {
       for(j=0;j<n;j++)
       {
            cin>>matrix[i][j];
       }
    }
    cout<<"The entered matrix is \n";
    for(i=0;i<m;i++)
    {
        for(j=0;j<n;j++)
        {
           cout<<matrix[i][j];
           cout<<"  ";
        }
        cout<<"\n";
    }
    //Definition of transpose
    for(i=0;i<n;i++)
    {
       for(j=0;j<m;j++)
       {
            transpose[i][j]=matrix[j][i];
       }
    } 
    cout<<"The transpose is \n";
    for(i=0;i<n;i++)
    {
        for(j=0;j<m;j++)
        {
           cout<<transpose[i][j];
           cout<<"  ";
        }
        cout<<"\n";
    }
}

For newer IDEs, visit this page.

Working:

First the user is asked to enter the order and subsequently the elements of a matrix. The given matrix is displayed for formality. The transpose has the number of rows is equal to the number of columns of the first matrix and number of columns equal to the number of rows of the first matrix. It is then defined appropriately and displayed. Here is the output based on the above example.



Happy Coding!

:)

Searching For A Character in a String - C++ Source Code

Here is another string-manipulation program. The program searches a character in a user given string, and if it finds the character, it displays the position, and if the character is not found the program displays a not-found message.

Code:
//Support us by sharing, commenting, and visiting often! :)
#include<iostream.h>
#include<string>
void main()
{
    int i;
    char a[100],b;
    cout<<"Enter the string\n";
    cin.getline(a, 50);
    cout<<"Enter the letter\n";
    cin>>b;
    int flag=0;
    for(i=0;i<strlen(a);i++)
    {
        if(b==a[i])
        {
              cout<<"Found at "<<i+1<<" :)\n";
              flag++;
        }
    }
    if(flag==0)
    {
        cout<<"Character not found! :(\n";
    }
}

For newer IDEs, visit this page.

Working:

We first input the string from the user and the character to be searched. We also declare an integer 'flag' and initially set it to 0. A for loop is initiated. If the character the user entered is same as the character the for loop is at, we output the position just after the position of the for loop (because, array usually begins at 0).
Also, the integer 'flag' is decremented. Outside the loop, if the flag is still equal to 0, the program outputs the error message, and if it is more than 1, it does nothing. Two sample outputs are given below..



Happy Coding!
:)

Saturday 22 February 2014

Bubble Sort in C++ - Source Code

There are many different types of sorting, including, merge sort, insertion sort, bubble sort, quick sort, e.t.c.,. Today I'm gonna show you how to implement bubble sort in C++. This program is very important in exam point-of-view and computer science theory point-of-view. Here is an awesome representation of bubble sort:

Bubble-sort-example-300px
Bubble Sort
Source : Wikipedia Commons


The aim is to display a set of numbers given by the user in ascending or descending order.

Code:
#include<iostream.h>
#include<conio.h>
void main()
{
    int i,j,a[100],num,t;
    cout<<"Enter the number of numbers : \n";
    cin>>num;
    cout<<"Enter the numbers to sort : \n";

    for(i=0;i<num;i++)
    {
        cin>>a[i]; 
    }

    for(i=0;i<num;i++)
    {
        for(j=0;j<num-1;j++)
        {
             if(a[j]>a[j+1])
             {
                 t=a[j];    
                 a[j]=a[j+1];  
                 a[j+1]=t;   
             }
        }
    }

    for(i=0;i<num;i++)
    {
         cout<<a[i]<<"\t";
    }
    cout<<"\n";
}

For newer IDEs, visit this page.

Working:
First we input the numbers into an array. Now we compare each element with the next element. If the first element is greater than the second, we just swap the values. So at last, the elements will be in order. Simple, huh?

Happy Coding!

Caesar Cipher - Implementation in C++ : Program Source code

This is one of my all-time favorite programs. This is the program code for one of the most popular and easiest encryption techniques in Cryptography. Hey... Don't get over-excited, because, this is not what governments are using to encrypt their secrets, but still, it's worth knowing. Let's start by understanding Caesar Cipher is.

Caesar Cipher

Like all ciphers, caesar ciphers are also used to communicate messages from a source to another, without the middleman/medium does not know about the message. Ciphers are exclusively used in wars to communicate military secrets. The field of Cryptography deals with these kind of stuff. In earlier days, encryption and decryption of messages were manual. This proved to be very inefficient, tedious, and time consuming. Then came computers. Computers aided cryptography very much. With the help of computers and computer programming, encryption, transmission, and decryption of messages became very easy.

Caesar cipher is said to be used first by Roman Emperor Julius Caesar, whose name became bound to the method with time. It is also called Caesar shift cipher, because, the method used can be described as shifting. Let's consider an example where number of letters shifted is 3. If the input letter is 'a', the output letter is the alphabet which is 3 letters after the input, which is 'd'. Similarly, all the letters are transformed into some other one, and the resulting string does not make sense at all, unless you decrypt it! Here is a graphical representation of what's happening in a caesar shift.



So, 'Hello, World!' gets transformed into, 'Khoor, zruog!', if the shift number is 3.

Now let's see the code, shall we?

Code
#include<iostream.h>
#include<string>
void main()
{
    cout<<"Enter the input message:\n";
    char inmsg[1000];
    int i, j, length,choice;
    cin.getline(inmsg,100);
    length = strlen(inmsg);
    cout<<"Enter your choice \n1. Encrypt \n2. Decrypt \n";
    cin>>choice;
    if(choice==1)
    {
         for(i=0;i<length;i++)
         {
             if(isalpha(inmsg[i]))
             {
                 inmsg[i]=tolower(inmsg[i]);
                 for(j=0;j<3;j++)
                 {
                    if(inmsg[i]=='z')
                    {
                        inmsg[i]='a';
                    }
                    else
                    {
                        inmsg[i]++;
                    }
                 }
             }
         }
         cout<<"The encrypted message is \""<<inmsg<<"\"\n";
    }
    else if (choice == 2)
    {
        for(i=0;i<length;i++)
        {
             if(isalpha(inmsg[i]))
             {
                 inmsg[i]=tolower(inmsg[i]);
                 for(j=0;j<3;j++)
                 {
                     if(inmsg[i]=='a')
                     {
                        inmsg[i]='z';
                     }
                     else
                     {
                        inmsg[i]--;
                     }
                 }
            }
       }
    cout<<"The decrypted message is \""<<inmsg<<"\"\n";
    }
}

For newer IDEs, visit this page.

Working

NOTE: The header 'string.h' is used in the program, which includes functions like strlen(), isalpha(), tolower()

First, we input the character string from the user. Also, we ask whether he wants to encrypt or decrypt the message given.
If he chooses to encrypt : We loop through the string array, and check whether all the characters are alphabets using the function, 'isalpha()', and also we change all the given upper case characters to lower case using 'tolower()'. Now we loop through it again, but this time only by the number of times to shift the alphabets, which in this case is 3. Now we encounter a problem : What if the user enters the letters 'x','y', or 'z'? There is no letter beyond 'z' right? This can be solved by a little adjustment. If the loop encounters the letter 'z', it's gonna automatically change it to 'a' on the next run. In all other cases, we just increment the letter by 1. So even if the user gives 'x', the loop increments the letter by 1 until it reaches 'z', and it's gonna change it to 'a'. Haha! That's all with encryption! Here is an output, when the user chooses encryption


Notice how the program is retaining those symbols without any change? This is because we put the function isalpha(). This function checks whether if a character is alphabet or not, and if it is not, the loop does not touches that character.
If he chooses to decrypt : Now also everything is same as above, except that the problem changes to the letter 'a', and the adjustment is made the other way around. Also, the letter is decremented by 1 instead of being decremented. Here is a sample decryption output.




That's all for today, guys...
kdssb frglqj!*


*Try on your decryptor! ;-)


Thursday 20 February 2014

Largest of n Numbers - C++ Program Sourcecode!

Our aim in this program is to accept any number of numbers from the user, and to display the largest from it. Let's jump into the sourcecode:

Code:
#include<iostream.h>
void main()
{
    int number[10], large, i,n;
    cout<<"Enter the number of numbers : ";
    cin>>n;
    for(i=0;i<n;i++)
    {
       cout<<"\nEnter number "<<i+1<<" : ";
       cin>>number[i];
    }
    large = number[1];
    for(i=0;i<n;i++)
    {
        if(large<=number[i])
        {
            large = number[i];
        }
    }
    cout<<"\nLargest number is "<<large<<endl<<endl;
}

For newer IDEs, visit this page.
Working:

First, we simply ask the user to specify the number of numbers, and input an array with all the numbers. Next step is processing the array. Consider the numbers to be 10,12,11,5, and 15.

Processing ~

STEP 1 : We let the variable large equal to the first element of the array. Hence in this case,  large = first element (i.e., number[0]) = 10.

STEP 2 : We open a for loop, with limits 0 and n (in this case n is 5). If large is less than or equal to number[i], the variable large is reset to number[i]. In this case, number[2] is less than number[1] (since 10 < 12), so the value of large is changed from 10 to 12.

This process continues n times so that all the elements are compared to large.

On the next run,value of large remains 12, since 12 is not less than 11.
Similarly, on the next run also, large remains 12, since 12 is not less than 5.
On the next run, value of large is reset to 15, since 12 is less than 15.
 Thus the loop is terminated and final value of large is set to 15.

Now we output the variable large, which will be set to the largest number in the array.

Output:


Of course, there are many other methods to do this program, but I chose this method to show you a simple array manipulation technique in C++. You may use your intuition to solve this problem in any other way!

Happy Coding!!!

You might also like