Java and Class Fundamentals

The General Form of a Class, When you define a class, you declare its exact form and nature.You do this by specifying the data that it contains and the code that operates on that data. A class’ code defines the interface to its data. A class is declared by use of the class keyword. The general form of a class definition is shown here:

class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list)
{
// body of method
}
type methodname2(parameter-list)
{
// body of method
}
// ...
type methodnameN(parameter-list)
{
// body of method
}
}

The data, or variables, defined within a class are called instance variables.The code is contained within methods. Collectively, the methods and variables defined within a class are called members of the class. In most classes, the instance variables are acted upon and accessed by the methods defined for that class. Thus, it is the methods that determine how a class’ data can be used. Variables defined within a class are called instance variables because each instance
of the class (that is, each object of the class) contains its own copy of these variables.
Thus, the data for one object is separate and unique from the data for another.
All methods have the same general form as main( ),however, most methods will not be specified as static or public. Notice that the general form of a class does not specify a main( ) method. Java classes do not need to have a main( ) method. You only specify one if that class is the starting point for your program. Further, applets don’t require a main( ) method at all.

Learn By Examples: Here is a class called Box that defines three instance variables: width, height, and depth. Currently, Box does not contain any methods.

class Box {
double width;
double height;
double depth;
}

A class defines a new type of data. The new data type is called Box. You will use this name to declare objects of type Box. It is important to remember that a class declaration only creates a template; it does not create an actual object. Thus, the preceding code does not cause any objects of type Box to come into existence.
To create a Box object, you will use a statement like the following:

Box mybox = new Box(); // create a Box object called mybox.

To assign the width variable of mybox the value 100, you would use the following statement:

mybox.width = 100;

Example-1: Here is a complete program that uses the Box class,

/* A program that uses the Box class.
Call this file BoxDemo.java
*/
class Box {
double width;
double height;
double depth;
}
// This class declares an object of type Box.
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
// assign values to mybox's instance variables
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
// compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}

You should call the file that contains this program BoxDemo.java, because the main( ) method is in the class called BoxDemo, not the class called Box. When you compile this program, you will find that two .class files have been created, one for Box and one for BoxDemo. The Java compiler automatically puts each class into its own .class file. It is not necessary for both the Box and the BoxDemo class to actually be in the same source file. You could put each class in its own file, called Box.java and BoxDemo.java, respectively. To run this program, you must execute BoxDemo.class. When you do, you will see the following output: Volume is 3000.0

Example-2: The followingprogram declares two Box objects:

// This program declares two Box objects.
class Box {
double width;
double height;
double depth;
}
class BoxDemo2 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// compute volume of first box
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is " + vol);
// compute volume of second box
vol = mybox2.width * mybox2.height * mybox2.depth;
System.out.println("Volume is " + vol);
}
}

The output produced by this program is shown here:
Volume is 3000.0
Volume is 162.0
Download The Source Code From Here

Adding Color in HTML

A collection of nearly 150 color names are supported by all major browsers.When you create a web page you will want to use different background and text colour's and to add images. This makes the site more attractive to visitors and generally makes the website look better. Take care not to make the text and background colour the same... :-0
To add color you would add the following HTML code into the body of your text file.

<body bgcolor = "#0000FF">


Notice how instead of saying We have used some strange looking code. Dont worry this is called "Hexadecimal colour" and can be used for inserting complex colours into your website.Check out some more Hexadecimal values below,

Hex values are written as 3 double digit numbers, starting with a # sign.

Color Color HEX Color RGB

#000000 rgb(0,0,0)

#FF0000 rgb(255,0,0)

#00FF00 rgb(0,255,0)

#0000FF rgb(0,0,255)

#FFFF00 rgb(255,255,0)

#00FFFF rgb(0,255,255)

#FF00FF rgb(255,0,255)

#C0C0C0 rgb(192,192,192)

#FFFFFF rgb(255,255,255)

16 Million Different Colors

The combination of Red, Green and Blue values from 0 to 255 gives a total of more than 16 million different colors to play with (256 x 256 x 256). Most modern monitors are capable of displaying at least 16384 different colors. If you look at the color table below, you will see the result of varying the red light from 0 to 255, while keeping the green and blue light at zero.

Red Light HEX RGB

#000000 rgb(0,0,0)

#080000 rgb(8,0,0)

#100000 rgb(16,0,0)

#180000 rgb(24,0,0)

#200000 rgb(32,0,0)

#280000 rgb(40,0,0)

#300000 rgb(48,0,0)

#380000 rgb(56,0,0)

#400000 rgb(64,0,0)

#480000 rgb(72,0,0)

#500000 rgb(80,0,0)

#580000 rgb(88,0,0)

#600000 rgb(96,0,0)

#680000 rgb(104,0,0)

#700000 rgb(112,0,0)

#780000 rgb(120,0,0)

#800000 rgb(128,0,0)

#880000 rgb(136,0,0)

#900000 rgb(144,0,0)

#980000 rgb(152,0,0)

#A00000 rgb(160,0,0)

#A80000 rgb(168,0,0)

#B00000 rgb(176,0,0)

#B80000 rgb(184,0,0)

#C00000 rgb(192,0,0)

#C80000 rgb(200,0,0)

#D00000 rgb(208,0,0)

#D80000 rgb(216,0,0)

#E00000 rgb(224,0,0)

#E80000 rgb(232,0,0)

#F00000 rgb(240,0,0)

#F80000 rgb(248,0,0)

#FF0000 rgb(255,0,0)

Shades of Gray

Gray colors are displayed using an equal amount of power to all of the light sources. To make it easier for you to select the right gray color we have compiled a table of gray shades for you:


RGB(0,0,0) #000000

RGB(8,8,8) #080808

RGB(16,16,16) #101010

RGB(24,24,24) #181818

RGB(32,32,32) #202020

RGB(40,40,40) #282828

RGB(48,48,48) #303030

RGB(56,56,56) #383838

RGB(64,64,64) #404040

RGB(72,72,72) #484848

RGB(80,80,80) #505050

RGB(88,88,88) #585858

RGB(96,96,96) #606060

RGB(104,104,104) #686868

RGB(112,112,112) #707070

RGB(120,120,120) #787878

RGB(128,128,128) #808080

RGB(136,136,136) #888888

RGB(144,144,144) #909090

RGB(152,152,152) #989898

RGB(160,160,160) #A0A0A0

RGB(168,168,168) #A8A8A8

RGB(176,176,176) #B0B0B0

RGB(184,184,184) #B8B8B8

RGB(192,192,192) #C0C0C0

RGB(200,200,200) #C8C8C8

