-->

Tuesday, March 25, 2014

C program to sort 10 elements of an array and a list of 11 names in ascending order using selection sort technique

C program to sort 10 elements of an array in ascending order using selection sort technique.

#include<stdio.h>
#include<conio.h>
void se1_sort_ao(int arr[],int n)
{
  int i, j, min, mops;
  for(i=0;i<n-1;i++)
   {
    min = arr[i]; mpos = 1;
    for(j=i+1; j<n; j++)
    if(arr[j] < min)
      {
      min = arr[j]; mops = j;

      }
    arr[mpos] = arr[i];   arr[i] = min;
   }
}
main()
{
    int a[10], i;
    printf("Enter 10 element of the array:\n \n");
    for(i=0;i<10;i++)
      scanf("%d",&a[i]);
    printf("The array before sorting:\n \n");
    for(i=0;i<10;i++)
      printf("%d",a[i]);
    sel_sort_ao(a,10);
    printf("\n \n The array after sorting:\n \n");
    for(i=0;i<10;i++)
      printf("%d",a[i]);
}

C program to sort a list of 11 names in ascending order using selection sort technique.

#include<stdio.h>
#include<conio.h>
#include<string.h>
void se1sortstrao(char a[][20],int n)
{
  int i, j, mops, k; char min[20];
  for(i=0;i<n-1;i++)
   {
    strcpy( min,a[i]); mpos=i;
    for(j=i+1; j<n; j++)
    if(strcmp(a[j],min)<0)
      {
       strcpy(min,a[j]);   mpos=j;

      }
    strcpy(a[mpos],a[i]);  strcpy(a[i],min);
   }
}
main()
{
    char a[11][20];
    int i;
    clrscr();
    printf("Enter List of 11 names:\n \n");
    for(i=0;i<11;i++)
    gets(a[i]);
    selsortstrao(a,11);
    clrscr();
    printf("The List after sorting:\n \n");
    for(i=0;i<11;i++)
    puts(a[i]);
}

Monday, March 24, 2014

'C' Function to implement 'selection sort' in ascending and descending order

‘C’ function to implement ‘selection sort’ in ascending order.


void se1_sort_ao(int arr[],int n)
{
    int i, j, min, mpos;
    for(i=0;i<n-1;i++)
    {
    min = arr[i];    mpos = i;
    for(j=i+1;j<n;j++)    /*selection of min element */
     if(arr[j] < min)
     {
      min = arr[j]; mpos =j;
     }
    arr[mpos] = arr[i];         /*replacing min element */
    arr[i] = min;
    }    
}

‘C’ function to implement ‘selection sort’ in descending order.

void se1_sort_ao(int arr[],int n)
{
    int i, j, max, mpos;
    for(i=0;i<n-1;i++)
    {
    max = arr[i];    mpos = i;
    for(j=i+1;j<n;j++)    /*selection of max element */
     if(arr[j] > max)
     {
      max = arr[j]; mpos =j;
     }
    arr[mpos] = arr[i];         /*replacing max element */
    arr[i] = max;
    }    
}

Algorithm to implement selection sort ascending and descending order

Algorithm to implement selection sort (ascending order):


SELECTIONSORTAO(arr,n)
Repeat For I =1 to n-1                [n-1 passes]
MIN <-- arr[I]
POS <-- I
Repeat for J=I+1 to n  [to select minimum element]
  If arr[J]< MIN Then:
     MIN <-- arr[J]
     POS <-- J
  [ End of if ]
 [ End of for J ]
 arr[pos] <-- arr[I]
 arr[I] <-- MIN
[End of For I ]
Exit.  

Algorithm to implement selection sort (descending order):

 SELECTIONSORTDO(arr,n)
[‘arr’ is an array of n elements]
Repeat For I =1 to n-1            
  MAX <-- arr[I]; POS <-- I
 Repeat for J=I+1 to n
   If arr[J]>MAX Then:
       MAX <-- arr[J];  POS <-- J
    [ End of if ]
   [ End of for J ]
   arr[pos] <-- arr[I];  arr[I] <-- MAX
[End of For I ]
Exit.  


How to use LINQ projection Operators in ASP.NET

Introduction

Projection operators are used to transform an object into a new object of a different type. By using the Projection operators, you can construct a new object of a different type that is built from each object. The Select and SelectMany clauses are the Projection operators used in LINQ.
The Select operator performs a projection over a sequence and projects the value that is based on a transform function. The Select operator in LINQ performs function just as the Select statement in SQL. The Select operator specifies which elements are to be retrieved. For example, you can use the Select clause to project the first letter from each string in a list of strings. The syntax of using the Select clause is:

C#
public static lEnumerable<S> Select<T, S>( this IEnumerable<T> source, Function<T, S> selector);

