Pages

Search

Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Tuesday, February 10, 2009

What are recursive functions?

We are aware about how functions are defined in C or C++ or Java or.Net.
In which ever case it is, in a programming language we start our process by defining a method or function.
We say Main method is the first method that gets called to start executing an application.
1) Function can expect parameters which is not mandatory.




2) When a function is called it is loaded then into memory with given parameters as well.
3) Function may or may not return a value



4) A function can call an another function or by itself.



5) Recursive function can be defined as a function calling by it self.




Memory structure:-
Let us consider a simple function as



If this is a recursive function (say it calls for it self 3 times) then



Example:-

I have created a .NET windows application for calculating the factorial of a given number.
If input is 5 then output should be 5*4*3*2*1
Code:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Sample
{
public partial class frmFactorial : Form
{
public frmFactorial()
{
InitializeComponent();
}

private void btnFactorial_Click(object sender, EventArgs e)
{

try
{
//Checking given value is numeric or not
if (!IsNumber(txtFact.Text))
throw new Exception("Enter numeric value for A");
//calling factorial function
MessageBox.Show(Factorial(Convert.ToInt32(txtFact.Text)).ToString());

}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
private int Factorial(int argVal)
{
//If input value is greater then one then once call once again
//by multiplying input value with the return value of
//factorial function by sending the value after deducting 1
//from the given input value
if (argVal > 1)
{
argVal = argVal * Factorial(argVal - 1);
}
//returning the final value, which is calculated after multiplying
//recursively
return argVal;
}

private bool IsNumber(string argValue)
{
try
{
//checking if the given value is numeric
Convert.ToInt32(argValue);
return true;
}
catch
{
return false;
}
}
}
}

output:-



Saturday, September 27, 2008

What is differnce between reference type and value type?

When we build applications that use variables they are allotted to memory blocks either in stack or heap memory.They can be either refernce type or value type.
Please find my source code below and screen shot next to it explaining what is reference and value type.

Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Learnings
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
class classtype
{
public int var;
}
struct stacktype
{
public int var;
}
private void button1_Click(object sender, EventArgs e)
{
stacktype objstk1 = new stacktype();
stacktype objstk2 = objstk1;
objstk2.var = 100;

classtype objcls1 = new classtype();
classtype objcls2 = objcls1;
objcls1.var = 200;

MessageBox.Show("Struct " + objstk1.var + ", " + objstk2.var);
MessageBox.Show("Class " + objcls1.var + ", " + objcls2.var);

}
}
}


Output:














You can observe I have defined a class and a stack.
We know that “new” helps in creating/assigning a memory block.

Variables objstk1 and objstk2 store values assigned to variable (var) in there specific memory locations.

References objcls1 and objcls2 points to a location or stores address of a memory block (heap memory) which is created and has variable var =200.

I am saying objstk1,objstk2 as variables (value variable) and objcls1,objcls2 as refernces (refernce variable) which sounds or says what I mean.


So value type says that it holds real value and reference says that it holds references of memory blocks.


When i say “stacktype objstk2 = objstk1;” then a new memory location is created for objstk2 in stack memory and a separate variable var in it.
When I assign value for var which is holded by objstk1 , obviously will not be assigned for var holded by objstk2.

If I do in this manner then we have same values in var holded by 2 variables.

stacktype objstk1 = new stacktype();
objstk1.var = 100;
stacktype objstk2 = objstk1;


That is first I assigned value to var holded by objstk1 and then assigned objstk1 to objstk2 , which does copy content from objstk1 to objstk2 (shallow copy).



Coming to refernce types,
When I say “classtype objcls1 = new classtype();” then
At run time a memory block is created in heap memory and its address is assigned to a stack memory block alias objcls1 which is refernce type variable.


When I say “classtype objcls2 = objcls1;” then the same content from objcls1 is copied to new memory block instack memory alias objcls2.


So both refernce variables hold same memory blocks address which is created in heap memory.

So when I assign value to var variable through objcls1 , and can retrieve same value from var holded by objcls2 , since both objcls1 and objcls2 hold same memory block address (heap memory).

Below screen shot helps to understand visually.






Monday, September 22, 2008

Memory concepts at runtime

We have two kind of memorys.
1) Heap Memory
2)Stack Memory.

Usually the variables might be value or referneced type should be stored in a memory to access.

As there are 2 different memories there sholud be set of rules defined where to store these variables.