RGB(208,208,208) #D0D0D0

RGB(216,216,216) #D8D8D8

RGB(224,224,224) #E0E0E0

RGB(232,232,232) #E8E8E8

RGB(240,240,240) #F0F0F0

RGB(248,248,248) #F8F8F8

RGB(255,255,255) #FFFFFF

If you are finding all of these different colour codes confusing dont worry!
As well as using the Hexadecimal method, you can also use good old fasioned English! Meaning that placing the following code into your HTML file would have the exact same effect:

<body bgcolor = "blue">


When inserted into your code, the code should look like this:

<html>
<head>
<title>My Own Home Page </title>
</head>
<body>
<body bgcolor= "blue">
<H1> I am Your-Name and this is my web Page!</H1>
</body>

Test your file by saving it, remember to save it as "index.html" and make sure you slect "All Files" from the save as type box. Now that we have our background colour sorted out, we can now alter the text colour. We go about doing this in the same way. This is the code we need to insert into our webpage:

<font color="Red">Text that you want to make red goes here</font>

Notice that you must put </font> after the text has ended. If you didnt insert the </font> then your entire document would have the text as red. This isnt to important for now but if you ever have more than one text colour on a page this may become a problem. Here is how your code should now look:

<html>
<head>
<title>My Own Home Page </title>
</head>
<body>
<body bgcolor= "blue">
<font color="Red">
<H1> I am Your-Name and this is my web Page!</H1>
</font>
</body>

Note:
A common error when coding with colours and HTML in general are simple spelling mistakes.
Remember that when typing "color" it is the american spelling, make sure you dont use the english spelling "colour" or your HTML wont work.

Statements, At-rules, Rule Sets and Selectors in CSS.

A CSS style sheet is composed from a list of statements. A statement is either an at-rule or a rule set. The following example has two statements; the first is an at-rule that is delimited by the semicolon at the end of the first line, and the second is a rule set that is delimited by the closing curly brace }.

@import url(base.css);
h2 {
color: #666;
font-weight: bold;
}

An at-rule is an instruction or directive to the CSS parser. It starts with an at-keyword: an @ character followed by an identifier . An at-rule can comprise a block delimited by curly braces, {}, or text terminated by a semicolon ;. An at-rule’s syntax will dictate whether it needs a block or text.
Parentheses, brackets, and braces must appear as matching pairs and can be nested within the at-rule. Single and double quotes must also appear in matching pairs. Here’s an example of an at-rule that requires a block—the @media at-rule:

@media print {
body {
font-size: 12pt;
}
}

Here’s an example of an at-rule terminated by a semicolon—the @import at-rule:
A rule set (also called a rule) comprises a selector followed by a declaration block the rule set applies the declarations listed in the declaration block to all elements matched by the selector.
Here’s an example of a rule set:

h2 {
color: #666;
font-weight: bold;
}

A selector comprises every part of a rule set up to but not including the left curly brace {. A selector is a pattern, and the declarations within the block that follows the selector are applied to all the elements that match this pattern. In the following example rule set, the selector is h2:

h2 {
color: #666;
font-weight: bold;
}

This selector—which is comprised of a single simple selector—will match all elements of type h2 in an HTML document. A simple selector can either be an element type selector or the universal selector (*), optionally followed by attribute selectors ,ID selectors, or pseudo-classes.
1 A selector can comprise a number of simple selectors separated by combinators , but it can contain only one pseudo-element , which must be appended to the last simple selector in the chain. Here’s a more complex selector:

h2+p.warning:first-line {
color: #666;
font-weight: bold;
}

This selector consists of two simple selectors separated by an adjacent sibling combinator and a pseudo-element. The first simple selector (h2) is a type selector. The second simple selector contains a type selector (p) and an attribute selector—in this case, a special form of attribute
selector called a class selector, which will match HTML class attributes containing the word “warning.” As such, the selector above would match the first line of text within any p element
that has a class attribute value of "warning" and is an adjacent sibling to an h2 element.
Finally, two or more selectors can be grouped, separated by commas (,); the declaration block that follows applies to both selectors. Consider these two rules:

#main ol {
margin-left: 2em;
}
#main ul {
margin-left: 2em;
}

They can be grouped like this:

#main ol, #main ul {
margin-left: 2em;
}

You can read about selectors in detail in the selector reference section. Declaration blocks begin with a left curly brace, {, and end with a right curly brace,}. They contain zero or more declarations separated by semicolons:

h2 {
color: #666;
}

A declaration block is always preceded by a selector . We can combine multiple rules that have the same selector into a single rule. Consider these rules:

h2 {
color: #666;
}
h2 {
font-weight: bold;
}

They’re equivalent to the rule below:

h2 {
color: #666;
font-weight: bold;
}

Although the last semicolon within a declaration block is optional, it’s good practice to include it, as it’ll help you avoid syntax errors in the future. As you start to add declarations to a block, it’s all too easy to forget the semicolon.

Variables and Parameters in C#

A variable represents a storage location that has a modifiable value. A variable can be a local variable, parameter, field or array element.The stack and the heap are the places where variables and constants reside. Each has very different lifetime semantics. The stack is a block of memory for storing local variables and parameters. The stack automatically grows and shrinks as a function is entered and exited.

static int Factorial (int x)
{
if (x == 0) return 1;
return x * Factorial (x-1);
}

This method is recursive, meaning that it calls itself. Each time the method is entered, a new int is allocated on the stack, and each time the method exits, the int is deallocated.

The heap is a block of memory in which objects reside. Whenever a new object is created, it is allocated on the heap, and a reference to that object is returned. During a program's execution, the heap starts filling up as new objects are created. The runtime has a garbage collector that periodically deallocates objects from the heap, so your computer does not run out of memory. An object is eligible for deallocation as soon as nothing references it. In the following code, the StringBuilder object is created on the heap, while the sb reference is created on the stack:

static void Test()
{
StringBuilder sb = new StringBuilder();
Console.WriteLine (sb.Length);
}

After the Test method finishes, sb pops off the stack, and the StringBuilder object is no longer referenced, so it becomes eligible for garbage collection.Value type instances live wherever the variable was declared. If the instance was declared as a field within an object, or as an array element, that instance lives on the heap. You can't explicitly delete objects in C#, as you can in C++. An unreferenced object is eventually collected by the garbage collector.The heap is also used to store static fields and constants. Unlike objects allocated on the heap (which can get garbage collected), these will live until the application domain is torn down.

