-->

Friday, February 28, 2014

Decrement operator in c# programming

Those operator, which is used for decrement by one in any value known as decrement operator. These are two types.

  1. Pre-Decrement operator
  2. Post-Decrement operator 

In pre-decrement operator appear before its operand, such as --a. Here "a" is a operand and -- is the decrement operator. In this case, value of the operand(a) will be decremented by one "after" it has been decremented.

In post-decrement operator appear after its operand, such as a--. Similarly again, "a" is a operand and -- is the decrement operator.In this case, value of the operand(a) will be decremented by one "before" it has been decremented.
Lets take an simple example of both pre and post decrement
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            double a;
            a = 1.5;
            Console.WriteLine(--a);
            a = 1.5;
            Console.WriteLine(a--);
            Console.WriteLine(a);

            Console.ReadKey();

        }      

    }
}

Code generate the following output

Decrement operator in c# programming

In this example, variable a hold 1.5 double number. When compiler compile third line of statement, which is 
Console.WriteLine(--a). Pre-decrement the value by one according to above definition. In forth line of statement again variable a replace with 1.5 double number. According to post-decrement, first print same value of variable a (according to line-5) that is 1.5 , after that value has been decremented by one (according to line-6) that is 0.5.

Decrement operators in expression

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            int a = 7;
            Console.WriteLine(--a * a--+a--*--a);            
            Console.ReadKey();

        }      

    }
}

Code generate the following output

Decrement operator in c# programming
In this example, compiler first check operator precedence, here multiply sign take high precedence than addition sign. Also expression evaluate left to right, so first variable a is pre-decrement (value of a=6) also multiply with post-decrement variable( a=6). So the result of first half is 36. In the next half, the value of variable a is post-decremented ( value of a=5) also multiply with pre-decrement (a=3 according to above definition). So the result of second half is 15. Now add both result, 36+15 is 51.

Merging the ordered Singly Linked List for Data Structure in 'C'

Merging the ordered Singly Linked List:

         Often it is necessary to merge two linked lists into a single linked list. Merging of two arrays consumes lots of time and storage whereas merging of two linked lists is simple. Just changing the address stored in link field of each node as and when required carries out the merging in case of linked list. Let us consider the example as follows before dealing with algorithm and program.



Both of the linked lists are in ascending order. First node address of each linked list is stored in ROOT1 and ROOT2 respectively. In order to merge these lists we can use another external pointer ‘ROOT’ to point to the first node of each list is compare. The node whose information is less become the first node of the merged list and the address of that node is stored in ‘ROOT’ .The process is continued till the end of each list.
In the above example the information of the first node of the second list is smaller than that of first node of the first linked list. So, ROOT is assigned with ROOT2 and ROOT2 is updated to point to the next node of the second linked list . Now ROOT2 points to a node with information 23.

Default selection RadiobuttonList Example in ASP.NET

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default5.aspx.cs" Inherits="Default5" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Default selection</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:RadioButtonList ID="RadioButtonList1" runat="server" AutoPostBack="True" 
            onselectedindexchanged="RadioButtonList1_SelectedIndexChanged">
            <asp:ListItem>Literal Control</asp:ListItem>
            <asp:ListItem>Label Control </asp:ListItem>
            <asp:ListItem>Localize control</asp:ListItem>
            <asp:ListItem>Multiview Control</asp:ListItem>
        </asp:RadioButtonList><br />
        <asp:Label ID="Label1" runat="server"></asp:Label>

    </div>
    </form>
</body>
</html>

Code behind code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default5 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (RadioButtonList1.SelectedIndex < 0)
        {
            RadioButtonList1.SelectedIndex = 0;
            Label1.Text += "Default selection in radio button list.";
        }
        else
        {
            Label1.Text = "Your item selected are : " + RadioButtonList1.SelectedItem.Text;
        }  
    }
}

Code generate the following output

Default selection RadiobuttonList Example in ASP.NET

Thursday, February 27, 2014

C# Programming: How to find pow of given number

You can easily find power of given number using Pow, which is static method of Math class. Here we take an example with integer number. Also gives II method , which is performed by programming.

