Copyright © Programs ++
Design by Dzignine
Friday, 17 February 2012

Bubble sort in C++


Sorting is used in many programming applications and as there are various sorting algorithms, each
having their respective pros and cons. Bubble sort, is one such search algorithm that is very easy to implement.
Bubble sort can be used to sort both in ascending order as well as in descending order. The basic idea of bubble sort
is to compare two adjoining value and exchange them if they are not in proper order. In every pass, the heaviest element
settles as its appropriate position in the bottom(if is to be sorted in ascending order) and the opposite is true for
sorting in descending order. Bubble sort is useful when a small no. of element are to be sorted as it is a simple algorithm.
However, due to comparatively large no of passes(loop counts), as compared to other sorting algorithms, its is advisable
to use other searching algorithms , e.g quick sort.
A program is given below that sorts an integer array in ascending order using bubble sort algorithm




// Program to implement bubble sort in C++\

#include <iostream>

int main()
{
     int arr[20];
     int size, temp,i,j;
     std::cout<<" Enter the no. of elements you want in the array (max 20 ) : ";
     std::cin>>size;
     std::cout<<" \n Now enter the elements in the array ";
     // loop to insert elements in the array, which is initially empty
     for (i=0; i<size; i++)
     {
          std::cout<<" \n Element "<<i<<" : ";
          std::cin>>arr[i];
     } // end of for loop

     // to sort using bubble sort algorithm(ascending order)

     for (i=0; i<size; i++)
     {
          for (j=0; j<=i; j++)
          {
               if( arr[j] > arr[i]) // exchanges heavy elements with lighter ones
               {
                    temp = arr[j];
                    arr[j] = arr[i];
                    arr[i] = temp;
               }

          } // end of sub loop
     } // end of main loop

     std::cout<<" \n The sorted array is as follows : \n";
     for (i=0; i<size; i++)
     {
          std::cout<<" \n Element "<<i<<" : "<<arr[i];
     } // end of main loop
     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 ------

Insertion Sort in C++ : http://programsplusplus.blogspot.in/2012/02/insertion-sort-in-c.html
Selection Sort in C++ : http://programsplusplus.blogspot.in/2012/02/selection-sort-in-c.html
 
Saturday, 11 February 2012

Basic password encryption program

Password encryption is basically converting a password in some other format(instead of text) into a format
that is not recognizable,so that i becomes secure. This is essential when we want to write down passwords without
the fear of having to risk the likelihood of revealing our password. Also since encrypted passwords contain special characters
such as %,$ , it becomes very difficult for brute force attacks to crack it. There are many password encrypters  available, that use
sophisticated techniques to encrypt passwords. One simple method is by converting a series of characters into their respective ASCII
values. The program given below encrypts the password as follows :

Step1 : The user enters a password to encrypt
Step2 : The password is checked to see whether it is UPPERCASE OR LOWERCASE
Step3 : If it is lowercase then it is converted into uppercase and vice-verse
Step4 : Then the converted string is converted into ASCII. Vola, the password is encrypted and contains only numeric values

Even though this encryption method is very simple, it is effective especially against a person who little knowledge of ASCII values.

// BASIC PASSWORD ENCRYPTER
// USES ASCII CODES FOR ENCRYPTION
// VERSION 1.0
// CREATED BY : DEEPAK SHARMA

#include <iostream>
#include <cctype>

int main()
{
     char password[20];
     char temp[20];
     int encrypt_password[20];
     int i,length;
     std::cout<<" Enter the password to encrypt (max 20 characters ) : ";
     std::cin.getline(password,sizeof(password));
      // to check whether the password is in UPPERCASE or LOWERCASE
     for (i=0; password[i] != '\0'; i++ )
     {
           if ( islower(password[i]) )
                    temp[i] = toupper(password[i]);
           else if ( isupper(password[i]) )
                    temp[i] = tolower(password[i]);
          else
                    temp[i] = password[i];
      } //end of loop
             temp[i] = '\0';

     // to convert the characters to their respective ASCII values
      for ( i=0; temp[i] != '\0'; i++ )
      {
               encrypt_password[i] = temp[i];
      }
        length = i;
      // to display the encrypted password

      std::cout<<"\n ENTERED PASSWORD : "<<password;

      std::cout<<" \n\n ENCRYPTED PASSWORD : ";
      for (i=0; i<length; i++)
      {
          std::cout<<encrypt_password[i];
      }

     return 0;
} // end of main
Basic password encrypter version 1.0









---
Sunday, 5 February 2012

Multiple increment opeartors in C and use of printf

This post is in reference to a problem about which I posted earlier, under the title "multiple increment operators". Now while using multiple increment operators in C , the results are completely different, which also encouraged me to explain a little bit about the printf(); used in C for basic output operations.
Consider the following snippet of code :-
// Multiple increment opearators in C

#include <cstdio>
int main()
{
     int x = 5;
     printf("%d%d%d%d%d",x++,x--,++x,--x,x);
     return 0;
}
The program give the output as 45545.
Now when the statement printf("%d%d%d%d%d",x++,x--,++x,--x,x); is executed, all the variables are processed from right to left , and pushed accordingly in the stack. i.e
x - PUSH --> means x = 5;
--x (per-decrement) - PUSH --> means x = 4;
++x (per-increment) - PUSH --> means x = 5;

x-- (post-decrement) - PUSH --> means x = 5 (but afterwards x = 4 due to post decrement)
x++(post-increment) - PUSH --> means x = 4; (but afterwards x = 5 due to post increment).
Now the printf() statement , prints the values of x , hence the output is 45545(remember stacks follow LIFO,last in first out).
------ OUTPUT ------
 












For more info on using printf(), follow this link : http://stackoverflow.com/questions/2198880/how-does-printf-work

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

Multiple increment operators in c++ : http://programsplusplus.blogspot.in/2012/01/multiple-increment-operators-in-sinlge.html

Deletion in an integer array

Deletion inside data structures is very common, especially inside arrays as they have static(fixed) memory allocation. To delete an element from the array simply move each element one step above. For example, if the array was initially as follows :
Element 0 : 23
Element 1 : 98
Element 2 : 87
Element 3 : 12
and suppose we want to delete an element at the 1st position(i.e.98), then we simply shift each element one position above. So, the new array after deleting value 98 from the 1st position would be as follows :
Element 0 : 23
Element 1 : 87
Element 2 : 12
Hence we have successfully deleted an element from the array. The process is contrary to the method that we have used to perform insertion operation in the array(see the previous post). Read the given code below, for a better understanding :

// Program to delete element in an array (for GCC compiler package and similar compilers)

#include <iostream>
// function to delete an element from the array
int deletion_array(int array[],int s,int pos)
{
     for (int i=pos; i<=s; i++)
     {
          array[i] = array[i+1];  //shifts each element one position above
     }
     s--;    // decrements the size, as one element is deleted
     return s;  // returns the new size of the new array
}

int main()
{
     int size,value,position;
     int arr[21];
      // prompts the used to enter the maximum no. of elements in the array
     std::cout<<" Enter the no of elements you want in the array (max 20) : ";
     std::cin>>size;
      // to insert the elements in the array
     for (int i=0; i<size; i++)
     {
          std::cout<<" \n Element "<<i<<" : ";
          std::cin>>arr[i];
     }
     std::cout<<"\n Enter the position where you want to delete the value : ";
     std::cin>>position;
     size = deletion_array(arr,size,position);
      // calls the function to delete the specified element
     std::cout<<" \n Deletion successfull !!! , the new array is as follows ";
     // displays the new array
     for (int i=0; i<size; i++)
     {
          std::cout<<"\n Element "<<i<<" : "<<arr[i];
     }
     return 0;
} // end of main
Note : If the console window shuts down immedeaitly, then add std::cin.get(); before return 0; to fix the problem. :) 

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





