Subarray with given sum

Given a list of integers,our task is to find if a sub-sequence which adds to a given number exists or not.

Example-

The given list is (1,4,20,5,5) and the given number or sum is 29.
Then,the sub-sequence which adds to 29 is (4,20,5).

Brute Force-

All the sub-sequences are considered and its sum is compared with the given value.Its time complexity is O(N^2).

Code-

[cpp]

//arr[0…N-1] contains the given integers
// and the given number is X.
for(i=0;i<N;i++)
{
s=arr[i];
for(j=i+1;j<N;j++)
{
s=s+arr[j];
if(s==X) return 1; // sub array found
}
}
return 0; //sub-array not found
[/cpp]

Efficient Code-

Algorithm-

1. Initialize a variable curr_sum as first element.
2. Start from the second element and add all elements one by one to the curr_sum.
3. If curr_sum becomes equal to X, then a sub-sequence/sub-array is found.
4. If curr_sum exceeds X, then remove trailing elements one by one until curr_sum is less than X.

Its time complexity is O(N).

Code-

[cpp]
{
curr_sum=arr[0];
start=0;

for (i = 1; i <= n; i++)
{
// If curr_sum exceeds X, then
// remove the starting elements

while (curr_sum > X && start < i-1)
{
curr_sum = curr_sum – arr[start];
start++;
}

// If curr_sum becomes equal to X,
// then return true

if (curr_sum == X)
{
return 1; //sub-array found
}

// Add this element to curr_sum

if (i < n)
curr_sum = curr_sum + arr[i];
}
return 0; //sub-array not found
}

[/cpp]

Android development primer: Looking into Eclipse IDE

This post is aimed at giving you a little idea about what Eclipse IDE is and how you can use it’s features to the fullest for relatively faster coding. This is based strictly on it’s use in Android Development.

  • Eclipse is a multi-language Integrated Development Environment.
  • In it’s primitive form it is mostly used for writing Java programs.
  • It can be used, with the help of various plug-ins, to develop applications in an array of languages. Some of the most widely used ones are C, C++, PHP and Python.
  • If we are not speaking strictly, we can say it is similar to any WYSIWYG editor.

If we look into what and how it can help us in Android Programming, a couple of striking features are present. They are described in layman terms.

XML ASSISTANCE

  • It allows developers having little or no knowledge of XML to create layouts.
  • It allows Dragging and Dropping of elements from Palette to the Layout. It adds the required source code to XML automatically.
  • It allows for changing the attribute values of elements from the Properties tab. The source code is edited to reflect the changes made.
  • If the attributes of a particular element is changed, it allows for reflection of the changes in all codes in a project where this element might have been referred. It saves the programmer both time and effort.
  • The elements can be added in different configurations depending on the type of Layout selected. While dragging and dropping, Eclipse understands this layout and places the elements accordingly. For instance, in Relative Layout it allows for attributes like android:toLeftOf and android:toRightOf etc. In Linear Layouts it doesn’t allows such attributes.
  • It also understands the orientation of layouts.

CODE HINTING

  • Code Hinting refers to a feature where the IDE guesses the commands you want to enter as soon as you enter a few letters and it presents you with suggestions.
  • Ctrl+Space in Windows and Cmd+Space in Mac is the default key combination for Code Hinting.
  • While typing long statements, hit the Code Hinting key combination and choose the suitable statement from the list of statements presented.
  • Based on the SDK you are using for Android, Eclipse tells you whether some functions and features are out of date. They are deprecated by Eclipse.
  • It shows warnings and errors progressively as you type in statements so you know whether you have got the syntax and function arguments correct.

Although these may not seem very useful or time-saving in the initial stages of development, but they save a lot of effort when you are in the later stages and every single code in your project consists of more than a hundred lines.

Android development primer: Multiple Screen Support for Android, using Intents

We saw that on creating an Android Application Project, a skeleton “Hello World” application is created. The “Hello World” module is always the first step to learning anything. I’m sure you did a Hello World program when you were learning your first programming language. Quite boring isn’t it? Well, let’s get a bit creative.