Both method include in single program

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 2, b = 4;   

            

            Console.WriteLine(" The power of given number is {0}",Math.Pow(a, b));
            // Second method
        int result= Fun(2, 6);
        Console.WriteLine(" The power of given number is {0}", result);
            Console.ReadKey();

        }

        private static int Fun(int a, int b)
        {
            if (b >= 1)
            {
                return (a * Fun(a, --b));
            }
            else
                return 1;
        }
      

    }
}

Code generate the following output

C# Programming: How to find pow of given number

c# programming : How to find largest number in given two number

You can easily find largest number between two number using Max, which is static method of Math class. This method is overload with multiple data types, such as Max(Byte, Byte) , Max(Decimal, Decimal) and many more data types. Here we take an example with integer number.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = -3, b = 52;
            Decimal deci = -4, deci1 = 53;

            Console.WriteLine(" the maximum number in between a= {0} and b={1} are {2}",a,b, Math.Max(a, b));

            Console.WriteLine(" the maximum number in between a= {0} and b={1} are {2}", deci, deci1, Math.Max(deci, deci1));

            Console.ReadKey();

        }
    }
}

Code generate the following output

c# programming : How to find largest number in given two number

C Program to reverse an ordered linked list for Data Structure for C Program

C Program to reverse an ordered linked list:

struct node
{
inf info;
struct node *link;
};typedef struct node sn;
sn*insert(sn *root, int i)
{
sn *new,*temp,*ptemp;
new=(sn*)malloc(sizeof(sn));
if(new= =NULL)
{
printf(“Memory allocation error…”);
exit(0);
}
new->info=I;new->link=NULL;
if(root= =NULL)
root=new;
else
if(i<root->info)
{
new->link=root;  root=new;
}
else
{
temp=root;
while(temp=NULL&&i>temp->info)
{
ptemp=temp;
temp=temp->link;
}
new->link=temp;
ptemp->link=new;
}return root; /*address of first node is returned*/
}
void traverse(sn *ptr)
{
while(ptr!=NULL)
{
printf(“%d”,ptr->info); ptr=ptr->link;
}
}
sn*reversell(sn *root)
{
sn *first=root,*pptr=root,*nptr;
nptr=nptr->link;
while(nptr!=NULL)
{
root=nptr;
nptr=nptr->link;
root->link=pptr;
pptr=root;
}
first->link=NULL;
return root;
}
main()
{
sn *root=NULL,*ptr;int info; char ch;
while(1)
{
printf(“/nEnter node information :”);
scanf(“%d”,&info);
root=insert(root,info);
printf(“\n Do you want to continue…(y/n)”);
ch=getche();
if(ch!=’y’)
 break;
}
printf(“\nOrdered (Asc)Singly Linked List :\n\n”);
treverse(root);getch();
printf(“\n\n The reversed (desc)linked list :\n\n”);
root=reversell(root);
traverse(root); getch();
}

The same reversing function also can be applied to the circular linked list by just changing the required condition to test the last node’s link. In normal linked list it is NULL. In circular linked list it become the address of the first node itself, stored in external pointer(root).

Reversing the ordered Singly Linked List for Data Structure in'C'

Special Operation on linked lists:

Reversing the ordered Singly Linked List:
              In order to reverse the ordered singly linked list, the root must point to the last node of the list. The first node’s address must be copied to the link of second node. Similarly the address of each node is copied in the link of the next node. It works like exchanging the links of each node with the address of the previous node. The algorithm is simple and self-explanatory.
The same is given as follows:

REVERSELL (ROOT)
FIRST<--ROOT [To store the first node’s address]
PPTR<--ROOT        [To store the address in link]
NPTR<--ROOT-->LINK [To store address of previous node]
Repeat While NPTR< >NULL
  ROOT<--NPTR
  NPTR<--NPTR-->LINK
  ROOT-->LINK<--PPTR
  PPTR<--ROOT
[End of while]
FIRST-->LINK<--NULL [To make first node as last]
Return ROOT
Exit.

Wednesday, February 26, 2014