The second type of Projection operator used in LINQ is the SelectMany operator. The SelectMany operator projects a sequence of values that are based on a transform function and then organize them into one sequence. The syntax of using the SelectMany clause is:
C#
public static IEnumerable<S> SeIectMany<T, S>( this IEnumerable<T> source, Function<T, IEnumerable<S»selector);

You must be wondering about the difference between the Select and SelectMany operators. The Select and
SelectMany operators are both used to produce a result value from a source of values. The difference lies in
the result value. The Select operator is used to produce one result value for every source value. The result
value is a collection that has the same number of elements from the query.
In contrast, the SelectMany operator produces a single result that contains a concatenated collection from the query.

Let's take an simple example of SelectMany Clause

Source view
  <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Select Many Clause" 
            onclick="Button1_Click" />
        <br />
    </div>
    <asp:ListBox ID="ListBox1" runat="server" Height="169px" Width="108px">
    </asp:ListBox>
    </form>
Code Behind View
 protected void Button1_Click(object sender, EventArgs e)
    {
        string[] mytext = new string[] { "Hello world", " this is simple", "example of projection operator" };
        IEnumerable<string[]> myword = mytext.Select(x => x.Split(' '));
        foreach (string[] item in myword)
            foreach (string wr in item)
                ListBox1.Items.Add(wr);
            
        
    }
Code Generate the Following Output
How to use LINQ projection Operators in ASP.NET

How to make custom password change control in asp.net

Introduction

This control is designed for authenticated user, he/she can change own profile password. Basically, it have three fields, such as old password field, New password field, and retype password field. Looking like

If your old password doesn't match with stored data then new password will not update. Id password match with stored data then your new password will be updated.

Algorithm behind the program 

Step-1 : First of all match your old password with table data using user_id, which is unique. For that, we will create a SELECT query.
Step-2 : Result of Select Query match with Text Box, which is defined for old password.
Step-3 : If Your inputted password is matched with fetched data, which is fetched from select query.
Step-4 : Design update query and will change your old password with new one.

Programming code

Step-1 : Create connection from SqlEngine using SqlConnection class, which is inside in System. Data. SqlClient namespace.

SqlConnection con;
 con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();


Step-2 : After establishing connection, check data which is inside in database table. Check data using SqlDataReader , if data is already exist in table, will not  update new password with old. If doesn't exist data in table , update database table

private void checkold()
    {
        con.Open();
        cmd.CommandText = "select * from Register";
        cmd.Connection = con;
        rd = cmd.ExecuteReader();
        while (rd.Read())
        {
            if (rd["Password"].ToString() == oldpwd.Text && rd["Email"].ToString() == Session["email"].ToString ())
            {
                flag = false;
                break;
            }

        }
        if (flag == false)
        {
            con.Close();
            updatepassword();
        }
        else
        {
            Label1.Text = "Password doesn't match";
            Label1.ForeColor = System.Drawing.Color.Red;            
        }
    } 


Step-3 : Update database table with new one password

private void updatepassword()
    {
        con.Open();
        cmd.CommandText = "update register set Password=@pass where email=@em";
        cmd.Parameters.AddWithValue("@pass", pass.Text);
        cmd.Parameters.AddWithValue("@em", Session["email"].ToString());
        cmd.Connection = con;
        int update = cmd.ExecuteNonQuery();
        if (update >0)
        {
            Label1.Text = "Password Update";
            Label1.ForeColor = System.Drawing.Color.Green; 
        }
        else
        {

            Label1.Text = "Error";
            Label1.ForeColor = System.Drawing.Color.Yellow; 
          
        }
    }

Code Generate the following output

How to make custom password change control in asp.net

How to make custom password change control in asp.net

How to make Register control in asp.net

Introduction

Design Register control for change unauthenticated user to authenticated user. It store user information in Database table permanently. Registration is the first stage of authentication. If you want to give membership to your website then you first design register control, Visual studio IDE  provide a in-built register control named as "CreateUserWizard".

How to Design Register Control

Need some controls, such as TextBox, Button, Label and validation etc. for design it. Let's go for design it in some steps. These are:

Step-1

First of all, Add Html table control on design window,Type 'username' Text in first cell of table. In second cell of table(first row and second column), Add TextBox control in it. Make some changes in TextBox property such as

Id of TextBox : usrname
ValidationGroup : rv

Now, Add RequiredField Validator control in third cell of table (first row and third column). Now, Set some properties of Requiredfield validator.

ErrorMessage : "UserName Must"
ControlToValidate : "usrname"
ForeColor: "Red"
Text : *

Step-2  

