Friday, 4 July 2014

C# array exercise: statistical information

Exercise : Write a C# program to answer about the statistical information such as arithmetic mean, median, mode, and standard deviation of an integer data set. The data points are input by the user from keyboard. This program will display the output similar to the one shown below:
C# program to answer about statistical information  
If you are not sure about statistical information such as arithmetic mean, median, mode, and standard deviation, you will need to read this page:
Descriptive Measures  
Solution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Csharp_exercises
{
class Program
{
static void Main(string[] args)
{
  int n;
  float mean,median,std;
  Console.Write("Enter number of data points:");
  n = int.Parse(Console.ReadLine());
  if (n < 3)
   {
    Console.WriteLine("The number of data points should be greater than 2.");

    }
  else
  {

    //declare an array of n size to store integral data points
    int[] dataset = new int[n];
   //allow user inputs
   int i = 0;
   for (i = 0; i < n; i++)
    {
      Console.Write("[{0}]:", i);
      dataset[i] = int.Parse(Console.ReadLine());
    }

   //sort the data set
   bubblesort(dataset, n);



  //calculate the mean
   int sum = 0;
   int j = 0;
   while (j < n)
  {
     sum = sum + dataset[j];
     j++;
   }

   mean = (float)sum / n;

  //calculate median
  //If n is odd, median=dataset[n/2]
  //If n is even, median=(dataset[n/2]+dataset[1+n/2])/2
  //The index of array starts from 0, so you need to subtract 1 from the           //indices   used in calculating the median
  if (n % 2 != 0) median = dataset[n / 2];
  else median = (dataset[(n / 2) - 1] + dataset[n / 2]) / (float)2;

   //calculate the mode
   int[,] mode = new int[n, 2];
  //initialize 2D array storing numbers of occurences, and values
  for (i = 0; i < 2; i++)
  for (j = 0; j < n; j++) mode[j, i] = 0;
  mode[0, 0] = 1;

  for (i = 0; i < n; i++)
    for (j = 0; j < n - 1; j++)
      if (dataset[i] == dataset[j + 1]) { ++mode[i, 0]; mode[i, 1] = dataset[i]; }

   int max;
   int k = 0;
   max = mode[0, 0];
   for (j = 0; j < n; j++)
     if (max < mode[j, 0]) { max = mode[j, 0]; k = j; }


   //calculate standard deviation, std
   float temp = 0.0f;

   for (j = 0; j < n; j++)
  {
     temp = temp + (float)Math.Pow(dataset[j] - mean, 2);
   }

   std = (float)Math.Sqrt(temp / (n - 1));

   //Show results

   Console.WriteLine("Statistical Information:");
   Console.WriteLine("..................................................");
   Console.WriteLine("Arithmetic mean:{0}", mean);
   Console.WriteLine("Median:{0}", median);
   if (mode[k, 1] != 0)
     Console.WriteLine("Mode:{0}", mode[k, 1]);
   else Console.WriteLine("Mode: no mode");
   Console.WriteLine("Standard deviation:{0}", std);


 }
   Console.ReadLine(); 

}

///bubble sort

static void bubblesort(int[] dataset, int n)
{
int i, j;
for (i = 0; i < n; i++)
  for (j = n - 1; j > i; j--)
    if (dataset[j] < dataset[j - 1])
      {
         int temp = dataset[j];
         dataset[j] = dataset[j - 1];
         dataset[j - 1] = temp;
  }

}
}
}

C# array exercise: Pascal triangle

Exercise: By using two-dimensional array of C# language, write C# program to display a table that represents a Pascal triangle of any size. In Pascal triangle, the first and the second rows are set to 1. Each element of the triangle (from the third row downward) is the sum of the element directly above it and the element to the left of the element directly above it. See the example Pascal triangle(size=5) below:

1
1
1
1
2
1
1
3
3
1
1
4
6
4
1

Solution:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
   
    class Program
    {

        static void Main(string[] args)
        {

            int size;
            Console.Write("Pascal triangle size:");
            size = Int32.Parse(Console.ReadLine());
            printPascalTr(size);
            Console.ReadLine();

        }

        public static void printPascalTr(int size){
         int[,] PascalTr=new int[size,size];
         int row,col;
         //assign zero to every array element
         for(row=0;row<size;row++)
            for(col=0;col<size;col++)  PascalTr[row,col]=0;
         //first and second rows are set to 1s  
         PascalTr[0,0]=1;
         PascalTr[1,0]=1;
         PascalTr[1,1]=1;
        
         for(row=2;row<size;row++){
              PascalTr[row,0]=1;
              for(col=1;col<=row;col++){
                        PascalTr[row,col]=PascalTr[row-1,col-1]+PascalTr[row-1,col];
                                        }
                            }
          //display the Pascal Triangle
          for(row=0;row<size;row++){
            for(col=0;col<=row;col++){               
                   Console.Write("{0}\t",PascalTr[row,col]);
                   }
            Console.WriteLine();   
            }
        
         }
     }

} 



C# array exercise: matrix

In this C# exercise, you are about to write C# program to display a matrix as shown below. The diagonal of the matrix fills with 0s. The lower side fills will -1s and the upper side fills with 1s.

0
1
1
1
1

