Wednesday, October 15, 2014

Trick SQL Interview Question and team work

I was sitting with friends at our legendary Firdos Market flat 94/H just yesterday. Adeel my brother, told us about a query that an interviewer had asked him to solve. It was dinner time, so we handed the query to Zaheer Chaudhary, who'd eaten a couple of hours ago.

After the dinner, Aweas Dar, Adeel's class fellow (Zaheer is also a class fellow), opened SQL Server and created table structures needed for the operation. The trio I just mentioned graduated in computer science from the University of Gujrat(UoG) in 2012.
All of us sat down and started talking about the query. The problem statement is given below:
subjects-table-design"
Suppose we have two tables, students and subjects. The student's table contains two fields id and name. The subjects table contains three fields: id, std_id, and subject.
students-table-design
When executed, we need a query to produce the result set with columns describing how many courses each student is taking. In a better version of the result set, we will have a student id, student name, and several subjects.
"



Table structures are also given above for reference.
Everybody knew that we would need to do a count on the subject field of the subjects table. So we wrote a couple of queries, poked some jokes at each other, and ultimately achieved the desired result.
Unfortunately, I couldn't save various versions of the query as it evolved.







Aweas also keyed in dummy data rows. Below is a screenshot of student table data and subjects table data.

select-top-students

select-top-subjects

Next, it occurred to us that we will need to use SQL Group By in this situation. The possibility of using a join was ruled out quickly, and finally, the SQL where clause was also needed.
The final SQL query was made even more beautiful by adding an ORDER BY clause. The result of our quick teamwork is the SQL Query given below.

SELECT students.id AS StudentID, students.name AS Students, COUNT(subjects.subject) AS NoOfSubjects
FROM subjects, students WHERE subjects.std_id=students.id GROUP BY students.name, students.id
ORDER BY StudentID

There are small emotional holes that we leave unplugged due to laziness. We could have left the query unsolved and kept thinking about it for a long time. Some of us would even feel guilty that we could not sort it out. This event shows the importance of teamwork and how a cooperative thought process can help us to solve puzzling questions and crack jokes.

Sunday, October 5, 2014

Framework vs IDE

Microsoft Visual Studio 2012 is an IDE(Integrated Development Environment), whereas Microsoft .Net 4.5 is a Platform.
Android is a Framework/Operating System, and Eclipse is an IDE.
I started off with solid examples of framework and IDE since I believe these will facilitate further explanation.
Microsoft Visual Studio 2012

Putting the term IDE in perspective?

It is a group of various tools  which work together to compile a computer program, and create an executable package.
dotnetframework-4

For example, on Windows we have Microsoft Visual Studio in which you can create a project and write some code. You just need to click a button or two and an execute-able file with extension .exe will be generated which you could take to any suitable computer and run.

Another example Android platform, you can write some code in C++ or maybe Java and use an IDE of your choice which might be Eclipse, Android Studio, or any other and click a few buttons, an executable package or .apk will be created for you which you may copy to any suitable Android device, install and run right away.
android-os-logo

Explaining Integrated Development Environment

When we click a button inside an IDE and order it to create a nice package for us, a lot of things happen in the background. For example code of both .Net and Java languages need to be converted into a "byte code" which is then interpreted by the Java Machine/Common Language Runtime. There is a software tool which performs this task.
eclipse-juno-ide

But before going on with the conversion, someone needs to make sure that the code supplied as the brick and mortar of your awesome software is correct or not. Incorrect code cannot be used to generate correct software. You must have guessed it by now, there is a separate tool which performs the job of error checking and compiling.
Yet another tools is the notepad like editor in which you type code, it automatically makes the code look pretty and colorful. This part is called "pretty printer" and it too is a separate tool.
There are numerous other tools, but let's just stop here and imagine that we got only three tools

  1. One that makes the code look pretty as we type it
  2. One that's responsible for making sure that our code is correct
  3. One that makes a software package (.exe or .apk) out of our correct code
All three of these tools need to work together and cooperate, and do their job in an integrated fashion so that you can retain your development job.
When various tools work together in an integrated fashion, we get an integrated environment for development. Just to make things look uglier, an Integrated Development Environment.

visual-studio-code-pretty-printing


