You are on page 1of 10

C# and .

Net Programming
/* Use commas in a for statement to find the largest and smallest factor of a number. */ using System; class Comma { public static void Main() { int i, j; int smallest, largest; int num; num = 100; smallest = largest = 1; for(i=2, j=num/2; (i <= num/2) & (j >= 2); i++, j--) { if((smallest == 1) & ((num % i) == 0)) smallest = i; if((largest == 1) & ((num % j) == 0)) largest = j; } Console.WriteLine("Largest factor: " + largest); Console.WriteLine("Smallest factor: " + smallest); } } int e; int result; for(int i=0; i < 10; i++) { result = 1; e = i; while(e > 0) { result *= 2; e--; } Console.WriteLine("2 to the " + i + " power is " + result); } } }

The output from the program is shown here:


2 2 2 2 2 2 2 2 2 to to to to to to to to to the the the the the the the the the 0 1 2 3 4 5 6 7 8 power power power power power power power power power is is is is is is is is is 1 2 4 8 16 32 64 128 256

Here is the output from the program:


Largest factor: 50 Smallest factor:2

/* Declare loop control variable inside the for.*/ using System; class ForVar { public static void Main() { int sum = 0; int fact = 1; // Compute the factorial of the numbers 1 through 5. for(int i = 1; i <= 5; i++) { sum += i; // i is known throughout the loop fact *= i; } // But, i is not known here. Console.WriteLine("Sum is " + sum); Console.WriteLine("Factorial is " + fact); } } /*Compute integer powers of 2.*/ using System; class Power { public static void Main() {

// Display the digits of an integer in reverse order. using System; class DoWhileDemo { public static void Main() { int num; int nextdigit; num = 198; Console.WriteLine("Number: " + num); Console.Write("Number in reverse order: "); do { nextdigit = num % 10; Console.Write(nextdigit); num = num / 10; } while(num > 0); Console.WriteLine(); } }

The output is shown here:


Number: 198 Number in reverse order: 891

C# and .Net Programming


Console.WriteLine(" " + area / occupants + " area per person"); } } // Use the areaPerPerson() method. class BuildingDemo { public static void Main() { Building house = new Building(); Building office = new Building(); // assign values to fields in house house.occupants = 4; house.area = 2500; house.floors = 2; // assign values to fields in office office.occupants = 25; office.area = 4200; office.floors = 3; Console.WriteLine("house has:\n " + house.floors + " floors\n " + house.occupants + " occupants\n " + house.area + " total area"); house.areaPerPerson(); Console.WriteLine(); Console.WriteLine("office has:\n " + office.floors + " floors\n " + office.occupants + " occupants\n " + office.area + " total area"); office.areaPerPerson(); } }

// A program that uses the Building class. using System; class Building { public int floors; // number of floors public int area; // total square footage of building public int occupants; // number of occupants } // This class declares an object of type Building. class BuildingDemo { public static void Main() { Building house = new Building(); // create a Building object int areaPP; // area per person // assign values to fields in house 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"); } } O/p: house has: 2 floors 4 occupants 2500 total area 625 area per person // Add a method to Building. using System; class Building { public int floors; // number of floors public int area; // total square footage of building public int occupants; // number of occupants // Display the area per person. public void areaPerPerson() {

This program generates the following output, which is the same as before:
house has: 2 floors 4 occupants 2500 total area 625 area per person office has: 3 floors 25 occupants 4200 total area 168 area per person

C# and .Net Programming

// A simple example that uses a parameter. using System; class ChkNum { // Return true if x is prime. public bool isPrime(int x) { for(int i=2; i <= x/i; i++) if((x %i) == 0) return false; return true; } } class ParmDemo { public static void Main() { ChkNum ob = new ChkNum(); for(int i=1; i < 10; i++) if(ob.isPrime(i)) Console.WriteLine(i + " is prime."); else Console.WriteLine(i + " is not prime."); } }