We will add a few elements to our application and see how they work.

Create a new application project or edit the Hello World Application. Open up the MainActivity.java file and activity_main.xml and get ready for some coding.

If you have a problem while adding code snippets to you code, please have a look at the complete code at the bottom.

In the activity_main.xml follow the below steps:

  • Drag and drop an EditText from the Palette on the left.
  • Drag and drop a Button from the Palette on the left.
  • Click on the EditText and it’s properties should appear on the Properties tab to the right. If it doesn’t, Right Click->Show In->Properties.
  • Edit the Id attribute of the EditText to “@+id/et” and click Yes/OK on any dialog that appears. Remember the name.
  • Click on the Button and it’s properties should appear on the Properties tab to the right. If it doesn’t, Right Click->Show In->Properties.
  • Edit the Id attribute of the Button to “@+id/but” and click Yes/OK on any dialog that appears. Remember the name.
  • For now, leave the EditText and the Button in their respective places. We will concentrate on how to make them work and not how to place them in the layout.

Save the activity_main.xml.
Now follow the below steps carefully:

  • Navigate to <yourpackagename> -> src. Right Click on <com.yourname.yourappname> and select New -> Class.
  • You are creating a new Class. In the Name field enter Second.
  • In the Superclass browse and type Activity. Select the android.app.activity. This makes your class an Activity.
  • Hit Finish and you the class opens up.
  • Navigate to <yourpackagename> -> res -> layout. Right Click on <com.yourname.yourappname> and select New -> Android XML File.
  • Name it second and choose relative layout from the Root Element list.
  • Hit Finish and the XML file opens up.

In the Second.java file add the following code inside the class.

[java]
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
}
[/java]

If you have read my previous posts you will know exactly what we are doing here.

Now open second.xml and follow the below steps:

  • Drag and drop a TextView and change the Id attribute to “@+id/tv”.
  • Enter in the Text attribute – “This is the second Activity.”

Save second.xml. Switch over to MainActivity.java and add the following code in the onCreate() function.

[java]
Button but = (Button) findViewById(R.id.but);
EditText et = (EditText) findViewById(R.id.et);
but.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,Second.class);
startActivity(intent);
}
}
);
[/java]


As you type in the first statement, you’ll notice that Eclipse places a small cross so as to indicate there is an error in that line. What is the error? We have not imported the Android Button widget in our activity and so Eclipse doesn’t know what we mean when we type in “Button”. Hit Ctrl+1 on your keyboard. This is a shortcut to bring up suggested fixes to the errors. Select Import ‘Button’ (android.widget). You will now see that the statement just after the ‘=’ symbol is now erroneous. Hit Ctrl+1 again and select Add cast to ‘Button’. This way we have used type casting and import statements with which you must already be familiar from your Java knowledge. Do the same for the EditText statement.

  • OnClickListener() :  This adds a listener to the button that triggers when it is clicked
  • OnClick() : Holds the set of instructions that need to be executed when the button is clicked
  • Intent : This is a very important feature of Android. For the time being, it’ll be sufficient for you to know that an Intent is used to call other Activities. We can also pass data using this across activities. We’ll see this in a while. The syntax of the constructor is new Intent(<currentactivityobject>, <destinationactivityclass>). The object of current activity is MainActivity.this and the class of the destination activity is Second.class.
  • startActivity() : It is used to start off a new activity while pushing the current one to the Back Stack. It takes an intent as an argument.

What we’ve done is we’ve added a button and configured it to fire the Second Activity when clicked. Run this application using the emulator. When the MainActivity is up and you click the button to go to the second Activity, your application will crash unexpectedly. Why? Because we have not added the Second activity to the AndroidManifest.xml file.

How do you get to know what went wrong? Well, here’s how. On the top right you can see Java and DDMS. DDMS (Dalvik Debug Monitor Server) tells you exactly what went wrong. Click on it and scroll to the top of the group of lines in red. You will see ActivityNotFoundException. It also says – “Have you declared this activity in your AndroidManifest.xml?”. So that’s how we know that we haven’t declared the Second activity in the Android Manifest file.

