You are on page 1of 30

1)

using using using using

System; System.Collections.Generic; System.Linq; System.Text;

namespace ConsoleApplication2 { class Program { static void Main(string[] args) { //Area of the Circle double radius; double area; radius=10.0; area=radius*radius*3.1416; Console.WriteLine("Area is "+area); } } } 2) using using using using System; System.Collections.Generic; System.Linq; System.Text;

namespace ConsoleApplication2 { class Program { static void Main(string[] args) { //Compute the sum and product of the numbers from 1 to 10. int sum = 0; int prod=1; int i; for (i = 1; i <= 10; i++) { sum = sum + i; prod = prod * i; } Console.WriteLine("Sum is " + sum); Console.WriteLine("Product is " + prod); } } } 3) using using using using System; System.Collections.Generic; System.Linq; System.Text;

namespace ConsoleApplication2 { class Program

{ static void Main(string[] args) { // IDENTIFIERS int @if; //use if as an identifier for(@if=0;@if<10;@if++) Console.WriteLine("@if is "+@if); } } }

Output: @if is 0 @if is 1 @if is 2 @if is 3 @if is 4 @if is 5 @if is 6 @if is 7 @if is 8 @if is 9 Press any key to continue . . . Identifier is a name assigned to a method, a variable, or any other user-defined item. Identifier can be one or more characters long. Variable names may start with any letter of the alphabet or a n underscore. @for is also used as a variables.

C# Value Types
Value types are also called Simple Types. Type Bool Byte Char Decimal Double Float Int Long Sbyte Short Uint Ulong Ushort Meaning represents true of false values 8-bit unsigned integer Character Numeric type for financial calculations Double-precision floating pint Single-precision floating point Integer Long Integer 8-bit signed integer short integer An unsigned integer An unsigned long integer An unsigned short integer

Integers
Char Byte s Byte Short Ushort Int Uint Long Ulong 0 to 255 -128 to 127 -32768 to 32767 0 to 65535 -2147483648 to 2147483647 0 to 4294967295 -9223372036854775808 to 9223372036854775807 0 to 18446744073709551615

4) using using using using

System; System.Collections.Generic; System.Linq; System.Text;

namespace ConsoleApplication2 { class Program { static void Main(string[] args) { // Compute the distance from the Earth to the sun, in inches. long inches; long miles; miles = 93000000; // 93000000 miles to the sun // 5,280 feet in a mile 12 inches in a foot. inches = miles * 5280 * 12; Console.WriteLine("Distance to the sum: " + inches + " inches."); } } } Output: Distance to the sum: 5892480000000 inches. Press any key to continue . . .

5) using using using using

System; System.Collections.Generic; System.Linq; System.Text;

namespace ConsoleApplication2 { class Program { static void Main(string[] args) {

// USE BYTE byte x; int sum; sum = 0; for (x = 1; x <= 100; x++) sum = sum + x; Console.WriteLine("Summation of 100 is " + sum); } } }

Summation of 100 is 5050 Press any key to continue . . .

6) using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication2 { class Program { static void Main(string[] args) { // Use Format Commands. int i; Console.WriteLine("Value\tSquared\tCubed"); for (i = 1; i < 10; i++) Console.WriteLine("{0}\t{1}\t{2}", i, i *i,i* i * i);

} } }

7) using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { decimal price; decimal discount; decimal discounted_price; // Compute discounted price price = 19.95m; // discont rate is 15% discount = 0.15m; discounted_price = price - (price * discount); Console.WriteLine("Discounted price: {0:C}", discounted_price);

} } } Discounted price: $16.96 Press any key to continue . . .

String Literals
C# supports one other type of literal: the string. A string literal is a set of characters enclosed by double quotes. this is a teat

Is a string. You have seen examples of strings in many of the WriteLine() statements in the preceding sample programs. In addition to normal characters, a string literal can also contain one or more of the escape sequences just described. For example, consider the following program. It uses the n and \t escape sequences. 8) using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { Console.WriteLine("Line One\nLineTwo\nLine Three"); Console.WriteLine("One\tTwo\tThree"); Console.WriteLine("Four\tFive\tSix"); // Embed quotes. Console.WriteLine("\"Why?\", he asked");

} } }

9) using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { // Lenght of slides. double s1= 4.0; double s2 = 5.0; // Dynamically initialize hypot. double hypot=Math.Sqrt((s1*s1)+(s2*s2)); Console.Write("Hypotenuse of triangle with slides " + s1 + " by " + s2 + " is "); Console.WriteLine("{0:#.###}.", hypot);

} } }

Hypotenuse of triangle wit sides 4 by 5 is 6.403

10) using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { int i; float f; i = 10; f = i; // assign an int to a float Console.WriteLine(f);

} } }