How to Use Operators with Strings in Java Programming

Operator + with strings

You have used the operator + with numbers. When you use + with numbers, the result is also a number. However, if you use operator + with strings, it concatenates them e.g.

5 + 6 results in to 11.
“5” + “6” results in to “56”.
“17” + “A, V. Vihar” result in to “17 A, V. Vihar”
“abc” + “123” results in to “abc 123”
“” + 5 + “xyz” results in to “5xyz”
“” + 5 results in to “5”

(In above two expressions Java would internally convert 5 in to “5” first and then concatenate with “xyz” and “” respectively.)

Increment/Decrement Operators (++, --)

Java includes two useful operators not generally found in other computer languages (expect C and C++). These are the increment and decrement operators, ++ and --. The operators ++ adds 1 to its operand, and – subtracts one.
In other words,
a = a + 1;
is the same as
++a ; or a++;
And
a = a – 1
is the same as
--a ; or a --;

However, both the increment and decrements come in to two varieties: they may either precede of=r fallow the operand. The prefix version comes before the operand (as in ++ a or -- a) and the post-fix version comes after the operand (as in a++ or a--). The two version have the same effect upon the operand, but they differ when they take place in an expression.

How to find absolute number of a given number in c# programming

In c# programming we easily find absolute number of a given number. We can use Abs function, which is include in Math class. Lets take an simple example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            sbyte sortbyte1 = -12, sortbyte2 = 12;
            short shnumber1 = -13, shnumber2 = 13;
            int integer1 = -14, integer2 = 14;
            long long1 = -15, long2 = 15;
            float float1 = -16.0f, float2 = 16.0f;
            double double1 = -17.1, double2 = 17.1;
            Decimal decimal1 = -18.0m, decimal2 = 18.0m;

            Console.WriteLine();
            Console.WriteLine("SortByte:   1) {0,-2} {1,-2}", Math.Abs(sortbyte1), Math.Abs(sortbyte2));

            Console.WriteLine("Integer 16 bit:   1) {0,-2} 2) {1,-2}", Math.Abs(shnumber1), Math.Abs(shnumber2));

            Console.WriteLine("Integer 32 bit:   1) {0,-2} 2) {1,-2}", Math.Abs(integer1), Math.Abs(integer2));

            Console.WriteLine("Integer 64 bit:   1) {0,-2} 2) {1,-2}", Math.Abs(long1), Math.Abs(long2));

            Console.WriteLine("Single:  1) {0,-2} 2) {1,-2}", Math.Abs(float1), Math.Abs(float2));

            Console.WriteLine("Double:  1) {0,-2} 2) {1,-2}", Math.Abs(double1), Math.Abs(double2));

            Console.WriteLine("Decimal: 1) {0,-2} 2) {1,-2}", Math.Abs(decimal1), Math.Abs(decimal2));

            Console.ReadKey();

        }
    }
}
Here Math class provide Abs static method for returning absolute value of a given number. Abs function is overloaded by some data types like double, decimal, Int16, Int32 and SByte.
Code generate the following output
How to find absolute number of a given number in c# programming

Memory representation of Linked List Data Structures in C Language

                                 Memory representation of Linked List

             In memory the linked list is stored in scattered cells (locations).The memory for each node is allocated dynamically means as and when required. So the Linked List can increase as per the user wish and the size is not fixed, it can vary.

               Suppose first node of linked list is allocated with an address 1008. Its graphical representation looks like the figure shown below:


      Suppose next node is allocated at an address 506, so the list becomes,



  Suppose next node is allocated with an address with an address 10,s the list become,


The other way to represent the linked list is as shown below:




 In the above representation the data stored in the linked list is “INDIA”, the information part of each node contains one character. The external pointer root points to first node’s address 1005. The link part of the node containing information I contains 1007, the address of next node. The last node of the list contains an address 0, the invalid address or NULL address.

Example:

The data stored in the linked list is: “The Is Another:
 Example Of Linked List”

Q. What is stored in the linked list shown below?



Q. What is stored in the Linked List shown below?



Tuesday, February 25, 2014

About the Default Action Methods in MVC Controller