The Android Manifest file needs to recognize each and every activity in your application.

  • Open up AndroidManifest.xml file from the project contents list and from the tabs at the bottom select AndroidManifest.xml
  • Just before </application> add this – <activity android:name=”.Second” />
  • Save.

Launch the application again and this time it should work just fine. 🙂

You must be wondering why we did not make use of the EditText that we added to the layout. I told you before that we can send data across activities using Intents. That is preciseld what this EditText is for. Here we go.

  • Add this line in the MainActivity.java before the startActivity() function :-
    [java]
    intent.putExtra(“data”, et.getText().toString());
    [/java]



  • Add the following lines in Second.java after the setContentView() function :
    [java]
    TextView tv = (TextView) findViewById(R.id.tv);
    tv.setText(getIntent().getStringExtra(“data”));
    [/java]

As you can see we can set the text to be displayed in the TextView from java too and this takes precedence over the xml.
What we have done here is that we will be displaying whatever text the user enters in the MainActivity in the Second Activity. Launch the application and see it work.

img1    img2

COMPLETE SOURCE CODE :

MainActivity.java

[java]
package com.nero.myfirstapp;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class Main extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button but = (Button) findViewById(R.id.but);
final EditText et = (EditText) findViewById(R.id.et);
but.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
Intent intent = new Intent(Main.this,Second.class);
intent.putExtra(“data”, et.getText().toString());
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
[/java]

Second.java

[java]
package com.nero.myfirstapp;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Second extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
TextView tv = (TextView) findViewById(R.id.tv);
tv.setText(getIntent().getStringExtra(“data”));
}
}
[/java]

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<EditText
 android:id="@+id/et"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignParentLeft="true"
 android:layout_marginLeft="30dp"
 android:ems="10" >

<requestFocus />
 </EditText>

<Button
 android:id="@+id/but"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignLeft="@+id/et"
 android:layout_below="@+id/et"
 android:layout_marginLeft="53dp"
 android:text="Button" />

</RelativeLayout>

second.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
 android:id="@+id/tv"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignParentLeft="true"
 android:layout_alignParentTop="true"
 android:text="This is the second Activity" />

</RelativeLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.nero.myfirstapp"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
 android:minSdkVersion="7"
 android:targetSdkVersion="17" />

<application
 android:allowBackup="true"
 android:icon="@drawable/ic_launcher"
 android:label="@string/app_name"
 android:theme="@style/AppTheme" >
 <activity
 android:name="com.nero.myfirstapp.Main"
 android:label="@string/app_name" >
 <intent-filter>
 <action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
 </activity>
 <activity android:name=".Second" />
 </application>

</manifest>

Binary Search

This is a short note on using binary search, in continuance of my series on Algorithms.

Suppose we have to find whether a particular element exists in the sorted list of N numbers or not.
Let “arr” be the array which contains the N elements and the element to be searched is “key”.
Then, the time complexity using brute force will be O(N).

CODE-

[cpp]

for(i=0;i<N;i++)
{
if(arr[i]==key)
{
printf(“Element is found\n”);break;
}
}

[/cpp]

But,using binary search,the time complexity will be O(log(N)).A binary search halves the number of items to be checked each time and thus has logarithmic complexity.

ALGORITHM-

In this algorithm,the key is compared with the middle element of the array.
Cases:
1.If the middle element is equal to the key,then the search is completed.
2.If the key is less than the middle element,then the algorithm is repeated on the sub-array to the left of the middle element.
3.If the key is greater than the middle element,then the algorithm is repeated on the sub-array to the right of the middle element.
4.If the remaining array to be searched is empty,then the key cannot be found in the array and the search is completed.

CODE-

Recursive solution-

