Friday 4 July 2014

C# OOP: Singly Linked List

By using C# objected-oriented concept, create a singly linked list.
The singly linked list is a chain of its item. Each item contain two parts--data and a link. The data part is to store information and the link part of an item is used to point or to store the address of the next item.
C single linked list
You are going to build a singly linked list that has two links--one(pfirst) links to the first item of the list and another one(plast) point to the last item of the list. The program also provides a menu of choices that a user can use do some operations on the linked list data structure.
C linkedlist operations menu  
Solution: To keep the solution simple, we divide it in to different steps as you see their links on the right menu.



C# OOP: Singly Linked List



Element of singly linked list

Step 1: Define element of the singly linked list
The linked list element has two parts--data and a link. Therefore, we define the the element of the linked list by using a class that has two members--data and next link.
C single linked list
//C# code to define list element
//List element class
class ListNode<T> //T is the generic type.
{
public ListNode(T elem) { val = elem;next = null; }
public T val; //element data
public ListNode<T> next;//next link
}






C# OOP: Singly Linked List



Add element to list singly linked list

Step 2: Add an element to the linked list
To add an element to the linked list, you need to consider 4 things:
1. When the list is empty, to add a new element to the list, you only let the pfirst and plast links point to the new item. We mark the null value of link of an element by crossed lines.
Add an item to the empty list 
2.If the new element is to be added to the beginning of  the list, you will need to let the link of the new item points to the pfirst and then update the pfirst to point to the new item.
Add a new element at the beginning of the list  
 3. If the new element is to be added to the middle position of the list, you need to let a link point to the position immediately before the position that the new element will be placed in.
Add a new item in the middle of the list  
4. If the new element is to be added to the last of the list, you need to let the link of the plast point to the new element then update the plast to point the new element.
Add the new item to the last of the list  
//C# code to insert a new item to the linkedlist

public void insert(T val, int pos)
{
ListNode<T> newnode = new ListNode<T>(val);
//empty list
if (pfirst == null && plast == null)
{
 newnode.next = null; 
 pfirst = newnode;
 plast = newnode;
 Console.WriteLine("Inserted:{0}", newnode.val);
}
//Insert at the beginning of the list
else if (pos == 1)
{
 newnode.next = pfirst;
 pfirst = newnode;
 Console.WriteLine("Inserted:{0}", newnode.val);
}
//Insert in the middle of the list
else if (pos > 1 && pos <= countitem())
{
ListNode<T> ta;
ta = pfirst;
for (int t = 1; t < pos - 1; t = t + 1) { ta = ta.next; }
 newnode.next = ta.next;
 ta.next = newnode; 
 Console.WriteLine("Inserted:{0}", newnode.val);
}
else if (pos == countitem() + 1)
{
 newnode.next = null; //The next link of the item is null.
 plast.next = newnode;
 plast = newnode;
 Console.WriteLine("Inserted:{0}", newnode.val);

}
else Console.WriteLine("Invalid position!");


}



C# OOP: Singly Linked List



Count elements of the singly linked list

Step 3: Count elements of the singly linkedlist
To count all elements of the linkedlist, we will need a loop to traverse through the linkedlist. We will let a variable (i) of ListElem type to point to the pfirst then move to its next element and increase the number of item(t) one at a time by using a while loop until the end of the linkedlist(indicated by null value) is reached.

//C# code count items in the linked list
public int countitem()
{
ListNode<T> i;
int t = 0;
for (i = pfirst; i != null; i = i.next)
{
   t = t + 1;
}
return t;
}





C# OOP: Singly Linked List



Delete item of singly linked list

Step 4: Delete an element of the singly linked list
To delete an element of the linked list, you need to consider the followings:
1. If the element to be deleted is the first element of the list and the list contains only one element, you only need to assign null to the pfirst and plast. If the element to be deleted is the first element of the list and the list contain more than one element, you need a temporary variable to point to the pfirst then move the pfirst to point to its next element and set the temporary varialbe to null.
Delete the first item of the list  
2. If the element to be deleted is in the middle of the list, you need a traversing variable(temp) to point to the element before the element to be deleted and a temporary variable(del) to point to the element to be deleted. Then let the link of the traversing pointer to point to the link of the temporary pointer. To handle situation where the element to be deleted is the last element of the list, you need to test whether the link of the temporary variable is null. If it is really null, you need to update the plast pointer to point to the traversing variable. Finally set the temporary pointer to null.
Delete middle item of the list  
//C# code to delete an item from the linked list
public void delete(int pos)
{
if (countitem() > 0)
{ //make sure the list is not empty.
ListNode<T> temp,del;

if (pos == 1)
{//delete the first item
if(countitem()==1){ //The list contains only one item
pfirst=null;
plast=null;

}
else{ //The list contains more than one item
temp=pfirst;
pfirst=pfirst.next; 
temp=null;
}
Console.WriteLine("Deleted");

}

else if (pos > 1 && pos <=countitem())
{//delete middle item
temp=pfirst;
int i;
for(i=1;i<pos-1;i=i+1){temp=temp.next;} //move to the item staying before the target item to be deleted
del=temp.next; //target item to be deleted
temp.next=del.next;
if(del.next==null)plast=temp; //delete last item
del=null;
Console.WriteLine ("Deleted");

}

else Console.WriteLine("Invalid position!");

}

else Console.WriteLine("No item found");

    }
}