10

11) using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { double n; for (n = 1; n <= 10; n++) { Console.WriteLine("The square root of {0} is {1}", n, Math.Sqrt(n)); Console.WriteLine("Whole number part: {0}", (int)Math.Sqrt(n)); Console.WriteLine("fractional part: {0}", Math.Sqrt(n) - (int)Math.Sqrt(n)); Console.WriteLine();

} } } }

12) using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { double n; for (n = 1; n <= 10; n++) { Console.WriteLine("The square root of {0} is {1}", n, Math.Sqrt(n)); Console.WriteLine("Whole number part: {0}", (int)Math.Sqrt(n)); Console.WriteLine("fractional part: {0}", Math.Sqrt(n) - (int)Math.Sqrt(n)); Console.WriteLine();

} } } }

ARITHMETIC OPERATORS
+ * / % ++ Addition Subtraction (also unary minus) Multiplication Division Modulus Increment

--Decrement

This % is also referred to as the reminder operator. It yields the remainder of an integer division. For example, 10%3 is 1. In C#, the % can be applied to both integer and floating point types.

Relational and Logical Operators


In the terms relational operator and logical operator, relational refers to the relationships that values can have with one another, and logical refers to the ways in which true and false values can be connected together. RELATIONAL OPERATORS Operator == != > < >= <= Meaning Equal to Not Equal to Greater than Less than Greater than or equal to Less than equal to

LOGICAL OPERATORS & | ^ || && ! AND OR XOR (exclusive OR) Short-circuit OR Short-circuit AND NOT

ASSIGNMENT OPERATOR The assignment operator is the single equal sign, =. Var-name=expression;

BITWISE OPERATORS
13) using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { ushort num; ushort i; for (i = 1; i < +10; i++) { num = i; Console.WriteLine("num: " + num); num = (ushort)(num & 0xFFFE); Console.WriteLine("num after turning off bit zero: " + num + "\n"); }

} } }

SWITCH CASE
14) using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { // Demonstrate the Switch int i; for(i=0;i<10;i++) switch (i) { case 0: Console.WriteLine("i is zero");

break; case 1: Console.WriteLine("i break; case 2: Console.WriteLine("i break; case 3: Console.WriteLine("i break; case 4: Console.WriteLine("i break; default: Console.WriteLine("i break; }

is one");

is wo");

is three");

is four");

is five or more");

} } }

15) using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { // Determine if a number is prime. If it is not, then // dislay its largest factor. int num; int i; int factor; bool isprime; for(num=2;num<20;num++) { isprime=true; factor = 0; // See if num is evenly divisible. for(i=2;i<=num/2;i++) { if((num%i)==0)

{ // num is evenly divisible. Thus, it is not rie. isprime=false; factor=i; } } if(isprime) Console.WriteLine(num+" is prime."); else Console.WriteLine("Largest factor of " + num + " is " + factor);

} } } }

WHILE LOOP 16) using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { int num; int mag; num = 435679; mag = 0; Console.WriteLine("Nmber: " + num); while (num > 0) { mag++; num = num / 10; }; Console.WriteLine("magnitude: " + mag);

} } }

DO-WHILE LOOP

17) using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { // Do while loop // Display the digits of an integer in reverse order. int num; int nextdigit; num = 198; Console.WriteLine("NUmber :" + num); Console.WriteLine("Number in reverse order: "); do { nextdigit = num % 10; Console.Write(nextdigit); num = num / 10; } while (num > 0); Console.WriteLine(); } } }

ARRAYS AND STRINGS


Arrays

An array is a collection of variables of the same type that are referred to by a common name. N C#, arrays can have one or more dimensions, although the one-dimensional array is the most common. Arrays are used for a variety of purposes because they offer a convenient means of grouping together related variables. For example, you might use an array to hold a record of the daily high temperature for a month, a list of stock prices, or your collection of programming books.

The principal advantage of an array is that it organises data in such a way that it can be easily manipulated. ONE-DIMENSIONAL ARRAYS A one-dimensional array is a list of related variables. Such lists are common in programming.

Type[]array name=new type[size];

18) using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { int[] sample = new int[10]; int i; for (i = 0; i < 10; i = i + 1) sample[i] = i; for (i = 0; i <= 10; i = i + 1) Console.WriteLine("Sample[" + i + "]: " + sample[i]);

} } }