Earlier article was about to add a controller (Student) and create its default views (having the same name as default actions). In this article we will discuss about the Index action which is used to show the list of particular table in database or any list container.

The index action by default have following code:
private StudentContext db = new StudentContext();
public ActionResult Index()
{
return View(db.Students.ToList());
}

In this code the first line is used to create the object of Student context class, which is used further to perform CRUD actions with the database. This action is simply a method having return type ActionResult which is basically encapsulates the result of an action method and used to perform a framework-level operation on behalf of the action method.

Just get in to the inner code of this action, having a single line of code, which is returning the view with the list of students stored in the database (from the db variable initialized in the first line).

Open the Index view in the Views>> Students folder having something like the below code:

@model IEnumerable<MvcApplication1.Models.Student>

<h2>Index</h2>
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th></th>
    </tr>
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Id })
        </td>
    </tr>
}
</table>

The first line contains the name of model specifying that this view is strongly typed view of the named mode. The total body of this view is in table written above. Table headers are bind with the model fields, it may be a simple string.

After the headers a loop is there for all the items contained in the model. The DisplayFor() method is used to show the value of name of item passed through the model and more fields have more headers as well as other fields.

GET and POST Create Action in MVC

C Program to implement doubly linked list for Data Structrue in 'C'

C Program to implement doubly linked list:

#include<stdio.h>
#include<alloc.h>
#include<stdlib.h>
#include<conio.h>
struct dlnode
{
Int info;
struct dlnode *link;
struct dlnode *prev;
}; typedef struct dlnode dln;
main( )
{
dln *root, *temp, *new, *ptr; char choice=’y’;
root=NULL;
while(choice= =’y’)
{
new=(dln*)malloc(sizeof(dln);
if(new= =NULL)
{
printf(“Memory allocation error…”); exit(0);
}
new->link=NULL; new->prev=NULL;
printf(“\nEnter node information :”);
scanf(“%d”,&new->info);
if(root= =NULL)
{
root=new;    temp=root;
}
else
{
new->prev=temp;   temp->link=new;
temp=new;
}
printf(“Do you want to continue…(y/n)”);
choice=getche();
}
printf(“\nDoubly linked list is:\n\n”);
/* Doubly linked list normal singly linked list if it is traversed using link field of the node*/
ptr=root;
while(ptr=NULL)
{
printf(“%d”,ptr->info);
ptr=ptr->link;
}
printf(“\n\nDoubly linked list(reverse order):\n\n”);
/*The pointer temp is pointing to the last node. So, we can use it traverse in reverse order*/
while(temp!=NULL)
{
printf(“%d”,temp->info);
temp=temp->prev;
}
getch();
}

Calculate duration between two dates in c# programming

Introduction

Design simple age calculator , calculate remaining days from two dates. Suppose your Date of Birth is 19/mar/1987 and you want to calculate total days on till date. Here we take an simple demonstration of this type of application.

Design

Step-1 : Add two DateTimerPicker and one button control on windows form.
Step-2 : Take Two Datetime class instance, first for starting date and second for ending date.
Step-3 :  Calulate difference between two dates using Timespan structure.
Step-4 :  Using TotalDays property of TimeSpan structure you can calculate days.

Calculate duration between two dates in c# programming

Code

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

namespace datecalulator
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DateTime dtstart = dateTimePicker1.Value;
            DateTime enddate = dateTimePicker2.Value;
            TimeSpan totaldays = enddate - dtstart;
            int calculate =Convert .ToInt32 (totaldays.TotalDays);
            MessageBox.Show(calculate.ToString()+" Days");

        }
    }
}

 Code generate the following output

Calculate duration between two dates in c# programming

Monday, February 24, 2014

Understanding creation of doubly linked list for Data Structrue in 'C'

Understanding creation of doubly linked list:
                                                                                                  
One node with information ‘6’ is added to the doubly linked list. Then the list become,
                                                                                                                                                                                                                                                         



Another node with information ‘16’ is added to the circular linked list. Then the list become,


Similarly when two more nodes are added with information ‘1’ and ’61’, the list become,



