Sunteți pe pagina 1din 115

.

NET TECH LOUNGE


Table of Contents
Module 1 (.Net)

Module 2 (User Interface)


1. Introduction to User Interface and HTML
2. CSS ( Cascading Style Sheets )
3. JavaScript
Module 1
Introduction to .NET

The objective of this course is understand about .Net.

Please go through below video which guides you through on each module in .Net Lounge:

https://www.youtube.com/watch?v=Rm79Rl429NA

1. Application Understanding

Objective

 Introduction to Application Understanding


 Different types of Applications
 Examples of each type of applications

IT applications are all about managing information using a technology. To Create, Read, Update

and Delete information are some of the main operations in all IT applications. Login, Search,

Validations etc are some common functionalities in all IT applications. For

example http://irctc.com/displayServlet is a web application and you can check all operations and

functionalities in this website. Three Tier Architecture is the common architecture used in modern

IT applications. Presentation, Business Logic and Database will be in three different physical

entities.

Different types of Applications

Desktop Application – is a computer software designed to help the user to perform specific

tasks. Eg: VLC Media Player, Microsoft Office.

Web Application - is an application that is accessed over a network such as the Internet or an

Intranet. Eg: www.Amazon.com, www.facebook.com.

Mobile Application - Mobile application software is developed for small low-power handheld

devices such as personal digital assistants, enterprise digital assistants or mobile phones. Eg:

Weather Forcast, News Reader, Games, Whatsapp etc.


Related Videos

https://www.youtube.com/watch?v=yGogBKK9Sn8

2. Problem Solving Orientation

Objective

 Introduction to Problem Solving Approach


 Identifying a problem
 Step-by-step approach to solve a problem
 Key elements required for problem solving and programming

2.1. Problem solving orientation


What is a problem??

A problem is a difficulty or a challenge, or situation that needs a solution.

Eg: Driving a car, Making Tea, Solving a crossword puzzle

Sample problem scenario

We can discuss a problem scenario faced by Railway department.


As part of service and development in nation lots of trains were added to the Railway

department. As a result the passenger services also increased. Railway stations increased.

Lakhs of passengers and customers started availing various services like regular ticket bookings,

reservation of tickets, ticket cancellations, enquires etc. Services for passengers and customers

at railway stations resulted in long queues. This created unhappy passengers and customers.

Railway employees were also overburdened with paper and manual work. Dissatisfied customers

and overburdened employees was the end result of development.

Railway wants to improve stake holder satisfaction. This was the problem scenario faced by

Railway department. This problem can be solved in 2 ways – manually or automated.

Railway department hired new staff and increased the number of customer service counters.

Passenger count and train services are steadily increasing, so this solution is not going to work

for a long term. Manual errors are also creeping up during calculations, leading to customer

dissatisfaction, and wastage of time to correct errors.

Management is now thinking why not automate the entire system.

 Ticket booking and seat availability tracking


 Passenger data management
 Regular ticketing and so on…

They decided to come up with a computerized system that handles various day to day activities

at their office.

Computer Programs

Computer is a machine. It needs to be instructed how to perform a task, how to handle data,

where to store it and so on.

Programs – Set of instructions that is carried out by the computer

Software – Collection of computer programs and data that tells computer what to do

In a computer based solution, business requirement of a user, ultimately get translated to lines of

code that instructs computer to work in such a way as to meet the requirement

How to solve a problem


Whenever a problem occurs, people tend to concentrate too much on the solution and

sometimes forget the essence of the problem. It is essential for the individual to have a right

approach to the problem itself in order to figure out the best solution.

People who are really good at solving problems go about it systematically. They have a way of

placing the problem in context and do not jump to conclusions. They evaluate all alternatives.

Steps in Problem Solving

Step 1 - Analyzing the problem

This involves understanding the input and output, various alternatives to reach the output, listing

the assumptions

Step 2 - Designing an algorithm

Defining a step by step procedure to solve the problem

Step 3 - Testing the design for correctness

Checking for the correctness of algorithm by walking through the algorithm manually

Step 4 - Implementing the solution (Translating to code)

Once the correctness of algorithm is checked, it can be translated to any programming language

Step 5 - Testing the program

Once the program is developed it needs to be tested against various test cases which checks if

the program is correct for all expected range of inputs.

Step 6 – Deployment and Maintenance

In this module, the product or the output is given to the customer or end user for their purpose.
Related Videos

https://www.youtube.com/watch?v=lzW7S55P1Gc

2.2. Key elements required for problem solving and


programming
1. Good analytical skills
2. Declarative and imperative knowledge about the solution
3. Ability to apply abstraction
4. Knowledge in a programming language
5. Following good programming practices

1. Good analytical skills

Analytical skill is the ability to use good reasoning in analyzing a situation and also the ability to

solve the problem. Analytical skill can also be said as the ability to organise a mass of data and

draw proper correlations, and then interpreting these trends in terms that are meaningful to

others.

Suppose you have rain data for your town for the past thirty years, given to you at random, with

no comments. You can organise the data chronologically, then draw a graph to demonstrate the

data and then , by extending the graph along its closest fitting curve, you can make reasonable

predictions about the extent of rain next year, assuming that all other factors remain STEADY.

2. Declarative and imperative knowledge about the solution

Declarative knowledge is the knowledge of what to do and imperative knowledge is the

knowledge of how to do. If you have problem in hand and when you know the solution of the

problem then you have declarative knowledge. So ―What is‖ type of knowledge is called

declarative knowledge. Imperative knowledge is a procedural knowledge which is the knowledge

exercised in the performance of some task. ―How to‖ type of knowledge is called Imperative

Knowledge.
Example:

Declarative Knowledge:

This What is type of knowledge is called Declarative knowledge

Imperative Knowledge:

This How to Knowledge is called Imperative Knowledge.


3. Ability to apply abstraction

Abstraction will modularize the logic for a specific functionality in a computer program. It will also

hide complexity of implementation details of a function behind a specific interface defined to

invoke the function. It is recommended that programmers use abstractions whenever suitable in

order to avoid duplication.

4. Knowledge in a programming language

A programming language is a formal language designed to communicate instructions to a

machine, particularly a computer. Programming languages can be used to create programs that

control the behaviour of a machine and/or to express algorithms precisely.

Elements of a programming language

1. Syntax: structural elements of the language. Programs must be syntactically correct.

2. Grammar: defines how syntactical elements need to be combined to form programs

3. Semantics: defines meaning of the code

5. Good programming practices

A good programming practice is related to writing efficient and readable code, a code which is

easily maintainable.

Related Videos

https://www.youtube.com/watch?v=jtuqZxClqKs

3. C# Introduction

3.1. .net and C#


We can use Visual Studio to create Console, Windows and web applications. Different

programming languages like C#,VB,VC++ and J# can be used to develop applications. Here we

will learn how C# can be used in Visual Studio 2010 Express Edition to create console

applications. Express edition will give you all basics options to code, debug and run applications
using C#. This series features Visual C# 2010 Express Edition however the content will be valid

no matter what edition or version of Visual Studio you have.

Get Visual Studio Express Edition

If you don’t already have some edition of Visual Studio installed you can use the link below to get

a free copy of Visual C# 2010 Express Edition.

http://www.visualstudio.com/en-us/downloads#d-2010-express

Follow the instructions in the website to install Visual Studio Express Edition 2010 in your

machine. You may need to register it if you want to use it for more than 30 days. The C# express

supports Console/Windows applications. Web developer Express is required for ASP.Net Web

Applications.

Quick Overview of Visual C# Express Edition IDE

After installing it you can go to All Programs and click on Microsoft Visual C# 2010 Express as

shown below.
In Visual Studio you can select File->New Project or New Project link below Microsoft Visual C#

2010 Express logo as shown below.

In Visual Studio you can select File?New Project or New Project link below Microsoft Visual C#

2010 Express logo as shown below.


When you click on ―OK‖ you will get an editor as shown below.

If you want see all files in the solution Click on solution explorer as shown below.

Static void main() function is the starting point of all C# programs.

Related Videos

https://www.youtube.com/watch?v=TgWrRSinbEY
4. C# Declaring and Assigning Variables

Objective

 Understand variables and DataTypes


 Understand variable Definition and Initialization
 Understand arrays
 Understand array Definition and Initialization

4.1. C# - Data types


What is a variable?

A variable is nothing but a name given to a storage area that our programs can manipulate.

Each variable in C# has a specific type, which determines the size and layout of the variable's

memory, the range of values that can be stored within that memory, and the set of operations

that can be applied to the variable.

The basic value types provided in C# can be categorized as:

In C#, variables are categorized into the following types:

 Value types
 Reference types

Value Types

Value type variables can be assigned a value directly. They are derived from the

class System.ValueType.

The value types directly contain data. Some examples are int, char, float, which stores numbers,

alphabets, floating point numbers, respectively. When you declare an int type, the system
allocates memory to store the value.

The following table lists the available value types in C# 2010:

To get the exact size of a type or a variable on a particular platform, you can use the sizeof

method. The expression sizeof(type) yields the storage size of the object or type in bytes.

Following is an example to get the size of int type on any machine:

namespace DataTypeApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Size of int: {0}", sizeof(int));
Console.ReadLine();
}
}
}

When the above code is compiled and executed, it produces the following result:

Size of int: 4

Reference Types

The reference types do not contain the actual data stored in a variable, but they contain a

reference to the variables.

In other words, they refer to a memory location. More than one variable can point to the same

memory location, the reference types can refer to a memory location. If the data in the memory

location is changed by one of the variables, the other variable automatically reflects this change

in value. Example of built-in reference types are: object and string.

Object Type

The Object Type is the ultimate base class for all data types in C# Common Type System (CTS).
Object is an alias for System.Object class. So object types can be assigned values of any other

types, value types, reference types, predefined or user-defined types.

Example:

object obj;
obj = 100;
obj = "Tom";

String Type

The String Type allows you to assign any string values to a variable. The string type is an alias

for the System.String class. It is derived from object type. The value for a string type can be

assigned using string literals as

String str = "Tutorials Point";

The user-defined reference types are: class, interface, or delegate, which shall be discussed

later.

4.2. Variable Definition & Initialization in C#


Syntax for variable definition in C# is:

<data_type> <variable_list>;

Here, data_type must be a valid C# data type including char, int, float, double, or any user-

defined data type, etc., and variable_list may consist of one or more identifier names separated

by commas.

Some valid variable definitions are shown here:

int i, j, k;

char c, ch;

float f, salary;

double d;

Variable Initialization in C#

Variables are initialized (assigned a value) with an equal sign followed by a constant expression.

The general form of initialization is:


variable_name = value;

Variables can be initialized (assigned an initial value) in their declaration. The initializer consists

of an equal sign followed by a constant expression as:

<data_type> <variable_name> = value;


Some examples are:

int d = 3, f = 5; /* initializing d and f. */


byte z = 22; /* initializes z. */
double pi = 3.14159; /* declares an approximation of pi. */
char x = 'x'; /* the variable x has the value 'x'. */

It is a good programming practice to initialize variables properly, otherwise program would

produce unexpected result.

Try the following example which makes use of various types of variables:

namespace VariableDefinition

class Program

static void Main(string[] args)

short a;

int b ;

double c;