TWO-DIMENSIONAL ARRAY Int[ , ] arrayname=new int[ , ];

19) using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication2 { class Program {

static void Main(string[] args) { // Demonstrate a two- demensional array. int t, i; int[,] table = new int[3, 4]; for (t = 0; t < 3; t++) { for (i = 0; i < 4; i++) { table[t, i] = (t * 4) + i + 1; Console.Write(table[t, i] + " "); } Console.WriteLine(); }

} } }

20) using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication2 { class Program { static void Main() { int i; int[] num = new int[10]; for (i = 0; i < 10; i++) num[i] = Convert.ToInt32(Console.ReadLine());

Console.Write("here is num: "); for (i = 0; i < 10; i++) Console.Write(num[i] + " "); Console.WriteLine(); } } }

21) using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { // Use the foreach loop. int sum = 0; int[] nums = new int[10]; // Gve nums some values. for (int i = 0; i < 10; i++) nums[i] = Convert.ToInt32(Console.ReadLine()); //Use foreach to display and sum the values. foreach(int x in nums) { Console.WriteLine("Values is: " + x); sum=+x; } Console.WriteLine("Summation: " + sum);

} } }

STRINGS
String defines and supports character strings. In string is an array of characters. This is not the Thus, string is a reference type. Although string discussion of string needed to wait until classes many other programming languages, a case with C#. In C#, strings are objects. is a built in data type in C#, a and objects had been introduced. Constructing Strings The earliest way to construct a string is to use a string literal. String str=C# strings are powerful.; In this case, str is initialized to the character sequence C# strings are powerful. You can also create a string from a char array. Char[] charray={t,e,s,t); Srting str=new string(charray);
22) using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { // Introduce string char[] charray={'A', ' ','s', 'r', 'i', 'n', 'g', '.'}; string str1=new string(charray); string str2="Another string"; Console.WriteLine(str1); Console.WriteLine(str2); } } } OUTPUT: A string Another string

Operating on Strings 23) using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { string str1="When it comes to .NET programing, C# is #1."; string str2=string.Copy(str1); string str3="C# strigns are powerfl."; string strUp, strLow; int idx, result; Console.WriteLine("str1: "+str1); Console.WriteLine("Length of str1: "+ str1.Length); // Create upper and Lowercase versio of sr1. strLow=str1.ToLower(); strUp=str1.ToUpper(); Console.WriteLine("Lowercase version of sr1:\n "+strLow); Console.WriteLine("Uppercase version of str1:\n "+strUp); Console.WriteLine(); // Display str1, one char at a time. Console.WriteLine("Display str1, one char at a time."); for(int i=0;i<str1.Length;i++) Console.Write(str1[i]); Console.WriteLine();

// Compare strings. if(str1==str2) Console.WriteLine("str1==str2"); else Console.WriteLine("str1!=str2");

if(str1==str3) Console.WriteLine("str1==str3"); else Console.WriteLine("str1!=str3"); result = str1.CompareTo(str3); if (result == 0) Console.WriteLine("str1 and str3 are equal"); else if (result < 0) Console.WriteLine("str1 is less than str3"); else Console.WriteLine("str1 is more than str3"); Console.WriteLine(); // Assigh a new string to str2.

str2="One two thee One"; // Search the index idx=str2.IndexOf("One"); Console.WriteLine("Index of first occurance of One : " + idx); idx=str2.LastIndexOf("One"); Console.WriteLine("Index of last occurance of One: " + idx); } } }

Arrays of Strings
24) using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { // Demonstrate string arrays. string[] str={"this", "is", "a", "test."}; Console.WriteLine("Original array: "); for(int i=0;i<str.Length;i++) Console.Write(str[i]+" "); Console.WriteLine("\n"); // Change a string str[1]="was"; str[3]="test, too!"; Console.WriteLine("Modified array: "); for(int i=0;i<str.Length;i++) Console.Write(str[i] +" ");

} } }

25) using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication2 { class Program { static void Main(string[] args) { // Display the digits of an integer using wordsw. int num; int nextdigit; int numdigits; int[] n = new int[20]; string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; Console.Write("Number: "); num = Convert.ToInt32(Console.ReadLine()); Console.Write("Number in words: "); nextdigit = 0; numdigits = 0; // Get individual gigits and store in n. // These digits are sotred i reverse order. do { nextdigit = num % 10; n[numdigits] = nextdigit; numdigits++; num = num / 10; } while (num > 0); numdigits--; // Display the words. for (; numdigits >= 0; numdigits--) Console.Write(digits[n[numdigits]] + " "); Console.WriteLine();

} } }