How to definite Assignment ?
C# enforces a definite assignment policy. In practice, this means that outside of an unsafe context, it's impossible to access uninitialized memory. Definite assignment has three implications:
  • Local variables must be assigned a value before they can be read.
  • Function arguments must be supplied when a method is called.
  • All other variables (such as fields and array elements) are automatically initialized by the runtime.
For example, the following code results in a compile-time error:

static void Main()
{
int x;
Console.WriteLine (x); // compile-time error
}

Fields and array elements are automatically initialized with the default values for their type. The following code outputs 0 because array elements are implicitly assigned to their default values:

static void Main()
{
int[] ints = new int[2];
Console.WriteLine (ints[0]); // 0
}

The following code outputs 0 because fields are implicitly assigned to a default value:

class Test
{
static int x;
static void Main() { Console.WriteLine (x); } // 0
}

How to set Parameters ?
A method has a sequence of parameters. Parameters define the set of arguments that must be provided for that method. In this example, the method Foo has a single parameter named p, of type int:

static void Foo (int p)
{
p = p + 1; // increment p by 1
Console.WriteLine(p); // write p to screen
}
static void Main() { Foo(8); }

You can control how parameters are passed with the ref and out modifiers.
How to pass arguments by value ?
By default, arguments in C# are passed by value, which is by far the most common case. This means a copy of the value is created when passed to the
method:

class Test
{
static void Foo (int p)
{
p = p + 1; // Increment p by 1
Console.WriteLine (p); // Write p to screen
}

static void Main( )
{
int x = 8;
Foo (x); // Make a copy of x
Console.WriteLine (x); // x will still be 8
}
}

Assigning p a new value does not change the contents of x because p and x reside in different memory locations.Passing a reference type object by value copies the reference, but not the object. In the following example, Foo sees the same StringBuilder object that Main instantiated, but has an independent reference to it. In other words, sb and fooSB are separate variables that reference the same StringBuilder object:

class Test
{
static void Foo (StringBuilder fooSB)
{
fooSB.Append ("test");
fooSB = null;
}

static void Main( )
{
StringBuilder sb = new StringBuilder( );
Foo (sb);
Console.WriteLine (sb.ToString( )); // test
}
}

Because fooSB is a copy of a reference, setting it to null doesn't make sb null. (If, however, fooSB was declared and called with the ref modifier, sb would become null.)

Note:
  1. You can't explicitly delete objects in C#, as you can in C++. An unreferenced object is eventually collected by the garbage collector.

  2. A parameter can be passed by reference or by value, regardless of whether the parameter type is a reference type or a value type.

Defining a Class with a Member Function using C++

First we describe how to define a class and a member function. Then we explain how an object is created and how to call a member function of an object. The first few examples contain function main and the GradeBook class it uses in the same file.

/Define class GradeBook with a member function displayMessage;
Create a GradeBook object and call its displayMessage function.*/
#include <iostream>
using std::cout;
using std::endl;

// GradeBook class definition
class GradeBook
{
public:
// function that displays a welcome message to the GradeBook user
void displayMessage()
{
cout << "Welcome to the Grade Book!" << endl;
} // end function displayMessage
}; // end class GradeBook
// function main begins program execution
int main()
{
GradeBook myGradeBook;
// create a GradeBook object named myGradeBook
myGradeBook.displayMessage();
// call object's displayMessage function
return 0; // indicate successful termination
} // end main

Class GradeBook:
Before function main can create an object of class GradeBook, we must tell the compiler what member functions and data members belong to the class. This is known as defining a class. The GradeBook class definition a member function called displayMessage displays a message on the screen . The class definition begins with the keyword class followed by the class name GradeBook. By convention, the name of a user-defined class begins with a capital letter, and for readability, each subsequent word in the class name begins with a capital letter. This capitalization style is often referred to as camel case, because the pattern of uppercase and lowercase letters resembles the silhouette of a camel. Every class's body is enclosed in a pair of left and right braces ({ and }).

The access-specifier label public:. The keyword public is called an access specifier. The member function appears after access specifier public: to indicate that the function is "available to the public"that is, it can be called by other functions in the program and by member functions of other classes. Access specifiers are always followed by a colon (:). For the remainder of the text, when we refer to the access specifier public, we will omit the colon. There's a second access specifier private.

Each function in a program performs a task and may return a value when it completes its taskfor example, a function might perform a calculation, then return the result of that calculation. When you define a function, you must specify a return type to indicate the type of the value returned by the function when it completes its task. In the code, keyword void to the left of the function name displayMessage is the function's return type. Return type void indicates that displayMessage will perform a task but will not return (i.e., give back) any data to its calling function when it completes its task.

The name of the member function, displayMessage, follows the return type. By convention, function names begin with a lowercase first letter and all subsequent words in the name begin with a capital letter. The parentheses after the member function name indicate that this is a function. An empty set of parentheses, indicates that this member function does not require additional data to perform its task.

The body of a function contains statements that perform the function's task. In this case, member function displayMessage contains one statement that displays the message "Welcome to the Grade Book!". After this statement executes, the function has completed its task.

Note:
  1. Forgetting the semicolon at the end of a class definition is a syntax error.
  2. Returning a value from a function whose return type has been declared void is a compilation error.
  3. Defining a function inside another function is a syntax error.

Arrays In C

An array is a group of related data items that share a common name or An array is a data structure consisting of a group of elements that are accessed by indexing. In most programming languages each element has the same data type and the array occupies a contiguous area of storage.

#include <stdio.h>
/* count digits, white space, others */
main()
{
int c, i, nwhite, nother;
int ndigit[10];
nwhite = nother = 0;
for (i = 0; i < 10; ++i)
ndigit[i] = 0;
while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
else if (c == ' ' || c == '\n' || c == '\t')
++nwhite;
else
++nother;
printf("digits =");
for (i = 0; i < 10; ++i)
printf(" %d", ndigit[i]);
printf(", white space = %d, other = %d\n",
nwhite, nother);
}

The output of this program on itself is
digits = 9 3 0 0 0 0 0 0 0 1, white space = 123, other = 345
The declaration

int ndigit[10];

declares ndigit to be an array of 10 integers. Array subscripts always start at zero in C, so the elements are ndigit[0], ndigit[1], ..., ndigit[9]. This is reflected in the for loops that initialize and print the array.
A subscript can be any integer expression, which includes integer variables like i, and integer constants.
This particular program relies on the properties of the character representation of the digits. For example, the test

if (c >= '0' && c <= '9')