/* actual initialization */

a = 10;

b = 20;

c = a + b;

Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);

Console.ReadLine();

}
}

When the above code is compiled and executed, it produces the following result:

a = 10, b = 20, c = 30

4.3. Accepting Values from User


The Console class in the System namespace provides a function ReadLine() for accepting input

from the user and store it into a variable.

For example,

int num;

num = Convert.ToInt32(Console.ReadLIne());

The function Convert.ToInt32() converts the data entered by the user to int data type, because

Console.ReadLine() accepts the data in string format.

The program below prompts the user to enter his name and he's given a welcome message with

his name:

namespace WelcomeProgram

class Program

static void Main(string[] args)

string name;

Console.Write("Hello, please enter your name: ");

name = Console.ReadLine();

Console.WriteLine("Welcome " + name);

}
4.4. Arrays
An array stores a fixed-size sequential collection of elements of the same type. An array is used

to store a collection of data, but it is often more useful to think of an array as a collection of

variables of the same type.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you

declare one array variable such as numbers and use numbers[0], numbers[1], and ...,

numbers[99] to represent individual variables. A specific element in an array is accessed by an

index.

All arrays consist of contiguous memory locations. The lowest address corresponds to the first

element and the highest address to the last element.

Declaring Arrays

To declare an array in C#, you can use the following syntax:

datatype[] arrayName;

where,

 datatype is used to specify the type of elements to be stored in the array.


 [ ] specifies the rank of the array. The rank specifies the size of the array.
 arrayName specifies the name of the array.

For example,

double[] balance;

Initializing an Array

Declaring an array does not initialize the array in the memory. When the array variable is

initialized, you can assign values to the array.

Array is a reference type, so you need to use the new keyword to create an instance of the array.

For example,

double[] balance = new double[10];

Assigning Values to an Array

You can assign values to individual array elements, by using the index number, like:
double[] balance = new double[10];
balance[0] = 4500.0;

You can assign values to the array at the time of declaration, like:

double[] balance = { 2340.0, 4523.69, 3421.0};

You can also create and initialize an array, like:

int [] marks = new int[5] { 99, 98, 92, 97, 95};

In the preceding case, you may also omit the size of the array, like:

int [] marks = new int[] { 99, 98, 92, 97, 95};

You can also copy an array variable into another target array variable. In that case, both the

target and source would point to the same memory location:

int [] marks = new int[] { 99, 98, 92, 97, 95};


int[] score = marks;

When you create an array, C# compiler implicitly initializes each array element to a default value

depending on the array type. For example for an int array all elements would be initialized to 0.

Related Videos

https://www.youtube.com/watch?v=GuO11WN1AFU

https://www.youtube.com/watch?v=lc-6RrVfsno
5. C# -Conditional Operators
Objective

 Understand conditional constructs, boolean operations and expressions, logical operators


and precedence
 Perform simple, nested and complex conditional operations
 Ability to choose right conditional constructs

5.1. Introduction
There are many scenarios in our everyday life, where we need to take some decisions based on

some criteria or condition. Decision making is one of the major parts of .Net also.

Conditional logic is involved when different operations are to be performed based on whether a

decision is true or not. Conditional expressions consists of conditions that results in a boolean

value and performs actions based on the boolean result. There are three types of decision

making statements in c#. They are:

1. if ...then – This statement is the most basic of all control flow statements. If then statement has

a certain condition expression. It executes a certain section of code only if that particular

condition is true. If the condition is false, control jumps to the end of the if then statement.

2. If ... then ... else – This statement provides a secondary path of execution when the condition

becomes false. There can be nested if then else statement also.

3. switch case – A switch statement allows a variable to be tested for equality against a list of

values. Each value is called a case, and the variable being input is checked for each case. This
statement helps to select one out of the many choices based on an integer or character value.

The conditions will accept only a value and not a range/comparison. The syntax is different from

if else statements. Here we are comparing the input value with different cases. We can set a

default case for inputs which do not satisfy any case.

The following rules apply to a switch statement:

1. The variable used in a switch statement can only be a simple datatype like string, int, char etc.

2. You can have any number of case statements within a switch. Each case is followed by the

value to be compared to and a colon. Every case is terminated by a break statement.

3. The value for a case must be the same data type as the variable in the switch and it must be a

constant or a literal.

4. When the variable is found equal to a case, the statements following that case will execute

until a break statement is reached. When a break statement is reached, the switch terminates,

and the flow of control jumps to the next line following the switch statement.

A switch statement can have an optional default case, which must appear at the end of the

switch. The default case can be used for performing a task when none of the cases is true.

Ternary Operator and If Else Statement

We have already discussed ternary operator in previous course. This operator can be considered

as the short hand of if then else statement.

Syntax

result = (someCondition) ? value1 : value2

This means,

someCondition is executed.

If the outcome of someCondition is true, assign the value of value1 to result,

else assign the value of value2 to result

Example

static void Main(String[] args)

Console.WriteLine("Enter two numbers");


int num1 = Convert.ToInt16(Console.ReadLine());

int num2 = Convert.ToInt16(Console.ReadLine());

int comparisonResult = (num1 > num2) ? num1 : num2;

Console.WriteLine(comparisonResult);

Console.ReadKey();

Thus we can conclude the ternary operator can be considered as the short hand of if then else

statement.

5.2. Conditional (Logical) Operators


Conditional (Logical) Operators are used to evaluate a condition that's applied to one or two

boolean expressions. The result of the evaluation is either true or false.

There are 2 conditional operators:

&& the logical AND operator.

|| the logical OR operator

The logical AND and logical OR operators both take two operands. Each operand is a boolean

expression (i.e., it evaluates to either true or false).

The logical AND condition returns true if both operands are true, otherwise it returns false.

Syntax

(condition1 && condition2) // will return true if both conditions are true

Example:

static void Main(String[] args)

Console.WriteLine("Enter three numbers");

int num1 = Convert.ToInt16(Console.ReadLine());

int num2 = Convert.ToInt16(Console.ReadLine());

int num3 = Convert.ToInt16(Console.ReadLine());

int result = 0;
if ((num1 >= num2) && (num1 >= num3))

result = num1;

else if ((num2 >= num1) && (num2 >= num3))

result = num2;

else

result = num3;

Console.WriteLine(result);

Console.ReadKey();

The logical OR condition returns false if both operands are false, otherwise it returns true.

Syntax

(condition1 || condition2) // will return true if at least one condition is true

Examples:

static void Main(String[] args)

Console.WriteLine("Enter three numbers");

int num1 = Convert.ToInt16(Console.ReadLine());

int num2 = Convert.ToInt16(Console.ReadLine());

int num3 = Convert.ToInt16(Console.ReadLine());

string result = "failure";

if ((num1 == 0) || (num2 == 0) || (num3 == 0))

result = "success";

Console.WriteLine(result);

Console.ReadKey();

Related Videos

https://www.youtube.com/watch?v=Eu9shw-rjFE

https://www.youtube.com/watch?v=byHHD8vXZoE
5.3. Practice Problems
1. Two numbers, num1 and num2 are input. Find whether num1 is greater, num2 is greater or

both are equal.

Our solution should have a method which input 2 numbers, compared the numbers and returns

the result of comparison. Here we have to use a conditional statement.

Solution:

class Program

static void Main(String[] args)

Console.WriteLine("Enter two numbers");

int num1 = Convert.ToInt16(Console.ReadLine());

int num2 = Convert.ToInt16(Console.ReadLine());

if (num1 > num2)

Console.WriteLine(num1 + " is greater than " + num2);

else if (num1 == num2)

Console.WriteLine(num1 + " is equal to " + num2);

else

Console.WriteLine(num2 + " is greater than " + num1);

Console.ReadKey();

Input : 5, 3
13, 5

15,15

Output :

5 is greater than 3

13 is greater than 5

15 is equal to 15

Here we have used the conditional statements to compare the 2 numbers using relational

operators. Based on the result of the condition the result is constructed as a string statement with

the numbers appended to for a meaningful statement. The result is printed.

2. Two numbers, num1 and num2 are input to the program. Based on the users choice one of the

arithmetic operation (add, subtract, multiply, divide) should happen.

Here we can use the switch case as decision maker. This can be implemented in if else also, but

we need to write more than 4 else cases. Instead a switch case can be used. Consider 1 - Add, 2

- Subtract, 3 - Multiply, 4 – Divide. Pass the 2 numbers and the operator to the program. Write a

switch case which will accept the operator number and decide which operation to do. Then

based on the decision made it will do the operation and assign the result. Break is used to break

one particular case after its execution. Break will bring the control at the end of switch case.

Default should be written so that, if the user enters a number other than 1,2,3 or 4 then it should

enter default and give a relevant message.

Solution:

class Program

static void Main(String[] args)

Console.WriteLine("Enter two numbers");

int num1 = Convert.ToInt16(Console.ReadLine());

int num2 = Convert.ToInt16(Console.ReadLine());


Console.WriteLine("Enter the operation:\n1.

Add\n2.Subtract\n3.Multiply\n4.Divide");

int operate = Convert.ToInt16(Console.ReadLine());

int result = 0;

switch (operate)

case 1:

Console.WriteLine("Addition");

result = num1 + num2;

break;

case 2:

Console.WriteLine("Subtraction");

result = num1 - num2;

break;

case 3:

Console.WriteLine("Multiplication");

result = num1 * num2;

break;

case 4:

Console.WriteLine("Division");

result = num1 / num2;

break;

default:

Console.WriteLine("Invalid operation");

result = 0;

break;

Console.WriteLine("Result : " + result);

Console.ReadKey();

}
Input : 10,2,1

Output : 12

6. C#- Basic Iterations (Loops)


Objective

 Understand iterations and loops


 Understand and implement solutions involving simple and nested iterations
 Understand iterator, state, counter and accumulator
 Understand finite, infinite loops
 Understand break and continue conditions

6.1. Loops
There may be a situation when we need to execute a block of code several number of times, and

is often referred to as a loop.

C# has three looping mechanisms. They are:

1. while Loop

2. do...while Loop

3. for Loop

While loop:

In the example a while loop is written to print the numbers from 0 to 5. The variable x is initialized

with 0. Then in while loop, x is checked whether the value is less than 6. If the value of x is less

than 6, it enters the loop and prints the value of x. Then we increment the value of x by 1. Again it
comes to while condition and checks the condition. While condition will be true until x = 5. When

x = 6, the loop exits.

static void Main(string[] args)

int x = 1;

while (x < 6)

Console.WriteLine("x is " + x);

x = x + 1;

Console.WriteLine("Exit testWhileLoop");

Console.ReadLine();

Output:

x is 1

x is 2

x is 3

x is 4

x is 5

Exit testwhileLoop

Note:

You can check the sample solution to know the implementation of code in Visual Studio

https://s3.amazonaws.com/cc-uploads/Sample1.zip

Do ... While loop:

The do while construct consists of a block of code and a condition. First the code within the block

is executed, and then the condition is evaluated. If the condition is true the block is executed

again, this repeats until the condition turns false.

do

statements
}

while (condition);

The example given for while is restructured in do while loop. The output is same.

static void Main(String[] args)

int x = 1;

do

Console.WriteLine("x is " + x);

x = x + 1;

} while (x < 6);