// Add a method that takes two arguments. using System; class ChkNum { // Return true if x is prime. public bool isPrime(int x) { for(int i=2; i <= x/i; i++) if((x %i) == 0) return false; return true; } // Return the least common factor. public int leastComFactor(int a, int b) { int max; if(isPrime(a) | isPrime(b)) return 1; max = a < b ? a : b; for(int i=2; i <= max/2; i++) if(((a%i) == 0) & ((b%i) == 0)) return i; return 1; } } class ParmDemo { public static void Main() { ChkNum ob = new ChkNum(); int a, b; for(int i=1; i < 10; i++) if(ob.isPrime(i)) Console.WriteLine(i + " is prime."); else Console.WriteLine(i + " is not prime."); a = 7; b = 8; Console.WriteLine("Least common factor for " + a + " and " + b + " is " + ob.leastComFactor(a, b)); a = 100; b = 8; Console.WriteLine("Least common factor for " + a + " and " + b + " is " + ob.leastComFactor(a, b)); a = 100; b = 75; Console.WriteLine("Least common factor for " + a + " and " + b + " is " + ob.leastComFactor(a, b));

Here is the output produced by the program:


1 2 3 4 5 6 7 8 9 is is is is is is is is is prime. prime. prime. not prime. prime. not prime. prime. not prime. not prime.

In the program, isPrime( ) is called nine times, and each time a different value is passed. Lets look at this process closely. First, notice how isPrime( ) is called. The argument is specified between the parentheses. When isPrime( ) is called the first time, it is passed value 1. Thus, when isPrime( ) begins executing, the parameter x receives the value 1. In the second call, 2 is the argument, and x then has the value 2. In the third call, the argument is 3, which is the value that x receives, and so on. The point is that the value passed as an argument when isPrime( ) is called is the value received by its parameter, x.

C# and .Net Programming


} } Console.WriteLine(t1.x + " " + t2.x); } }

when leastComFactor( ) is called, the arguments are also separated by commas. The output from the program is shown here:
1 is prime. 2 is prime. 3 is prime. 4 is not prime. 5 is prime. 6 is not prime. 7 is prime. 8 is not prime. 9 is not prime. Least common factor for 7 and 8 is 1 Least common factor for 100 and 8 is 2 Least common factor for 100 and 75 is 5 // A simple constructor. using System; class MyClass { public int x; public MyClass() { x = 10; } } class ConsDemo { public static void Main() { MyClass t1 = new MyClass(); MyClass t2 = new MyClass(); Console.WriteLine(t1.x + " " + t2.x); } }

The output from this program is shown here:


10 88

// A simple program using System; class Rect { public int width; public int height; public Rect(int w, int h) { width = w; height = h; } public int area() { return width * height; } } class UseRect { public static void Main() { Rect r1 = new Rect(4, 5); Rect r2 = new Rect(7, 9); Console.WriteLine("Area of r1: " + r1.area()); Console.WriteLine("Area of r2: " + r2.area()); } } // use of this operator using System; class Rect { public int width; public int height; public Rect(int w, int h) { this.width = w; this.height = h; } public int area() { return this.width * this.height; } } class UseRect { public static void Main() { Rect r1 = new Rect(4, 5); Rect r2 = new Rect(7, 9); Console.WriteLine("Area of r1: " + r1.area()); Console.WriteLine("Area of r2: " + r2.area()); }

the output from the program is


10 10 // A parameterized constructor. using System; class MyClass { public int x; public MyClass(int i) { x = i; } } class ParmConsDemo { public static void Main() { MyClass t1 = new MyClass(10); MyClass t2 = new MyClass(88);

C# and .Net Programming


} // Demonstrate a one-dimensional array. using System; class ArrayDemo { public static void Main() { 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]); } } avg = avg + nums[i]; avg = avg / 10; Console.WriteLine("Average: " + avg); } }

The output from the program is shown here:


Average: 53 // Compute the average of a set of values. using System; class Average { public static void Main() { int[] nums = { 99, 10, 100, 18, 78, 23, 63, 9, 87, 49 }; int avg = 0; for(int i=0; i < 10; i++) avg = avg + nums[i]; avg = avg / 10; Console.WriteLine("Average: " + avg); } } // Demonstrate an array overrun. using System; class ArrayErr { public static void Main() { int[] sample = new int[10]; int i; // generate an array overrun for(i = 0; i < 100; i = i+1) sample[i] = i; } }

The output from the program is shown here:


sample[0]: sample[1]: sample[2]: sample[3]: sample[4]: sample[5]: sample[6]: sample[7]: sample[8]: sample[9]: 0 1 2 3 4 5 6 7 8 9

Conceptually, the sample array looks like this:

// Compute the average of a set of values. using System; class Average { public static void Main() { int[] nums = new int[10]; int avg = 0; nums[0] = 99; nums[1] = 10; nums[2] = 100; nums[3] = 18; nums[4] = 78; nums[5] = 23; nums[6] = 63; nums[7] = 9; nums[8] = 87; nums[9] = 49; for(int i=0; i < 10; i++)

As soon as i reaches 10, an IndexOutOfRangeException is generated and the program is terminated.


// Demonstrate a two-dimensional array. using System; class TwoD { public static void Main() { int t, i; int[,] table = new int[3, 4]; for(t=0; t < 3; ++t) { for(i=0; i < 4; ++i) {

C# and .Net Programming


table[t,i] = (t*4)+i+1; Console.Write(table[t,i] + " "); } Console.WriteLine(); } } }

// Initialize a two-dimensional array. using System; class Squares { public static void Main() { int[,] sqrs = { { 1, 1 }, { 2, 4 }, { 3, 9 }, { 4, 16 }, { 5, 25 }, { 6, 36 }, { 7, 49 }, { 8, 64 }, { 9, 81 }, { 10, 100 } }; int i, j; for(i=0; i < 10; i++) { for(j=0; j < 2; j++) Console.Write(sqrs[i,j] + " "); Console.WriteLine(); } } }

In this example, table[0, 0] will have the value 1, table[0, 1] the value 2, table[0, 2] the value 3, and so on. The value of table[2, 3] will be 12. Conceptually, the array will look like that shown in Figure 71.

Figure 7-1: A conceptual view of the table array created by the TwoD program
// Sum the values on a diagonal of a 3x3x3 matrix. using System; class ThreeDMatrix { public static void Main() int[,,] m = new int[3, 3, int sum = 0; int n = 1; for(int x=0; x < 3; x++) for(int y=0; y < 3; y++) for(int z=0; z < 3; z++) m[x, y, z] = n++; sum = m[0,0,0] + m[1,1,1] 2, 2]; Console.WriteLine("Sum of diagonal: " + sum); } }

Here is the output from the program:


1 1 2 4 3 9 4 16 5 25 6 36 7 49 8 64 9 81 10 100

{ 3];

Jagged Arrays
+ m[2, first

The output is shown here:


Sum of first diagonal: 42

C# also allows you to create a special type of two-dimensional array called a jagged array. A jagged array is an array of arrays in which the length of each array can differ. Thus, a jagged array can be used to create a table in which the lengths of the rows are not the same. Jagged arrays are declared by using sets of square brackets to indicate each dimension. For example, to declare a two-

C# and .Net Programming


dimensional jagged array, you will use this general form:
type[ ] [ ] array-name = new type[size][ ]; for(i=0; i < 5; i++) Console.Write(jagged[2][i] + " "); Console.WriteLine(); } }

size indicates the number of rows in the array. The rows, themselves, have not been allocated. Instead, the rows are allocated individually. This allows for the length of each row to vary. For example, the following code allocates memory for the first dimension of jagged when it is declared. It then allocates the second dimensions manually.
int[][] jagged = new int[3][]; jagged[0] = new int[4]; jagged[1] = new int[3]; jagged[2] = new int[5];

The output is shown here:


0 1 2 3 0 1 2 0 1 2 3 4

// Assigning array reference variables. using System; class AssignARef { public static void Main() { int i; int[] nums1 = new int[10]; int[] nums2 = new int[10]; for(i=0; i < 10; i++) nums1[i] = i; for(i=0; i < 10; i++) nums2[i] = -i; Console.Write("Here is nums1: "); for(i=0; i < 10; i++) Console.Write(nums1[i] + " "); Console.WriteLine(); Console.Write("Here is nums2: "); for(i=0; i < 10; i++) Console.Write(nums2[i] + " "); Console.WriteLine(); nums2 = nums1; // now nums2 refers to nums1 Console.Write("Here is nums2 after assignment: "); for(i=0; i < 10; i++) Console.Write(nums2[i] + " "); Console.WriteLine(); // now operate on nums1 array through nums2 nums2[3] = 99; Console.Write("Here is nums1 after change through nums2: "); for(i=0; i < 10; i++) Console.Write(nums1[i] + " "); Console.WriteLine(); } }

After this sequence executes, jagged looks like this:

It is easy to see how jagged arrays got their name!


// Demonstrate jagged arrays. using System; class Jagged { public static void Main() { int[][] jagged = new int[3][]; jagged[0] = new int[4]; jagged[1] = new int[3]; jagged[2] = new int[5]; int i; // store values in first array for(i=0; i < 4; i++) jagged[0][i] = i; // store values in second array for(i=0; i < 3; i++) jagged[1][i] = i; // store values in third array for(i=0; i < 5; i++) jagged[2][i] = i; // display values in first array for(i=0; i < 4; i++) Console.Write(jagged[0][i] + " "); Console.WriteLine(); // display values in second array for(i=0; i < 3; i++) Console.Write(jagged[1][i] + " "); Console.WriteLine(); // display values in third array

The output from the program is shown here:


Here is nums1: 0 1 2 3 4 5 6 7 8 9

C# and .Net Programming


Here is nums2: 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 Here is nums2 after assignment: 0 1 2 3 4 5 6 7 8 9 Here is nums1 after change through nums2: 0 1 2 99 4 5 6 7 8 9 // Use the Length array property. using System; class LengthDemo { public static void Main() { int[] nums = new int[10]; Console.WriteLine("Length of nums is " + nums.Length); // use Length to initialize nums for(int i=0; i < nums.Length; i+ +) nums[i] = i * i; // now use Length to display nums Console.Write("Here is nums: "); for(int i=0; i < nums.Length; i+ +) Console.Write(nums[i] + " "); Console.WriteLine(); } } int[] nums2 = new int[10]; for(i=0; i < nums1.Length; i++) nums1[i] = i; Console.Write("Original contents: "); for(i=0; i < nums2.Length; i++) Console.Write(nums1[i] + " "); Console.WriteLine(); // reverse copy nums1 to nums2 if(nums2.Length >= nums1.Length) // make sure nums2 is long enough for(i=0, j=nums1.Length-1; i < nums1.Length; i++, j--) nums2[j] = nums1[i]; Console.Write("Reversed contents: "); for(i=0; i < nums2.Length; i++) Console.Write(nums2[i] + " "); Console.WriteLine(); } }

Here is the output:

Original contents: 0 1 2 3 4 5 6 7 8 9 Reversed contents: 9 8 7 6 5 4 3 2 1 0 // Demonstrate Length with jagged arrays. using System; class Jagged { public static void Main() { int[][] network_nodes = new int[4][]; network_nodes[0] = new int[3]; network_nodes[1] = new int[7]; network_nodes[2] = new int[2]; network_nodes[3] = new int[5]; int i, j; // fabricate some fake CPU usage data for(i=0; i < network_nodes.Length; i++) for(j=0; j < network_nodes[i].Length; j++) network_nodes[i][j] = i * j + 70; Console.WriteLine("Total number of network nodes: " + network_nodes.Length + "\n"); for(i=0; i < network_nodes.Length; i++) { for(j=0; j < network_nodes[i].Length; j++) {