C# OOP: Singly Linked List



Print items of singly linked list

Step 5: Print all elements of the linked list
To print all elements of the list is simple, you need to traverse through the list and output the data of each element.
//Print all elements
public void showall()
{
  ListNode<T> t;
  if (countitem() > 0)
  {
    Console.WriteLine("All items in the list:");
    for (t = pfirst; t != null; t = t.next)
    {

         Console.WriteLine(t.val);
    }
  }
else Console.WriteLine("No item found!");
}





C# OOP: Singly Linked List



Menu to operate singly linked list

Step 6: Display a menu of choices
To show the menu that allow the user to choose an operation on the linked list, you need the showmenu() and select() functions as shown below:
 public static void showmenu(){

Console.WriteLine("=================================");
Console.WriteLine("Linked List Operations Menu");
Console.WriteLine("=================================");
Console.WriteLine("1.Add a new item");
Console.WriteLine("2.Delete an item");
Console.WriteLine("3.Show number of items");
Console.WriteLine("4.Show all items");
Console.WriteLine("5.Exit");

}


public static void select(){

LinkedList<int> mylist=new LinkedList<int>();
int val,ch, pos;
char yes = 'y';

while (yes == 'y')
{
Console.Write("Enter your choice:");
ch =int.Parse(Console.ReadLine().ToString ());

switch (ch)
{

case 1:
Console.Write("Value:");
val = int.Parse(Console.ReadLine());
Console.Write("Position:"); pos = int.Parse(Console.ReadLine()); 
mylist.insert(val, pos);
break;

case 2:
Console.Write("Position:"); pos = int.Parse(Console.ReadLine());
mylist.delete(pos);
break;

case 3:
Console.WriteLine("Number of items:" + mylist.countitem());
break;

case 4:
Console.WriteLine("All items:");
mylist.showall();
break;

case 5: Environment.Exit(0); break;

default: Console.WriteLine("Invalid choice!"); break;

}


Console.Write("Continue? Press y to continue:");
yes =char.Parse (Console.ReadLine());

}



}





C# String: English Word Prefix game

Write a C# program create a simple English Word Prefix game. The program starts the first two questions by asking the user to guess the answer of each question. The answers are collected and report is produced. The report should show a list of words, prefixes, and descriptions. See the sample screen shot below:
C# English word prefix gage
The program also allows the user to play the next words.
Solution:

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

namespace Projecttest
{
class Program
{

//main method
static void Main(string[] args)
{
//Declaring multi-dimensional array to store words, prefixes, and descriptions
//Each default answer is incorrect
//we store 4 works, 4 prefixes, and 4 default answers
string[,] terms=new string[4,3]; 
int row = 0;
terms[row, 0] = "substring";
terms[row, 1] = "sub";
terms[row, 2] = "incorrent";
row++;

terms[row, 0] = "hypertext";
terms[row, 1] = "hyper";
terms[row, 2] = "incorrent";

row++;

terms[row, 0] = "antivirus";
terms[row, 1] = "anti";
terms[row, 2] = "incorrent";

row++;

terms[row, 0] = "immutable";
terms[row, 1] = "im";
terms[row, 2] = "incorrent";
//play the first two words 
int numrows = 0;
playnext(terms, numrows );
//allow the user to play the next two words
Console.Write("Next? press y for next play:");
string next = Console.ReadLine();
if (next.CompareTo("y") == 0)
{
  Console.Clear();//clear screen
  numrows+=2;
  playnext(terms, numrows);
}


Console.ReadLine();


}

static void playnext(string[,] terms, int rows)
{
 Console.WriteLine(".............................................................")
Console.WriteLine("\t\t\tENGLISH WORD PREFIX GAME");
Console.WriteLine(".............................................................");
//collect answer and make comparison then update the array
for (int i = rows; i <rows+2 ; i++)
{
  Console.Write("What is the correct prefix of {0}:", terms[i, 0]);
  string ans = Console.ReadLine();
  if (terms[i, 1].ToLower().CompareTo(ans.ToString().ToLower()) == 0)
    terms[i, 2] = "correct";
  Console.WriteLine();


}


//Print report
Console.WriteLine("CHECK YOUR ANSWERS");
Console.WriteLine("=============================================");
Console.WriteLine("Word\t\tPrefix\tDescription");
Console.WriteLine("=============================================");

for (int i = rows; i < rows+2; i++)
 {
   for (int j = 0; j < 3; j++)
  Console.Write("{0}\t", terms[i, j]);
  Console.WriteLine();
}
}

}

}