[cpp]
int binarysearch(int arr[],int key,int beg,int last)
{

// beg and last indicate the starting and ending indices of the subarray.
// Initially,beg has the value 0 and last has the value n-1.</em>

if(beg >last) return 0; // key not found</em>

else
{
int mid=(beg+last)/2; // finding the middle element</em>

if(key==arr[mid])return 1; // key found</em>

else if(key < arr[mid]) return binarysearch(arr,key,beg,mid-1);

else
return binarysearch(arr,key,mid+1,last);
}
}
[/cpp]

NOTE- Binary Search is used only when the given list is sorted.If the list is unordered,brute force is better as sorting will have a complexity of O(N*log(N)).

Linux intro and Basic commands

Linux is a Unix-like computer operating system. Linux was originally developed as a free operating system for Intel x86-based personal computers. Now its popular on PCs, tablets, smart phones,  and is a leading operating system on servers and other big iron systems such as mainframe computers and supercomputers.

Best Linux quotes–

“The box said ‘Required Windows 95 or better’. So, I installed LINUX.”
“A Windows user spends 1/3 of his life sleeping, 1/3 working, 1/3 waiting.”
“We all know Linux is great, it does infinite loops in 5 seconds.”
“Avoid the Gates of Hell. Use Linux.”
“..Linux really *is* the best thing since sliced bread.”
“Linux: the operating system with a CLUE, Command Line User Environment.”
“I develop for Linux for a living, I used to develop for DOS.Going from DOS to Linux is like trading a glider for an F117.”

Advantages of LINUX over Windows–

Cost– Linux is available free (as in free food) !
Security– Linux is perceived as more safe that Windows. Which means Linux does not require any anti-virus which again reduces comparative cost even further.
Open Source – With Linux technically, you have the power to control just about every aspect of the operating system.
Software on Linux tends to be packed with more features and greater usability than software on Windows.

Although Linux is as user friendly and intuitive to use as Windows, it will help programmers if they know the basic Linux commands.

This blog lists all those commands for LINUX based FILE system that a beginner should know. These are the basic commands which are generally asked on Linux usage in the interviews too.

1. pwd – To view the present working directory.
2. mkdir directory_name – To create a new directory in the present working directory.
3. cd – To change working directory. Example- cd /home/new/help
4. ls -l -To list the files as well as directories present in the particular working directory.
5. ls -la – It lists the hidden files or directories as well.
6. touch file_name.ext – To create a new file with a name and extension.Extension is not necessary.
7. cat file_name – To view the contents of the file.
8. vi file_name – To insert data in the file.After entering this command,press I and then type the data you want to enter.To quit,command is ‘ :wq ‘.
9. rm file_name – To remove an empty file.
10. rmdir directory_name – To remove an empty directory.
11. rmdir -r directory_name – To remove a directory which contains subdirectories or files.’r’ stands for recursion.
12. clear – To clear the screen.Shortcut is Ctrl+L.
13. useradd user_name – To add a new user.
14. passwd user_name– To change the existing password of a user.
15. groupadd group_name – To add a new group. Many users form a single group.
16. userdel user_name – To delete a user.
17. groupdel group_name -To delete a group.
18. cp source_path destination_path– To copy something in a file or directory.Example of source path or destination path – /home/mango/abcd.txt
19. mv source_path destination_path – To move something in a file or directory.
20. su – user_name – To switch from one user to another user.

MASTER command—

command_name info – To view the information about any command.Example: mkdir info

Android development primer: Layout elements in Android

I’m sure when you look at the Graphical Layout of any xml file in Android, what catches your attention more than the layout itself is the long list of elements on the left, called Palette. Well, here’s a list of a few frequently used Layout elements and their functions.

FORM WIDGETS

  • TextView Large/Medium/Small : This element is used to display a static text in the layout. It is available in three sizes Large, Medium and Small.
  • Button/Small Button : Well, it’s a button. Just like buttons on webpages are required to achieve a certain tasks, so it is used here. Although in reality a button is touched in an Android device to trigger it’s function, we’ll be referring it as a click hereafter.
  • CheckBox : If you want your users to have options from which they can select more than one, you are going to need checkboxes.
  • RadioButton : If you want your users to have options from which they can select only one, you are going to need radio buttons.
  • ProgressBar Large/Small/Horizontal : It is a progress bar that you might require if your application is in the middle of something and a screen staring at the user in the meantime, is just not your style.

