Thursday 11 September 2014

#1 : Bare Basics - Quick C++ Tutorial

How to use an IDE

You can use any IDE (if you are going to use one) out there. The one I prefer is Code::Blocks, which is a free IDE which can compile and run C/C++ programs. Later on, you may use a more sophisticated IDE like Microsoft Visual C++ or Eclipse. Open it up, create a new project, open up 'main.cpp' from the side panel, and get cracking!

First C++ Program

Copy (or type, which is much better) this code into the IDE.
#include <iostream>

int main()
{
    std::cout<<"Hello, world!"<<std::endl;
    return 0;
}

Now click Build -> Build and Run to compile and run the program. If you have copied/typed correctly, you will now see the output now, which will say, "Hello, World!". Congratulations on running your first C++ program.




Now let's break down what is happening.

  • #include <iostream> 'include's or gets the program access to all the things inside the 'library' iostream (which stands for input-output stream). You can think of iostream as a folder, inside which there are certain files that are required to do input/output operations. By 'include'ing the library in your program, the program can access these files.
  • int main() is a function. A function is simply an entity or a block of code that does something. main() function is the most fundamental block of code in your program. As the name indicates, it is the most important function in your program, without which, your program will not run. Since our aim is to output a message to the user, we do this inside the main function. int stands for integer. This is called a return type, indicates that the function which we are working on has something to do with numbers, As per the new standards, every main() function must have a return type int. We will learn to make other functions as per our needs later on. return 0; at the end of the code puts an end to the main function. 
  • std::cout<< is the used to output the message to the screen. Anything that comes after std::cout<< is put to the screen. In this case a string (which is enclosed by two double inverted commas) is output. std::endl puts anything that comes after it, on the next line. Since std::endl is not a string (it is not to be enclosed between two double inverted commas) it requires another <<.
  • As you cans see, most of the lines in this program ends with a semicolon (;). This is to let the compiler know the particular operation is over. Also the all the operations inside the main() function is enclosed by a pair of flower brackets. Everything inside one pair of flower braces is called one block of code. As the programs get more complex number of blocks in your program will increase.
A peek on namespaces

Include a line 'using namespace std;' just below the first line of code. Now you can write just cout<< instead of std::cout<< or just endl instead of std::endl<< in your codes. We will learn why this happens later in the course. Run the modified code given and you will see that the output is exactly the same as the first one

#include <iostream>
using namespace std;

int main()
{
    cout<<"Hello, world!"<<endl;
    return 0;
}

Exercises
  • Remove the semicolon in your code and try running the program. What do you see? 
  • Write your own message in the program.
  • Write the words 'hello' and 'world' in two separate lines using endl.

Saturday 21 June 2014

C Program to Determine the Sum of Harmonic Series - Source Code

So, as you may know harmonic series implies:


In this program, we take the integer value of n from the user and display the sum of the series according to this value. I just used a for loop, although there are many other ways to do the same.

Here is the code:
#include <stdio.h>
#include <conio.h>