combine the C# code together and test program.

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

namespace Projecttest
{
class Program
{
//Declare student structure
struct student

{
public string stnumber;

public string stname;

public string sex;

public float quizz1;

public float quizz2;

public float assigment;

public float midterm;

public float final;

public float total;


};

//main method
static void Main(string[] args)
{

try
{
student[] st = new student[20]; //create an array to store only 20 students'records for testing.
int itemcount = 0;
//show menu
displaymenu();
int yourchoice;
string confirm;

do
{

Console.Write("Enter your choice(1-8):");

yourchoice = int.Parse(Console.ReadLine());


switch (yourchoice)
{

case 1:add(st, ref itemcount); break;
case 2:delete(st, ref itemcount); break;
case 3:update(st, itemcount); break;
case 4:viewall(st, itemcount); break;
case 5:average(st, itemcount ); break;
case 6:showmax(st, itemcount); break;
case 7:showmin(st, itemcount); break;
case 8:find(st, itemcount); break;
case 9: bubblesort (st, itemcount); break; 

default: Console.WriteLine("invalid"); break;

}



Console.Write("Press y or Y to continue:");

confirm = Console.ReadLine().ToString();

} while (confirm == "y" || confirm == "Y");



}
catch (FormatException f) { Console.WriteLine("Invalid input"); }


///////////////

Console.ReadLine();

}


//Menu contruction

static void displaymenu(){

Console.WriteLine("=====================================================");

Console.WriteLine(" MENU ");

Console.WriteLine("=====================================================");

Console.WriteLine(" 1.Add student records");
Console.WriteLine(" 2.Delete student records");
Console.WriteLine(" 3.Update student records");
Console.WriteLine(" 4.View all student records");
Console.WriteLine(" 5.Calculate an average of a selected student's scores");
Console.WriteLine(" 6.Show student who get the max total score"); 
Console.WriteLine(" 7.Show student who get the min total score");
Console.WriteLine(" 8.Find a student by ID");
Console.WriteLine(" 9.Sort students by TOTAL");



}
//method add/append a new record
static void add(student[] st,ref int itemcount){

Again:
Console.WriteLine(); 
Console.Write("Enter student's ID:");
st[itemcount].stnumber=Console.ReadLine().ToString() ;

if(search(st,st[itemcount].stnumber,itemcount)!=-1){

Console.WriteLine("This ID already exists.");
goto Again;

}


Console.Write("Enter student's Name:"); 

st[itemcount].stname=Console.ReadLine ().ToString();


Console.Write("Enter student's Sex(F or M):");
st[itemcount].sex=Console.ReadLine().ToString();


Console.Write("Enter student's quizz1 score:");
st[itemcount].quizz1=float.Parse(Console.ReadLine());


Console.Write("Enter student's quizz2 score:");
st[itemcount].quizz2=float.Parse(Console.ReadLine());


Console.Write("Enter student's assigment score:");
st[itemcount].assigment=float.Parse(Console.ReadLine());


Console.Write("Enter student's mid term score:");
st[itemcount].midterm=float.Parse(Console.ReadLine());

Console.Write("Enter student's final score:");
st[itemcount].final=float.Parse(Console.ReadLine());

st[itemcount].total=st[itemcount].quizz1+st[itemcount].quizz2+st[itemcount].assigment+st[itemcount].midterm+st[itemcount].final;



++itemcount;



}
//method to search for the location of the target record
static int search(student[] st, string id,int itemcount){
int found =-1;
for (int i = 0; i < itemcount && found==-1; i++)
{

if (st[i].stnumber == id) found=i;

else found=-1 ;
}

return found;

}
//method display all students' records
static void viewall(student[] st,int itemcount)
{

int i = 0;

Console.WriteLine("{0,-5}{1,-20}{2,-5}{3,-5}{4,-5}{5,-5}{6,-5}{7,-5}{8}(column index)", "0", "1", "2", "3", "4", "5", "6", "7", "8");
Console.WriteLine("{0,-5}{1,-20}{2,-5}{3,-5}{4,-5}{5,-5}{6,-5}{7,-5}{8,-5}", "ID", "NAME", "SEX", "Q1", "Q2", "As", "Mi", "Fi", "TOTAL");

Console.WriteLine("=====================================================");

while (i < itemcount)
{

if (st[i].stnumber !=null )
{

Console.Write("{0,-5}{1,-20}{2,-5}", st[i].stnumber, st[i].stname, st[i].sex);

Console.Write("{0,-5}{1,-5}{2,-5}",st[i].quizz1,st[i].quizz2,st[i].assigment);

Console.Write("{0,-5}{1,-5}{2,-5}",st[i].midterm,st[i].final,st[i].total);

Console.Write("\n");
}

i = i + 1;



}

}



// method to elete record

static void delete(student[] st, ref int itemcount)
{
string id;
int index;
if (itemcount > 0)
{
Console.Write("Enter student's ID:");
id = Console.ReadLine();
index = search(st, id.ToString(),itemcount); 

if ((index!=-1) && (itemcount != 0))
{
if (index == (itemcount-1)) //delete the last record
{

clean(st, index);
--itemcount;

Console.WriteLine("The record was deleted.");
}
else //delete the first or middle record
{
for (int i = index; i < itemcount-1; i++)
{
st[i] = st[i + 1];
clean(st, itemcount);
--itemcount ;
}

}

}
else Console.WriteLine("The record doesn't exist.Check the ID and try again.");


}
else Console.WriteLine("No record to delete");
}

//method ot update record

static void update(student[] st, int itemcount)
{
string id;
int column_index;
Console.Write("Enter student's ID:");
id=Console.ReadLine();
Console.Write("Which field you want to update(1-7)?:");
column_index=int.Parse(Console.ReadLine());

int index = search(st, id.ToString(),itemcount);

if ((index != -1) && (itemcount != 0))
{
if (column_index == 1)
{
Console.Write("Enter student's Name:");

st[index].stname = Console.ReadLine().ToString();
}

else if (column_index == 2)
{
Console.Write("Enter student's Sex(F or M):");
st[index].sex = Console.ReadLine().ToString();
}
else if (column_index == 3)
{
Console.Write("Enter student's quizz1 score:");
st[index].quizz1 = float.Parse(Console.ReadLine());
}
else if (column_index == 4)
{
Console.Write("Enter student's quizz2 score:");
st[index].quizz2 = float.Parse(Console.ReadLine());
}
else if (column_index == 5)
{
Console.Write("Enter student's assigment score:");
st[index].assigment = float.Parse(Console.ReadLine());
}
else if (column_index == 6)
{
Console.Write("Enter student's mid term score:");
st[index].midterm = float.Parse(Console.ReadLine());
}
else if (column_index == 7)
{
Console.Write("Enter student's final score:");
st[index].final = float.Parse(Console.ReadLine());
}
else Console.WriteLine("Invalid column index");
st[index].total = st[index].quizz1 + st[index].quizz2 + st[index].assigment + st[index].midterm + st[index].final;


}
else Console.WriteLine("The record deosn't exits.Check the ID and try again.");

}


//method to calculate average score
static void average(student[] st, int itemcount)
{
string id;
float avg=0;
Console.Write("Enter students'ID:");
id = Console.ReadLine();
int index = search(st, id.ToString(),itemcount);
if (index != -1 && itemcount>0)
{
st[index].total = st[index].quizz1 + st[index].quizz2 + st[index].assigment + st[index].midterm + st[index].final;
avg = st[index].total /5;
}

Console.WriteLine("The average score is {0}.", avg);
}
//method to show max total score 
static void showmax(student[] st, int itemcount)
{
float max = st[0].total;
int index=0;
Console.WriteLine(itemcount);
if (itemcount >= 2)
{

for (int j = 0; j < itemcount-1; ++j)
if (max < st[j+1].total) {
max = st[j+1].total;
index = j+1;

}


}

else if (itemcount == 1)
{
index = 0;
max = st[0].total;
}


else Console.WriteLine("Not record found!");

if (index != -1) Console.WriteLine("The student with ID:{0} gets the highest score {1}.", st[index].stnumber, max);


}
//method to show min total score
static void showmin(student[] st, int itemcount)
{

float min = st[0].total;
int index = 0;
if (itemcount >= 2)
{
for (int j = 0; j < itemcount-1; ++j)
if (min > st[j+1].total)
{
min = st[j+1].total;
index = j+1;

}



}

else if (itemcount == 1)
{
index = 0;
min = st[0].total;
}
else Console.WriteLine("No record found!");

if (index != -1) Console.WriteLine("The student with ID:{0} gets the lowest score {1}.", st[index].stnumber, min);


}
//method to find record
static void find(student[] st, int itemcount)
{
string id;
Console.Write("Enter student's ID:");
id=Console.ReadLine();

int index=search(st,id.ToString(),itemcount);
if (index != -1)
{
Console.Write("{0,-5}{1,-20}{2,-5}", st[index].stnumber, st[index].stname, st[index].sex);

Console.Write("{0,-5}{1,-5}{2,-5}", st[index].quizz1, st[index].quizz2, st[index].assigment);

Console.Write("{0,-5}{1,-5}{2,-5}", st[index].midterm, st[index].final, st[index].total);
Console.WriteLine(); 

}
else Console.WriteLine("The record doesn't exits.");

}


//method to sort records by total score
static void bubblesort(student[] dataset, int n)
{
int i, j;
for (i = 0; i < n; i++)
for (j = n - 1; j > i; j--)
if (dataset[j].total < dataset[j - 1].total )
{
student temp = dataset[j];
dataset[j] = dataset[j - 1];
dataset[j - 1] = temp;
}

}
//method to clean deleted record
static void clean(student[] st,int index)
{
st[index].stnumber = null;
st[index].stname = null;
st[index].sex = null;
st[index].quizz1 = 0;
st[index].quizz2 = 0;
st[index].assigment = 0;
st[index].midterm = 0;
st[index].final = 0;
st[index].total = 0;

}


}
}