Traversing the Doubly Linked List

       Set a pointer variable PTR with ROOT. Process PTR-->INFO and update PTR by LINK of PTR i.e. PTR<--PTR-->LINK. Repeat till the PTR is NULL. The algorithm is as follows:

      TRAVERSDLL (ROOT)
      PTR<--ROOT
      Repeat While PTR< >NULL
      Apply process to PTR-->INFO
      PTR<--PTR-->LINK
      [End of while]
      Exit

Algorithm to print the contents of a linked list:

      TRAVERSEDLL (ROOT)
      PTR<--ROOT
      Repeat While PTR< >NULL
      Write: PTR-->INFO;  PTR<--PTR-->LINK
      [End of while]
      Exit.

        From the just created doubly list in the example shown it is possible to traverse the doubly linked list in reverse order starting from the last node. Address of the last node is available in external pointer TEMP. Set a pointer variable PTR with TEMP. Process PTR-->INFO and update PTR by storing the address of previous node given by the pointer part PREV of PTR i.e. PTR<--PTR-->PREV. Repeat till the PTR is NULL.
The algorithm is as follows:

       TRAVERSEDLLRO
       PTR<--TEMP
       Repeat While PTR< >NULL
       Apply process to PTR-->INFO; PTR<--PTR-->PREV
       [End of while]
       Exit.
  Rests of the operations are similar to singly linked list and are left out as exercises.

How to Create User-Defined Database in SQL Programming

In addition to system databases, the SQL Server also contains user-defined databases where the users store and manages their information. When the users create a database, it is stored as a set of files on the hard disk of the computer.

To create a user-defined database, you can use the CREATE DATABASE statement. The syntax of the CREATE DATABASE statement is:

CREATE DATABASE database_name
[ON [ PRIMARY ] [ < filespec >]]
[LOG ON [ < filespec >}}
< filespec > : : =
( [ NAME = logical_file_name , ]
FILENAME = ‘os_file_name’
[ , SIZE = size]
[ , MAXSIZE = { max_size | UNLIMITED } ]
[ , FILEGROWTH = growth_increment ] ) [ ,…n ]

Where
  • Database_name is the name of the new database.
  • ON specifies the disk files used to store the data portion of the database (data files).
  • PRIMARY specifies the associated <filespec> list that defines file in the primary filegroup.
  • LOG ON specifies the disk files used to store the log files.
  • NAME=logical_file_name specifies the logical name for the file.
  • FILENAME=os_file_name specifies the operating-system file name for the file.
  • SIZE=size specifies the initial size of the file defined in the <filespec> list.
  • MAXSIZE=max_size specifies the maximum size to which the file defined in the <filespec> list can grow.
  • FILEGROWTH=growth_increment specifies the growth increment of the file defined in the <filespec> list. The FILEGROWTH setting for a file cannot exceed the MAXSIZE setting.

To create a database, you must be a member of the dbcreator server role. In addition, you must have the CREATE DATABASE, CREATE ANY DATABASE, or ALTER ANY DATABASE permissions.

The following SQL query creates a database named Personnel to store the data related to all the employees:
CREATE DATABASE Personnel
The preceding statement creates a database named Personnel in the C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data folder. The data file name of the database is Personnel.mdf and the log file name is Personnel_Log.ldf.
You can also create a database in the Object Explorer window by right-clicking the Databases folder and selecting the New Database option from the shortcut menu. When the database is created, the user, who creates the database, automatically becomes the owner of the database. The owner of the database is called dbo.
After a database has been created, you may also need to see the details of the database. For this purpose, you can use he sp_helpdb command. The synbtax of the sp_helpdb command is:
sp_helpdb [database name]

Store information in database
Rename or Drop Database

How to Identify the Database Files in SQL Server

In SQL Server programming context, each database is stored as a set of files on the hard disk of the computer. These files may be of following types including

Primary data file

The primary data file contains the database objects. The primary file can be used for the system tables and objects, and the secondary file can be used to store user data and objects. The primary data file has (.mdf) extension.

Secondary data file