Similarly again, Add some other control on design window and also set properties using property window.
Now the complete code of source page is
   <div>
 
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <br />
 
        UserName:
        <asp:TextBox ID="usrname" runat="server" Width="175px" ValidationGroup="rv"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
            ControlToValidate="usrname" ErrorMessage="UserName Must" ForeColor="Red">*</asp:RequiredFieldValidator>

        <br />

        Password:&nbsp;
        <asp:TextBox ID="pwdtxt" runat="server" Width="175px" TextMode="Password" 
            ValidationGroup="rv"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" 
            ControlToValidate="pwdtxt" Display="Dynamic" ErrorMessage="Password Must" 
            ForeColor="Red" ValidationGroup="rv">*</asp:RequiredFieldValidator>
        <br />

        Re-Type:&nbsp;&nbsp;
        <asp:TextBox ID="repwdtxt" runat="server" Width="175px" TextMode="Password" 
            ValidationGroup="rv"></asp:TextBox>
        <asp:CompareValidator ID="CompareValidator1" runat="server" 
            ControlToCompare="pwdtxt" ControlToValidate="repwdtxt" Display="Dynamic" 
            ErrorMessage="Password doesn't match" ForeColor="Red" ValidationGroup="rv">*</asp:CompareValidator>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" 
            ControlToValidate="repwdtxt" Display="Dynamic" 
            ErrorMessage="Retype Password Required" ForeColor="Red" ValidationGroup="rv">*</asp:RequiredFieldValidator>

        <br />

        Email :&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:TextBox ID="emailtxt" runat="server" Width="175px" ValidationGroup="rv"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" 
            ControlToValidate="emailtxt" Display="Dynamic" ErrorMessage="Email Must" 
            ForeColor="Red" ValidationGroup="rv">*</asp:RequiredFieldValidator>
        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" 
            ControlToValidate="emailtxt" Display="Dynamic" ErrorMessage="Email Required" 
            ForeColor="Red" 
            ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" 
            ValidationGroup="rv">*</asp:RegularExpressionValidator>
        <br />
        <br />

        <asp:Button ID="Button1" runat="server" Text="Register it" Width="114px" 
            ValidationGroup ="rv" onclick="Button1_Click" />
 
        <asp:ConfirmButtonExtender ID="Button1_ConfirmButtonExtender" runat="server" 
            ConfirmText="Are You sure You want to create an account" Enabled="True" TargetControlID="Button1">
        </asp:ConfirmButtonExtender>
 
        <br />
 
    </div>
    <asp:Label ID="Label1" runat="server"></asp:Label> 

Design view of your source code is:

Design view of register control


Design Business logic code on Button_click event

DOTNET provides a Namespace, such as System.Data.SqlClient, which connects front-end to back-end. This Namespace contains multiple classes such as SqlConnection, SqlCommand and etc.
Front-end can connect with back-end using SqlConnection class. First of all, we create an object for it.
We can access the Data member and member function of class with the help of that object. such as

Step-1

using System. Data. SqlClient;

// Create an instance of SqlConnection class
SqlConnection con = new SqlConnection( );

// Access connection string using con instance.

con. ConnectionString = " Connection String Parameter ";

// Initialize connection string with database parameter

Some ConnectionString parameters which passes inside the ConnectionString. like
Data Source : Server Name;
Database Name : Name of your Database;
User-name : Database user name;
Password :  Password of your Database

For example
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"

Step-2

Now, open the state of connection. Because state of connection close by default. So call open method from instance of SqlConnection class, such as

con.open( );

After making connection, you can access or delete data from Database table. CommandText property of SqlCommand class provide interface with Database table. You can access this property by instance of SqlCommand class, such as

Step-3

SqlCommand cmd = new SqlCommand( );
  cmd.CommandText = "select * from Register";
With the help of  this query,  we can access whole data of register table. If you want to access particular column from table, must include column name inside the query. Like

cmd. CommandText = "Select column-name from [Table-name]";

Step-4

Now, Connect SqlCommand class with Connection object using connection property of SqlCommand class.
cmd. Connection = con;

Step-5

After fetching the data from database table, Read must from SqlDataReader class, which is inside in System.Data.SqlClient Namespace. Like

SqlDataReader rd= cmd. ExecuteReader( ); 

Read all rows of Database table using Read ( ) method of SqlDataReader class. Also check data, which is inputted by unauthenticated user whether is already exist or not in Database table. If Exist then set dirty flag is false and break while loop.If inputted data does not exist in Database table, you can insert inoutted data into database table.

while (rd.Read ())
  {
    if (rd["UserName"].ToString () == usrname .Text || rd["Email"].ToString ()==emailtxt .Text)
  {
flag=false;
   rd.Close ();
     break;
     
  }
           
  }
    if (flag ==false)
  {
                    Label1 .Text ="User Name and Email already registred";
                    Label1 .ForeColor =System.Drawing.Color.Red;
       
     
  }
                else
                {
                    insertdata();

                }