Sort records

 Defining the sort(student[] st, int itemcount) function to sort the records in ascending order by total scores. For the sort technique we use bubble sort algorithm.
static void bubblesort(student[] dataset, int n)
{
int i, j;
for (i = 0; i < n; i++)
for (j = n - 1; j > i; j--)
if (dataset[j].total < dataset[j - 1].total )
{
  student temp = dataset[j];
  dataset[j] = dataset[j - 1];
  dataset[j - 1] = temp;
  }

}

If you want to sort the records in descending order, you need to modify the C# code above to:
static void bubblesort(student[] dataset, int n)
{
int i, j;
for (i = 0; i < n; i++)
for (j = n - 1; j > i; j--)
if (dataset[j].total > dataset[j - 1].total )
{
student temp = dataset[j];
dataset[j] = dataset[j - 1];
dataset[j - 1] = temp;
}

}






Find record in the list

Defining the find(student[] st, int itemcount) method to find the record in the list. This method asks the user to enter the id of the student record. Then this id is checked to make sure it really exists. If the record is found, the information of the target student will be displayed. If the record is not found the message "The record doesn't exist." will be displayed.
static void find(student[] st, int itemcount)
{
  string id;
  Console.Write("Enter student's ID:");
  id=Console.ReadLine();

  int index=search(st,id.ToString(),itemcount);
  if (index != -1)
  {
    Console.Write("{0,-5}{1,-20}{2,-5}", st[index].stnumber, st[index].stname, st[index].sex);
    Console.Write("{0,-5}{1,-5}{2,-5}", st[index].quizz1, st[index].quizz2, st[index].assigment);
    Console.Write("{0,-5}{1,-5}{2,-5}", st[index].midterm, st[index].final, st[index].total);
    Console.WriteLine(); 

}
  else Console.WriteLine("The record doesn't exits.");

} 