determines whether the character in c is a digit. If it is, the numeric value of that digit is
c - '0'
This works only if '0', '1', ..., '9' have consecutive increasing values. Fortunately, this is true for all character sets.
By definition, chars are just small integers, so char variables and constants are identical to ints in arithmetic expressions. This is natural and convenient; for example c-'0' is an integer expression with a value between 0 and 9 corresponding to the character '0' to '9' stored in c, and thus a valid subscript for the array ndigit.

Write a program in C-Sharp to demostrate Arrays.

An array represents a fixed number of elements of a particular type. The elements in an array are always stored in a contiguous block of memory, providing highly efficient access.An array is denoted with square brackets after the element type. Like,

char[] vowels = new char[5]; // It declare an array of 5

Square brackets also index the array, accessing a particular element by position:

vowels [0] = 'a';
vowels [1] = 'e';
vowels [2] = 'i';
vowels [3] = 'o';
vowels [4] = 'u';
Console.WriteLine (vowels [1]); //To print e.

This prints "e" because array indexes start at zero. We can use a for loop statement to iterate through each element in the array.The Length property of an array returns the number of elements in the array. Once an array has been created, its length cannot be changed. The System.Collection namespace and subnamespaces provide higher-level data structures, such as dynamically sized arrays and dictionaries. All arrays inherit from the System.Array class, which defines common methods and properties for all arrays. This includes instance properties such as Length and Rank, and static methods to:
  • Dynamically create an array (CreateInstance)
  • Get and set elements regardless of the array type (GetValue/SetValue)
Creating an array always preinitializes the elements with default values. The default value for a type is the result of a bitwise-zeroing of memory.

int[] a = new int[1000];
Console.Write (a[123]); // It will print 0(zero).

Multidimensional arrays come in two varieties: rectangular and jagged. Rectangular arrays represent an n-dimensional block of memory, and jagged arrays are arrays of arrays.Rectangular arrays are declared using commas to separate each dimension,

int[,] matrix = new int [3, 3];

A rectangular array can be initialized as follows,

int[,] matrix = new int[,]
{
{0,1,2},
{3,4,5},
{6,7,8}
};

Jagged arrays are declared using successive square brackets to represent each dimension,

int [][] matrix = new int [3][];

A jagged array can be initialized as,

int[][] matrix = new int[][]
{
new int[] {0,1,2},
new int[] {3,4,5},
new int[] {6,7,8}
};

Example: Write a program in C-Sharp to store Student Name, Roll No and Marks of three subjects in an Array. Find the Student record with highest total Marks. Download Code

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

namespace Assignment_3
{
struct StudentInfo
{
public string stdName ;
public long stdRollNo ;
public int stdMarks1 ;
public int stdMarks2 ;
public int stdMarks3 ;
public int total;

}

class Program
{
static void Main(string[] args)
{
StudentInfo[] std = new StudentInfo[2];
int[] total =new int[2];
for (int i = 0; i < std.Length; i++)
{
Console.Write("\nEnter Student Name: ");
std[i].stdName = Console.ReadLine();
Console.Write("Enter Student RollNo: ");
std[i].stdRollNo = long.Parse(Console.ReadLine());
Console.Write("Enter Student Marks1: ");
std[i].stdMarks1 = int.Parse(Console.ReadLine());
Console.Write("Enter Student Marks2: ");
std[i].stdMarks2 = int.Parse(Console.ReadLine());
Console.Write("Enter Student Marks3: ");
std[i].stdMarks3= int.Parse(Console.ReadLine());
std[i].total = std[i].stdMarks1 + std[i].stdMarks2 + std[i].stdMarks3;
Console.WriteLine("The Student Totoal Marks is {0}",std[i].total);
}

double max = std[0].total;
int maxstd = 0;
for (int j = 0; j < std.Length; j++)
{
if (max < std[j].total)
{
max = std[j].total;
maxstd = j;
}

}
Console.WriteLine("\n\nThe Student with Heightest total is : \n\nName: {0}\nRoll No: {1}\nTotal Marks: {2}",std[maxstd].stdName,std[maxstd].stdRollNo,std[maxstd].total);
Console.ReadLine();
}


}
}

What's New in C# 3.0

C# 3.0 features are centered on Language Integrated Query capabilities, or LINQ for short. LINQ enables SQL-like queries to be written directly within a C# program, and checked statically for correctness. Queries can execute either locally or remotely; the .NET Framework provides LINQ-enabled APIs across local collections, remote databases, and XML.

C# 3.0 features include:
  • Lambda expressions
  • Extension methods
  • Implicitly typed local variables
  • Query comprehensions
  • Anonymous types
  • Implicitly typed arrays
  • Object initializers
  • Automatic properties
  • Partial methods
  • Expression trees

Lambda expressions are like miniature functions created on the fly. They are a natural evolution of anonymous methods introduced in C# 2.0, and in fact, completely subsume the functionality of anonymous methods. For example:

Func<int,int> sqr = x => x * x;
Console.WriteLine (sqr(3));



The primary use case in C# is with LINQ queries, such as the following:

string[] names = { "Tom", "Dick", "Harry" };

// Include only names of >= 4 characters:

IEnumerable<string> filteredNames =
Enumerable.Where (names, n => n.Length >= 4);



Extension methods extend an existing type with new methods, without altering the type's definition. They act as syntactic sugar, making static methods feel like instance methods. Because LINQ's query operators are implemented as extension methods, we can simplify our preceding query as follows:

IEnumerable<string> filteredNames =
names.Where (n => n.Length >= 4);



Implicitly typed local variables let you omit the variable type in a declaration statement, allowing the compiler to infer it. Because the compiler can determine the type of filteredNames, we can further simplify our query:

var filteredNames = names.Where (n => n.Length == 4);



Query comprehension syntax provides SQL-style syntax for writing queries. Comprehension syntax can simplify certain kinds of queries substantially, as well as serving as syntactic sugar for lambda-style queries. Here's the previous example in comprehension syntax:

var filteredNames = from n in names
where n.Length >= 4
select n;



Anonymous types are simple classes created on the fly, and are commonly used in the final output of queries:

var query = from n in names where n.Length >= 4
select new {
Name = n,
Length = n.Length
};



Here's a simpler example:

var dude = new { Name = "Bob", Age = 20 };



Implicitly typed arrays eliminate the need to state the array type, when constructing and initializing an array in one step:

var dudes = new[]
{
new { Name = "Bob", Age = 20 },
new { Name = "Rob", Age = 30 }
};



Object initializers simplify object construction by allowing properties to be set inline after the constructor call. Object initializers work with both anonymous and named types. For example:

Bunny b1 = new Bunny {
Name = "Bo",
LikesCarrots = true,
};



The equivalent in C# 2.0 is:

Bunny b2 = new Bunny( );
b2.Name = "Bo";
b2.LikesCarrots = false;