int main()
{
     int n,i;
     float inverse;
     double sum=0.0;
     //Preliminary
     printf(\"Program to find:\\n\");
     printf(\"\\n   1    1    1    1          1\\n\");
     printf(\"  __ + __ + __ + __ + ... + __\\n\");
     printf(\"\\n   1    2    3    4          n\\n\");

     //Prompting for the value for 'n'

     printf(\"\\n\\nEnter the value of n: \");
     scanf(\"%d\", &n);

     //Iterating and summing

     for(i=1; i<=n; i++)
     {
         inverse = (1.0/i);
         sum += inverse;
     }
 
     //Displaying the answer

     printf(\"\\nRequired sum is %f\", sum);
 
     getch();
     return 0; 
}

Here is the output:

Happy Coding!
:)

Wednesday 4 June 2014

Collatz Conjecture - Implementation in Java

Let's begin with a short intro to Collatz Conjecture*. It's also known in the names (3n+1) conjecture, Hasse's Algorithm, Syracuse problem, and a ton of others I really have a hard time remembering. The problem can be represented as a mathematical function as given below, which is iterated until the value of variable is reduced to 1.


The proposal of Collatz conjecture, is that, no matter what number you start with, you will eventually, at some point, reach 1. We all know that computers are especially good at repeating stuff! For this reason, many mathematicians, and computer scientists rely upon algorithms and computers to test these kind of problems. There is a lot of underlying math to this problem, some of which you can see at Wikipedia, and Wolfram Alpha. I'm not going into the math. Here is the code:


/* Implementation of Collatz Conjecture/ Hasse's Algorithm/ Syracuse Problem in Java using Recursion */
import java.util.Scanner;

public class CollatzConjecture {
    public static void Collatz(int x) {
        System.out.print(x + ", ");
        if (x == 1) {
           return; 
           // If x is 1, then the function is terminated
        } 
        else if (x % 2 == 0) {
           Collatz(x / 2);       
           // If x is even, then function is called with the argument x/2
        } 
        else if (x % 2 != 0) {
           Collatz((3 * x) + 1); 
           // If x is odd, then function is called with the argument 3x+1
        }
    }

    public static void main(String[] args) {
       System.out.print("Collatz Conjecture");
       System.out.print("\nEnter the starting number: ");
       Scanner in = new Scanner(System.in);
       int n = in.nextInt();
       Collatz(n);
       in.close();
   }
}

I have used recursion to carry out the iteration, you may also use any loop of your choice.
Here is a sample output. As you can see, even a number as small as 27 takes 111 steps to reach unity, and it touches a number as large as 9232 on its way!

27 reaches unity, taking 111 steps, touching the maximum 9232 on its way!


Don't jump into conclusions though. Specific numbers, as large as 1024, takes only 10 steps to reach 1. This is because 1024 is the tenth power of 2.

1024 reaches unity faster, because it is a power of 2


From these examples, it is safe to say that the number of steps taken is purely depended upon the nature of the number. Some numbers tend to reach 1 faster, and some takes a larger amount of time. This is the magic of Mathematics!

*Conjecture - An unproved proposition
Happy Coding!
:)

Friday 30 May 2014

Project Euler : Problem #2 - C++ Solution

This time, the problem is:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
I'm using a do-while loop here. Here is the code:
#include <iostream>
using namespace std;

int main()
{
    int a = 0, b = 1;
    int c, answer = 0;
    do{
        c = a + b;
        a = b;
        b = c;
        if(b%2==0){answer = answer + b;}
    }while(b<=4000000);
    cout<<"Answer is "<<answer;
    return 0;
}

Thursday 1 May 2014

Project Euler : Problem #1 - C++ Solution


I was recently wandering around the internet, and I found out this awesome website, with some great mathematical problems which has to be solved using any programming language. You can easily get into the website by searching for "Project Euler" on Google. It has a great set of problems, to sharpen your problem solving skills in any programming languages. Here I'm posting the solution to the first problem. I will try to continue to give more solutions to more problems.

The problem is :

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
First go ahead an try to solve it on your own, and then refer the solution.
The solution to the problem is given below:


#include<iostream>
#include "conio.h";
using namespace std;
int main()
{
    int i;
    int result = 0;
    for(i=0;i<1000;i++)
    {
          if( i%3==0 || i%5==0 )
          {
                result = result + i;
          }    
    }
    cout<<"The answer is "<<result;
    getch();
    return 0;
}

Here is the output:

 :)

Tuesday 11 March 2014

Signing off... (for a while)

Heyyyyy! Just staying away from the computer for a while (exams...).. Will be back in some days!

Code the world away guys!!!
 :)

Monday 10 March 2014

Date Calc - Software Free Download!

Here is the software, the source code of which I had posted recently on this blog (here).

You can download the file from these links:

  • As .exe file  -   from here
  • As .rar file   -   from here

    Please give us your feedback by commenting below to keep us motivated!

Trace of a square matrix - C++ Program source code

Trace of a square matrix is the sum of elements of the principal diagonal of the matrix.

So without any intro, let's move on to code:
Code:
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
    int mat[100][100],tr=0,i,j,m,n;
    cout<<"Enter the order of the matrix : \n";
    cin>>m>>n;
    while(m!=n){
        cout<<"Not a square matrix!\n";
        exit(0);
    }
    cout<<"Enter the elements of the matrix : \n";
    for(i=0;i<m;i++){
        for(j=0;j<n;j++){
            cin>>mat[i][j];
        }
    }
    cout<<"The matrix is : \n";
    for(i=0;i<m;i++){
        for(j=0;j<n;j++){
            cout<<mat[i][j];
            cout<<"\t";
        }
        cout<<endl;
    }
    for(i=0;i<m;i++){
        for(j=0;j<n;j++){
            if(i==j){
                tr = tr + mat[i][j];
            }
        }
    }
    cout<<"The trace is "<<tr;
}

Working:
First we input the order of the matrix. If number of columns is not equal to number of rows, the matrix is not a square matrix and will not have a trace. So if they aren't same, the program terminates using exit(0) [in the header <cstdlib>]. Now inside a nested for loop, if an element is on the principal diagonal, then the trace tr, initially set to zero, adds itself to the element. At the end of the loop, tr will be equal to the sum of diagonal elements. 
A couple of sample outputs is given below:




Happy Coding!
:)


Saturday 8 March 2014

Adding an icon to a Dev-C++ Program

If you go to the Dev C++ folder, you can find the .exe file of the program, but the icon will be the old default clumsy one. Just for an example let me create a small program and show you the exe file. Here ya go!


To change the icon, you need two things :
1. Dev-C++                    2. .ico file


.ico file basically is just an image file which is used as an icon. You can easily find an ico creator or an ico converter online.


  • In Dev-C++, click on Project -->  Project Options.

                

  • Click on the 'Browse' button in the icon section.


  • Click on the 'Browse' button in the icon section.
  • Navigate to the .ico file and click Ok.



  • Now compile the program again, and the desired program will have the icon you selected!


Happy Coding!
:)