C# structure: student records application

Exercise:
Write a C# program to keep records and perform statistical analysis for a class of 20 students. The information of each student contains ID, Name, Sex, quizzes Scores (2 quizzes per semester), mid-term score, final score, and total score.
The program will prompt the user to choose the operation of records from a menu as shown below:

========================================================
                                                   MENU
========================================================
1. Add student records

2. Delete student records

3. Update student records

4. View all student records

5. Calculate an average of a selected student’s scores

6. Show student who gets the max total score

7. Show student who gets the min total score

8. Find student by ID

9. Sort records by total scores

Enter your choice:1


Note: All students records are stored in an array of structures

Solution:
To make this solution simple and easy to follow, we divide this solution in to different steps:
Step1: Declaring a structure called student to store the records
struct student

{
public string stnumber;

public string stname;

public string sex;

public float quizz1;

public float quizz2;

public float assigment;

public float midterm;

public float final;

public float total;


};




C# structure: student records application



Menu of choices

Step2: Defining the displaymenu() method to display the menu. The simple menu provides nine choices from 1 to 9 to work with the records.
static void displaymenu(){

Console.WriteLine("=====================================================");

Console.WriteLine(" MENU ");

Console.WriteLine("=====================================================");

Console.WriteLine(" 1.Add student records");
Console.WriteLine(" 2.Delete student records");
Console.WriteLine(" 3.Update student records");
Console.WriteLine(" 4.View all student records");
Console.WriteLine(" 5.Calculate an average of a selected student's scores");
Console.WriteLine(" 6.Show student who get the max total score");
 
Console.WriteLine(" 7.Show student who get the min total score");
Console.WriteLine(" 8.Find a student by ID");
Console.WriteLine(" 9.Sort students by TOTAL");



}