Console.WriteLine("Exit testDoWhileLoop");

Console.ReadLine();

Output:

x is 1

x is 2

x is 3

x is 4

x is 5

Exit testDoWhileLoop

Note:

You can check the sample solution to know the implementation of code in Visual Studio

https://s3.amazonaws.com/cc-uploads/Sample2.zip

See the same example with the value of x = 6, here we can see the difference of while and do

while loops. Here we can see the condition x< 6 is giving false as x = 6. But since its do while
loop, the statements get executed first. So we get xis 6 as output. Then it will check the condition

and exit the loop. If it was while loop the condition is checked first and loop will be exited.

static void Main(String[] args)

int x = 6;

do

Console.WriteLine("x is " + x);

x = x + 1;

} while (x < 6);

Console.WriteLine("Exit testDoWhileLoop");

Console.ReadLine();

Output:

x is 6

Exit testDoWhileLoop

Note:

You can check the sample solution to know the implementation of code in Visual Studio

https://s3.amazonaws.com/cc-uploads/Sample3.zip

For loop:

For loops are used when the number of iterations are known before entering the loop.

Counter based for loops: for loops that work on the basis of a counter value. The start and end

values of counter will be mentioned and loop will be executed as many times until the counter

reaches the end value. The counter will be incremented/decremented during each iteration.

for (initialization; termination; increment/decrement) { statement(s) }

class Program

static void Main(string[] args)

