Q.1. Explain the different types of iteration control systems used in C#, using
appropriate syntax with an example for each.
Ans. Iteration Statements (C# Reference)
You can create loops by using the iteration statements. Iteration statements cause
embedded statements to be executed a number of times, subject to the loop-termination
criteria. These statements are executed in order, except when a jump statement is
encountered. The following keywords are used in iteration statements:
• do
The do statement executes a statement or a block of statements enclosed in {}
repeatedly until a specified expression evaluates to false. In the following example the
do loop statements execute as long as the variable y is less than 5.
Example
// statements_do.cs
using System;
public class TestDoWhile
{
public static void
{
int x = 0;
do
{
Console.WriteLine(x);
x++;
}
while (x <>
}
}
Unlike the while statement, the body loop of the do statement is executed at least once
regardless of the value of the expression
• for
The for loop executes a statement or a block of statements repeatedly until a specified
expression evaluates to false. The for loop is handy for iterating over arrays and for
sequential processing. In the following example, the value of int i is written to the
console and i is incremented each time through the loop by 1.
Example
// statements_for.cs
// for loop
using System;
class ForLoopTest
{
static void
{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(i);
}
}
}
The for statement executes the enclosed statement or statements repeatedly as follows:
• First, the initial value of the variable i is evaluated.
• Then, while the value of i is less than 5, the condition evaluates to true, the
Console.WriteLine statement is executed and i is reevaluated.
• When i is greater than 5, the condition becomes false and control is transferred
outside the loop.
Because the test of conditional expression takes place before the execution of the loop,
therefore, a for statement executes zero or more times.
All of the expressions of the for statement are optional; for example, the following
statement is used to write an infinite loop:
for (;;)
{
// ...
}
• foreach , IN
The foreach statement repeats a group of embedded statements for each element in an
array or an object collection. The foreach statement is used to iterate through the
collection to get the desired information, but should not be used to change the contents
of the collection to avoid unpredictable side effects.
The embedded statements continue to execute for each element in the array or
collection. After the iteration has been completed for all the elements in the collection,
control is transferred to the next statement following the foreach block.
Example
In this example, foreach is used to display the contents of an array of integers.
// cs_foreach.cs
class ForEachTest
{
static void
{
int[] fibarray = new int[] { 0, 1, 2, 3, 5, 8, 13 };
foreach (int i in fibarray)
{
System.Console.WriteLine(i);
}
}
}
• while
The while statement executes a statement or a block of statements until a specified
expression evaluates to false.
Example
// statements_while.cs
using System;
class WhileTest
{
static void
{
int n = 1;
while (n <>
{
Console.WriteLine("Current value of n is {0}", n);
n++;
}
}
}
Q.2. Discus the exception handling concept using following statement.
Ans. (a) Catching with try – Catch
try-catch
The try-catch statement consists of a try block followed by one or more catch clauses,
which specify handlers for different exceptions. This statement takes one of the
following forms:
try try-block
catch (exception-declaration-1) catch-block-1
catch (exception-declaration-2) catch-block-2
...
try try-block catch catch-block
where:
try-block
Contains the code segment expected to raise the exception.
exception-declaration, exception-declaration-1, exception-declaration-2
The exception object declaration.
catch-block, catch-block-1, catch-block-2
Contains the exception handler.
The try-block contains the guarded code block that may cause the exception. The block
is executed until an exception is thrown or it is completed successfully. For example, the
following attempt to cast a null object raises the NullReferenceException exception:
object o2 = null;
try
{
int i2 = (int) o2; // Error
}
The catch clause can be used without arguments, in which case it catches any type of
exception, and referred to as the general catch clause. It can also take an object
argument derived from System.Exception, in which case it handles a specific exception.
For example:
catch (InvalidCastException e)
{
}
It is possible to use more than one specific catch clause in the same try-catch
statement. In this case, the order of the catch clauses is important because the catch
clauses are examined in order. Catch the more specific exceptions before the less
specific ones.
A throw
rethrow the exception, which has been caught by the catch statement. For example:
catch (InvalidCastException e)
{
throw (e); // Rethrowing exception e
}
If you want to rethrow the exception currently handled by a parameterless catch clause,
use the throw statement without arguments. For example:
catch
{
throw;
}
When inside a try block, only initialize variables that are declared therein; otherwise, an
exception can occur before the execution of the block is completed. For example, in the
following code example, the variable x is initialized inside the try block. An attempt to
use this variable outside the try block in the Write(x) statement will generate the
compiler error: Use of unassigned local variable.
public static void
{
int x;
try
{
x = 123; // Don't do that.
// ...
}
catch
{
// ...
}
Console.Write(x); // Error: Use of unassigned local variable 'x'.
}
(b) Catching up with Try-Finally.
The finally block is useful for cleaning up any resources allocated in the try block.
Control is always passed to the finally block regardless of how the try block exits. This
statement takes the following form:
try try-block finally finally-block
where:
try-block
Contains the code segment expected to raise the exception.
finally-block
Contains the exception handler and the cleanup code.
Whereas catch is used to handle exceptions that occur in a statement block, finally is
used to guarantee a statement block of code executes regardless of how the preceding
try block is exited.
In this example, there is one invalid conversion statement that causes an exception.
When you run the program, you get a run-time error message, but the finally clause will
still be executed and display the output.
// try-finally
using System;
public class TestTryFinally
{
public static void
{
int i = 123;
string s = "Some string";
object o = s;
try
{
// Invalid conversion; o contains a string not an int
i = (int) o;
}
finally
{
Console.Write("i = {0}", i);
}
}
(c) Handling all with Try-Catch-Finally
A common usage of catch and finally together is to obtain and use resources in a try
block, deal with exceptional circumstances in a catch block, and release the resources
in the finally block.
// try-catch-finally
using System;
public class EHClass
{
public static void
{
try
{
Console.WriteLine("Executing the try statement.");
throw new NullReferenceException();
}
catch(NullReferenceException e)
{
Console.WriteLine("{0} Caught exception #1.", e);
}
catch
{
Console.WriteLine("Caught exception #2.");
}
finally
{
Console.WriteLine("Executing finally block.");
}
}
}
Q.3. Write simple illustration program for handling the database in C# for
(a) Creating a Table Using
Imports System.Data.SqlClient
Public Class frmDataTable
Inherits System.Windows.Forms.Form
Private cn As New SqlConnection("server=(local);uid=sa;pwd=;database=emp")
Private WithEvents dadept As New SqlDataAdapter("select * from dept", cn)
Private dt As DataTable
Private Sub frmDataTable_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
dt = New DataTable("Dept")
Dim dc1 As New DataColumn("dname")
dt.Columns.Add(dc1)
Dim dc2 As New DataColumn("loc")
dt.Columns.Add(dc2)
dgdept.DataSource = dt
txtDname.Focus() 'THIS IS TEXTBOX FOR DEPT NAME
End Sub
Private Sub btnadd_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnadd.Click
Dim drow As DataRow = dt.NewRow
drow("dname") = txtDname.Text
drow("loc") = txtDloc.Text 'THIS IS TEXTBOX FOR LOC NAME
dt.Rows.Add(drow)
btnClear_Click(sender, e) 'THIS BUTTON CLEAR CONTENTS
End Sub
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnSave.Click
Dim cb As New SqlCommandBuilder(dadept)
Dim dt1 As DataTable
Try
dt1 = CType(dgdept.DataSource, DataTable)
dadept.Update(dt1)
dt.AcceptChanges()
MessageBox.Show("Data Updated To Databse...")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnClear.Click
txtDname.Clear()
txtDloc.Clear()
txtDname.Focus()
End Sub
Private Sub dadept_RowUpdated(ByVal sender As Object, ByVal e As
System.Data.SqlClient.SqlRowUpdatedEventArgs) Handles dadept.RowUpdated
If e.Status = UpdateStatus.ErrorsOccurred Then
e.Row.RowError = "Sandeep Says " & e.Errors.Message
e.Status = UpdateStatus.Continue
End If
End Sub
End Class
(b) Inserting new record from Database
To insert new records into a database using the TableAdapter.Insert method
• Call the TableAdapter's Insert method, passing in the values for each column as
parameters
NorthwindDataSetTableAdapters.RegionTableAdapter regionTableAdapter =
new NorthwindDataSetTableAdapters.RegionTableAdapter();
regionTableAdapter.Insert(5, "NorthWestern");
(c) Selecting record from Database
using System;
using System.IO;
using System.Xml;
using System.Xml.XPath;
public class Sample
{
public static void
{
XPathDocument doc = new XPathDocument("booksort.xml");
XPathNavigator nav = doc.CreateNavigator();
//Select all books by Jane Austen.
XPathExpression expr;
expr = nav.Compile("descendant::book[author/last-name='Austen']");
//Sort the selected books by title.
expr.AddSort("title", XmlSortOrder.Ascending, XmlCaseOrder.None, "", XmlDataType.Text);
//Display the selection.
XPathNodeIterator iterator = nav.Select(expr);
while (iterator.MoveNext()){
XPathNavigator nav2 = iterator.Current.Clone();
nav2.MoveToFirstChild();
Console.WriteLine("Book title: {0}", nav2.Value);
}
}
}
0 Comments:
Post a Comment