The secondary data file also stores the database objects. Very large databases may need multiple secondary data files spread across multiple disks. Databases need not have secondary data files, if the primary data file is large enough to hold all the data in the database. The secondary data file has (.ndf) extension.

Transaction log file

The transaction log file records all modifications that have occurred in the database and the transactions that caused those modifications. At least one transaction log file holds all the transaction’s information and can be used to recover a database. At least one transaction log file must exist for a database. There can be more than one transaction log file. The minimum size of a transaction log file is 512K. The size of the transaction log file should be 25 – 40 percent of the size of the database. The log file have an (.Idf) extension.
A database must consist of a primary data file and one transaction log file.
The database files are stored in filegroups. A filegroup is a collection of files. A database comprises a primary filegroup and any user-defined filegroup. A primary filegroup contains the primary data file and any other files that are not put into any other filegroup. The primary filegroup also contains the system database. When objects are created in the database without specifying the filegroup, they are assigned to the default filegroup. Only one filegroup in a database can be the default filegroup.

A user-defined filegroup is a filegroup that is created by users. You can create filegroups to distribute the data amongst more than one filegroups to improve the performance of database.

Sunday, February 23, 2014

Print one month later date in ASP.NET

You can use DateTime class for add months in current object of DateTime. DateTime class provides different types of methods to add this types of query like AddDays(), AddMonths() etc. This example cover AddMonth. Now take an simple example for that.

Complete Code 

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:Label ID="Label1" runat="server"></asp:Label>
    
    </div>
    </form>
</body>
</html>
//code file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default4 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DateTime d1 = new DateTime();
        Label1.Text += d1.ToLongDateString() + "<br/>";
        DateTime onemonthlater= d1.AddMonths(1);
        Label1.Text += onemonthlater.ToString()+ "<br/>";

        TimeSpan difference = onemonthlater - d1;
        Label1.Text += "difference in days" + difference.Days;

    }
}

Output
Print one month later date in ASP.NET


Doubly Linked List for Data Structure in C Programming

Doubly Linked List:

 A little more variation to linear linked list gives another type of linked list called as doubly linked list. You might have observed in the linear list that every node contains two parts. One part contains the information and the other part contains the address of the next node in the list. If another pointer part is added to the node, to contain the address of previous node then the linear linked list becomes doubly linked list. In such lists you can traverse only in one direction. In the middle of traverse if you want to come back to the previous node it is not possible. The movement is one-way. It is possible to move in both the directions in doubly linked list. You can traverse in both the directions. This application of variation is very simple. The node in doubly linked list looks as follows:


If the node is the first node of the list been previous pointer contains a NULL address because there are no previous nodes. If the node is the last node then next pointer contains a NULL address because there are no next nodes. A simple representation of doubly linked list is as follows:


In the above doubly linked list, ROOT, the external pointer points to the first node with information 12. The first node’s previous pointer points to NULL. The first node’s next pointer points to the second node with information 15. The second node’s previous pointer points to the previous node containing information 15. The last node’s next pointer points to NULL address. Creation of doubly linked list is almost similar to singly linked list. Only addition is assigning the previous pointer of every node except the first node, with the address of the previous node. The operations like traversing, searching, insertion and deletion are almost similar to singly linked list. While traversing the operation can be reversed from any point in the doubly linked list. While insertion and deletion the operations are similar to singly linked list except the change in previous as well as next pointer values.

Algorithm to create a doubly linked list:

CREATEDLL
ROOT<--NULL; CHOICE<--‘Y’
Repeat While CHOICE=’Y’
 If AVAIL = NULL Then:
  Write: ’Memory Allocation Error’ 
  Exit.
Else 
NEW<--AVAIL;   NEW-->LINK<--NULL
NEW-->PREV<--NULL;   NEW-->INFO<--Information
[Information is the data to be stored in linked list]
AVAIL<--AVAIL-->LINK
[End of it]
If ROOT=NULL Then:
   ROOT<--NEW;   TEMP<--NEW
Else 
TEMP-->LINK<--NEW;     NEW-->PREV<--TEMP
TEMP<--NEW
[End of If]
Write: ‘Do you want to add another node?(Y/N)’
 Read: CHOICE