------ Related Posts ------
Insertion in array : http://programsplusplus.blogspot.in/2012/02/insertion-in-integer-array.html
Saturday, 4 February 2012

Insertion in an integer array

Insertion in an array is a widely used practice used when programming with C/C++. Simply , it involves inserting a value from a user and inserting in an array. Now, how this is done is interesting and simple :-). First we create the array (simple!!! ), then we prompt the user to enter the position where he/she wants to insert and finally, the user is prompted to enter the value to insert in the array. Consider an example, 

Suppose the array initially contains the following values, along with their positions :-
Element 0 : 3
Element 1 : 7
Element 2 : 89
Element 3 : 8
Then inserting any value(say 145) at position '1', then the new array would be like this :-
Element 0 : 3
Element 1 : 145
Element 2 : 7
Element 3 : 89
Element 4 : 8
Who la, the value 145 has been inserted at the 1st position in the array.
Note : Notice, that the size of the array has increased(obviyo!!!) , so always take the size of the array one greater than the no of elements you want to have. This will prevent overwrite problems in the array.
Consider the following snippet of code for a better understanding.

// Program to insert element in an array (for GCC compliler package and similar compilers)

#include <iostream>
// function to insert elements in the array
int insertion_array(int array[],int s,int pos,int val)
{
     for (int i=s; i>=pos; i--) // shifts every element one step below
     {
          array[i+1] = array[i];
     }
     array[pos] = val; // inserts the given value at the specified position
     s++;                  // increments the size, as one extra element is now inserted
     return s;
}

