0% found this document useful (0 votes)
10 views10 pages

AWP Notes 2

Notes for advance web programming

Uploaded by

adamscarlet99
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views10 pages

AWP Notes 2

Notes for advance web programming

Uploaded by

adamscarlet99
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Advanced Web Reverse ()

Programming
Reverses a one-dimensional array so that its elements are backward, from
last to first.

2.8 CONDITIONAL LOGIC

• Conditional logic means deciding which action to take based on user


input, external conditions, or other information—is the heart of
programming.
• All conditional logic starts with a condition: a simple expression that
can be evaluated to true or false.
• Your code can then make a decision to execute different logic
depending on the outcome of the condition.
• To build a condition, you can use any combination of literal values
or variables along with logical operators. Table below lists the basic
logical operators.

• You can use all the comparison operators with any numeric types.
With string data types, you can use only the equality operators (==
and !=). C# doesn’t support other types of string comparison
operators.

int result;
result = String.Compare("apple", "attach"); // result = -1
result = String.Compare("apple", "all"); // result = 1
result = String.Compare("apple", "apple"); // result = 0
// Another way to perform string comparisons.
string word = "apple";
result = word.CompareTo("attach"); // result = -1

34
34
2.8.1 Conditional Statements The C# Language
The if Statement
• The if statement is the if (myNumber > 10)
powerhouse of conditional {
logic, able to evaluate any
combination of conditions // Do something.
and deal with multiple and }
different pieces of data. else if (myString == "hello")
• Here’s an example with an if {
statement that features two
else conditions: // Do something.
• An if block can have any }
number of conditions. If you else
test only a single condition, {
you don’t need to include any
else blocks. // Do something.
}

• Keep in mind that the if construct matches one condition at most.


• For example, if myNumber is greater than 10, the first condition will
be met.
• That means the code in the first conditional block will run, and no
other conditions will be evaluated.

• Whether my String contains the text hello becomes irrelevant,


because that condition will not be evaluated. If you want to check
both conditions, don’t use an else block—instead, you need two if
blocks back-to-back, as shown here:

if (myNumber > 10)


{
// Do something.
}
if (myString == "hello")
{
// Do something.
}
The switch Statement

• C# also provides a switch statement that you can use to evaluate a


single variable or expression for multiple possible values. The only
limitation is that the variable you’re evaluating must be an integer-
based data type, a bool, a char, a string, or a value from an
enumeration. Other data types aren’t supported.
35
Advanced Web • In the following code, each case examines the myNumber variable
Programming
and tests whether it’s equal to a specific integer:

switch (myNumber) • You’ll notice that the C# syntax


inherits the convention of C/C++
{ programming, which requires that
case 1: every branch in a switch statement be
ended by a special break keyword.
// Do something.
• If you omit this keyword, the
break; compiler will alert you and refuse to
build your application.
case 2:
• The only exception is if you choose to
// Do something. stack multiple case statements directly
on top of each other with no
break;
intervening code.
default:
• This allows you to write one segment
// Do something. of code that handles more than one
case. Here’s an example:
break;
}

switch (myNumber) • Unlike the if statement, the


switch statement is limited to
{ evaluating a single piece of
case 1: information at a time.

case 2: • However, it provides a


cleaner, clearer syntax than
// This code executes if the if statement when you
myNumber is 1 or 2. need to test a single variable.

break;
default:
// Do something.
break;
}

2.8 LOOPS IN C#

Introduction
• Loops allow you to repeat a segment of code multiple times. C# has
three basic types of loops. You choose the type of loop based on the
type of task you need to perform. Your choices are as follows:
36
36
• You can loop a set number of times with a for loop. The C# Language

• You can loop through all the items in a collection of data by using a
foreach loop.

• You can loop while a certain condition holds true with a while or
do...while loop.

• The for and foreach loops are ideal for chewing through sets of data
that have known, fixed sizes.

• The while loop is a more flexible construct that allows you to


continue processing until a complex condition is met. The while
loop is often used with repetitive tasks or calculations that don’t
have a set number of iterations.
2.8.1 The for Loop

• The for loop is a basic ingredient in many programs. It allows you to


repeat a block of code a set number of times, using a built-in
counter.

• To create a for loop, you need to specify a starting value, an ending


for (int i = 0; i < 10; i++)
{
// This code executes ten times.
System.Diagnostics.Debug.Write(i);
}

value, and the amount to increment with each pass. Here’s one
example:

• You’ll notice that the for loop starts with parentheses that indicate
three important pieces of information. The first portion (int i = 0)
creates the counter variable (i) and sets its initial value (0).

• The third portion (i++) increments the counter variable. In this


example, the counter is incremented by 1 after each pass.

• That means i will be equal to 0 for the first pass, equal to 1 for the
second pass, and so on. However, you could adjust this statement so
that it decrements the counter (or performs any other operation you
want).

string[] stringArray = {"one", "two", "three"};


for (int i = 0; i < stringArray.Length; i++)
{
System.Diagnostics.Debug.Write(stringArray[i] + " "); }

37
Advanced Web • The middle portion (i < 10) specifies the condition that must be met
Programming
for the loop to continue. This condition is tested at the start of every
pass through the block. If i is greater than or equal to 10, the
condition will evaluate to false, and the loop will end.
2.8.2 The foreach Loop

• C# also provides a foreach loop that allows you to loop through the
items in a set of data.

• With a foreach loop, you don’t need to create an explicit counter


variable.

• Instead, you create a variable that represents the type of data for
which you’re looking. Your code will then loop until you’ve had a
chance to process each piece of data in the set.

• The foreach loop is particularly useful for traversing the data in


collections and arrays.

• For example, the next code segment loops through the items in an
array by using foreach.