TEXT FIELDS

  • All this field contains, is lots and lots of EditText. An EditText is used to create a text field where the user can provide a written input.
  • There are various types of EditTexts. They differ in their “Input Type” i.e. the type of value that can be entered in them.

LAYOUTS

This field contains various types of layouts. A layout can be nested within another to achieve desired UI.

  • LinearLayout Vertical/Horizontal : This allows elements within it to be added linearly.
  • RelativeLayout : This allows elements within it to be added relatively to other elements.
  • GridLayout : It is used to achieve a grid like UI.

COMPOSITE

  • ListView : This is a rather widely used element. It helps display a number of items in a list in the layout.
  • GridView : This presents a grid like view of elements. This is not at all related to GridLayout.
  • ScrollView/Horizontal Scroll View : Sometimes it is required to limit the size of a layout to a certain value. However it’s content might be more than what can be accommodated in it. ScrollView is used here so that the content can be scrolled.
  • SearchView : This allows searching. You must have seen a Google SearcView in an Android device.
  • SlidingDrawer : This is a neat and a handy element in many situations. It is a drawer that can be opened and closed with clicks. This can be put over the layout of an activity.

IMAGES AND MEDIA

  •  ImageView : It is a view in which you can put in an image.
  • ImageButton : It is an image and also a button. A rather fancy way to have a button, eh?
  • Gallery : It is a view that can have more than one picture and hence is a gallery.

TIME AND DATE

  • TimePicker : Sometimes when in your application you need the user to enter a time, a TimePicker can do that neatly. Good old EditText can serve the purpose too, but TimePicker is much more fancy and easy to work with.
  • DatePicker : Just like TimePicker, DatePicker is used to pick a date.

TRANSITIONS

  • It deals with animations that can be used while transitions between layouts occur.

ADVANCED

  • NumberPicker : Just like TimePicker and DatePicker, this is used to pick numbers.
  • ZoomButton/ZoomControls : Used to control zoom in/zoom out operations mainly in galleries.

These elements are used most frequently. There are a bunch of other elements that are present. Keep adding them to your layout and experimenting!!

Android development primer: Creating your first Android Application

So now that you have a little idea what Android is all about, we will create our very first Android Project.

Launch Eclipse IDE. Navigate to File->New->Android Application Project. The “New Android Application” dialog comes to the front.

Depending on the version of Eclipse and Android SDK you are using, some options may or may not be present and some might be distributed over a number of dialogs.

  • Project Name is the name of the project you want your application to be in.
  • Application Name is the name of the application. This is the name by which your application will be installed in users’ devices.
  • Package Name is the package in which your application resides. It often looks something like “com.example.yourappname” and automatically appears once you put in the Application Name. You can choose to edit it or leave it be. Usually developers replace “example” with their name.
  • Minimum Required SDK  or Min SDK Version shows the lowest Android version that your application supports. For instance if you set this to API 9 (Gingerbread), devices with API 1-8 will not be able to install your application. It is generally advisable to use as low an API as possible. But then there arises a problem that you will not be able to include features or elements that have been introduced in the later versions. You need to analyze this trade-off and choose this accordingly.
  • Target SDK or Build Target is the version of Android that your applications targets.
  • Compile With should generally be the same as Target SDK.
  • Theme shows the basic theme that you want your application to have. Choose whichever suits your needs.
  • Create Activity is to be checked and the name of an activity to be provided. Usually, this is the activity that appears when your applications is launched and is named Main or MainActivity.
  • If you have the latest versions of Android SDK you will be taken to a number of dialogs from here where you can select the icon of your application, navigation type etc. Since it is our first application, we will let them be at their default values.
  • When you are done Click Finish.