Code Generate the following output

User Name and Email already registred

Step-6

Design Data insertion algorithm 

Step-1 : Repeat step I and II
Step-2 : Now, Create insertion query for Data insertion into database table. Your query look like this

cmd.CommandText = "insert into Register(UserName,Password,Email)values(@uname,@pass,@em)";

Step-3 : Add some Parameters using AddWithValue ( ) method of SqlParameter class.

cmd.Parameters .AddWithValue ("@uname",usrname.Text);
                cmd.Parameters .AddWithValue ("@pass",pwdtxt .Text);
                cmd.Parameters .AddWithValue ("@em",emailtxt .Text);

Step-4 : Now, call ExecuteNonQuery (); method of SqlCommand class for update rows of database table.
Step-5 :  If Rows is affected by ExecuteNonQuery (); method then it returns 1 bydefault.
How to make Register control in asp.net

The complete code Data Insertion

using System;
using System.Data.SqlClient;
using System.Configuration;

public partial class registerrcontrol : System.Web.UI.Page
{
    bool flag = true;
    public registerrcontrol()
    {

    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        using (SqlConnection con = new SqlConnection())
        {
            con.ConnectionString =ConfigurationManager.ConnectionStrings ["ConnectionString"].ToString ();
            con.Open ();
            using(SqlCommand cmd = new SqlCommand ())
{
                cmd.CommandText = "select * from Register";
                cmd.Connection =con;
                SqlDataReader rd=cmd.ExecuteReader ();
                while (rd.Read ())
{
                    if (rd["UserName"].ToString () == usrname .Text || rd["Email"].ToString ()==emailtxt .Text)
{
flag=false;
                        rd.Close ();
                        break;

 
}
        
}
                if (flag ==false)
{
                    Label1 .Text ="User Name and Email already registred";
                    Label1 .ForeColor =System.Drawing.Color.Red;
             


 
}
                else
                {
                    insertdata();

                }

 
}
        }

       
    }

    private void insertdata()
    {
        using (SqlConnection con = new SqlConnection())
        {
            con.ConnectionString =ConfigurationManager.ConnectionStrings ["ConnectionString"].ToString ();
            con.Open ();
            using(SqlCommand cmd = new SqlCommand ())
{
                cmd.CommandText = "insert into Register(UserName,Password,Email)values(@uname,@pass,@em)";
                cmd.Connection =con;
                cmd.Parameters .AddWithValue ("@uname",usrname.Text);
                cmd.Parameters .AddWithValue ("@pass",pwdtxt .Text);
                cmd.Parameters .AddWithValue ("@em",emailtxt .Text);
                
               cmd.Connection =con;
                int a= cmd.ExecuteNonQuery ();
                if (a>0)
{
                    Label1 .Text ="Data Inserted";
                    Label1 .ForeColor =System.Drawing.Color .Green ;
 
}
            }
        }
       
    }
}

Sunday, March 23, 2014

Reverse array item example in c#

Sorting means ," arranging items of array either in ascending or descending order, known as sorting. Here this example display reverse order of any array items. If you take string type then use Reverse method of Array.

Source code in ASP.NET

<%@ 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:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button"
        Width="100px" />
    <div style="width: 180px">
   
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
   
    </div>
    </form>
</body>
</html>

Code behind code

    protected void Button1_Click(object sender, EventArgs e)  
    {
        string[] fruits = new string[]
        {
            "Red Apple",
            "Yellow Papaya",
            "Orang Orange"
        };

        int[] numbers = new int[] { 65,105,640,800};

        Label1.Text = " fruits array elements.........<br />";
        for (int j = 0; j < fruits.Length; j++)
        {
            Label1.Text += fruits[j] + "<br />";
        }

        Array.Reverse(fruits);
        Label1.Text += "<br /> fruits array elements [after reverse array elements].........<br />";
        for (int j = 0; j < fruits.Length; j++)
        {
            Label1.Text += fruits[j] + "<br />";
        }

        Label1.Text += "<br />numbers array elements.........<br />";
        for (int j = 0; j < numbers.Length; j++)
        {
            Label1.Text += numbers[j].ToString() + "<br />";
        }

        Array.Reverse(numbers);
        Label1.Text += "<br />numbers array elements [after reverse array elements].........<br />";
        for (int j = 0; j < numbers.Length; j++)
        {
            Label1.Text += numbers[j].ToString() + "<br />";
        }
    }  
 

Reverse array item example in c#

© Copyright 2013 Computer Programming | All Right Reserved