string[] stringArray = {"one", "two", "three"};


foreach (string element in stringArray)
{
// This code loops three times, with the element variable set
to
// "one", then "two", and then "three".
System.Diagnostics.Debug.Write(element + " ");
}
• This code has exactly the same effect as the example in the previous
section, but it’s a little simpler:

• In this case, the foreach loop examines each item in the array and
tries to convert it to a string. Thus, the foreach loop defines a string
variable named element.

• If you used a different data type, you’d receive an error.

• The foreach loop has one key limitation: it’s read-only.

• For example, if you wanted to loop through an array and change the
values in that array at the same time, foreach code wouldn’t work.

38
38
The C# Language

int[] intArray = {1,2,3};


foreach (int num in intArray)
{
num += 1;
}

• Here’s an example of some flawed code:

2.8.3 The While Loop

• Finally, C# supports a while loop that tests a specific condition


before or after each pass through the loop.
• When this condition evaluates to false, the loop is exited. Here’s an
example that loops ten times.
• At the beginning of each pass, the code evaluates whether the
counter (i) is less than some upper limit (in this case, 10). If it is, the
loop performs iteration.

int i = 0;
while (i < 10)
{
i += 1;
// This code executes ten times. }

• You can also place the condition at the end of the loop by using the
do...while syntax. In this case, the condition is tested at the end of
each pass through the loop:

int i = 0;
do
{
i += 1;
// This code executes ten times.
}
while (i < 10);

39
Advanced Web
Programming
2.9 METHODS IN C#

• Methods are the most basic building block you can use to organize
your code.

• Essentially, a method is a named grouping of one or more lines of


code.

• Ideally, each method will perform a distinct, logical task.

• By breaking down your code into methods, you not only simplify
your life, but also make it easier to organize your code into classes
and step into the world of object-oriented programming.

• When you declare a method in C#, the first part of the declaration
specifies the data type of the return value, and the second part
indicates the method name.

• If your method doesn’t return any information, you should use the
void keyword instead of a data type at the beginning of the
declaration.

// This method doesn’t return any information.


void MyMethodNoReturnedData()
{
// Code goes here.
}
// This method returns an integer.
int MyMethodReturnsData()
{
// As an example, return the number 10.
return 10;
}

• Notice that the method name is always followed by parentheses.


This allows the compiler to recognize that it’s a method.

• In this example, the methods don’t specify their accessibility. This is


just a common C# convention. You’re free to add an accessibility
keyword (such as public or private), as shown here:

40
40
The C# Language
private void MyMethodNoReturnedData()
{
// Code goes here.
}

• The accessibility determines how different classes in your code can


interact.

• Private methods are hidden from view and are available only locally,
whereas public methods can be called by all the other classes in your
application.

• To really understand what this means, you’ll need to read the next
chapter, which discusses accessibility in more detail.

• Invoking your methods is straightforward—you simply type the


name of the method, followed by parentheses.

• If your method returns data, you have the option of using the data it
returns or just ignoring it:

// This call is allowed.


MyMethodNoReturnedData();
// This call is allowed.
MyMethodReturnsData();
// This call is allowed.
int myNumber;
myNumber = MyMethodReturnsData();
// This call isn’t allowed.
// MyMethodNoReturnedData() does not return any
information.
myNumber = MyMethodNoReturnedData();

2.9.1 Parameters
• Methods can also accept information through parameters.
Parameters are declared in a similar way to variables.

• By convention, parameter names always begin with a lowercase


letter in any language.

41
Advanced Web • Here’s how you might create a function that accepts two parameters
Programming
and returns their sum:

private int AddNumbers(int number1, int number2)


{
return number1 + number2;

• When calling a method, you specify any required parameters in


parentheses or use an empty set of parentheses if no parameters are
required:

// Call a method with no parameters.


MyMethodNoReturnedData();
// Call a method that requires two integer parameters.
MyMethodNoReturnedData2(10, 20);
// Call a method with two integer parameters and an
integer return value.
int returnValue = AddNumbers(10, 10);

2.9.2 Method Overloading

• C# supports method overloading, which allows you to create more


than one method with the same name but with a different set of
parameters.
• When you call the method, the CLR automatically chooses the
correct version by examining the parameters you supply.
• This technique allows you to collect different versions of several
methods together.
• For example, you might allow a database search that returns an array
of Product objects representing records in the database.
• Rather than create three methods with different names depending on
the criteria, such as GetAllProducts(), GetProductsInCategory(), and
GetActiveProducts(), you could create three versions of the
GetProducts() method.
• Each method would have the same name but a different signature,
meaning it would require different parameters.
• This example provides two overloaded versions for the
GetProductPrice() method:
42
42
The C# Language
private decimal GetProductPrice(int ID)
{
// Code here.
}
private decimal GetProductPrice(string name)
{
// Code here.
}
// And so on...

• Now you can look up product prices based on the unique product ID
or the full product name, depending on whether you supply an
integer or string argument:

decimal price;
// Get price by product ID (the first version).
price = GetProductPrice(1001);
// Get price by product name (the second version).
price = GetProductPrice("DVD Player");

• You cannot overload a method with versions that have the same
signature that is, the same number of parameters and parameter data
types because the CLR will not be able to distinguish them from
each other.

• When you call an overloaded method, the version that matches the
parameter list you supply is used. If no version matches, an error
occurs.
Optional and Named Parameters

• Method overloading is a time-honored technique for making


methods more flexible, so you can call them in a variety of ways.
• C# also has another feature that supports the same goal: optional
parameters.
• An optional parameter is any parameter that has a default value.
• If your method has normal parameters and optional parameters, the
optional parameters must be placed at the end of the parameter list.
• Here’s an example of a method that has a single optional parameter:

43

You might also like