Now to the left of your coding area, you can see a “Package Explorer” tab that lists all packages your workspace contains. You package sould be visible in this area.

If you can see a small cross in the icon of you project, don’t worry. Android needs a little time to set itself up, after which the cross vanishes. In fact all packages will have this cross every time you launch Eclipse.

UNDERSTANDING THE SKELETON APPLICATION.

You have just created an Android Application Project. In order to assist you Android creates a “Hello World” skeleton application on it’s own. Navigate to <yourprojectname> -> src -> <com.yourname.yourappname> -> Main.java. In newer SDKs Main.java is named MainActivity.java. Once this opens up, take a good look at the source code. If you have prior java experience, you can see some familiar things. You can see the import packages, class name and the parent class name from which this class is inherited. You can also see some functions/methods in the source code. Below is the explanation of all the elements of the source code.

  • import android.app.activity : This is the Android Activity package. This package contains all the functions that one can possibly use in an Activity.
  • public class MainActivity extends Activity : Each activity in your application will be in the form of a Class. This class inherits from the Class Activity. This class/activity hence should override the required functions of the original class.
  • onCreate() : This is the function that is called when an activity is first created. This takes an argument Bundle savedInstanceState. For the time being, it will be sufficient for you to know that the state of an activity is saved in a Bundle. We will get into further details later.
  • super.onCreate() : This calls the onCreate() method of the super class i.e. the Activity class with the same arguments.
  • setContentView() : This assigns a layout to the Activity. The argument to this function is R.layout.activity_main. We’ll come to it in a minute.

So, when the activity is first created a couple of things are done. The super class method is called and a layout is assigned to the activity. There are many other functions such as onPause(), onStart(), onResume() etc. in order to monitor the life-cycle of an activity. We’ll discuss this in detail at a later time.
In order to understand what a layout is navigate to yourprojectname -> res -> layout. You can now see the “activity_main.xml” file. In some systems it might be named “main.xml”. This is the layout of your activity. Open it and have a look at the source code.

  • You can see that there are two tabs at the bottom – Graphical Layout and activity_main.xml
  • The Graphical Layout shows what your layout would look like in the device/emulator.
  • activity_main.xml shows the xml code of the layout.

Depending on the version of SDK some of the below components may or may not be present in your xml code.

  • LinearLayout : It tells you that all the components in your layout will be laid down in a linear fashion i.e. one below the other.
  • RelativeLayout : It tell you that all the components in your layout will be laid down in a relative fashion i.e. you can choose the height and width of it’s location from the axes.
  • TextView : This is a rather widely used component in applications. It is used to create static text in an application.

You can also see some properties inside the tags in the xml code. Here’s a brief description of them

  • layout_width/height determines the width and height respectively of the particular element. match_parent/fill_parent means that it covers the entire width/height of it’s parent layout i.e. the layout it is inside of. wrap_content means that it only occupies the space that it requires.
  • margin_top/bottom/left/right determines the margin between two components or the borders of the screen
  • orientation determines the orientation in which elements will be added within this layout. If the orientation is horizontal elements will be added side-by-side. It is mainly a feature of Linear Layout.
  • text is present in the textview. It determines the text that the textview is to show on the screen.

So, now that you are familiar with the skeleton application that Android provided you with, it is time to see how it will look like in a device. For this we will use an AVD that we have previously created. If you haven’t created an AVD create one now.
Click the “Run” button which will pop up a dialog box in which you should select Android Application. This dialog appears only the first time an activity of an application is run. If the emulator was already running when you ran the application it installs on your emulator and if not, the most suitable emulator from your created AVDs is selected and launched. Once the application is installed it runs automatically. You can see the “Hello World, Main!” message on the screen.