26) using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication2 { class Building { public int Floors;

public int Area; public int Occupants; } class BuildingDemo { static void Main() { Building house = new Building(); int areaPP; house.Occupants = 4; house.Area = 2500; house.Floors = 2; // Compute the area per person. areaPP = house.Area / house.Occupants; Console.WriteLine("house has:\n " + house.Floors +" floors\n " + house.Occupants +" occupants\n" + house.Area + " total area\n " + areaPP + " area per person");

} } }

Methods
Methods are subroutines that manipulate the data defined by the class and, in many cases, provide access to that data. Typically, other parts of your program will interact with a class through its methods. A method contains one or more statements. In well-written C# code, each method performs only one task. Each method has a name, and it is this name that is used to call the method. In general, you can name a method using any valid identifier that you please. However, remember that Main() is reserved for the method that begins execution of your program. Also, dont use C# keywords for method names. When denoting method in text, this book has used and will continue to use a convention that has become common when writing about C#. A method will have parentheses after its name. Access re-type name(parameter-list) { // body of method } Here, access is an access modifier that governs what other parts of your program can call the method. As explained earlier, the access modifier is optional. If not present, then the method is private to the class in which it is declared. For now, we will declare methods as public so that they can be called by any other code in the program. The ret-type specifies

the type of data returned by the method. This can be any valid type, including class types that you create. If the method does not return a value, its return type must be void. The name of the method is specified by name. This can be any legal identifier other than those that would cause conflicts within the current declaration space. The parameter-list is a sequence of type and identifier pairs separated by commas. Parameters are variables that receive the value of the arguments passed to the method when it is called. If the method has no parameter, then the parameter list will be empty.
27) using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication2 { class Building { public int Floors; public int Area; public int Occupants; } class BuildingDemo { static void Main() { Building house = new Building(); int areaPP; house.Occupants = 4; house.Area = 2500; house.Floors = 2; // Compute the area per person. areaPP = house.Area / house.Occupants; Console.WriteLine("house has:\n " + house.Floors +" floors\n " + house.Occupants +" occupants\n" + house.Area + " total area\n " + areaPP + " area per person");

} } }

28) using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication2 { class Program { public static void Main(string[] args) { Console.WriteLine("Enter string str1");

string str1 = Convert.ToString(Console.ReadLine()); Console.WriteLine("Enter string str2"); string str2 = Convert.ToString(Console.ReadLine());

int dx = str1.IndexOf(str2); Console.WriteLine(dx);

Console.ReadLine();

} } }

Sorting Data
There are various sorting algorithms that are used to sort data. Some of them are: 1. 2. 3. 4. 5. 6. Bubble sort Selection Sort Insertion sort Shell sort Merge sort Quick sort

7. Heap sort

Bubble Sort
using using using using System; System.Collections.Generic; System.Linq; System.Text;

namespace ConsoleApplication2 { class Program { public static void Main(string [] args) { int[] a = new int[20]; //Enter the elements in the array Console.WriteLine("Enter the no. of elements: "); int n = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter the elements int he array "); for (int i = 0; i < n; i++) { a[i] = Convert.ToInt32(Console.ReadLine()); } // Bubble Sort for (int j = 1; j < n; j++) { for (int k = 0; k < n; k++) { if (a[k] > a[k { int temp = a[k] = a[k a[k + 1] = } } } Console.WriteLine("Sorted Array "); for (int f = 0; f < n; f++) { Console.WriteLine(a[f]); } Console.ReadLine(); } } + 1]) a[k]; + 1]; temp;

Selection Sort
using using using using System; System.Collections.Generic; System.Linq; System.Text;

namespace ConsoleApplication2 { class Program { public static void Main(string [] args) { int[] a = new int[20]; //Enter the elements in the array Console.WriteLine("Enter the no. of elements: "); int n = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter the elements int he array "); for (int i = 0; i < n; i++) { a[i] = Convert.ToInt32(Console.ReadLine()); } // Linear Sort for (int i = 0; i < n - 1; i++) { int smallest = i; for (int k = i + 1; k < n; k++) { if (a[smallest] > a[k]) { smallest = k; } if (i != smallest) { int temp = a[i]; a[i] = a[smallest]; a[smallest] = temp; } } }

Console.WriteLine("Sorted Array "); for (int f = 0; f < n; f++) {

Console.WriteLine(a[f]); } Console.ReadLine(); } } }

You might also like