Tuesday 4 March 2014

Days Between Two Days Calculator - C++ Program Source Code

Hey there! Here is an awesome program which outputs the number of days between two given dates! This program is particularly useful for students like me, who wants to calculate duration to the day of examination. No time for working now, but I will update it later!
Code:

#include<iostream>
#include "process.h";
using namespace std;
int main()
{

      int days_in_months[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
      int day1, day2;
      int month1, month2;
      int year1, year2;
      int y_diff, d_diff;
      int tot_mon;
      int years = 365;
    
      cout<<"Program to calculate how many days are in between the day/month/year entered"<<endl;
      cout<<endl;

  start:
      cout<<"Please enter the date by day, month, year"<<endl;
      cout<<endl;

      cout<<"First date : "<<endl;
      cout<<endl;

      cout<<"Day : ";
      cin>>day1;
      if(day1 > 31 || day1 <= 0)
      {
          cout<<"Incorrect day entered"<<endl;
          cin.ignore();
          return 0;
      }
      cout<<"Month: ";
      cin>>month1;
      if(month1 > 12 || month1 <= 0)
      {
          cout<<"Incorrect Month entered"<<endl;
          cin.ignore();
          return 0;
      }
      cout<<"Year: ";
      cin>>year1;
      if(year1 > 9999 || year1 < 0)
      {
          cout<<"Incorrect Year Entered"<<endl;
          cin.ignore();
          return 0;
      }
 
      cout<<endl;
      cout<<"\nSecond date:: "<<endl;
      cout<<endl;

      cout<<"Day: ";
      cin>>day2;
      if(day2 > 31 || day2 <= 0)
      {
          cout<<"Incorrect day entered"<<endl;
          cin.ignore();
          return 0;
      }
      cout<<"Month: ";
      cin>>month2;
      if(month2 > 12 || month2 <= 0)
      {
          cout<<"Incorrect Month entered"<<endl;
          cin.ignore();
          return 0;
      }
      cout<<"Year: ";
      cin>>year2;
      if(year2 > 9999 || year2 < 0)
      {
          cout<<"Incorrect Year Entered"<<endl;
          cin.ignore();
          return 0;
      }
 
      if(year1 == year2)
      {
          y_diff = 0;
      }
      else
      {
         if(year1 % 4 == 0 && year1 % 100 != 0 || year1 % 400 == 0)
         {
             if(year2 % 4 == 0 && year2 % 100 != 0 || year2 % 400 == 0)
             {
                if(year1 > year2)
                {
                     y_diff = (year1 - year2) * (years) + 2;
                }
                else
                {
                     y_diff = (year2 - year1) * (years) + 2;
                }
                if(month2 > month1)
                {
                    if(days_in_months[month1 - 1] > days_in_months[1])
                    {
                        --y_diff;
                    }
                }
             }
             else
             {
                if(year1 > year2)
                {
                    y_diff = (year1 - year2) * (years) + 1;
                }
                else
                {
                    y_diff = (year2 - year1) * (years) + 1;
                }
                if(month1 > month2)
                {
                    if(days_in_months[month2 - 1] > days_in_months[1])
                    {
                        --y_diff;
                    }
                }
             }
         }
         else
         {
            if(year1 > year2)
            {
                y_diff = (year1 - year2) * (years);
            }
            else
            {
                  y_diff = (year2 - year1) * (years);
            }
         }
     }
 
     if(month1 == month2)
     {
         tot_mon = 0;
     }
     else
     {
         if(month1 > month2)
         {
             for(int i = (month1 - 1); i > (month2 - 1); i--)
             {
                  static int tot_mon_temp = 0;
                  tot_mon_temp += days_in_months[i];
                  tot_mon = tot_mon_temp;
             }
         }
         else
         {
             for(int i = (month1 - 1); i < (month2 - 1); i++)
             {
                  static int tot_mon_temp = 0;
                  tot_mon_temp += days_in_months[i];
                  tot_mon = tot_mon_temp;
             }
         }
     }

     int days_total;

     if (day1 == day2)
     {
        d_diff = 0;
        days_total = (y_diff + tot_mon) - d_diff;
     }
     else
     {
        if(day1 > day2)
        {
            d_diff = day1 - day2;
            days_total = (y_diff + tot_mon) - d_diff;
        }
        else
        {
            d_diff = day2 - day1;
            days_total = (y_diff + tot_mon) + d_diff;
        } 
     }

     if(year1 == year2)
     {
     }
     else
     {
        if(year1 > year2)
        {
           for(int i = (year2 + 1); i < year1; i++)
           {
               if(i % 4 == 0 && i % 100 != 0 || i % 400 == 0)
               {
                  cout<<endl;
                  cout<<i<<endl;
                  ++days_total;
               }
           }
       }
       else
       {
           for(int i = (year1 + 1); i < year2; i++)
           {
                if(i % 4 == 0 && i % 100 != 0 || i % 400 == 0)
                {
                     cout<<endl;
                     cout<<i<<endl;
                     ++days_total;
                }
           }
       }
  }

 here:
     cout<<"\nInclude the end date? (Y/N) : ";
     char ch;
     cin>>ch;
     if(ch=='Y'||ch=='y')
     {
          cout<<endl;
          cout<<"\nThe total days in between your dates are: "<<days_total<<endl;
          cout<<endl;
     }
     else if(ch=='N'||ch=='n')
     {
         cout<<endl;
         cout<<"\nThe total days in between your dates are: "<<(days_total-1)<<endl;
         cout<<endl;
     }
     else
     {
         cout<<"Invalid choice, try again!";
         goto here;
     }
 here2:
     cout<<"\n\nCheck with another pair of dates? (Y/N)"<<endl;
     char ch2;
     cin>>ch2;
     if(ch2=='Y'||ch2=='y')
     {
         goto start;
     }
     else if(ch2=='N'||ch2=='n')
     {
         exit(0);
     }
     else
     {
          cout<<"Invalid choice, try again!";
          goto here2;
     }
     cin.get();
     cin.ignore();
     return 0;
}


Happy Coding!
:)