a) When we try to create an object in runtime they will created inside heap memory.
But the reference type variable refering to this object can be in heap or stack. To explain when they will be in stack or heap we should be aware with the
following concepts.

i) A variable can be declared inside a function or as a variable member to a class.

The above mentioned line is vital while considering memory management.
A variable declared as local in a function will be stored in stack where as declared as a variable member in a class will be stored in heap.

So that is why it is recommended to use a very less global variables in a class whose memory gets created in heap memory.

So for stack memory it is not required to trap memory cleaning, but for heap memory we have (GC) garbage collector which should run algorithm for cleaning the
heap memory.

b) Static funtions and variable will always be created in heap memory which will created only once but not for every instance of the class.

c) Instance functions get loaded into stack memory so when a function gets called by another , as soon as called function is completed it will be removed from
stack memory, obviously relevant variables will be removed from stack.

d) A refernce type variable pointing to a object is also declared as variable members to class then that refernce type variable along with its pointing object will be stored in heap memory.

So we should be sure about the variable (reference or value) that we declare is according to set of rules defined above.

Saturday, September 20, 2008

How to handle try catches?

Many programmers hit there minds with this question. I considered yes and so I use to avoid using it but at final release to client , I found many issues raised by him and I am unable to replicate few of them , client is not able to guide me the way he got the error , some times the page (asp.net) showing “/Server Exception” which makes user irritated etc…

At last I believed this is all because of improper exceptional handling. I does not mean that if try catches are implemented these errors could not occur , but instead if you implement this exception handling by logging errors into a error log file in catch blocks, client can give you that error log file for reference and you can resolve the issues easily than expecting how they have come?



I felt 3 different ways to apply these try catches.
try
{
}
catch
{
throw;
}

(1)


try
{
}
catch(Excexption exp)
{
LogError(exp.Messagge);
throw exp;
}
(2)

try
{
}
catch
{
}

(3)


In the above mentioned cases
1) If you would not like to handle the exception or log it you can thow the expecption, such that be sure that if and only if you are throwing to a calling or parent function.
You cannot throw exception in a parent function instead if you would like to handle you can write (label.Text=exp.Message), which displays the error on to user interface instead having server exceptions or making user irritated.
Before showing error you can log that error into a text file.
Ex:-
public void btn_Calculate(object sender,Eventargs e)
{
try
{
//Since this function is called when user clicks on calculate button from UI
//i.e; the first function executed it is called parent function.
//Now this function calls Calculate() function which becomes child function.
…
…
int c=Calculate(a1,b1);
..
..

}
catch(Exception exp){
logError(exp.Message,” btn_Calculate”);
lblError.Text=exp.Message;
}
}
//This calculate function is a child function which is called by another function.
private int Calculate(a,b){
//Child function that has to be actually to handle exceptions.
try
{
…
…
return value;

}
catch (Exception exp)
{
logerror(exp.Message,”Sum()”);
throw exp;
}
}

private int Sum(a,b){

//Child function that logs error but returns -1 instead of throwing exception
try
{
…
…
return value;
}
catch (Exception exp)
{
logerror(exp.Message,”Sum()”);
return -1;
}
}
private int Sum(a,b){
//Child function that doesnot even log error but returns -1
try
{
…
…
return value;
}
catch (Exception exp)
{
return -1;
}
}
private int Sum(a,b){
//Child function that doesnot handle exception
…
…
return value;
//When there is any exception in child function , then the exception is raised in //parent function, so the error can be handled , but if there are multiple child //functions even error is handled at parent function but you cannot trace in //which function the error occurred unless you handle in each and log to error //log text file.
}
There are also specific exceptions like OracleException,SMTPException etc…
These Exceptions are child classes to a parent class called Excpetion.


So things like when you connect to oracle or retrieve data using datareader connected to oracle and send a mail to user, it could be good if you use OracleException,SMTPException objects.
try
{
}
catch(OracleException oraexp){
//This catch block holds error when oracle error ossurs
LogError(oraexp.ErrorNumber,”Excpetion due to oracle”);
}
catch(SMTPException smtpexp){
//This catch block holds error when smtp error occurs
LogError(smtpexp.innerExpetion.Message,”Excpetion while sending mail”);
}
Functions which you feel that they are perfect and 100% there is no way of throwing errors then you need not handle try catches.

Note : Finally blocks can also be appended which depends upon you function.

try
{
}
catch
{
}
finnally
{
//To dispose objects that are local to this function and imperative that the value or object
//returned to parent function should not be disposed :)
}