C# structure: student records application



Append record to list

Step3: defining the add(student[] st, ref int itemcount) method to add a new record to the the array of student objects. This method takes two arguments. The first argument is the array of student objects(st) and the second argument is the number of items in the array. The two arguments are passed by references. For an array, we don't need to use the ref keyword when we want to pass it by reference. However, we need to use the ref keyword when we want to pass an argument of primitive type such as int, float, dobule,etc. When the new item is added the value itemcount variable increases by 1 that means the number of records in the list increases.
//method add/append a new record
static void add(student[] st,ref int itemcount){

Again:
Console.WriteLine();
 
Console.Write("Enter student's ID:");
st[itemcount].stnumber=Console.ReadLine().ToString() ;

//making sure the record to be added doesn't already exist
if(search(st,st[itemcount].stnumber,itemcount)!=-1){

Console.WriteLine("This ID already exists.");
goto Again;

}


Console.Write("Enter student's Name:");
 

st[itemcount].stname=Console.ReadLine ().ToString();


Console.Write("Enter student's Sex(F or M):");
st[itemcount].sex=Console.ReadLine().ToString();


Console.Write("Enter student's quizz1 score:");
st[itemcount].quizz1=float.Parse(Console.ReadLine());


Console.Write("Enter student's quizz2 score:");
st[itemcount].quizz2=float.Parse(Console.ReadLine());


Console.Write("Enter student's assigment score:");
st[itemcount].assigment=float.Parse(Console.ReadLine());


Console.Write("Enter student's mid term score:");
st[itemcount].midterm=float.Parse(Console.ReadLine());

Console.Write("Enter student's final score:");
st[itemcount].final=float.Parse(Console.ReadLine());

st[itemcount].total=st[itemcount].quizz1+st[itemcount].quizz2+st[itemcount].assigment+st[itemcount].midterm+st[itemcount].final;



++itemcount; //increase the number of items by one



}




C# structure: student records application



Show all records in list

Step4: Defining the viewall(student[] st, int itemcount) method to display the list of all records in the set. To display all records, we need a while loop to traverse through the array of student objects.
static void viewall(student[] st,int itemcount)
{

int i = 0;

Console.WriteLine("{0,-5}{1,-20}{2,-5}{3,-5}{4,-5}{5,-5}{6,-5}{7,-5}{8}(column index)", "0", "1", "2", "3", "4", "5", "6", "7", "8");
Console.WriteLine("{0,-5}{1,-20}{2,-5}{3,-5}{4,-5}{5,-5}{6,-5}{7,-5}{8,-5}", "ID", "NAME", "SEX", "Q1", "Q2", "As", "Mi", "Fi", "TOTAL");

Console.WriteLine("=====================================================");

while (i < itemcount)
{

if (st[i].stnumber !=null )
{

Console.Write("{0,-5}{1,-20}{2,-5}", st[i].stnumber, st[i].stname, st[i].sex);

Console.Write("{0,-5}{1,-5}{2,-5}",st[i].quizz1,st[i].quizz2,st[i].assigment);

Console.Write("{0,-5}{1,-5}{2,-5}",st[i].midterm,st[i].final,st[i].total);

Console.Write("\n");
}

i = i + 1;



}

}



C# structure: student records application



Find record index

Step5: Defining the search(student[] st, int itemcount) method to search for the index of a target record. This method is useful as we need it to find the location of the target record in the array of student objects. It can help us to make sure the record does exit before we allow the record for deletion or updating. If the target element is found, the method returns the index of this element. It return -1, if the target element is not found in the array.
static int search(student[] st, string id,int itemcount){
int found =-1;
for (int i = 0; i < itemcount && found==-1; i++)
{

  if (st[i].stnumber == id) found=i;

  else found=-1 ;
}

return found;

}