Saturday 1 March 2014

Switch Statement Example - Number to Day Converter

Let me first clear up the aim. User enters a number from 1 to 7 and we output corresponding day, where 1 is Sunday and 7 is Saturday. We here use 'switch' statement, the syntax of which is given:
switch(expression){
                 case constant - 0:
                           statement(s);
                           break;
                 case constant - 1:
                           statement(s);
                           break;
                               .
                               .
                               .
                 case constant - (n-1):
                           statement(s);
                           break;
                 default:
                           statement(s);
       }

Code:

#include<iostream>
#include "conio.h";
using namespace std;
int main()
{
    int ch;
    cout<<"Enter the number of the day\n";
    cin>>ch;
    switch(ch)
    {
              case 1:
                   cout<<"Sunday";
                   break;
              case 2:
                   cout<<"Monday";
                   break;
              case 3:
                   cout<<"Tuesday";
                   break;
              case 4:
                   cout<<"Wednesday";
                   break;
              case 5:
                   cout<<"Thursday";
                   break;
              case 6:
                   cout<<"Friday";
                   break;
              case 7:
                   cout<<"Saturday";
                   break;
    }
    getch();
}
Working:
           We just input the number from the user, and output corresponding days using switch statement. Switch statement is just like an if-else statement.

Sample output of the above program is:



Happy Coding!
:)

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

Wednesday 8 January 2014

Changing color of output window in Visual C++

Okay. Have you ever wondered how it would be to try something different than the same old black and white output window? Then this post is just for you.

For this, you will have to use the Visual C++ IDE [ :'( ]. Here are the steps:

1.You must add the header <windows.h>
2. The statement to change the color is :
system("color <color_code>");
 Color code is a couple of hexadecimal numbers, the first one corresponding to background color and the second one to font color.
Here is a simple example:

    #include<windows.h>
    void main()
    {
        system("color 95");
    }
This program renders the background color of output window as blue and font color as purple!


You can try different hexadecimal numbers instead of numbers to change the color according to your will. Here is the list of numbers and corresponding colors:

0 = Black                                    8 = Gray
1 = Blue                                      9 = Light Blue
2 = Green                                   A = Light Green
3 = Aqua                                    B = Light Aqua
4 = Red                                      C = Light Red
5 = Purple                                   D = Light Purple
6 =  Yellow                                  E = Light Yellow
7 = White                                    F = Bright White

e.g., If you want a Light Green background with Blue font in it, the statement should be
system("color A1");
You could play around with this command and have lots of fun with it!

NOTE : "color" is not to be confused with "colour" because former is American spelling and latter is British. Most of the programming and scripting languages use American spelling.

That's all for today folks.... Later!


You might also like