This program displays the following output:


Length of nums is 10 Here is nums: 0 1 4 9 16 25 36 49 64 81 // Use the Length array property on a 3-D array. using System; class LengthDemo3D { public static void Main() { int[,,] nums = new int[10, 5, 6]; Console.WriteLine("Length of nums is " + nums.Length); } }

The output is shown here:


Length of nums is 300 // Reverse an array. using System; class RevCopy { public static void Main() { int i,j; int[] nums1 = new int[10];

C# and .Net Programming


Console.Write("CPU usage at node " + i + " CPU " + j + ": "); Console.Write(network_nodes[i][j] + "% "); Console.WriteLine(); } Console.WriteLine(); } } } Value is: 2 Value is: 3 Value is: 4 Value is: 5 Value is: 6 Value is: 7 Value is: 8 Value is: 9 Summation: 45 // Use break with a foreach. using System; class ForeachDemo { public static void Main() { int sum = 0; int[] nums = new int[10]; // give nums some values for(int i = 0; i < 10; i++) nums[i] = i; // use foreach to display and sum the values foreach(int x in nums) { Console.WriteLine("Value is: " + x); sum += x; if(x == 4) break; // stop the loop when 4 is obtained } Console.WriteLine("Summation of first 5 elements: " + sum); } }

The output is shown here:


Total number CPU usage at CPU usage at CPU usage at CPU usage at CPU usage at CPU usage at CPU usage at CPU usage at CPU usage at CPU usage at CPU usage at CPU usage at CPU usage at CPU usage at CPU usage at CPU usage at CPU usage at of network node 0 CPU node 0 CPU node 0 CPU node 1 CPU node 1 CPU node 1 CPU node 1 CPU node 1 CPU node 1 CPU node 1 CPU node 2 CPU node 2 CPU node 3 CPU node 3 CPU node 3 CPU node 3 CPU node 3 CPU nodes: 4 0: 70% 1: 70% 2: 70% 0: 70% 1: 71% 2: 72% 3: 73% 4: 74% 5: 75% 6: 76% 0: 70% 1: 72% 0: 70% 1: 73% 2: 76% 3: 79% 4: 82%

// Use the foreach loop. using System; class ForeachDemo { public static void Main() { int sum = 0; int[] nums = new int[10]; // give nums some values for(int i = 0; i < 10; i++) nums[i] = i; // use foreach to display and sum the values foreach(int x in nums) { Console.WriteLine("Value is: " + x); sum += x; } Console.WriteLine("Summation: " + sum); } }

This is the output produced:


Value is: Value is: Value is: Value is: Value is: Summation 10

0 1 2 3 4 of first 5 elements:

// Use foreach on a twodimensional array. using System; class ForeachDemo2 { public static void Main() { int sum = 0; int[,] nums = new int[3,5]; // give nums some values for(int i = 0; i < 3; i++) nums[i,j] = (i+1)*(j+1);

The output from the program is shown here:


Value is: 0 Value is: 1

C# and .Net Programming


// use foreach to display and sum the values foreach(int x in nums) { Console.WriteLine("Value is: " + x); sum += x; } Console.WriteLine("Summation: " + sum); } } Value found!

The output from this program is shown here:


Value is: 1 Value is: 2 Value is: 3 Value is: 4 Value is: 5 Value is: 2 Value is: 4 Value is: 6 Value is: 8 Value is: 10 Value is: 3 Value is: 6 Value is: 9 Value is: 12 Value is: 15 Summation: 90

// Search an array using foreach. using System; class Search { public static void Main() { int[] nums = new int[10]; int val; bool found = false; // give nums some values for(int i = 0; i < 10; i++) nums[i] = i; val = 5; // use foreach to search nums for key foreach(int x in nums) { if(x == val) { found = true; break; } } if(found) Console.WriteLine("Value found!"); } }

The output is shown here:

10

You might also like