int main()
{
     int size,value,position;
     int arr[21];
     std::cout<<" Enter the no of elements you want in the array (max 20) : ";
     std::cin>>size;

     // prompts the user to enter elements in the array
     for (int i=0; i<size; i++)
     {
          std::cout<<" \n Element "<<i<<" : ";
          std::cin>>arr[i];
     }
     std::cout<<"\n Enter the position where you want to insert the value : ";
     std::cin>>position;
     std::cout<<"\n Enter the value to insert at the "<<position<<" : ";
     std::cin>>value;
     // calls the above function to insert values in the array
     size = insertion_array(arr,size,position,value);
     std::cout<<" \Insertion successfull !!! , the new array is as follows ";
      // displays the new array
     for (int i=0; i<size; i++)
     {
          std::cout<<"\n Element "<<i<<" : "<<arr[i];
     }
     return 0;
} // end of main
------ OUTPUT ------





















Note : If the console window shuts down immedeaitly, then add std::cin.get(); before return 0; to fix the problem. :)
------ Related Posts ------

Deletion in an array : http://programsplusplus.blogspot.in/2012/02/deletion-in-integer-array.html
Thursday, 2 February 2012

Binary Search in array



Binary search is also a widely used searching technique used to find elements in an array. As the name suggests, binary search involves splitting the entire array into two pieces again and again until we find that we have searched for.Note: the array needs to be sorted first in order for this method to work.  In binary search, the starting, ending and middle positions are found out first. Then , the array is broken down into smaller and smaller pieces of two and the middle position is found out. The advantage of binary search is that it requires less no of passes through the array, making it a simple and efficient searching technique in an array compared to other searching techniques such as linear search.


 Consider the following code snippet :
// Program to search using binary search
#include <iostream.>

int main()
{
    int arr[20],position,value;
    int size,flag = 0;
    int beg,mid,end;
    mid = 0;
    // prompts the user to enter the maximum no of elements in the array
    std::cout<<" Enter the max no of elements you want in the array (max 20) : ";
    std::cin>>size;
    for (int i=0; i<size; i++)
    {
        std::cout<<"\n Element : "<<i<<" : ";
        std::cin>>arr[i];
    }
    std::cout<<"\n Enter the value that you want to search : ";
    std::cin>>value; // takes the value that is to be searched
    std::cin.ignore();
    beg = 0;
    end = size-1;
    mid = (beg+end)/2; // finds the middle index

    while ( beg <= end )
    {
          if ( arr[mid] == value ) // breaks loop if the element is found
          {
             position = mid;
             flag = 1;
             break;
             }
            
          else if ( arr[mid] > value )
               end = mid -1;
          else
              beg = mid + 1;
                     
        mid = (beg+end)/2; // finds the middle index at each pass
    } // end of while
   
     if ( flag == 1 ) // displays the found element
        std::cout<<"\n Value "<<value<<" found at position "<<position;

                         // displays an error if the element is not found
     else
         std::cout<<" \nVALUE NOT FOUND !!! ";
   
    std::cin.get();
    return 0;
} // end of main

Binary Search in array

















Note : The array must be sorted beforehand for this technique to work.

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

 
Wednesday, 1 February 2012

Linear Search in array

Linear search is one of the most basic techniques used while programming in C, C++ or any other programming language for that matter. It is also taught in school and college and is one of the fundamental techniques used to search in an array. Linear search is implemented by searching each element in the array with the value that is to be searched.

In this method, the user is prompted to insert the value which has to be searched and the position where the element is stored is given as output. In simple words, the user enters the value which has to be searched, the program searches the array to find that value and if the value is found then the position where the element is found is displayed.
Consider the following code snippet :
// Program to implement linear search (by value)
#include <iostream>

int main()
{
    int arr[20],n;
    int position,value,flag = 0;
    // prompts the user to enter the no of elements in the array
    std::cout<<" Enter the no of elements you want to insert (max 20) ? ";
    std::cin>>n;
    for (int i=0; i<n; i++) // loop to enter the elements in the array
    {
        std::cout<<" \n Element "<<i<<" : ";
        std::cin>>arr[i];
    }
    // asks the user to enter the value that is to be searched
    std::cout<<"\n Enter the value to find in the array : ";
    std::cin>>value;
    std::cin.ignore();
    // searches the position by checking each value in the array
    for(int i=0; i<n; i++)
    {
            if ( arr[i] == value )
            {
                 position = i;
                 flag = 1;
                 break; //breaks the loop if value is found
            }
            else
                flag = -1; // assigns -1 to flag variable if value is not found
    }
   
    if ( flag == -1 ) // displays error message if value is not found
       std::cout<<" \n Element NOT FOUND !!! ";
    else             // displays the searched value along with its position
       std::cout<<" Value "<<value<<" found at postiton : "<<position;
   
    std::cin.get();
    return 0;
} // end of main
 

Linear search using value to find position

NOTE : Since linear search involves processing the entire array, it takes considerable time and resources if the size of the array is quite large. Hence, more efficient searching techniques are used such as binary search etc.

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

Binary Search : http://programsplusplus.blogspot.in/2012/02/binary-search-in-array.html