Framework Explained
A framework is a set of various software tools and standards which work together and make a computer programmer's job easy. A framework might contain things like
  1. Application Programming Interface (API)
  2. Just in time (JIT) compiler
  3. Virtual machine (JVM/CLR)
  4. Standards for making various language work together e.g. CTS or common type system(C#, F#, C++/CLI)
For a detailed description of framework, examples, and comparison with API please see following article:


I'm working as a full time freelance programmer through ODesk.com, I have a strong profile over there. Feel free to ping me if you need an Android app. Elance widget is given on top right of the page, for ODesk follow the link given below:


https://www.odesk.com/users/~012d73aa92fad47188

Saturday, October 4, 2014

c++ string to char array

C++ standard template library (STL) string A.K.A std::string was a novel concept back in the day when it was first introduced to the programming community with C++ programming language. Now we see every programming language be it Java or C# or Ruby contains an excellent implementation of string. Similarities between the modern string libraries can be traced back to yesteryear's string.h header file.

It is important to note that the std::string classes were actually a wrapper around C style null terminated character pointer string.

c-plus-plus-string-char-array-code

Even the apparently sophisticated(and complicated) BSTR of COM era are just a sequence of characters with some meta data(i.e. length of string).

c++ string to char* code

Since we know every std::string actually contains a char * (read character pointer) buffer in the background, there must be some way to convert C++ string to C style char array. The character arrays are also called zero terminated strings.







The good news is that there is a function in std::string class which lets us retrieve the const char * which is in the background of the string instance. The method is called

c_str

An exact example in code about how to use std::string.c_str() function is given below.

Code C++ string to char * or char array

using namespace std;

#include<string>
#include<iostream>

int main(int argc, char* argv[])
{
 std::string strILoveYou = "i<3U";// new object of std::string

 const char * szMe2 = strILoveYou.c_str();// new object of c style null terminated character pointer

 cout << strILoveYou << endl; 
 cout << szMe2  << endl;

 return 0;
}// code highligting with http://tohtml.com/cpp/


You must have noticed that the const char * retrieved this way is read only. If you want to extract a changeable string out of std::string we'll need to add a couple of lines to the code. We will use the strcpy C function, some might argue that this is not true C++ but I say everything from C is in the genesis of C++ so there's nothing untrue to spirit of C++ if we use functions from the C programming language which is the mother of all languages. The new code will look like

using namespace std;

#include<string>
#include<iostream>

int main(int argc, char* argv[])
{
 std::string strILoveYou = "i<3U";

 const char * szMe2 = strILoveYou.c_str();

 char * notConstantCharPtr = new char[strILoveYou.length()]; 
 strcpy(notConstantCharPtr, strILoveYou.c_str());

 cout << strILoveYou  << endl; 
 cout << szMe2   << endl;
 cout << notConstantCharPtr << endl;

 return 0;
}// highlight with tohtml.com/cpp

HAPPY CODING FELLAS!!!
I hope you found this small programming tutorial to be useful. Please do check my online courses which are listed on the top right of this page.

Thursday, October 2, 2014

C# Nested Switch Statement

Nested Switch C#Net code


private void button1_Click(object sender, EventArgs e)
        {
            switch(textBox1.Text){// outer switch statement c#
                case "1":
                    System.Diagnostics.Debug.Print("1");
                    switch (textBox2.Text)// inner switch statement c#
                    {
                        case "a":
                            System.Diagnostics.Debug.Print("1a");
                            break;
                        case "b":
                            System.Diagnostics.Debug.Print("1b");
                            break;
                        default:
                            System.Diagnostics.Debug.Print("1NA");
                            break;
                    }
                    break;
                case "2":
                    switch (textBox2.Text)// second nested switch statement c#.net
                    {
                        case "a":
                            System.Diagnostics.Debug.Print("2a");
                            break;
                        case "b":
                            System.Diagnostics.Debug.Print("2b");
                            break;
                        default:
                            System.Diagnostics.Debug.Print("2NA");
                            break;
                    }
                    break;
                case "3":
                    switch (textBox2.Text)// third nested switch statement in c#
                    {
                        case "a":
                            System.Diagnostics.Debug.Print("3a");
                            break;
                        case "b":
                            System.Diagnostics.Debug.Print("3b");
                            break;
                        default:
                            System.Diagnostics.Debug.Print("3NA");
                            break;
                    }
                    break;
                default:
                    switch (textBox2.Text)// default section of outer switch statement
                    {
                        case "a":
                            System.Diagnostics.Debug.Print("DEFAULTa");
                            break;
                        case "3b":
                            System.Diagnostics.Debug.Print("DEFAULTb");
                            break;
                        default:
                            System.Diagnostics.Debug.Print("DEFAULTNA");
                            break;
                    }
                    break;
            }
        }

Please note that the same nested switch logic can be reused in C++ and Java languages with a little language specific changes.

Switch statement is a very important programming language construct, appropriate usage can significantly speed up your code.
Keeping the importance of nested switch statement I've decided to put together a quick code example and make it available for the welfare of programmer community.

Example Background:
In case of this C# switch statement example, we have two text boxes and a button placed on a WinForm, when the user puts some text inside the first text box some text in second text box and then clicks the button our switch statement is fired in a button click handler.

The results are being printed using System.Diagnostics.Debug.Print function which cause them to show up in output console.

The user can enter 1, 2, or 3 in first text box and values a, b, or c in second text box. Anything else is handled in nested default sections.




C# .Net nested switch might not be used very commonly, but you never know when you'll run into a problem that's better handled by the gimmick like consumption of the construct. The exact code of a nested switch statement in C# .Net programming language is given at the beginning of this article.


Wednesday, October 1, 2014

C++ char array to string

The c style null terminated arrays might be considered a thing of past by many but as a matter fact these things are still there are used in many many large scale legacy software.\

Just recently I observed that a lot of people are trying to find an easy way to make a string out of a character array in C++ so I thought I should write a post and help the poor souls stuck in dark chambers of C++.

Without any further ado, the C++ code to achieve this extremely difficult task is given below.

char array to string c++