{
for (int x = 1; x < 6; x++)

Console.WriteLine("x is " + x);

Console.WriteLine("Exit testForLoop");

Console.ReadLine();

Output:

x is 1

x is 2

x is 3

x is 4

x is 5

Exit testForLoop

Iterator based loops: This is commonly known as for-each loop. Some languages (E.g. Java,

PHP,C#) has a for each loop that iterates through a collection of items. This type of for loop does

not maintain an explicit counter.

foreach(string s in stringList)

//do something to item

Finite and Infinite Loops

Finite loops: Loops that terminate after a particular number of iterations based on either a

counter value or event within the loop is known as finite loop.

Infinite loops: A loop that do not terminate is known as infinite loop. Programmers should check

for conditions or errors that might result in an infinite loop which is not expected during the

execution of a program.
Some times infinite loops are used to make a program segment loop for ever until an exceptional

conditional such as an error arises. Such loops created intentionally will usually have a control

structure that controls termination of loop.

Eg. An event driven program should loop for ever handling events as they occur only stopping

when terminated by an operator.

6.2. Break & Continue Keyword


The break keyword is used to stop any conditional statement or loop. The break keyword must

be used inside any loop or a switch statement. Break statement terminates a for, while or do

while loop. The control is transferred to the first statement after the loop. The break keyword will

stop the execution of the innermost loop and start executing the next line of code after the block.

Syntax: break; (The syntax of a break is a single statement inside any loop)

You have already used break in switch case in conditional operators. We can see an example

where we use break in a loop. Here we have a for loop from 1 to 5. Also there is a break in the

flow when value of x = 3. After the break happens, the flow jumps out of for loop and prints Exit

testForLoop.

static void Main(string[] args)

for (int x = 1; x < 6; x++) {

if(x==3){

Console.WriteLine("Breaking the loop");

break;

Console.WriteLine("x is " + x);

Console.WriteLine("Exit testForLoop");

Console.ReadLine();

Output:
x is 1

x is 2

Breaking the loop

Exit testForLoop

Continue Keyword

The continue keyword can be used in any of the loop control structures. Continue statement

skips the current iteration of a for, while or do while loop. It causes the loop to immediately jump

to the next iteration of the loop.

Syntax: continue; (The syntax of a continue is a single statement inside any loop)

We can see an example where we use continue in a loop. Here we have a for loop from 1 to 5.

Also there is a continue statement in the flow when value of x = 3. After the continue happens,

the flow stops the execution of that iteration and jumps to the next iteration of the loop. See the

output printed. Here when x = 3, the continue statement executes and skips rest of that iteration .

So the value of x when x = =3 is not printed. This is because the print statement is below the

continue. The continue statement will stop the current running iteration and starts the next

iteration.

static void Main(string[] args)

for (int x = 1; x < 6; x++)

if (x == 3)

Console.WriteLine("Continuing the loop");

continue;

Console.WriteLine("x is " + x);

}
Console.WriteLine("Exit testForLoop");

Console.ReadLine();

Output:

x is 1

x is 2

Continuing the loop

x is 4

x is 5

Exit testForLoop

Related Videos

https://www.youtube.com/watch?v=_Q1HvBgzows
https://www.youtube.com/watch?v=uErKDQpwjy0

6.3. Practice Problems


1. Find the even numbers below a given number.

The requirement is to find and print all the even numbers present below a given number.

The method should accept a number from the main. There should be a loop in the method, which

will start from 1 and increment by 1. Each number need to be checked whether its an even

number or not. If its an even number print the number else continue.

Solution:

static void Main(string[] args)

int input;

Console.WriteLine("Enter the Number");

input = Convert.ToInt32(Console.ReadLine());
for (int x = 1; x <= input; x++)

if ((x % 2) == 0)

Console.WriteLine(x);

Console.ReadLine();

Output:

Here the basic logic to find whether a number is even or odd is to divide the number by 2 and

see whether the remainder is 0. So to find the reminder we can use modulus operator %. Then

the reminder is checked whether its 0. If the reminder is 0, then that number is even. The loop

will continue till the max limit that is the input number.

7. C# - Introduction to Object Oriented Programming


Approach
Objective

 Evolution of different programming approach


 Introduction to Object Oriented Programming Approach
 Overview of Object Oriented Programming
 Characteristics of an Object
7.1. Evolution of Programming Approaches
As we have seen in the previous course, for automating the solution of a problem, we need to do

programming. There were different programming approaches which evolved based on

requirements and better programming practices. In the beginning the programs will be small and

simple. Later the programs will become more and more complex based on the requirements. So

there is a need for better programming approaches.

The following are the different programming approaches which evolved.

 Unstructured Programming
 Structured Programming
 Procedural Programming
 Modular Programming
 Object Oriented Programming

Related Videos

https://www.youtube.com/watch?v=8T1Mion6ilw

7.2. Elements of Programming


Data

Programs are set of instructions that act upon data that is received (input) and transforms it into

required information.

Expressions

Instructions that carry out required operations on the given data.

Functions/Methods

A block of instructions that accept some data, carry out some operations and returns an output.

Structured Programming Approach

Structured approach to programming, implements a system as a collection of functions that

accepts data, processes it and returns an output. A function some times calls another function,

when it wants to make use of the functionality defined in the other function.

A program to calculate salary of an employee might look some what like this. A function to
calculate salary, calling another two functions that calculates HRA and DA. The values returned

by these modules is added up in the module that calculates salary,

In Structured programming the flow of program execution is based on the structure of the

program written. There is more dependency between the variables and the program like a chain.

Example : C language

Object Oriented Programming Approach

We write programs that make up a software to solve a problem in real world. In real world

problem domains we do not find any functions that work on data. We find objects that are

described by some state (data) and having some behaviours (functions).

Object Oriented Approach to programming is about implementing a system as collection of

objects that have state and behaviours, interacting with each other to achieve expected

functionalities.

Example: C++ & C#

In OO programming, the program basic entity is object. An object is any real world entity that has

a well-defined structure and behaviour. Eg: Pencil, Laptop, Mobile, Car, Book, and Human. Every

object has its own characteristics. Every object has 5 sets of characteristics.
7.3. Characteristics of an object
An object is a real world entity that has a well-defined structure and behaviour. It typically

processes the following characteristics:

 State
 Behaviour
 Responsibility
 Communication
 Identity

State

State of an object is a set of properties that describes the object, which can take different values

during the life time of the object.

Eg: Bob is an employee of tech smart, let us have a look into Bob’s properties as an employee:

Knowing Responsibility: It is the responsibility of an object to know its state


Behaviour

Behaviour is how objects react to its state changes or any other operations performed on it

A bank account can perform these responsibilities, by making use of state values or other data

provided to it.

Doing Responsibility: It is the responsibility of object to behave according the operations

performed on it.

Responsibility

 Doing responsibilities
 Doing something itself, like creating an object/doing a calculation
 Initiating action in other objects
 Controlling and coordinating activities in other objects

Knowing responsibilities

 Knowing about state


 Knowing about related objects
 Knowing about things it can derive or calculate

Communication

Objects can communicate with each other, provided they know each other.

Objects can respond to the message send by another object, by performing an action, or

returning some data.

Identifying objects and behaviours

The nouns in the requirements specification would suggest the Objects in the problem domain.

The verbs from the requirements specification would suggest object behaviours.
Related Videos

https://www.youtube.com/watch?v=wE3t1NTlDlE

8. C# - Classes and Objects


Objective

 Introduction to Classes
 Data-Types
 Access Level Modifiers
 Object State - Properties
 Constructors
 OOP Concepts – Encapsulation
 Main Method
 Sample Programs

8.1. Introduction to Classes


We know Class describes the state & behaviour of objects. Thus a Class decides/ defines what

an object does and what data it holds. After creating/ designing a Class, any number of similar

objects can be created.

Thus, a class becomes the template for an object .An object becomes the instance of its class.

How to write a C# Class


The syntax of the class is as follows:

class ClassName

//code here

For e.g.; Suppose we have to create a class for Customer, then

Class Customer

//code here;

Classes – Properties, Get & Set

The variables declared inside a Class are by default not accessible from other Classes, but to

access the values from outside,properties are used.

The properties are special methods called as Accessors, which allows the data to be assigned

to/ accessed from the variable, through Read-only/ Write-only/ Read-Write permissions. The

properties enable a class to expose only the getting & setting of values, while hiding the

implementation of code.

The syntax of the property is as follows:

Accessmodifier datatype PropertyName

get { return variablename; }

set { variablename= value; }

The property contains 2 blocks, a get block, which is called Get accessor & set block, which

is called Set accessor. When the data has to be read using the property, the get accessor will

work & when the data has to be assigned to, the set accessor will work.
Thus the property restricts the access to the value. Property containing only the get block/

get accessor is a Read-Only Property. A property containing only the set block/ set accessor is

the Write-Only property, the Property containing both the Get & Set Accessor is a Read-Write

Property.

For e.g.; we will include the properties for Id & name in our customer class. The Id of the

customer is restricted from modification whereas the name can be given with Read-Write

Permission. Our Class will look like as follows:

class Customer

//Declaration of Variable

private int _id=0 ;

//Property for ID restricted from assigning new values

public int ID

get { return _id; }

//Declare Variable for name & use Property for Read & Write

private string _name;

public string Name

get { return _name; }

set { _name = value; }

Related Videos

https://www.youtube.com/watch?v=wk2SRUEvzzo
8.2. Classes - Constructors
Constructors help to pass the initial values to the variables declared in a class, during the

creation of its object.

In C#, the variables inside a class are initialized with default values using a constructor. A

constructor should have the same name as that of the class. The initial values are passed as

parameters.

The Syntax of a Constructor is as follows:

AccessModifier ClassName(datatype parameter1,datatype parameter2)

variable1 =parameter1;

variable2 = parameter2;

Since the constructor needs to be accessed from other Classes, the Access modifier will always

be public (most permissive).

For e.g.; we can include a Constructor also in our class Customer, for initializing the Id and name

of any customer. Now, our class will look like:

class Customer

//Declaration of Variable

private int _id = 0;

//Property for ID restricted from assigning new values

public int ID

get { return _id; }

//Declare Variable for name & use Property for Read & Write

private string _name;

public string Name

{
get { return _name; }

set { _name = value; }

//Constructor for passing the initial value(as parameter) to the variables

public Customer(int id, string name)

//variable = parameter

_id = id;

_name = name;

A class can have multiple constructors. Also, if a class does not contain a constructor, C# will

instantiate the default values using a default Constructor.

Encapsulation - OOPS Concept

C# support object- Oriented Programming Approach, which include : Encapsulation, inheritance

& Polymorphism.

Encapsulation: A group of related members treated as a single unit. A Class is a single unit

which keeps the variables, its related properties, constructors & other members inside it. Here

the members are encapsulated within the Class.

For e.g; our customer class holds some members. Using Encapsulation, all the members are

treated as a single unit using the class name Customer.

Related Videos

https://www.youtube.com/watch?v=jwlSagZcPOk

8.3. Object Creation and Initialization


A class defines the type of object. So the object will have the type as the Class name. And the

object is created using the ―new‖ keyword followed by the constructor. The constructor is invoked

by the new operator.


The syntax of creating an object using a default constructor for a Class with name ClassName, is

as follows:

ClassName objectName= new ClassName();

Here, ClassName() - is used to invoke the default constructor.

The syntax of creating an object with parameterized constructor is as follows:

ClassName objectName = new ClassName(newValue);

Here, ClassName(newValue) – is used to invoke the parameterized Constructor taking only one

value as the parameter and newValue represent the value to the variable initialised inside the

Constructor.

For e.g.; we will see how to create an object of our class customer, using a default Constructor:

Customer customer= new Customer();

Now, we will see how to create an object of our class customer using parametrized Constructor:

Customer newCustomer = new Customer(100, ―Jack‖);

Classes - Main Method

In C#, Console Application or a Windows Application needs to have starting point for the

program. The Main Method is defined as the entry point of a ―.exe‖ program, i.e. the program

starts execution from the Main Method.

One class should contain a Main Method. Since the execution starts from the Main Method

and it is invoked without creating an object of the Class, the Main method should be defined

using the "static" keyword.

Main method should also specify a return type. The return type can be either "void" type

which means returns nothing or ―int‖ datatype which means returns an integer value by the

completion of Main method.

Main Method can be defined with or without parameters. The Parameter are used to take the

Command line Arguments and the parameters are defined using string[] args.

The syntax of the Main Method can be given as follows:


static void Main()

//code here

or

static void Main(string[] args)

//code here

Here we will see the Class program with the Main Method creating the objects of class customer

and using the members defined inside.

class Program

static void Main(string[] args)

Customer customer = new Customer();

customer.Name="Joe";

Console.WriteLine("{0} :: {1}", customer.ID, customer.Name);

Customer newCustomer = new Customer(100, "Jack");

Console.WriteLine("{0} :: {1}", newCustomer.ID, newCustomer.Name);

Console.ReadKey();

class Customer

//Declaration of Variable

private int _id = 0;

//Property for ID restricted from assigning new values

public int ID

{
get { return _id; }

//Declare Variable for name & use Property for Read & Write

private string _name = string.Empty;

public string Name

get { return _name; }

set { _name = value; }

//Constructor for passing the initial value(as parameter) to the variables

public Customer(int id, string name)

//variable = parameter

_id = id;

_name = name;

//Constructor with 0 arguments

public Customer()

//

Output:

0 :: Joe

100 :: Jack
Related Videos

https://www.youtube.com/watch?v=c29e4Zj7gtI

8.4. C# Code and Naming Conventions


1. Class Naming Convention - Class names should be nouns, in Pascal casing.

For e.g; class Customer, class CustomerManager.

2. Variable Naming Convention - Variable names can be short, but need to be meaningful for

the purpose. All variable names can start with a lower case first letter and the next word in the

same start with capital letter. Variable name should be mnemonic — that is, designed to indicate

to the casual observer the intent of its use. One-character variable names should be avoided.

3. Property Naming Convention – Property names are given Similar as that of corresponding

member, in pascal casing.

For e.g; Id, Name, BasicPay, RegistrationStatus.

4. Comments – In C#, single line Comments are given using // & multi-Line comments are given

using /* and */.

8.5. Practice Problems


Write a class with a main method that will print you the Name, Designation, and Place on the

console.

output should be

Name: Jacquil

Designation: Consultant

Place: LA

9O9 is a web shoppe which helps the user to purchase their item in a convenient manner. But to

order the items the user need to register first and then generate an online Bill after the internet

banking.
In this scenario, you might have identified some objects, what are they? What is the name of the

Class chosen for the Registration details of the User?

The objects that we can find here are User, Item, Bill. We need an object for the user for the

registration details.

To create an object for the user, we need a class with name User. We need variables for taking

the user details like First Name, Last Name, age and Location and Email ID. We will be passing

the values to the user object during the time of object creation, so we need a Constructor. Then

we need to provide Properties for the variables.

To start with the execution and work with the User class, we will include a Program class with

Main method.

Test the User registration by using 3 user objects. Print the name of the user using the objects

created.

Output Should be:

Give the details of users like Haris Jack . Print the Last name, First name of the user as output.

I.e;

Jack, Haris

Solutions:

class User

//Variables

private string _firstname = string.Empty;

private string _lastname = string.Empty;

private int _age =0;

private string _location = string.Empty;

private string _email = string.Empty;

//Constructors
public User()

//

public User(string firstname, string lastname, int age,string location, string

email)

_firstname = firstname;

_lastname = lastname;

_age = age;

_location = location;

_email = email;

//Properties

public string FirstName

get

return _firstname;

set

_firstname = value;

}
}

public string LastName

get

return _lastname;

set

_lastname = value;

public int Age

get

return _age;

set

_age = value;

public string Location


{

get

return _location;

set

_location = value;

public string EmailId

get

return _email;

set

_email = value;

class Program

{
static void Main(string[] args)

//Assign values using constructors.

User user1 = new User("Haris","Jack", 40, "LA", "jac.1990@live.in");

Console.Write(user1.LastName);

Console.Write(", ");

Console.WriteLine(user1.FirstName);

User user2 = new User();

//Assign values using properties.

user2.FirstName = "Robert";

user2.LastName = "George";

user2.Age = 60;

user2.Location = "LA";

user2.EmailId = "roberto.georgie@live.in";

Console.Write(user2.LastName);

Console.Write(", ");

Console.WriteLine(user2.FirstName);

//Assign values using constructors by getting input from user.

Console.WriteLine("Enter first name,last name,age,location and email");

string firstname = Console.ReadLine();

string lastname = Console.ReadLine();

int age = Convert.ToInt32(Console.ReadLine());

string location = Console.ReadLine();

string email = Console.ReadLine();


User user3 = new User(firstname,lastname,age,location,email);

Console.Write(user1.LastName);

Console.Write(", ");

Console.WriteLine(user1.FirstName);

Console.ReadKey();

Output:

Jack, Haris

George, Robert

Enter first name,last name,age,location and email

Joe

Wilson

50

London

hwilson@live.in

Wilson,Joe

This solution shows 3 types of object creation and data initialization.


9. C# - Access specifiers, Properties and Methods
Objective

 Overview and Types of Access Specifiers


 Properties Overview and concepts
 Methods Overview and concepts

9.1. Overview and Types of Access Specifiers


Access modifiers (or Access Specifiers) are keywords used to specify the declared accessibility

of a member or a type. There are four access modifiers:

a. public

b. protected

c. internal

d. private

The following five accessibility levels can be specified using the access modifiers:

Public:

Access is not restricted.

Protected:

Access is limited to the containing class or types derived from the containing class.

Internal:

Access is limited to the current assembly.

Protected Internal:

Access is limited to the current assembly or types derived from the containing class.
Private:

Access is limited to the containing type.

Types or Classes can only have internal or public accessibility. The default accessibility for these

types is internal.

Nested types/classes, which are members of other types/classes, can have declared

accessibilities as indicated in the following table.

The following examples demonstrate how to specify access modifiers on a type and member:

public class Bicycle

public void Pedal() {

// pedal implementation

To set the access level for a class or struct member, add the appropriate keyword to the member

declaration, as shown in the following example.

// public class:

public class Tricycle

{
// protected method:can be accessed in the derived classes

protected void Pedal() { }

// private field: can be accessed within the same class

private int wheels = 3;

// protected internal property: can be accessed from any class within

assembly

protected internal int Wheels

get { return wheels; }

9.2. Properties Overview


A property is a member that provides a flexible mechanism to read, write, or compute the value

of a private field. Properties can be used as if they are public data members, but they are actually

special methods called ―accessors‖. This enables data to be accessed easily and still helps

promote the safety and flexibility of methods.

A property generally has a private data member accompanied by accessor functions and is

accessed syntactically as a field of a class. (Although properties can have different access levels,

the more common case is public access.)

A property definition generally consists of the following two pieces:

i. Definition of a private data member.

private int number = 0;

ii. Definition of a public property using the property declaration syntax. This syntax associates the

private data member with a public property through get and set accessor functions.

public int MyNumber

// Retrieves the number data member.

get
{

return number;

// Assigns to the number data member.

set

number = value;

In this second example, the Time class stores a time period. Internally the class stores the time

in seconds, but a property named Hours enables a client to specify a time in hours. The

accessors for the Hours property perform the conversion between hours.

class Time

private double seconds;

public double Hours

get { return seconds / 3600; }

set { seconds = value * 3600; }

class Program

static void Main()

Time t = new Time();

// Assigning the Hours property causes the 'set' accessor to be called.

t.Hours = 24;

// Evaluating the Hours property causes the 'get' accessor to be called.

Console.WriteLine("Time in hours: " + t.Hours);


}

// Output: Time in hours: 24

The term value is a keyword in the syntax for the property definition. The variable value is

assigned to the property in the calling code.

The type of a property can be a primitive type, a collection of primitive types, a user-defined type,

or a collection of user-defined types.

Properties enable a class to expose a public way of getting and setting values, while hiding

implementation or verification code.

A get property accessor is used to return the property value, and a set accessor is used to assign

a new value. These accessors can have different access levels.

The value keyword is used to define the value being assigned by the set accessor.

Properties that do not implement a set accessor are read only.

Video on C# – More on Classes

http://channel9.msdn.com/Series/C-Sharp-Fundamentals-Development-for-Absolute-

Beginners/Understanding-and-Creating-Classes-14

9.3. Methods Overview


A method is a code block that contains a series of statements. A program causes the statements

to be executed by calling the method and specifying any required method arguments. In C#,

every executed instruction is performed in the context of a method. The Main method is the entry

point for every C# application and when the program is started it is called by the CLR.

Basic characteristics of methods are:

1. Access level
2. Return value type
3. Method name
4. Method parameters
5. Parentheses
6. Block of statements

Access Level
Access level of methods is controlled with access modifiers. They set the visibility of methods.

They determine who can call the method. In the following class method GetTopSpeed can be

accessed by any class since it is public. In this Example it is called within the Main method in the

same class.

class TestMotorcycle
{

public double GetTopSpeed()


{
return 108.4;
}

static void Main()


{

TestMotorcycle moto = new TestMotorcycle();


double speed = moto.GetTopSpeed();
Console.WriteLine("My top speed is {0}", speed);
}
}

Return Value

Methods may return a value to the caller. In case our method returns a value, we provide its data

type. If not, we use the void keyword to indicate that our method does not return values. Method

parameters are surrounded by parentheses and separated by commas. Empty parentheses

indicate that the method requires no parameters. The method block is surrounded with { }

characters. The block contains one or more statements that are executed, when the method is

invoked. In the following example, the method calculateArea() returns the variable Area as a

double value.

class ReturnTest
{
static double CalculateArea(int r)
{
double area = r * r * Math.PI;
return area;
}

static void Main()


{
int radius = 5;
double result = CalculateArea(radius);
Console.WriteLine("The area is {0:0.00}", result);

// Keep the console open in debug mode.


Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
// Output: The area is 78.54

Method Signature

A method signature is a unique identification of a method for the C# compiler. The signature

consists of a method name and the type and kind (value, reference, or output) of each of its

formal parameters. Method signature does not include the return type.

The following example shows a set of overloaded method declarations along with their

signatures.

void F(); // F()


void F(int x); // F(int)
void F(ref int x); // F(ref int)
void F(int x, int y); // F(int, int)

Note that any ref and out parameter modifiers are part of the method signature. F(int) and F(ref

int) are unique signatures.

Method Access
Calling a method on an object is like accessing a field. After the object name, add a period, the

name of the method, and parentheses. Arguments are listed within the parentheses, and are

separated by commas (if there are multiple arguments).

Static methods can be called using Class name then add a period, the name of the method and

parenthesis with arguments.

In the following example, method CalculateArea is called in the Console's Main method in the

Program class. The method is accessed as test.CalculateArea(radius) where test is the object of

the ReturnTest class.

class ReturnTest
{
public double CalculateArea(int r)
{
double area = r * r * Math.PI;
return area;
}
}

class Program
{
static void Main()
{
ReturnTest test = new ReturnTest();
double result = test.CalculateArea(10);
Console.WriteLine("The area is {0:0.00}", result);

// Keep the console open in debug mode.


Console.WriteLine("Press any key to
exit.");
Console.ReadKey();
}
}
In the following example, static method CalculateArea is called in the Console's Main method in

the Program class. The method is accessed as Returntest. CalculateArea(radius) where

ReturnTest class is used directly to access the method.

class ReturnTest
{
public static double CalculateArea(int r)
{
double area = r * r * Math.PI;
return area;
}
}

class Program
{
static void Main()
{
//Method is called using the Class name and dot operator
double result = ReturnTest.CalculateArea(10);
Console.WriteLine("The area is {0:0.00}", result);

// Keep the console open in debug mode.


Console.WriteLine("Press any key to
exit.");
Console.ReadKey();
}
}

Method Parameters

The method definition specifies the names and types of any parameters that are required. When

a program calls the method, it provides concrete values called arguments for each parameter.

The arguments must be compatible with the parameter type.

In the following example, method CalculateBMI is called passing the arguments 123(weight) and

64(height).
class ParameterExample
{
static void Main(string[] args)
{
// The method can be called by passing arguments for the
parameters
int bmi = CalculateBMI(123, 64);
Console.WriteLine( bmi);

static int CalculateBMI(int weight, int height)


{
return (weight * 703) / (height * height);
}
}

Pass By Ref and Pass By Value

By default, when a value type is passed in a method, a copy is passed instead of the object itself.

Therefore, changes to the argument have no effect on the original copy in the calling method.

When an object of a reference type is passed in a method, a reference to the object is passed.

That is, the method receives not the object itself but an argument that indicates the memory

location of the object. If we change a member of the object by using this reference, the change is

reflected in the argument in the calling method.

In the following example, Method is called passing argument by ref and the changes done in the

method reflected in the output(45).

When the method ValMethod is called where the argument is passed by value, there is no

change in the value(val) and output is 45.

class RefExample
{
static void Method(ref int i)
{
i = i + 44;
}

static void ValMethod(int i)


{
i = i + 44;
}

static void Main()


{
int val = 1;
Method(ref val);
Console.WriteLine(val);
// Output: 45
ValMethod(val);

Console.WriteLine(val);
// Output: 45
}
}

Return Values

Methods can return a value to the caller. If the return type, the type listed before the method

name, is not void, the method can return the value by using the return keyword. A statement with

the return keyword followed by a value that matches the return type will return that value to the

method caller. The return keyword also stops the execution of the method. If the return type is

void, a return statement without a value is still useful to stop the execution of the method. Without

the return keyword, the method will stop executing when it reaches the end of the code block.

Methods with a non-void return type are required to use the return keyword to return a value.

In the following example method CalculateTax returns calculated Tax to the calling method. The

returned value is assigned to the taxAmount variable.

Method PrintTax does not have a return value. So when this method is called it prints the Tax

value to the Console and it exits when the end of the code block is reached.
class ReturnExample
{
static void Main(string[] args)
{
// The method can be called by passing arguments for the parameters
Tax oTax = new Tax();
double taxAmount = oTax.CalculateTax(1000000, 20);
oTax.PrintTax(taxAmount);
Console.ReadLine();
}
}

class Tax
{
public double CalculateTax(double Amount, double taxRate)
{
return (Amount * taxRate) / 100;
}

public void PrintTax(double TaxAmount)


{
//print the tax amount to the console
Console.WriteLine(TaxAmount.ToString());
}

Video on C# – More on Classes


http://channel9.msdn.com/Series/C-Sharp-Fundamentals-Development-for-Absolute-
Beginners/More-about-Classes-and-Methods-15
10. C# - Working with Collections
Objective

 To store and process with a set of objects.


 Learn generic and non-generic collection and its usage.

10.1. Array
 Array is used to store multiple values of same type in a variable.
 It is used to store values of value types and reference types
 Size of the array should be decided at the time of creation itself.

Syntax:

dataType[] varName=new dataType[size];

Eg int[] marks=new int[10];

marks is an integer array which can hold 10 integer values.

Array store from index 0 till size-1 values. 'marks' array can hold values from marks[0] to

marks[9].

Sample which stores and retrieve the marks of 5 subjects

static void Main(string[] args)


{
int[] marks = new int[5];
Console.WriteLine("Enter marks of 5 subjects");
for (int i = 0; i < 5; i++)
{
marks[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Marks are as follows: ");
for (int i = 0; i < 5; i++)
{
Console.WriteLine(marks[i]);
}
Console.ReadKey();
}

Output:

Enter marks of 5 subjects

78

89

67

98

72

Marks are as follows:

78

89

67

98

72

In case we have to store set of employee details then we can use array of type class. So in the

following sample, for each employee we have to store name, id and performance pay. So first we

create an employee array with the required attributes and a constructor is written to assign the

values and there are properties used to retrieve the values.

In our main program the employee array is created and values are stored and finally retrieved.

The size of employee array is 100. So it can store a maximum of 100 employees.
//In the following line and Array of type employee is created

Employee[] empList = new Employee[100];

//In the following line the object of type employee is created by passing the required values and

storing it in array.

empList[i] = new Employee(name, id, performancePay);

//In the following line the Id of employee is accessed from array.

Console.WriteLine("Id is "+empList[i].Id);

Sample:

class Employee
{
string name;
int id;
int performancePay;

public Employee(string name, int id, int performancePay)


{
this.name = name;
this.id = id;
this.performancePay = performancePay;
}

public string Name


{
get
{
return (name);
}
set
{
name = value.ToUpper();
}
}
public int PerformancePay
{
get
{
return (performancePay);
}
set
{
performancePay = value;
}
}
public int Id
{
get
{
return (id);
}
set
{
id = value;
}
}
class Program
{
static void Main(string[] args)
{
//Array of type employee is created
Employee[] empList = new Employee[100];
string name;
int id;
int performancePay;
for (int i = 0; i < 100; i++)
{
Console.WriteLine("Enter name,id,performance pay");
name=Console.ReadLine();
id=Convert.ToInt32(Console.ReadLine());
performancePay=Convert.ToInt32(Console.ReadLine());
//ith employee object is created
empList[i] = new Employee(name, id, performancePay);

}
//View the details of all the employees
for (int i = 0; i < 100; i++)
{
Console.WriteLine("Details of Employee no :"+ i+1);
Console.WriteLine("Id is "+empList[i].Id);
Console.WriteLine("Name is "+empList[i].Name);
Console.WriteLine("Performance Pay is
"+empList[i].PerformancePay);

}
Console.ReadKey();
}
}

10.2. Array list


Array list provides a dynamically sized array of objects

 There is no size limit for array list


 It is a non-generic collection. We can store values of any type
 Appending elements is efficient compared to Array, but inserting elements can be slow.
 We can perform add, edit, delete and display in array list.
 In the top of the page along with other using statements add

using System.Collections; to access array list class.

Syntax for array list declaration


ArrayList list = new ArrayList();

Syntax to add elements:

listName.Add(object);

object can be of any type.

Syntax to remove an element from list:

listName.Remove(object);

It is simple for Array list to store 3 values, display them and remove a value

static void Main(string[] args)

ArrayList list = new ArrayList();

//Adds value to the list

list.Add(10);

list.Add(20);

list.Add(30);

//Display all the values in a list

foreach (int i in list)

Console.WriteLine(i);

//Remove the values from the list

list.Remove(20);

//Display all the values in a list

foreach (int i in list)

{
Console.WriteLine(i);

Console.ReadKey();

Output

10 ----All the values in the list

20

30

10---The result after removing 20 from the list

30

A company has a set of departments. We will see how to add department to the arraylist, how to

change the existing details, how to delete a department and finally view the department's details

class Department

string name;

int id;

public Department(string name, int id)

this.name = name;

this.id = id;

public string Name

get
{

return (name);

set

name = value;

public int Id

get

return (id);

set

id = value;

class Program

static void Main(string[] args)

{
ArrayList list = new ArrayList();

int choice;

string name;

int id;

do

Console.WriteLine("Menu");

Console.WriteLine("1.Add new department");

Console.WriteLine("2.Change department name");

Console.WriteLine("3.Delete a department");

Console.WriteLine("4.View all departments");

Console.WriteLine("5.Exit");

Console.WriteLine("Enter your choice");

choice = Convert.ToInt32(Console.ReadLine());

switch (choice)

case 1:

Console.WriteLine("Enter id,name");

id = Convert.ToInt32(Console.ReadLine());

name = Console.ReadLine();

//Create a department object

Department d = new Department(name, id);

//Add the department object to the list

list.Add(d);
break;

case 2:

Console.WriteLine("Enter id of the department");

id = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter the new name of the department");

name = Console.ReadLine();

//Loop through the department array list to find if the department

exists & change the name

//if the department with the specified

id exists

foreach (Department dept in list)

//checks the department id

if (dept.Id == id)

//change the name of the department

dept.Name = name;

break;

case 3:

Console.WriteLine("Enter id of the department");

id = Convert.ToInt32(Console.ReadLine());

//Loop through the department array list to find


if the department with that id exists

//and delete the department

foreach (Department dept in list)

//checks the department id

if (dept.Id == id)

//removes the department from the list

list.Remove(dept);

//break statement is mandatory since an item is removed from the


list

//the iteration can not continue further

break;

break;

case 4:

//Loop through the department list and view all the department
details

foreach (Department dept in list)

Console.WriteLine("Id is " + dept.Id);

Console.WriteLine("Name is " + dept.Name);

}
break;

} while (choice != 5);

Console.ReadKey();

Output

Menu

1.Add new department

2.Change department name

3.Delete a department

4.View all departments

5.Exit

Enter your choice

Enter id,name

Admin

Menu

1.Add new department

2.Change department name

3.Delete a department

4.View all departments

5.Exit
Enter your choice

Enter id,name

HR

Menu

1.Add new department

2.Change department name

3.Delete a department

4.View all departments

5.Exit

Enter your choice

Id is 1

Name is Admin

Id is 2

Name is HR

Menu

1.Add new department

2.Change department name

3.Delete a department

4.View all departments

5.Exit

Enter your choice


2

Enter id of the department

Enter the new name of the department

IS

Menu

1.Add new department

2.Change department name

3.Delete a department

4.View all departments

5.Exit

Enter your choice

Id is 1

Name is Admin

Id is 2

Name is IS

Menu

1.Add new department

2.Change department name

3.Delete a department

4.View all departments

5.Exit

Enter your choice


3

Enter id of the department

Menu

1.Add new department

2.Change department name

3.Delete a department

4.View all departments

5.Exit

Enter your choice

Id is 2

Name is IS

Menu

1.Add new department

2.Change department name

3.Delete a department

4.View all departments

5.Exit

Enter your choice

5
10.3. Generic list
 List provides a dynamically sized set of objects of same type.
 Generic collections are type safe since it allows only the specified types of input to be
added to the list
 It is a generic collection.
 We can perform add, edit, delete and display in generic list.
 We have to add the namespace using System.Collections.Generic; to access generic list

Syntax:

List<dataType> list = new List<dataType>();

--dataType can be primitive data-Types or classes

eg.

List<int> intList = new List<int>();

Creates an integer list which can store any number elements

List<string> namelist = new List<string>();

Creates an name list which stores a set of names

List<Project> list = new List<Project>();

This list can process with a set of departments.

Syntax to add elements:

listName.Add(object);

Syntax to remove an element from list:

listName.Remove(object);

Sample program which will process a set of projects shown below. Using this sample add,

update, delete and display operations are performed

class Project
{
string name;
int id;
public Project(string name, int id)
{
this.name = name;
this.id = id;
}
public string Name
{
get
{
return (name);
}
set
{
name = value;
}
}

public int Id
{
get
{
return (id);
}
set
{
id = value;
}
}
}
class Program
{
static void Main(string[] args)
{
List<Project> list = new List<Project>();

int choice;
string name;
int id;
do
{
Console.WriteLine("Menu");
Console.WriteLine("1.Add new Project");
Console.WriteLine("2.Change project name");
Console.WriteLine("3.Delete a project");
Console.WriteLine("4.View all project");
Console.WriteLine("5.Exit");
Console.WriteLine("Enter your choice");
choice = Convert.ToInt32(Console.ReadLine());
switch (choice)
{
case 1:
Console.WriteLine("Enter id,name");
id = Convert.ToInt32(Console.ReadLine());
name = Console.ReadLine();
//Create a project object
Project d = new Project(name, id);
//Add the project object to the list
list.Add(d);
break;
case 2:
Console.WriteLine("Enter id of the
project");
id = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the new name of the
project");
name = Console.ReadLine();
//Loop through the project array list to
find

//if the project exists and change the name only

//if the project with the specified id exists


foreach (Project dept in list)
{
if (dept.Id == id)
{
dept.Name = name;
}
}
break;
case 3:
Console.WriteLine("Enter id of the
project");
id = Convert.ToInt32(Console.ReadLine());
//Loop through the project array list to
find

//if the project with that id exists and delete the project
foreach (Project dept in list)
{
if (dept.Id == id)
{
//removes the department from the list
list.Remove(dept);
//break statement is mandatory since an item is removed from the
list
break;
}
}
break;
case 4:
//Loop through the project list and view all the project details
foreach (Project dept in list)
{
Console.WriteLine("Id is " + dept.Id);
Console.WriteLine("Name is " +
dept.Name);
}
break;
}
} while (choice != 5);

Console.ReadKey();
}
}

Output

Menu

1.Add new Project

2.Change project name

3.Delete a project

4.View all project

5.Exit

Enter your choice

Enter id,name
1

Admin

Menu

1.Add new Project

2.Change project name

3.Delete a project

4.View all project

5.Exit

Enter your choice

Enter id,name

HR

Menu

1.Add new Project

2.Change project name

3.Delete a project

4.View all project

5.Exit

Enter your choice

Enter id of the project

Enter the new name of the project

IS

Menu

1.Add new Project

2.Change project name


3.Delete a project

4.View all project

5.Exit

Enter your choice

Id is 1

Name is Admin

Id is 2

Name is IS

Menu

1.Add new Project

2.Change project name

3.Delete a project

4.View all project

5.Exit

Enter your choice

Enter id of the project

Menu

1.Add new Project

2.Change project name

3.Delete a project

4.View all project

5.Exit

Enter your choice

Id is 1

Name is Admin
Menu

1.Add new Project

2.Change project name

3.Delete a project

4.View all project

5.Exit

Enter your choice

10.4. Generic Vs Non Generic list

10.5. Conclusion
Roadblocks:

Some topics in this series may take time to understand but make sure that you keep pushing

forward. Keep learning from different resources like Chanel 9 videos and

microsoftvirtualacademy. See the links below for learning material in Chanel 9 and

Microsoftvirtualacademy.

Chanel 9:

http://channel9.msdn.com/Series/C-Sharp-Fundamentals-Development-for-Absolute-Beginners
Microsoftvirtualacademy:

http://www.microsoftvirtualacademy.com/Content/ViewContent.aspx?et=3371&m=3369&ct=1817

3#?fbid=aKxmACFWEx8

Learning the topic from different authors will help you to understand topics better.

It is common to get stuck when you tried to solve problems in this series. It may be Installation &

configuration issues with Visual Studio or compilation errors when you build your program. There

are many good websites which will help you in internet to solve these problems. When you

search for the solution in internet you need to use the key phrases in error message you get.

Make sure that you are focusing on the actual error message.

Where do you go for help?

There are many websites and forums which will help you to learn .Net and C# but it is always

good to refer websites from Microsoft. Visual Studio Developer Center is an official website which

will give you enough help to learn and understand Microsoft Technologies. You can find the link

below.

http://msdn.microsoft.com/en-us/vstudio/aa718325.aspx
What Next?

In this series we have given an introduction of C# language and you can learn more about C#

language by using Chanel 9 and MicrosoftVirtualAcademy videos. You can also learn about SQL

server database concepts and ADO.Net.

You can also try to learn asp.net to create webpages using Visual Studio.

Module 2 (User Interface)


1. Introduction to User Interface and HTML
Sub-Modules
1.1 Introduction
1.2 Types of User Interface
1.3 Introduction to HTML
1.4 HTML basic elements
1.5 HTML basic list elements
1.6 HTML other elements
1.7 HTML forms

1.1 Introduction

User Interface (UI) is a space where interactions between humans and machines occur. In
IT world, machines generally refer to computers. Hence it is also known as HCI (Human
Computer Interaction). In all IT applications you can find a form which will help the user to
interact with the system.

What is User Interface?

For a computer program, the user interface refers to the graphical, textual and auditory
information the program presents to the user. It also includes below user actions that are
invoked to control the program:
 Keyboard keystrokes /Mouse movements
 Voice commands
 Touch

User Interface involves both hardware and software components that provide means of :
 Input : Allows users to perform / trigger operations
 Output : Allows system to indicate effects of user operations

Need for a good User Interface?


The look and feel that a User Interface provides is one of the major factors that decide the
User Satisfaction and User Experience.

The importance of good User Interface Design can be the difference between product
acceptance and rejection in the marketplace. A cumbersome, not easy to learn / use UI, in
an otherwise excellent product could result in the failure of that product. Good User Interface
can make a product easy to understand and use, which results in greater user acceptance.
Poor user interface is the reason why many software systems are never used.

1.2. Types of User Interface


The most common types of User Interfaces are listed below:
 Graphical User Interface (GUI)
 Web User Interface (WUI)
 Command-line User Interface (CUI)
 Touch User Interface
 Voice User Interface

Different Types of User Interactions


Two problems must be addressed in interactive systems design
1) How should information from the user be provided to the computer system?
2) How should information from the computer system be presented to the user?

Different types of User Interactions are:


1) Command Language
2) Form Fill In
3) Menu Selection
4) Direct Manipulation
Command Language:
Generally used by expert users who type in commands and possibly some parameters that
will affect the way the command is executed.

Advantages:
 Good for expert users
 Generally support creation of user defined scripts or macros
 Consumes low Bandwidth and hence suitable in a networked environment.

Disadvantages:
 Learn-ability and Retention of commands is generally poor
 Not suitable for non-expert users
 Not very user friendly and hence error rates are high
 Provision of appropriate error messages is difficult because of diversity of
possibilities

Form Fill In:


Generally used when application needs to collect good amount of data from user.

Advantages:
 Simplifies data entry
 Shortens learning time since the fields are predefined and need only be 'recognised'.
 Guides the user via predefined rules
Disadvantages:
 Consumes screen space

Menu Selection:
Menu indicates a set of options displayed on a UI. Selecting a menu item would execute the
functionality associated with that menu item

Direct Manipulation:
In this type of interaction objects of interest are represented as distinguishable objects in the
UI and are manipulated in a direct fashion.

1.3. Introduction to HTML


It is very common now to use websites for doing our daily activities in a better way. For
example you can read newspapers in a news website which is a digital form of physical
newspaper. HTML is the basic mark-up language used to create webpages for websites. We
always need good layout, structure and navigation for all webpages in a website. In coming
sections you can see how to use HTML to create a webpage with proper Layout, structure
and navigation.

What is HTML?
HTML is a language for describing web pages. HTML stands for Hyper Text Markup
Language. It is a markup language and uses markup tags to describe web pages. HTML
markup tags are usually called HTML tags. The purpose of a web browser (like Internet
Explorer or Firefox) is to read HTML documents and display them as web pages. The
browser does not display the HTML tags, but uses the tags to interpret the content of
the page.

Example:
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph</p>
</body>
</html>
If you copy and paste HTML tags above in a notepad to save it as sample.htm then it will
become an HTML document which can be opened in a web browser to display web content
as shown below.

Create a simple HTML Page:


You can see the HTML code for a simple HTML page below. Don't worry about what the
code means yet. We start to look at it in more detail on the next page. Note that the HTML
code is in red, and the text you see on screen is in black.
<html>
<body>
<h1>This is the Main Heading</h1>
<p>This text might be an introduction to the rest of the page. And if the
page is a long one it might be split up into several subheadings.
<p>
<h2>This is a Sub-Heading</h2>
<p>Many long articles have sub-headings so to help you follow the
structure of what is being written. There may even be sub-subheadings
(or lower-level headings).
</p>
<h2>Another Sub-Heading</h2>
<p>Here you can see another sub-heading.</p>
</body>
</html>
If you copy and paste HTML tags above in a notepad to save it as sample.htm then it will
become an HTML document which can be opened in a web browser to display web content
as shown below.

 The text between <html> and </html> describes the web page
 The text between <body> and </body> is the visible page content
 The text between <h1> and </h1> is displayed as a heading
 The text between <p> and </p> is displayed as a paragraph

1.4. HTML Basic Elements


Syntax:
An HTML element starts with a start tag and ends with an end tag. Ex: <html></html>. The
element content is the text between the start and the end tag. HTML elements can have
attributes.
Ex: <a href="www.google.com">Click Here</a>
Basic Text Elements:
<html> - All HTML pages should start with <html> tag.
</html>- All HTML pages should end with </html> tag
<body>- Everything inside this element is shown inside the main browser window
</body>-End of body
<head> - This contains information about the page.(Usually it will contain a <Title> element.
</head>-End of head
<title>- The contents of the <title> element are shown in the top of the browser, above where
you usually type in the URL of the page you want to visit
</title>-End of Title
Headings:
HTML has six "levels" headings:
<h1>
<h2>
<h3>
<h4>
<h5>
<h6>
Example:
Code:
<html>
<body>
<h1>This is a Main Heading</h1>
<h2>This is a Level 2 Heading</h2>
<h3>This is a Level 3 Heading</h3>
<h4>This is a Level 4 Heading</h4>
<h5>This is a Level 5 Heading</h5>
<h6>This is a Level 6 Heading</h6>
</body>
</html>
Result:

Paragraph:
To create a paragraph, surround the words that make up the paragraph with an opening <p>
tag and closing </p> tag.
Example:
<html>
<body>
<p> Many long articles have sub-headings so to help you follow the structure of what is
being written. There may even be sub-sub- headings (or lower-level headings). </p>
</body>
</html>
Result:

Bold & Italic:


By enclosing words in the tags <b> and </b> we can make characters appear bold.
Example:
<html>
<body>
<p>This is how we make a word appear <b>bold.</b>
</p>
<p>Inside a product description you might see some
<b>key features</b> in bold.</p>
</body>
</html>
Result:
This is how we make a word appear bold.
Inside a product description you might see some key features.

Line Breaks & Horizontal rules:


If you wanted to add a line break inside the middle of a paragraph you can use the line break
tag <br />.
Example:
<html>
<body>
<p>The Earth<br />gets one hundred tons heavier
every day<br />due to falling space dust.</p>
</body>
</html>
Result:
The earth
gets one hundred tons heavier every day
due to falling of space dust
To create a break between themes — such as a change of topic in a book or a new scene in
a play — you can add a horizontal rule between sections using the <hr /> tag.
Example:
<html>
<body>
<p>This is Theme1</p>
<hr />
<p> This is Theme2</p>
</body>
</html>
Result:

Try <strong> and <em> element and see how it will display text in the browser.
Other Elements in HTML:
<blockquote> - Used for longer quotes that take up an entire paragraph.
<q> - Used for shorter quotes that sit within a paragraph
<s> - Indicates something that is no longer accurate or relevant (but that should not be
deleted)

1.5. HTML Basic List Elements


In a webpage there are so many occasions where we need to use lists. HTML provides us
with three different types: Ordered Lists, Unordered Lists and Definition Lists.
Ordered Lists are lists where each item in the list is numbered
Unordered Lists are lists that begin with a bullet point
Definition Lists are made up of a set of terms along with the definitions for each of those
terms.
The ordered list is created with the <ol> element. Each item in the list is placed between an
opening <li> tag and a closing </li> tag.
Example:
<html>
<body>
<ol>
<li>JAVA</li>
<li>MS.Net</li>
<li>C++</li>
<li>SAP</li>
<li>Mainframe</li>
</ol>
</body>
</html>
Result:

Replace <ol> with <ul> to create unordered list.


The definition list is created with the <dl> element and usually consists of a series of terms
and their definitions. <dt> is used to contain the term being defined (the definition term).
<dd> is used to contain the definition.
Example:
<html>
<body>
<dl>
<dt>Sashimi</dt>
<dd>Sliced raw fish that is served with
condiments such as shredded daikon radish or
ginger root, wasabi and soy sauce</dd>
</dl>
</body>
</html>
Result:

1.6. HTML Other Elements


<a> - This is used to create links. Specify which page you want to link to using the href
attribute.
<a href=‖http://www.google.com‖>Google</a> - To give hyperlink to google
<a href=‖pageName.html‖>Page Name</a> - To give hyperlink to a particular page
<img> - This is used to add an image into a page. It must carry the

Attribute src which will give the path to image file.


Ex: <img src="images/Sample.jpg" alt="Group of Images" title="Sample1" />
Tables:
A table represents information in a grid format. To create a basic table structure you need to
use <table>, <tr>
and <td>. <tr> is used to create row and <td> will be used to create column.
Example:
<html>
<body>
<table>
<tr>
<td>JAVA</td>
<td>MS.Net</td>
<td>Mainframe</td>
</tr>
<tr>
<td>15</td>
<td>60</td>
<td>45</td>
</tr>
</body>
</html>
Result:

The <th> element is used just like the <td> element but its purpose is to represent the
heading for either a column or a row. Sometimes you may need the entries in a table to
stretch across more than one column. The colspan attribute can be used on a <td> element
and indicates how many columns that cell should run across.
Example:
<html>
<body>
<table>
<tr>
<th></th>
<th>10am</th>
<th>11am</th>
<th>12am</th>
<th>1pm</th>
</tr>
<tr>
<th>Monday</th>
<td colspan="2">Geography</td>
<td>JAVA</td>
<td>MS.Net</td>
</tr>
</body>
RESULT:
The rowspan attribute can be used on a <th> or <td> element to indicate how many rows a
cell should span down the table.

Explore more about table in http://www.w3schools.com/html/html_tables.asp.

1.7. HTML Forms


Forms are used to display information, get information and inputs from the user. Forms also
allow users to perform other functions online. You will see forms when registering as a
member of a website and when signing up for newsletters. There are different types for form
controls which can be used to collect information users of website.
Create a Form with input controls:
We need to use <form> element with action attribute to create a form. See elements we use
when creating a form for website.
<form> - Form controls live inside a <form> element. This element should always carry the
action attribute and will usually have a method and id attribute too.
Action - Every <form> element requires an action attribute. Its value is the URL for the page
on the server that will receive the information in the form when it is submitted.
Method – Forms can be sent using get or post. With the get method, the values from the
form are added to the end of the URL specified in the action attribute. With the post method
the values are sent in what are known as HTTP headers. Get method is used for short forms
and post method is used for long forms.
<input> - Used to create several different form controls. The value of the type attribute
determines what kind of input they will be creating. When the type attribute has a value of
text, it creates a single-line text input.
Id - The value of Id is used to identify the form distinctly from other elements on the page.
Name - When users enter information into a form, the server needs to know in which form
control each piece of data was entered into. Name will uniquely identify the control.
Maxlength - You can use the maxlength attribute to limit the number of characters a user
may enter into the text field.
Example:
<html>
<body>
<form action=" www.google.com" method=”get”>
<p>Username:
<input type="text" name="username" maxlength="30" />
</p>
</form>
</body>
</html>
Result:

If you want to create a textbox for entering password use HTML code below.
<input type="password" name="password" maxlength="30" />
You can give maximum 30 characters in the textbox.
<textarea> - used to create a mutli-line text input.
Ex: <textarea name="Address" cols="20" rows="4">Enter your Address</textarea>
If you want to create a radio button for 3 options use the code below.
<input type="radio" name="Language" value="rock" checked="checked" /> C++
<input type="radio" name=" Language" value="pop" /> JAVA
<input type="radio" name=" Language" value="jazz" /> MS.Net
Note: name property is used to group set of radio buttons together
Example:
<html>
<body>
<form action=" www.google.com" method=”get”>
<p>
<input type="radio" name="Language" value="rock" checked="checked" /> C++
<input type="radio" name=" Language" value="pop" /> JAVA
<input type="radio" name=" Language" value="jazz" /> MS.Net
</p>
</form>
</body>
</html>
Result:
If you want to create a checkbox for 3 options use the code below.
<input type="checkbox" name="service" value="JAVA" checked="checked" /> JAVA
<input type="checkbox" name="service" value="C++" /> C++
<input type="checkbox" name="service" value="MS.Net" /> MS.Net
Create a dropdown list box using the code below.
<select name="devices">
<option value="JAVA"> JAVA </option>
<option value="C++"> C++</option>
<option value="MS.Net"> MS.Net</option>
</select>
A submit button is used to send information in a form to the server. The information will send
to the page specified in the form's action attribute.
Example:
<html>
<body>
<form name="input" action="https://www.google.co.in/" method="get">
Username: <input type="text" name="user">
<input type="submit" value="Submit">
</form>
</body>
</html>
Result:

2. CSS ( Cascading Style Sheets )


SUBMODULES
1. Introduction
2. CSS Selectors
3. Advantages and Disadvantages

2.1. Introduction
Introduction
CSS allows you to create rules that specify how the content of an element should appear.
For example, you can specify that the background of the page is blue, all paragraphs should
appear in gray using the verdana font. When you learn about CSS you should learn what is
CSS, How you can write CSS and finally how you can apply style in an HTML page using
CSS.
CSS Rules
A CSS rule contains two parts: a selector and a declaration.
Example: p{color:yellow;}
Here p is Selector and color:yellow; is declaration. This rule says that whenever you use <p>
in your HTML page the colour should be yellow.
CSS declarations sit inside curly brackets and each is made up of two parts: a property and
a value, separated by a colon. You can specify several properties in one declaration, each
separated by a semi-colon.
Example for a simple CSS in HTML
HTML File:
<html>
<head>
<title>Simple CSS</title>
<link href="css/sample.css" type="text/css" rel="stylesheet" />
</head>
<body>
<h1>Heading 1</h1>
<p>A <i>JAVA</i> resource is required</p>
<h2>Heading 2</h2>
</body>
</html>
Sample CSS:
body {
font-family: Arial, Verdana, sans-serif;}
h1, h2 {color: #ee3e80;}
p {
color: #665544;}
Here the <link> element can be used in an HTML document to tell the browser where to find
the CSS file used to style the page. It is an empty element (meaning it does not need a
closing tag), and it lives inside the <head> element. It should use three attributes:
href: path to the CSS file
type: specifies the type of document being linked to. The value should be text/css.
Rel: specifes the relationship between the HTML page and the file it is linked to. The value
should be stylesheet when linking to a CSS file.

Check more about CSS inhttp://www.w3schools.com/css/css_syntax.asp

2.2. CSS Selectors


CSS selectors allow you to select and manipulate HTML element(s).
CSS selectors are used to "find" (or select) HTML elements based on their id, classes,
types, attributes, values of attributes and much more.
There are many different types of CSS selectors that allow you to target rules to specific
elements in an HTML document.
Type Selector/Element Selector
It selects elements based on the element name. Ex: p{…}
ID Selector
Matches an element whose id attribute has a value that matches the one specified after the
pound or hash symbol.
Ex: #introduction {…} Targets the element whose id attribute has a value of introduction
Class Selector
The class selector finds elements with the specific class. The class selector uses the HTML
class attribute.
Ex: .theme{…} Targets any element whose class attribute has a value of theme
p.theme Targets only <p> elements whose class attribute has a value of theme
In HTML you can give the class name as below.
<h1 class=― theme‖>
Check more about CSS in
http://www.w3schools.com/css/css_selectors.asp
How to apply style using CSS
4 Ways to Put CSS and HTML Together:
1. Defining a style sheet inside of the HTML document, inside the <HEAD> tag.
2. Referring to an external file which contains a style sheet, by using the 'LINK' element.
3. Referring to an external file which contains a style sheet, by using the '@import’ notation.
4. Using a style element inside the document body attached to a tag
1. Internal CSS
Style characteristics are embedded in the HEAD section of the webpage.
It is usually best used when a single page requires a unique style sheet.
<head>
<style type=“text/css”>
p {color: red}
body {margin-left: 20px}
</style>
</head>
2. External CSS
An external style sheet can be written in any text editor. The file should not contain any html
tags. The style sheet should be saved with a .css extension. Connection made via the LINK
tag; use the optional TYPE attribute to specify a media type text/css.
<head>
<link rel=“stylesheet” type=“text/css” href=“mystyle.css” />
</head>
3. @import
The @import rule can be used to import an external CSS.
<style type="text/css">
@import url(import.css);
</style>
4. Inline CSS
It requires each element to be tagged if they have to appear differently. It is the least flexible
way to apply style.
<p style=“color: red; font-family: arial”>
This is a paragraph.
</p>

2.3. Advantages & Disadvantages


Some advantages and disadvantages of Stylesheet are given below.
Advantages:
 Design of web page separated from the content
 Easier site maintenance
 The style sheet information can be stored separate from your HTML document, and
shared among many HTML files.
 Change one style sheet file, and the appearance of the entire site is updated.
Disadvantages:
 Browser compatibility must be the most common difficulty
3.JavaScript
Sub modules
1. Introduction
2. Implement JavaScript
3. Practice Problems

3.1. Introduction
Introduction
JavaScript is a scripting language which was designed to add interactivity to HTML pages.
Javascript can directly embed into HTML pages. Usually we use javascript for client side
validations and client side operations.
Use of Javascript
JavaScript gives HTML designers a programming tool which can put dynamic text into an
HTML page. It can react to events and can read and write HTML elements. JavaScript can
be used to validate data, to detect the visitor's browser, to create cookies and interact with
and control frames.
To add a javascript into an HTML page use <script> tag
Example:
<html>
<body>
<script type="text/javascript">
document.write("Hello World!");
</script>
</body>
</html>
Basics:
Variable declaration:
In javascript we declare variables using var keyword. Ex: var variableName
Dot Notation:
Javascript uses dot notation to access properties and Methods on
objects:myObject.propertyName references propertyName on myObject,
and myObject.methodName() invokesmethodName on myObject.
Alert Function:
It is a common function used in javascript to display some text in browser.
It pops open a small window that displays the string you provided.
Ex: alert(―Hi‖);
Expressions, Statements and Operators:
Expression and Statements are building blocks of Javascript programs. An expression is any
section of code that resolves to a value. Since literal expressions evaluate to actual values,
JavaScript supports the same broad types of expressions as it does of variables: boolean,
number, string, and object.
Ex:
10 // Literal expression, resolves to 10
"Hello World" // Literal expression, resolves to the string "Hello World"
3+7 // Mathematical expression, resolves to 10
A statement is a collection of one or more expressions that performs a specific action.
Ex:
var x = 5, // variable assignment, a statement
y = 3,
z = x + y; // mathematical operation, also a statement
Operators perform operations on expressions. Operators perform their function. Javascript
operators fall into the following broad categories:
Arithmetic operators: Perform arithmetical operations on their operands, such as addition,
multiplication, etc.
Assignment operators: Modify variables, either by assigning their values or altering their
values according to specific rules.
Bitwise operators: Treat their operands as a set of 32 bits, and perform their operations in
that context.
Comparison operators: Compare their operands and return a logical value (true or false)
based on whether or not the comparison is true.
Logical operators: Perform logical operations on their operands and are often used to link
together multiple comparisons.
String operators: Perform operations on two strings, such as concatenation.
Miscellaneous operators: Operators that don’t fall into any of the above categories. This
category includes the conditional operator and operators such as the void operator and the
comma operator.
Variables:
A variable is a named storage location with an associated value.
In Javascript, variables are declared using the var keyword.
Ex: var myVar = 1;
It’s common practice to declare many variables at once. You can use the var keyword for
each variable, or you can use the var keyword once and separate the variable declarations
with commas. It’s also common practice to place each variable declaration on its own line.
Learn more about Javascript in http://www.w3schools.com/js/js_examples.asp
Check JavaScript Statements, Comments and Blocks, JavaScript Variables, JavaScript
Conditional If ... Else,JavaScript Popup Boxes, JavaScript Functions, JavaScript Loops and
JavaScript Events.

3.2. Implement JavaScript


function myFunction()
var varName = "Here"; // scope of varName is limited in scope to
myFunction
// Create a new function within myFunction
function myInternalFunction() {
alert(varName); // varName is available here
}
myInternalFunction(); // call myInternalFunction when myFunction is called
You can use the javascript function in HTML page as shown below.
Use the code below to apply Javascript in HTML page.
<html>
<head>
<script>
function myFunction()
var varName = "Here"; // scope of varName is limited in scope to
myFunction
// Create a new function within myFunction
function myInternalFunction() {
alert(varName); // varName is available here
}
myInternalFunction(); // call myInternalFunction when myFunction
is called
</script>
<body>
<form action=" www.google.com" method=”get”>
<h1>Sample Javascript</h1>
<p id="demo">Click the Button</p>
<input type="button" value="Click Me" onclick="myFunction()">Click
Here</button>
</form>
</body>
</html>
Sample.html
You can create a javascript function in an external document and refer it from HTML as
shown below.
<html>
<head>
<script src="sample.js"></script>
<body>
<form action=" www.google.com" method=”get”>
<h1>Sample Javascript</h1>
<p id="demo">Click the Button</p>
<input type="button" value="Click Me" onclick="myFunction()">Click
Here</button>
</form>
</body>
</html>
function myFunction()
var varName = "Here"; // scope of varName is limited in scope to
myFunction
// Create a new function within myFunction
function myInternalFunction() {
alert(varName); // varName is available here
}
myInternalFunction(); // call myInternalFunction when myFunction is called
Learn more about JavaScript inhttp://www.w3schools.com/js/js_examples.asp.
Fetch a control's value:
We can use document.getElementById to fetch the value of any control
var result=document.getElementById(―controlName‖).value;
We can use it to retrieve values from your input control
Following code shows the javascript code to validate a textbox with id fname
<script type="text/javascript">
function calculate() {
var firstname = document.getElementById("fname").value;
if (firstname == "") {
alert("Please enter your first name");
document.getElementById("fname").focus();
return true;
}
}
</script>
Following is the input element added to the page
<input id="fname" type="text" />
Check Where to Insert JavaScript and Advanced JavaScript Examples.

3.3. Practice Problems


1. Create a html page with the following list, with inserted and deleted content:
Ingredients:
 3/4 cup coffee
 2 eggs
 1 cup flour
 1 Bread
 75g 50g butter
 pinch of salt
2. Create 2 HTML pages for Rooms, Opening and Contact
For a menu page, add a level 2 heading titled Hotel. This should be followed by a paragraph
saying The rooms will go here. Update the content of the <title> element to reflect that this
page will feature the rooms at the Hotel.
Save the file with the name rooms.html.
For an opening times page, add a level 2 heading saying Opening hours. This should be
followed by a paragraph saying Details of opening hours and how to find us will go here.
Update the <title> element to reflect that the page tells visitors opening hours. Save the file
with the name opening.html.
3. Create an e-mail feedback form that looks like the one shown below. The first textbox is a
readonly textbox so that the user cannot alter the name of the person the e-mail is sent to.
4. Create a web page that display the daily news with heading and description for the news.
5. Create a web page that displays blogs with the blog title and description.
6. Create a web page that displays book with topics and specific contents.
7. Create a website for adding 2 products to a store at a time.The website will take the
following inputs.
Product ID which will start from PRD . For ex-PRD101
Product name should be characters only.
Available units should be greater than 0 and it should not be decimal.
Unit Price
Apply styles using style sheet. Show success message if all the inputs are valid.
8. Create a website for registration of a customer in a particular company.
The page should contain the following fields:
 Username ,
 Date of joining should not be a future date.
 Email id should be of expected format
 Password should be minimum 8 charaters
 Phone number should be of 10 digits

Apply styles using style sheet. Show success message if all the inputs are valid.
9. Create a website for submitting the final report of a student. The page should contain the
following things: First Name of student should be mandatory and should contain only
characters Middle Name is optional Last Name of student should be mandatory and should
contain only characters Mark1, Mark2 and Mark3 should be only positive numbers less than
100. There will be a text box with total marks and Also a button for calcultaing the total.
On clicking the calculate total it will add all the marks and then displays in place of total
marks, Also the submit button appears.Clicking on the submit button it will show proper
successful message.
10. Create web page for the requirement below.
General Instructions for these exercises:
 There are total five pages to be created.
 First one is home page with links to below three pages.
 From below pages, on successful submit, navigate to welcome page.
 Welcome page should have link to home page.
 Place CSS and Javascript code in separate files.
 Use effective styling as per your choice.
 Use div tags and table for better layout.
 Maintain consistency for all pages.
Add a doctor
 Design a UI page / screen to capture the following details when registering a new
doctor in HMS.
 First name, Middle name Last name, Registration No, Date of Birth , Gender(use
radio button), Email,
 Specialization , Qualification, contact number, Address, Visiting Time, Visiting
Days(multiple selection
 should be allowed), NoOfPatientsPerDay, DepartmentNo.
 Indicate the mandatory fields on the page. All fields except middle name and address
are mandatory.
 Use below mentioned sample values for drop down/check boxes:
 Visiting Days – Mon,Tues,Wed,Thurs, Fri,Sat,Sun.
 Visiting Time – Morning, Afternoon, Evening
Add a department
 Design a UI page / screen to capture the following details when adding a new
department in HMS.
 Department name, Department Description(use text area), No. Of Doctors, Number
of general rooms,
 Number of ac rooms, Number of non ac rooms , Number of ICU , Cost of general
room, Cost of ac room,
 Cost of non ac room, Cost of each ICU.
 All fields are mandatory.
Add a patient
 Design a UI page / screen to capture the following details when adding a new patient
in HMS.
 First Name, Last Name , Date of birth, Gender(Use radio button), Father/Spouse
name, blood group(dropdown), Contact number, Visited earlier(check box)
 All fields are mandatory except contact number.
 Indicate mandatory fields on the page / screen.
Use below mentioned values in the dropdown :-
 Blood Group – O+,O-,AB+,AB-,A+,A-,B+,B-,Others

_________________________________________________________________________

S-ar putea să vă placă și