Automatic properties cut the work in writing properties that simply get/set a private backing field. In the following example, the compiler automatically generates a private backing field for X:

public class Stock
{
public decimal X { get; set; }
}


Partial methods let an auto-generated partial class provide customizable hooks for manual authoring. LINQ to SQL makes use of partial methods for generated classes that map SQL tables.

Expression trees are miniature code DOMs that describe lambda expressions. The C# 3.0 compiler generates expression trees when a lambda expression is assigned to the special type Expression<TDelegate>:

Expression<Func<string,bool>> predicate =
s => s.Length > 10;



Expression trees make it possible for LINQ queries to execute remotely (e.g., on a database server) because they can be introspected and translated at runtime (e.g., into an SQL statement).

The EMPLOYEE table in SQL.

A single set of a group of fields is known as a record or row. For example, to create a relational database consisting of employee data, you might start with a table called EMPLOYEE that contains the following pieces of information: Name, Age, and Occupation. These three pieces of data make up the fields in the EMPLOYEE table.


The six rows are the records in the EMPLOYEE table. To retrieve a specific record from this table, for example, Dave Davidson, a user would instruct the database management system to retrieve the records where the NAME field was equal to Dave Davidson. If the DBMS had been instructed to retrieve all the fields in the record, the employee's name, age, and occupation would be returned to the user. SQL is the language that tells the database to retrieve this data. A sample SQL statement that makes this query is

SELECT * FROM EMPLOYEE

Write a program in C-Sharp to find the sum of all the digits of a given number.

The problem here is to sum the digits of a give number for example,
if the number x is input as 123 the result should be calculated as 1 + 2 + 3 = 6. To Implement this logic in C, C++, C-Sharp we should use the Modulo operator. For example..,
using System;
using System.Collections.Generic;
using System.Text;

namespace SumOfDig
{
class Program
{
static void Main(string[] args)
{
long modulo,sum=0;
Console.Write("Enter the Number:");
long number = long.Parse(Console.ReadLine());
while (number > 0)
{
modulo = (number % 10);
sum = sum + modulo;
number = number / 10;
}
Console.WriteLine("The Sum of Digits of number is {0}",sum);
Console.ReadLine();
}
}
}

Write a program in HTML to demonstrate the use of basic tags.

HTML stands for "Hyper Text Markup Language".HTML is the bricks and mortar of the WWW. Without HTML the World Wide Web could not have become as important as it is today. HTML is a document formatting language common the all computers on the WWW. Html permits cross platform communication between Macs, Apples, SUNs, PCs and others to view a document in a similar way. Every webpage that you visit uses HTML in some way, you can view the HTML code behind a website in Internet Explorer by selecting: View>Source.
HTML has two sections, the "Head" section and the "Body" section. The head section is where the information about the web page is put for the browser. This has nothing to do with the heading that you want to see on your web page. Things that can be stored in the head section include Keywords for search engines or the title of your webpage. The body section is where the web page is coded. This is where you put the information for your web page.We are now going to create our very own webpage, for now we are going to create a simple page telling people your name.Please follow these instructions:
  • Create a new folder so you have some where to save your website, call this folder anything you wish, this is where all pages and images for your website will be saved.
  • Open notepad and type the following code, you may change the code in yellow to suit your needs: Type the following code into NotePad.
    <html>
    <head>
    <title>My Own Home Page </title>
    </head>
    <body>
    <H1> I am Your-Name and this is my web Page!</H1>
    </body>
    </html>

  • Thats it! You have just coded your first webpage. Now save the notepad file by selecting "Save as" (make sure you save the file in the folder you have just created) In the filename box type "index.html" and from the "Save as type" box select "All Files"Then click "Save".
  • You are now ready to view your first webpage, navigate to the folder where you saved the file, double click on it and you will see your first webpage. It should look something like this:

What are Dr. Codd's 12 Rules for a Relational Database Model.

The most popular data storage model is the relational database, which grew from theseminal paper "A Relational Model of Data for Large Shared Data Banks," written by Dr. E. F. Codd in 1970. SQL evolved to service the concepts of the relational databasemodel. Dr. Codd defined 13 rules, oddly enough referred to as Codd's 12 Rules, for therelational model:

  1. A relational DBMS must be able to manage databases entirely through its relational capabilities.
  2. Information rule-- All information in a relational database (including tableand column names) is represented explicitly as values in tables.
  3. Guaranteed access--Every value in a relational database is guaranteed to beaccessible by using a combination of the table name, primary key value, and column name.
  4. Systematic null value support--The DBMS provides systematic support for the treatment of null values (unknown or inapplicable data), distinct from default values, and independent of any domain.
  5. Active, online relational catalog--The description of the database and its contents is represented at the logical level as tables and can therefore be queried using the database language.
  6. Comprehensive data sublanguage--At least one supported language must have a well-defined syntax and be comprehensive. It must support data definition,manipulation, integrity rules, authorization, and transactions.>
  7. View updating rule--All views that are theoretically updatable can be updated through the system.
  8. Set-level insertion, update, and deletion--The DBMS supports not only set level retrievals but also set-level inserts, updates, and deletes.
  9. Physical data independence--Application programs and ad hoc programs arelogically unaffected when physical access methods or storage structures arealtered.
  10. Logical data independence--Application programs and ad hoc programs are logically unaffected, to the extent possible, when changes are made to the table structures.
  11. Integrity independence--The database language must be capable of defining integrity rules. They must be stored in the online catalog, and they cannot be by passed.
  12. Distribution independence--Application programs and ad hoc requests are logically unaffected when data is first distributed or when it is redistributed.
  13. Nonsubversion--It must not be possible to bypass the integrity rules defined through the database language by using lower-level languages.


This method has several advantages and many disadvantages. In its favor is the fact that the physical structure of data on a disk becomes unimportant. The programmer simply stores pointers to the next location, so data can be accessed in this manner. Also, data can be added and deleted easily. However, different groups of information could not be easily joined to form new information. The format of the data on the disk could not be arbitrarily changed after the database was created. Doing so would require the creation of a new database structure.Codd's idea for an RDBMS uses the mathematical concepts of relational algebra to break down data into sets and related common subsets.

Introduction to SQL, A Brief History.