[End of while]

Saturday, February 22, 2014

Searching In Circular linked list for Data Structure in 'C'

Searching:

               In order to do searching in circular linked list, get the information to be searched and set PTR with ROOT. Compare Information with INFO of PTR, if it is equal ‘search is successful’ and terminate operation otherwise update PTR with LINK of PTR and repeat the process. Continue the operation till the end. The end is recognized by an address of first node given by ROOT stored in Link of PTR.

Algorithm for searching:

       SEARCHCLL(ROOT, IN)
       [ROOT is starting address of Linked List and
         IN is Information to search in Linked List]
        PTR<--ROOT
        If PTR = NULL Then:
         Write: ‘Empty Circular linked list’
         Exit.
        [End of If]
        Repeat While IN< >PTR-->INFO
         If PTR-->LINK = ROOT Then:
            Break
         [End of If]
         PTR<--PTR-->LINK
         [End of while]
         If PTR-->INFO = IN Then:
           Write: ‘Search Successful’
         Else:
          Write: ‘Search Unsuccessful’
         [End of If]
         Exit.

The insertion and deletion operations in circular linked list are similar to that of linear linked list and they are left as exercise. The hint is to only replace the end node checking condition of the linear linked list with that of circular linked list. This condition replacement you have learned in traversing and searching in circular linked list.

Friday, February 21, 2014

Understanding traversing in circular linked list for Data Structure in 'C


Understanding traversing in circular linked list:

Let us consider the following circular linked list.

Let us assign a pointer PTR with ROOT, address of the first node. PTR is not equal to NULL. So, the circular linked list is not empty.

Repeat while TRUE

                Write: PTR-->INFO    i.e. 6 is written
                PTR-->LINK is not equal to ROOT. So, no break.
                PTR<--PTR-->LINK     Now PTR points to second node
                Write: PTR-->INFO     i.e. 16 is written
                PTR-->LINK is not equal to ROOT. So, no break.
                PTR<--PTR-->LINK       Now PTR points to third node
                Write: PTR-->INFO        i.e.  1 is written
                PTR-->LINK is not equal to ROOT. So, no break.
                PTR<--PTR-->LINK        Now PTR points to third node
               Write: PTR-->INFO         i.e. 61 is written
               PTR-->LINK is equal to ROOT. So, break.
The infinite loop breaks. So, the traversing is complete.

C Program to create and traverse Circular linked list:

     struct node
    {
      int info; struct node*link;
    };
    typedef struct node sn;
    main( )
    {
     sn *root,*temp,*new; char choice=’y’;
     root=NULL;
     clrscr( );
     while (choice==’y’)
     {
      new=(sn*)mallloc(sizeof(sn));
      if(new==NULL)
       {
        printf(“Memory allocation error…”); exit(0);
       }
        printf(“\nEnter node information:”);
        scanf(“%d”,&new->info);
        if(root==NULL)
        {
         root=new;     temp=root;
         }
        else
        {
         temp->link=new;   temp=new;
         }
       new->link=root;
       printf(“Do you want to continue…(y/n)”);
       choice=getche( );
     } /* end of while */
     printf(“\nThe Circular Linked list is:\n\n”);
     temp=root;
     while(1)
      {
       printf(“%d”,temp->info);
       if(temp->link==root)  break;
       temp=temp->link;
      }
     }      /* end of main( )*/


How to use Editor Ajax Control in ASP.NET

Editor control is a editor or you can say modifier, as a name suggest you can format article like bold.

How to use Editor 

Step-1 : Add Script Manager Control to the design page
Step-2 : Add Editor control to the page.
Step-3 : Add one button control also handle button_click event.

Code View

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit.HTMLEditor" tagprefix="cc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">


    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <br />
    <cc1:Editor ID="Editor1" runat="server" Height="300px" Width="300px" />
    <p>
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Save " 
            Width="111px" />
    </p>


    </form>
</body>
</html>

Code Generate the following output

How to use Editor Ajax Control in ASP.NET

Thursday, February 20, 2014