Although this is a basic way to get started with an application, I’m gonna go ahead and tell you a couple of things that might interest you. Navigate to <yourprojectname> -> gen -> R.java.
Caution : Take care not to edit the contents of R.java file as it is an Auto-Generated file by the Android system.
Let’s look at how things work

  • With every resources that you add to your project (resources reside in <yourprojectname> -> res) Android is going to add an entry to the R.java file.
  • drawable/layout/string are all resources that you can see in <yourprojectname> -> res. You can now understand why the argument in the setContentView() is R.layout.activity_main.
  • In order to refer to each resource, Android assigns a numerical value that is represented in the hexadecimal form.

Another interesting thing is the res folder. It contains all the resources that your application might need.

  • drawable hdpi/ldpi/mdpi/xhdpi/xxhdpi : These contain the pictures or icons that you have in your applications. In order to put an icon in you application, navigate to <eclipseworkspacelocation> -> <yourprojectname> -> res -> drawablehdpi, paste the icon in it and from your code refer to it as R.drawable.<youriconname>
  • You can choose to have the same icon in different resolutions for devices that have hdpi/ldpi/mdpi/xdhpi/xxhdpi screens.
  • You can also see values folder in the “res” folder. It contains dimens.xml, strings.xml, styles.xml. Click on each one and have a look at the source code.

Now, that you have an idea how to create an application, I will discuss about the elements of the layout and multiple screen support in my later posts.

Best Code to find n to the power k(n^k)

To find n^k,using brute force,

ALGORITHM-
Initialize result to 1.
Iterate from 1 to k and multiply n to result.
Return result.

CODE-

result=1;
for(i=1;i<=k;i++)
{
result=result*n;
}

Complexity for this code is O(k).

Its not only about coding for a given task but also making the code efficient in terms of space as well as time.The above code will take a lot of time for computation for larger values of k.

Efficient code–

Complexity for this code is O(log(k)).

ALGORITHM-

power (n,k)
{

if (k==0)
return 1;

if (k is even)
return (power(n,k/2) * power (n,k/2) );

else if (k is odd)
return (power (n,k/2) * power (n,k/2) * n );

}

CODE-

result=1;
while(k)
{
if(k%2!=0){result=result*n;}
n=n*n;
k=k/2;
}

Tips & Tweaks when programming Math !

In this post,I am going to tell you some tips and tricks which you should know & you can implement in your codes if required.You dont need to require long codes for short tasks.

To check if a number is power of 2,just calculate log2(n) and if it is an integer,it is a power of 2 else it is not.

Number of digits in a number is ceil[log(n)]. This formula is used to calculate the number of digits in n!.

nCr denotes the number of ways of choosing ‘r’ objects from ‘n’ objects.
nCr=(n-1)C(r) + (n-1)C(r-1)

To find the gcd/hcf of two numbers,you should use Euclid’s algorithm.
Program in C —

gcd(int a,int b)
{
if(b==0) return a;
else gcd(b,a%b);
}

LCM of two numbers= (a*b)/gcd(a,b)

To find the number which occurs odd number of times in a list given that all other numbers appear even number of times-
XOR all the numbers and the result gives you the element which occurs odd number of times.

To check if the nth bit of a number is on/off.AND the number with 2 to the power i.If the result is 0,then it is OFF.

To find the nth Fibonacci number-

fib(n)
{
if(n==0) return 0;
if(n==1) return 1;
return f(n-1)+f(n-2);
}

Given a list of numbers from 1 to n and a number is missing,you have to find the missing number.
Method 1-
Find the sum of all given numbers and subtract it from n*(n+1)/2,you get the unknown number.
Method 2-
XOR all the numbers from 1 to n.Let the result be A1.
XOR all the given numbers.Let the result be A2.
XOR A1 and A2.The result gives the unknown number.

Android development primer: Getting to know Android a little better

Once you have set up the Android SDK and AVD in your system, I would like to take some time and provide you with a little description of the Android Platform so that a read-through of it may give you a basic idea of it’s features and fundamentals.