C# structure: student records application



Delete record

Step6: Defining the delete(student[] st, ref int itemcount) method to delete a target record from the array of student objects. The user will be prompted to enter the id of student record that his/her want to delete. Then this id will be checked to make sure it does exist in the list. If the target record or element really exists, the deletion process can be made. The deletion process starts by checking whether the target record is the last record, beginning or middle record. If the target record is the last record in the list, we simply delete the record by supplying it to the clean(student[] st, int index) method. The last record is the record that has it index equal to itemcount subtracted by 1. If the target record stays at the beginning or in the middle of the list, we need to use a loop to allow the previous element to take over the next element. This process continue until it reaches the end of the list(itemcount-1). Then the clean() method is called to clean the last element of the list that should not exit. After the element is cleaned, the itemcount variable decreases by 1. This means that the number of elements in the list decreases.
static void delete(student[] st, ref int itemcount)
{
string id;
int index;
if (itemcount > 0)
{
Console.Write("Enter student's ID:");
id = Console.ReadLine();
index = search(st, id.ToString(),itemcount);
 

if ((index!=-1) && (itemcount != 0))
{
if (index == (itemcount-1)) //delete the last record
{

clean(st, index);
--itemcount;

Console.WriteLine("The record was deleted.");
}
else //delete the first or middle record
{
for (int i = index; i < itemcount-1; i++)
{
st[i] = st[i + 1];
clean(st, itemcount);
--itemcount ;
}

}

}
else Console.WriteLine("The record doesn't exist. Check the ID and try again.");


}
else Console.WriteLine("No record to delete");
}
static void clean(student[] st,int index)
{
st[index].stnumber = null;
st[index].stname = null;
st[index].sex = null;
st[index].quizz1 = 0;
st[index].quizz2 = 0;
st[index].assigment = 0;
st[index].midterm = 0;
st[index].final = 0;
st[index].total = 0;

}



C# structure: student records application



Update record

Step7: Defining the update_rec(struct student st[], int itemcount) method to update a specified record. The update process starts by asking the user to input the id of the record to be changed. The id value is check to make sure it really exists. If it exits the change to the target record can be made after asking the user to input the new value of the field that need change.
static void update(student[] st, int itemcount)
{
string id;
int column_index;
Console.Write("Enter student's ID:");
id=Console.ReadLine();
Console.Write("Which field you want to update(1-7)?:");
column_index=int.Parse(Console.ReadLine());

int index = search(st, id.ToString(),itemcount);

if ((index != -1) && (itemcount != 0))
{
if (column_index == 1)
{
Console.Write("Enter student's Name:");

st[index].stname = Console.ReadLine().ToString();
}

else if (column_index == 2)
{
Console.Write("Enter student's Sex(F or M):");
st[index].sex = Console.ReadLine().ToString();
}
else if (column_index == 3)
{
Console.Write("Enter student's quizz1 score:");
st[index].quizz1 = float.Parse(Console.ReadLine());
}
else if (column_index == 4)
{
Console.Write("Enter student's quizz2 score:");
st[index].quizz2 = float.Parse(Console.ReadLine());
}
else if (column_index == 5)
{
Console.Write("Enter student's assigment score:");
st[index].assigment = float.Parse(Console.ReadLine());
}
else if (column_index == 6)
{
Console.Write("Enter student's mid term score:");
st[index].midterm = float.Parse(Console.ReadLine());
}
else if (column_index == 7)
{
Console.Write("Enter student's final score:");
st[index].final = float.Parse(Console.ReadLine());
}
else Console.WriteLine("Invalid column index");
st[index].total = st[index].quizz1 + st[index].quizz2 + st[index].assigment + st[index].midterm + st[index].final;


}
else Console.WriteLine("The record deosn't exits.Check the ID and try again.");

}
 




C# structure: student records application



Average score

Step8: Defining the average(student[] st, int itemcount) method to calculate the average score of a selected student. The method alo starts by asking the user to input the id of the target student. This id is checked to make sure it really exist. The average score can be calculated by dividing the sum of quizz1 score, quizz2 score, assignment score, mid-term score, and final score by 5.
static void average(student[] st, int itemcount)
{
string id;
float avg=0;
Console.Write("Enter students'ID:");
id = Console.ReadLine();
int index = search(st, id.ToString(),itemcount);
if (index != -1 && itemcount>0)
{
st[index].total = st[index].quizz1 + st[index].quizz2 + st[index].assigment + st[index].midterm + st[index].final;
avg = st[index].total /5;
}

Console.WriteLine("The average score is {0}.", avg);
}