The history of SQL begins in an IBM laboratory in San Jose, California, where SQL was developed in the late 1970's. The initials stand for Structured Query Language, and the language itself is often referred to as "sequel." It was originally developed for IBM's DB2 product (a relational database management system, or RDBMS, that can still be bought today for various platforms and environments). In fact, SQL makes an RDBMS possible. SQL is a nonprocedural language, in contrast to the procedural or third generation languages (3GLs) such as COBOL and C that had been created up to that time.
The characteristic that differentiates a DBMS from an RDBMS is that the RDBMS provides a set-oriented database language. For most RDBMSs, this set-oriented database language is SQL. Set oriented means that SQL processes sets of data in groups.
Two standards organizations, the American National Standards Institute (ANSI) andthe International Standards Organization (ISO), currently promote SQL standards toindustry. The ANSI-92 standard is the standard for the SQL used throughout this book.Although these standard-making bodies prepare standards for database system designersto follow, all database products differ from the ANSI standard to some degree. Inaddition, most systems provide some proprietary extensions to SQL that extend thelanguage into a true procedural language. We have used various RDBMSs to preparethe examples in this book to give you an idea of what to expect from the commondatabase systems. (We discuss procedural SQL--known as PL/SQL--on Day 18, "PL/SQL: AnIntroduction," and Transact-SQL on Day 19, "Transact-SQL: An Introduction.")
A little background on the evolution of databases and database theory will help you understand the workings of SQL. Database systems store information in every conceivable business environment. From large tracking databases such as airline reservation systems to a child's baseball card collection, database systems store and distribute the data that we depend on. Until the last few years, large database systems could be run only on large mainframe computers. These machines have traditionally been expensive to design, purchase, and maintain. However, today's generation of powerful, inexpensive workstation computers enables programmers to design software that maintains and distributes data quickly and inexpensively.

Write a simple program using PYTHON.

Python is a powerful yet easy to use programming language developed by Guido van Rossum, first released over a decade ago in 1991. With Python, you can quickly write a small project. But Python also scales up nicely and can be used for mission-critical, commercial applications.
Python is a dynamic object-oriented programming language that can be used for many kinds of software development. It offers strong support for integration with other languages and tools, comes with extensive standard libraries, and can be learned in a few days. Many Python programmers report substantial productivity gains and feel the language encourages the development of higher quality, more maintainable code.
There are a lot of programming languages out there. What's so great about Python? Let me tell you.
  1. Python Is Easy to Use
  2. Python Is Powerful
  3. Python Is Object-Oriented
  4. Python Is a "Glue" Language
  5. Python Runs Everywhere
  6. Python Has a Strong Community
  7. Python Is Free and Open Source
At the command prompt (>>>), type:

print "Game Over"
raw_input("\n\nPress the enter key to exit.")

The interpreter responds by displaying

Game Over

Try By Yourself:
  1. Create a syntax error of your very own by entering your favorite ice cream flavor in interactive mode. Then, make up for your misdeed and enter a statement that prints the name of your favorite ice cream.
  2. Write and save a program that prints out your name and waits for the user to press the Enter key before the program ends. Then, run the program by double-clicking its icon.
  3. Write a program that prints your favorite quote. It should give credit to the person who said it, on the next line (hint: use two different print statements).
Your Comments Are Precious To Us. Please Reply About This Post.

Wrate a program in Java Script to demonstrate Java Script Execution.

In early December 1995, just prior to the formal release of Navigator 2, Netscape and Sun Microsystems jointly announced that the scripting language thereafter would be known as JavaScript. Though Netscape had several good marketing reasons for adopting this name, the changeover may have contributed more confusion to both the Java and HTML scripting worlds than anyone expected.
The JavaScript language, working in tandem with related browser features, is a Web-enhancing technology. When employed on the client computer, the language can help turn a static page of content into an engaging, interactive, and intelligent experience. Applications can be as subtle as welcoming a site’s visitor with the greeting “Good morning!” when it is morning in the client computer’s time zone—even though it is dinnertime where the server is located. Or applications
can be much more obvious, such as delivering the content of a slide show in a one-page download while JavaScript controls the sequence of hiding, showing, and “flying slide” transitions while navigating through the presentation.
follow these steps to enter and preview your first JavaScript script:
1. Activate your text editor and create a new, blank document.
2. Type the script into the window exactly as shown.
3. Save the document with the name script1.html.
4. Switch to your browser.
5. Choose Open (or Open File on some browsers) from the File menu and select
script1.html. (On some browsers, you have to click a Browse button to reach the File
dialog box.)

<html>
<head>
<title>My First Script</title>
<style type=”text/css”>
.highlight {font-weight: bold}
</style>
</head>
<body>
<h1>Let’s Script...</h1>
<hr>
<script type=”text/javascript”>
<!-- hide from old browsers
document.write(“This browser is version “ + navigator.appVersion);
document.write(“of <span class=’highlight’>” + navigator.appName + “</span>.”);
// end script hiding -->
</script>
</body>
</html>

Write a program in CSS to demonstrate the use of Style Element.

Cascading Style Sheets were created to provide a powerful, yet flexible means for formatting HTML content. CSS works much like style sheets in a word processing program—you define a
“style” that contains formatting options that can be applied to document elements.

For example, consider the following code:

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN”
“http://www.w3.org/TR/html4/strict.dtd”>
<html>
<head>
<title>A Sample Style</title>
<style type=“text/css”>
h1 { color: Red; }
</style>
</head>
<body>
...


Note the <style> element inside of the <head> element. It defines one style, setting the font color of all <h1> elements to red. This is the same as using the following code throughout the document, wherever <h1> elements are used:

<h1><font color=“red”>Heading Text</font></h1>

Using the preceding method (<font> tags), you would need to change every instance in the document if you later changed your mind about the formatting. Using CSS requires that you change only the style definition at the top of the document to affect all <h1> elements.
NOTE: CSS can be a complicated beast, especially once you get into the different selector methods, inheritance, and the complete cascade picture. However, at its core it is a very simple concept: Assign formatting attributes in one place that can be easily modified later. As you read through the chapters in Part II, keep this concept in mind and resist getting bogged down in the CSS concepts that you may not need.

Write a program in PHP to display "Hello, World !" message.

PHP is an excellent choice for Web programming. It has many advantages
over other languages, including other Web-oriented languages. To get a
very general understanding of how the common Web programming languages
compare, let’s compare them. ASP is Microsoft’s Web programming environment. (It’s not a languageitself because it allows the programmer to choose from a few actual languages,
such as VBScript or JScript.) ASP is simple, but too simple for programs
that use complex logic or algorithms.

Tip:: An algorithm is a formula-like method for accomplishing a particular task. Here’s a simple
example: Some bank accounts use the last four digits of a person’s Social Security
number as his PIN number. An algorithm could be formed to create this PIN number
based on the already-known Social Security number.