ANDROID ARCHITECTURE

  •  Android runs on Linux i.e. it is based on Linux Operating System, more specifically Linux 2.6
  • It makes use of a virtual machine named Dalvik Virtual Machine, which in particular is optimized for mobile devices. It is analogous to the Java Virtual Machine with which most Java programmers must already be familiar.
  • It makes use of embedded version of OpenGL named OpenGL ES for graphical purposes.
  • It uses SQLite for storage of data in databases. Web Developers can find analogy in the fact that PHP uses MySQL and ASP.NET uses Microsoft SQL Server.
  • For browsing purposes it uses the open-source WebKit Engine.

ABOUT ANDROID APPLICATIONS

  • As most of you may already know Android applications are written in Java programming language.
  • The Android API helps separate layout from functionalities. The layout is usually written in XML, however many programmers also write it in Java.
  • Each application runs in it’s own Linux process just like different processes run in a computer’s Operating System.
  • All applications must possess components, a manifest file and resources.
  • There are four major components of an Android Application namely Activities, Services, Content Providers, Broadcast Receivers.
  • A manifest file named “AndroidManifest.xml” exactly, is required for each application. This serves the purpose of giving a clear picture to the Android system what your application is all about, what permissions it requires and other related details. I will cover the Android Manifest file and it’s importance in detail in a later post.
  • Resources may consist of xml scripts, colors, shapes, pictures and any other things that your application makes use of.

ACTIVITIES

Any single screen with a user interface is an activity i.e. every screen a user sees is a separate activity. For instance, when you check your text/multimedia messages, the screen that lists the sms/mms conversations, is an activity. When you click on one and enter the conversation screen, that is another activity. Practically, every single application that you come across will have more than one activity. The user can navigate from one activity to another while using the application.

The question now arises, how does the flow of control work in a multi-activity application? Well, it is the responsibility of the Application Programmer to decide how and when will a user be taken from one particular activity to another. Remember that when switching activities, the current activity is paused and the next activity is brought to the front.

Also if you have used an Android device before, you must know that on pressing the “back” key on the device, the user is brought to the screen/activity he/she was on immediately before coming to the current activity. Quite intuitively, it is done using a stack data structure. This stack is known as Back Stack in Android.

SERVICES

Services are programs that perform long-running operations in the background. Since they run in the background, they obviously do not contain a user interface. The most striking feature of a service is that it runs independently of the activity that created it. In simple terms it means that on closing the activity that created a particular service, the service keeps running and does not close with the activity. Another very useful feature of services is that, if allowed, any application can bind to a service and manipulate it.

Now, if you have used an Android device before, you can definitely think of a few services that you have come across. One of them is playing music. When you go to the music player, queue your favorite tracks and then close the music player the music continues to play. This is a very simple day-to-day example of a service.

CONTENT PROVIDERS

Have you ever thought how data can be shared between applications in an Android device? Since each Android Application runs in it’s own process, any and every data to be shared need to be centrally located, so that each application may have access to it. That is exactly what is achieved using Content Providers. Android already contains a number of providers like Contacts, Calls, Media etc. that applications can get access to. An application can also create a provider so that other applications can share it’s data and perform whatever tasks they need to.

Data is stored as a simple table in a Database Model. Data from a Content Provider is accessed with the help of a public URI (Uniform Resource Identifier). A URI uniquely identifies a particular data set.

BROADCAST RECEIVERS

Broadcast Receiver is a component that receives broadcasts from the Android System. A broadcast can be considered to be a system wide announcement of the occurrence of an event. Any and every applications programmed to receive to a particular type of  broadcast, will trigger off as soon as a broadcast occurs.

Applications can also create their own broadcasts such that other applications might receive it and execute a specific set of instructions. Just like services, Broadcast Receivers do not have a user interface. You must have seen that a dialog appears on your device whenever the battery is low. That is a classic example of a broadcast receiver. When the battery is below a certain level, a broadcast is initiated by the Android system. The inbuilt applications receive this broadcast and show a dialog box informing you of the same.

With this, we come to the end of a thorough introduction and we are now ready to plunge ourselves into some real-time Android Application Programming. In my next post I will brief you about the Eclipse IDE and show you how to create your first Android Application