Retrieve Record from Database using QueryString Parameter in ASP.NET

In my previous article, we already covered query string concepts. In this article, we will cover how to get record from database using query string parameter. For this types of problem, we will take two webform, first webform is used for sending querystring and pass into second web form.

Design pattern

Step-1 : Take two Web Form in solution explorer (default.aspx, default2.aspx)
Step-2 :  Bind GridView on first page (default.aspx page) using SqlDataSource control.
Step-3 : Check "select checkbox using show smart tag.
Step-4 : Handle GridView SelectedIndexChanged event , also generate QueryString in it. look like



protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        Response.Redirect("~/Default2.aspx?id=" + GridView1.SelectedRow.Cells[1].Text);
    }


Step-5 : In second page( Default2.aspx), Bind form view using SqlDataSource with Query String parameter.

Retrieve Record from Database using QueryString Parameter in ASP.NET

Retrieve Record from Database using QueryString Parameter in ASP.NET

Code view 

Default.aspx with Default.aspx.cs page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
        SelectCommand="SELECT * FROM [usertable]"></asp:SqlDataSource>
    <div>
    
    </div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
        DataKeyNames="id" DataSourceID="SqlDataSource1" 
        onselectedindexchanged="GridView1_SelectedIndexChanged">
        <Columns>
            <asp:CommandField ShowSelectButton="True" />
            <asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" 
                ReadOnly="True" SortExpression="id" />
            <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
            <asp:BoundField DataField="address" HeaderText="address" 
                SortExpression="address" />
        </Columns>
    </asp:GridView>
    </form>
</body>
</html>

// Code view

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        Response.Redirect("~/Default2.aspx?id=" + GridView1.SelectedRow.Cells[1].Text);
    }
}

Default2.aspx 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:FormView ID="FormView1" runat="server" DataKeyNames="id" 
            DataSourceID="SqlDataSource1" Height="174px" Width="158px">
            <EditItemTemplate>
                id:
                <asp:Label ID="idLabel1" runat="server" Text='<%# Eval("id") %>' />
                <br />
                name:
                <asp:TextBox ID="nameTextBox" runat="server" Text='<%# Bind("name") %>' />
                <br />
                address:
                <asp:TextBox ID="addressTextBox" runat="server" Text='<%# Bind("address") %>' />
                <br />
                <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" 
                    CommandName="Update" Text="Update" />
                &nbsp;<asp:LinkButton ID="UpdateCancelButton" runat="server" 
                    CausesValidation="False" CommandName="Cancel" Text="Cancel" />
            </EditItemTemplate>
            <InsertItemTemplate>
                name:
                <asp:TextBox ID="nameTextBox" runat="server" Text='<%# Bind("name") %>' />
                <br />
                address:
                <asp:TextBox ID="addressTextBox" runat="server" Text='<%# Bind("address") %>' />
                <br />
                <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" 
                    CommandName="Insert" Text="Insert" />
                &nbsp;<asp:LinkButton ID="InsertCancelButton" runat="server" 
                    CausesValidation="False" CommandName="Cancel" Text="Cancel" />
            </InsertItemTemplate>
            <ItemTemplate>
                id:
                <asp:Label ID="idLabel" runat="server" Text='<%# Eval("id") %>' />
                <br />
                name:
                <asp:Label ID="nameLabel" runat="server" Text='<%# Bind("name") %>' />
                <br />
                address:
                <asp:Label ID="addressLabel" runat="server" Text='<%# Bind("address") %>' />
                <br />

            </ItemTemplate>
        </asp:FormView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
            SelectCommand="SELECT * FROM [usertable] WHERE ([id] = @id)">
            <SelectParameters>
                <asp:QueryStringParameter Name="id" QueryStringField="id" Type="Int32" />
            </SelectParameters>
        </asp:SqlDataSource>
    </div>
    </form>
</body>
</html>

Code Generate the following output

Retrieve Record from Database using QueryString Parameter in ASP.NET

Retrieve Record from Database using QueryString Parameter in ASP.NET

© Copyright 2013 Computer Programming | All Right Reserved