<!-- File: hello.php -->
<html>
<head><title>PHP By Example :: Example 1</title></head>
<body bgcolor=”white” text=”black”>
<h4>PHP By Example :: Example 1</h4>
<?php
/* Display a text message */
echo “Hello, world! This is my first PHP program.”;
?>
</body>
</html>


Output:
Hello, world!

Write a program in C-Sharp to generate E-Bill using Switch Case.

The switch statement is a control statement that handles multiple selections and enumerations by passing control to one of the case statements within its body as the following example:

int caseSwitch = 1;
switch (caseSwitch)
{
case 1:
Console.WriteLine("Case 1");
break;
case 2:
Console.WriteLine("Case 2");
break;
default:
Console.WriteLine("Default case");
break;
}

Control is transferred to the case statement which matches the value of the switch. The switch statement can include any number of case instances, but no two case statements can have the same value. Execution of the statement body begins at the selected statement and proceeds until the break statement transfers control out of the case body. A jump statement such as a break is required after each case block, including the last block whether it is a case statement or a default statement. With one exception, (unlike the C++ switch statement), C# does not support an implicit fall through from one case label to another. The one exception is if a case statement has no code.

If no case expression matches the switch value, then control is transferred to the statement(s) that follow the optional default label. If there is no default label, control is transferred outside the switch. Here come's the E-Billing code in C-Sharp,

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

namespace Assignment1
{
class Program
{
static void Main(string[] args)
{
double total_amount;
l: Console.WriteLine("Enter from following choices.\n\n1.Press One For Demostic\n2.Press Two For Commercial\n3.Press Three For Industrial");
Console.Write("\n\nYou hava entered the choice: ");
int choice = int.Parse(Console.ReadLine());
if (choice == 1 || choice == 2 || choice == 3)
{
r: Console.Write("\nEnter Previous Reading: ");
long previous_reading = long.Parse(Console.ReadLine());
Console.Write("Enter Present Reading: ");
long present_reading = long.Parse(Console.ReadLine());
if (present_reading > previous_reading)
{
long total_reading = (present_reading - previous_reading);
switch (choice)
{
case 1:
if (total_reading >= 0 && total_reading <= 50) { total_amount = total_reading * 1.50; Console.WriteLine("\nThe Amount For Total Reading {0} units Is Rs.{1}/-", total_reading, total_amount); } else if (total_reading >= 51 && total_reading <= 100) { total_amount = total_reading * 2.0; Console.WriteLine("\nThe Amount For Total Reading {0} units Is Rs.{1}/-", total_reading, total_amount); } else if (total_reading > 100)
{
total_amount = total_reading * 2.50;
Console.WriteLine("\nThe Amount For Total Reading {0} units Is Rs.{1}/-", total_reading, total_amount);
}
break;
case 2:
if (total_reading >= 0 && total_reading <= 50) { total_amount = total_reading * 2.50; Console.WriteLine("\nThe Amount For Total Reading {0} units Is Rs.{1}/-", total_reading, total_amount); } else if (total_reading >= 51 && total_reading <= 100) { total_amount = total_reading * 3.0; Console.WriteLine("\nThe Amount For Total Reading {0} units Is Rs.{1}/-", total_reading, total_amount); } else if (total_reading > 100)
{
total_amount = total_reading * 3.50;
Console.WriteLine("\nThe Amount For Total Reading {0} units Is Rs.{1}/-", total_reading, total_amount);
}
break;
default:
if (total_reading >= 0 && total_reading <= 50) { total_amount = total_reading * 3.50; Console.WriteLine("\nThe Amount For Total Reading {0} units Is Rs.{1}/-", total_reading, total_amount); } else if (total_reading >= 51 && total_reading <= 100) { total_amount = total_reading * 4.0; Console.WriteLine("\nThe Amount For Total Reading {0} units Is Rs.{1}/-", total_reading, total_amount); } else if (total_reading > 100)
{
total_amount = total_reading * 4.50;
Console.WriteLine("\nThe Amount For Total Reading {0} units Is Rs.{1}/-", total_reading, total_amount);
}
break;

}
}
else
{
Console.WriteLine("\nInvalid Input Reading....");
Console.Write("\nWould You Like To Continue Y or N: ");
string d = Console.ReadLine();
if (d == "y" || d == "Y")
{
goto r;
}
else
{
Console.WriteLine("Your Good For Nothing.....");
}
}
}
else
{
Console.WriteLine("\nInvalid Input");
Console.Write("\nWould You Like To Continue Y or N: ");
string d = Console.ReadLine();
if(d == "y" || d == "Y")
{
goto l;
}
else
{
Console.WriteLine("Your Good For Nothing.....");
}
}
Console.ReadLine();
}
}
}



Output:
Enter from following choices.

1.Press One For Demostic
2.Press Two For Commercial
3.Press Three For Industrial


You hava entered the choice: 1

Enter Previous Reading: 23598
Enter Present Reading: 23958

The Amount For Total Reading 360 units Is Rs.900/-

Write a program in C-Sharp to demostrate 'TYPECASTING'.

'Typecasting' is one of the methods used in programming. The name given to transforming one type into another. There are two types of casting that can be performed on data types, implicit and explicit

Implicit Typecas:

Implicit casting is performed by the compiler when there is no possible loss of data. This is when a smaller data type is copied into a larger data type - e.g., converting a 16-bit short to a 32-bit integer value.

We could also say, implicit casting is used when casting from a basic type to a more general one. Therefore you use implicit typecasts when transforming a square into a rectangle or when transforming a circle into an ellipse. Because the later is the more general, the typecast can be done implicitly.

Here is a simple example to how implicit typecasting is done:

Int32 iNumber = 185;
Double dNumber = 36.485d;

dNumber = iNumber;
// implicit typecast; dNumber is now 185.0d

In this example the typecast can be done implicitly. You can implement an implicit typecast in your classes using the implicit keyword. In our example we want to transform a square into a rectangle.

using System;
using System.Drawing;

public class MySquare
{
// Remember: please do not make private variables public.
// Use accessors instead.
private Point pos;
private Int32 width;

#region Constructors, Methods etc.
// ...
#endregion

#region Methods
public Point Position
{
get { return this.pos; }
set { this.pos= value; }
}

public Int32 Width
{
get { return this.width; }
set { this.width = value; }
}
#endregion
}

public class MyRectangle
{
private Point pos;
private Int32 width, height;

#region Constructors, Methods etc.
// ...
#endregion

#region Implicit Type Conversion
public static implicit operator MyRectangle(MySquare Square)
{
this.pos = Square.Position;
this.width = Square.Width;

// Because MySquare has no heigth property we set a
// default value
this.height = Square.Height;
}
#endregion
}