-1
0
1
1
1
-1
-1
0
1
1
-1
-1
-1
0
1
-1
-1
-1
-1
0

Solution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

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

            printMatrix();
            Console.ReadLine();

        }


        public static void printMatrix()
        {

            int[,] matrix = new int[5, 5];
            int i, j;
            for (i = 0; i < 5; i++) //assign values to the matrix
                for (j = 0; j < 5; j++)
                { //if row=column=> fill the matrix with 0
                    if (i == j) matrix[i, j] = 0;//if row>columns=> fill matrix with -1
                    else if (i > j) matrix[i, j] = -1;//if row<columns=> fill matrix with 1
                    else matrix[i, j] = 1;
                }

            for (i = 0; i < 5; i++)
            { //print the matrix
                for (j = 0; j < 5; j++)
                    Console.Write("{0}\t", matrix[i, j]);
                Console.WriteLine();
            }

        }
  }
}


C# array exercise: series of numbers

Exercise: A two-dimensional array stores values in rows and columns. By using two-dimensional array, write C# program to display a table of numbers as shown below:

1
2
3
4
5

6
7

9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

Solution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
   
  class Program
    {
      

        static void Main(string[] args)
        {

            printSeries();
            Console.ReadLine();

        }
        public static void printSeries()
        {
            int[,] tArr = new int[5, 5];
            int i, j;
                           
                for (i = 0; i < 5; i++) //assign values to the two-dimensional array
                    for (j = 0; j < 5; j++)
                    {
                        if (i == 0) tArr[i, j] = j + 1; //fill the first row
                        else if (i > 0 && j == 0)
                            tArr[i, j] = tArr[i - 1, 4] + 1; //fetching the value of the last cell in the previous row
                        else
                         tArr[i, j] = tArr[i, j - 1] + 1; //fill subsequent cells
                    }
         
     for(i=0;i<5;i++){ //print the array
        for(j=0;j<5;j++)
            Console.Write("{0}\t",tArr[i,j]);
        Console.WriteLine();  
       }

  }
 }
}


Modify the C# code in exercise 1 in order to search for an element of the array using binary search algorithm.

Solution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

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

int[] arr = new int[10] { 23, 2, 3, 34, 6, 1, 24, 45, 78, 8 }; //unsorted data set
int pos, target;
Console.Write("Enter value to find:");
target = int.Parse(Console.ReadLine());
pos = binsearch(arr, 23, 10);
if (pos != -1)
Console.WriteLine("The target item was found at location:{0}", pos);
else
Console.WriteLine("The target item was not found in the list.\n");
Console.ReadLine();

}

///binary search
static int binsearch(int[] dataset,int target, int l,int u){
  insertsort(dataset,dataset.Length);//make sure the list sorted
  while(u>=l){  

    int mid=(l+u)/2;  
    if(target==dataset[mid]) return mid;  
    else if(target>dataset[mid]) l=mid+1;  
    else if(target<dataset[mid]) u=mid-1;  
}
return -1;
}


static void insertsort(int[] dataset, int n)
{

int i, j;
for (i = 1; i < n; i++)
{
int pick_item = dataset[i];
int inserted = 0;
for (j = i - 1; j >= 0 && inserted != 1; )
{
if (pick_item < dataset[j])
{
dataset[j + 1] = dataset[j];
j--;
dataset[j + 1] = pick_item;
}
else inserted = 1;
}
}

}
}
} 

C# Arrays exercise: search (con) By using the sequential search algorithm, write C# code to search for an element of an integer array of 10 elements.

Solution:

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

namespace Csharp_exercises
{
class Program
{
static void Main(string[] args)
{
  int[] arr = new int[10] { 23, 2, 3, 34, 6,1,24,45,78,8}; //data set
  int pos,target;
  Console.Write("Enter value to find:");
  target = int.Parse(Console.ReadLine());
  pos = seqsearch(arr, target, 10);
  if (pos != -1)
    Console.WriteLine("The target item was found at location:{0}", pos);
  else
    Console.WriteLine("The target item was not found in the list.\n");
  Console.ReadLine();

}
///sequential search
static int seqsearch(int[] dataset, int target, int n)
{
  int found = 0;
  int i;
  int pos = -1;
  for (i = 0; i < n && found != 1; i++)
    if (target == dataset[i]) { pos = i; found = 1; }

   return pos;
  }
}
}

Modify the C# code in exercise 1 in order to sort the array in descending order.

Solution:

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

namespace Csharp_exercises
{
class Program
{
static void Main(string[] args)
{
int[] arr = new int[10] { 23, 2, 3, 34, 6,1,24,45,78,8}; //unsorted data set
bubblesort(arr, 10); //sorting process using bubble sort
int i;
for (i = 0; i < 10; i++)
Console.Write(arr[i] + "\t"); //after sorting in descending order

Console.ReadLine();

}
///bubble sort

static void bubblesort(int[] dataset, int n)
{
int i, j;
for (i = 0; i < n; i++)
  for (j = n - 1; j > i; j--)
    if (dataset[j] > dataset[j - 1])
     {
       int temp = dataset[j];
       dataset[j] = dataset[j - 1];
       dataset[j - 1] = temp;
         }

    }
  }
}