C# structure: student records application



Min and Max scores

Step9: Defining the showmax(student[] st, int itemcount) and showmin(student[] st, int itemcount) methods show about the student who gets the maximum score and the student who gets the minimum score. To find the highest total core or lowest total core, we need to compare every total score of each element.
static void showmax(student[] st, int itemcount)
{
float max = st[0].total;
int index=0;
Console.WriteLine(itemcount);
if (itemcount >= 2)
{

for (int j = 0; j < itemcount-1; ++j)
if (max < st[j+1].total) {
max = st[j+1].total;
index = j+1;

}


}

else if (itemcount == 1)
{
index = 0;
max = st[0].total;
}


else Console.WriteLine("Not record found!");

if (index != -1) Console.WriteLine("The student with ID:{0} gets the highest score {1}.", st[index].stnumber, max);


}
\

static void showmin(student[] st, int itemcount)
{

float min = st[0].total;
int index = 0;
if (itemcount >= 2)
{
for (int j = 0; j < itemcount-1; ++j)
if (min > st[j+1].total)
{
min = st[j+1].total;
index = j+1;

}



}

else if (itemcount == 1)
{
index = 0;
min = st[0].total;
}
else Console.WriteLine("No record found!");

if (index != -1) Console.WriteLine("The student with ID:{0} gets the lowest score {1}.", st[index].stnumber, min);


}
//method to find record
static void find(student[] st, int itemcount)
{
string id;
Console.Write("Enter student's ID:");
id=Console.ReadLine();

int index=search(st,id.ToString(),itemcount);
if (index != -1)
{
Console.Write("{0,-5}{1,-20}{2,-5}", st[index].stnumber, st[index].stname, st[index].sex);

Console.Write("{0,-5}{1,-5}{2,-5}", st[index].quizz1, st[index].quizz2, st[index].assigment);

Console.Write("{0,-5}{1,-5}{2,-5}", st[index].midterm, st[index].final, st[index].total);
Console.WriteLine();
 

}
else Console.WriteLine("The record deosn't exits.");

}




C# array exercise: stem leaf


Exercise : Write a C# program to display an integer data set in the form of stem and leaf. 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 how to display a data set in the form of stem and leaf, you will need to read this page:
Stem and Leaf display  
Solution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Csharp_exercises
{
class Program
{
static void Main(string[] args)
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

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

  int n;
  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);
//show data in stem and leaf display
//Display sorted array
  Console.WriteLine("The sorted array is:");
   for (i = 0; i < n; i++)
    {
      Console.Write("{0}\t", dataset[i]);
      if (i % 5 == 0 && i != 0) Console.Write("\n");
     }

//store stem and leaf in a 2D array
    int[,] stem_leaf = new int[n, 2];
    for (i = 0; i < n; i++)
    {
      stem_leaf[i, 0] = dataset[i] / 10;
      stem_leaf[i, 1] = dataset[i] % 10;
    }

//initialize 2D array storing numbers of occurences, and values
   int[,] mode = new int[n, 2];

   for (i = 0; i < n; i++)
     for (int j = 0; j < 2; j++) mode[i, j] = 0;

       mode[0, 0] = 1;
//find mode

   int count = 1;
   for (i = count - 1; i < n; i++)
   {
     for (int j = count - 1; j < n - 1; j++)
      {
        if (stem_leaf[i, 0] == stem_leaf[j + 1, 0]) { count++; mode[i, 0]++; mode[i, 1] = stem_leaf[i, 0]; }
       else if (i == 0) mode[i, 1] = stem_leaf[i, 0];
       }
   }
    Console.WriteLine();
    Console.WriteLine("Stem and Leaf Display:");
    Console.WriteLine("Frequency\tStem\tLeaf");
    Console.WriteLine("================================");
    int c = 0, leaf = 0;
    for (i = 0; i < n; i++)
     {
       if (mode[i, 1] != 0)
        {
          leaf += mode[i, 0];

          Console.Write("{0,-18}", mode[i, 0]);
          Console.Write("{0,-6}", mode[i, 1]);
          for (int j = c; j < leaf; j++)
            {
              Console.Write("{0}", stem_leaf[j, 1]);
             }

         c = leaf;
        Console.WriteLine();
      }
   }
 }
Console.ReadLine();
}

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;
            }

      }

  }
}


}

}

}