Now we can do type conversion with ease:

MySquare square = new MySquare(...);
MyRectangle rectangle = square;


Explicit Typecast:

Explicit casting requires the use of the cast operator (parentheses) when there is a possible loss of data - e.g., converting a 32-bit integer into an 8-bit byte as in the code below.


int fourBytes = 0x000000FE;
byte lowestByte = (byte)fourBytes;

Using the implicit example, we want to look at the case if there is a data loss on typecasting:

MyRectangle rectangle = new MyRectangle(...);
MySquare square = rectangle; // Error

Because a rectangle may have different width and height, it's not possible to convert the rectangle into a square. We can solve this issue by defining how to handle this case.

A possibility to do so is checking if the width and height is equal. If so, the rectangle represents a square and we can convert gracefully. Otherwise, either a type cast exception has to get thrown.

public class MySquare
{
// ...

public explicit operator MySquare(MyRectangle Rectangle)
{
if(Rectangle.Width == Rectangle.Height)
{
this.Width = Rectangle.Width;
// no information lost
this.pos = Rectangle.Position;
}
else
{
throw new TypeCastException("Rectangle is not square.");
}
}
}

Alternatively we define how the information is transformed, which does not require any exceptions to be thrown.

public class MySquare
{
// ...

public explicit operator MySquare(MyRectangle Rectangle)
{
this.width = Rectangle.Width;
this.pos = Rectangle.Position;
// ignore the height of the rectangle
}
}

Write a program in C-Sharp to evaluate an equation.

In C#, Console.WrilLine(""); is like printf() function in C. There are three syntax method a programmer can choose to display his result and they are,

Console.WriteLine("Hello, World"); //Normal Method.
//Below is the Concatenation Method.
Console.WriteLine(" The Sum Of "+a+" + "+b+" = "+c);
//Last Method.
Console.WriteLine("Sum Of {0} + {1} = {2}");

Let us now see, How to evaluate an expression like this,

( a + b ) * c
----------------
4 * d
using System;
using System.Collections.Generic;
using System.Text;

namespace prog1
{
class Program
{
static void Main(string[] args)
{
double a, b, c, d;
Console.Write("Enter the values for a: ");
a = double.Parse(Console.ReadLine());
Console.Write("Enter the values for b: ");
b = double.Parse(Console.ReadLine());
Console.Write("Enter the values for c: ");
c = double.Parse(Console.ReadLine());
Console.Write("Enter the values for d: ");
d = double.Parse(Console.ReadLine());
Console.WriteLine("The value of the expression is "+(((a+b)*c)/(4*d)));
Console.ReadLine();
}
}
}

Output:
Enter the values for a: 4
Enter the values for b: 5
Enter the values for c: 2
Enter the values for d: 4
The value of the expression is 1.125

Write a program in C-Sharp to display "Hello World" message.

The .NET Framework supports multiple languages such as Visual Basic, C#, J#, and so on.C# has emerged as one of the most powerful object-oriented programming language. It implements all the object-oriented concepts , such as encapsulation, inheritance, polymorphism, and bstraction. However, there are certain things that differentiate it form C++. For instance, C# does not support multiple inheritance in classes, whereas C++ does.Being a .NET language, C# has access to the classes defined in the .NET Framework and to the unique features of the Common Language Runtime (CLR) such as, garbage collection, just-in-time compilation etc.., All the programs a compiled and tested in Visual Studio 2005. To Download free Trail of Visual Studio 2008 click here


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

namespace prog1
{
class Program
{
static void Main(string[] args)
{
Console.Write("Hello, World.......!");
Console.ReadLine();
}
}
}

Output:
Hello, World.......!


Write a program in JAVA to preform Arithmetic Operation.

The Arithmetic Operation are Addition, Multiplication, Division, Subtraction. It is demonstrated below using java.


/* Arithmetic Operation Using Java */
class ArithOp {
public static void main(String args[]) {
int num1,num2,Add,Mul,Div,Sub;
num1 = 200;
num2 = 100;
System.out.println(" This is num1: "+num+" and num2: "+num2);
Add = num1 + num2;
Mul = num1 * num2;
Div = num1 / num2;
Sub = num1 - num2;
System.out.println("Addition =" +Add);
System.out.println("Multiplication =" +Mul);
System.out.println("Division =" +Div);
System.out.println("Subtraction =" +Sub);
}
}


Output:
This is num1: 200 and num2: 100
Addition = 300
Multiplication = 200
Division = 2
Subtraction = 100

Write a program in JAVA to display a string.

The descriptions that follow use the standard java 2 SDK ( Software Development kit), which is available from Sum Microsystems. Click here to download . The First thing that you must learn about java is that the name you give to a source file is very important. Therefor, class name and program name should be same.

/*This is a simple java program.*/
class Example {
//Your program begins with a call to main().
public static void main(String args[]) {
System.out.println("This is a simple Java Program.");
}
}

Output:

This is a simple Java program.

Write a program to obtain average of two numbers.

Here the compile reads two inputs at the run time and perform the average. Its a simple logic to perform average of two numbers.

#include <iostream.h>
int main()
{
float number1, number2,
sum,average;
cout << "Enter two number: ";
cin >> number1;
cin >> number2;
sum = number1 + number2;
average = sum/2;
cout << "Sum =" << sum <<"\n";
cout << "Average =" << average <<"\n";
return 0;
}

Output:

Enter two numbers: 6.5 7.5
Sum = 14
Average = 7

Write a program to print a string using C++.

C++ is an Object-Oriented Programming Language. C++ is an extension of C with a major addition of the class construct feature Simula97. The most important facilities that C++ adds on to C are Classes, inheritance, function, overloading, and operator overloading. The object-oriented features in C++ allow programmers to build large programs with clarity, extensibility and ease of maintenance, incorporating the spirit and efficiency of C.

#include <iostream.h> // include header file
int main()
{
cout << "Welcome To C++.\n"; // C++ statement
return 0;
} // End of example

Output:

Welcome To C++.
 

About Me

It's Me!Hi, I'm Moinuddin. I'm a Software Engineer at WIPRO working on Microsoft .NET Technology. I'm interested in a wide range of technology topics, mainly Microsoft including Windows Azure, WCF, WPF, Silverlight and any other cool technology that catches the eye.

Site Info

ProjectCSharp.com is mainly about demonstrating real time examples in different technologies like ASP.NET, WCF, WPF, Silverlight, Azure etc..,

Followers

Help Links

Project CSharp (C#) Copyright © 2011. All Rights Reserved.