Wednesday, February 1, 2012

Wednesday, 2-1-12

static void Main(string[] args)
{
SystemArrayFunctionality();
}

static void SystemArrayFunctionality()
{
Console.WriteLine("=> Working with System.Array");
//initialize items at startup
string[] gothicBands = { "Tones on Tail", "Bauhaus", "Sisters of Mercy" };

//print out names in declared order
Console.WriteLine("-> Here is the array:");
for (int i = 0; i < gothicBands.Length; i++)
{
//print a name
Console.Write(gothicBands[i] + ", ");
}
Console.WriteLine("\n");

//reverse them
Array.Reverse(gothicBands);
Console.WriteLine("-> The reversed array");
//...and print them
for (int i = 0; i < gothicBands.Length; i++)
{
//print a name
Console.Write(gothicBands[i] + ", ");
}
Console.WriteLine("\n");

//clear out all but the final member
Console.WriteLine("-> Cleared out all but one...");
Array.Clear(gothicBands, 1, 2);
for (int i = 0; i < gothicBands.Length; i++)
{
//print a name
Console.Write(gothicBands[i] + ", ");
}
Console.WriteLine();
}

Friday, January 27, 2012

Friday 1-27-12

class Program
{
static void Main(string[] args)
{
RectMultidimensionalArray();
JaggedMultidimensionalArray();
GenerateArray();
PassAndReceiveArrays();
}

static void RectMultidimensionalArray()
{
Console.WriteLine("=>Rectangular multidimensional array.");
//a rectangular md array
int[,] myMatrix;
myMatrix = new int[6, 6];


//populate (6 *6_ array
for (int i = 0; i < 6; i++)
for (int j = 0; j < 6; j++)
myMatrix[i, j] = i * j;

//print (6*6) array
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 6; j++)
{
Console.Write(myMatrix[i, j] + "\t");
}
Console.WriteLine();
}
Console.WriteLine();
}

static void JaggedMultidimensionalArray()
{
Console.WriteLine("=> Jagged multidimensional array.");
//a jagged MD array (i.e. an array of arrays)
//here we have an array of 5 different arrays
int[][] myJagArray = new int[5][];

//create the jagged array
for (int i = 0; i < 5; i++)
{
myJagArray[i] = new int[i + 7];
}

//print each row (remember, each element is defaulted to zero!)
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < myJagArray[i].Length; j++)
{
Console.Write(myJagArray[i][j] + " ");
}
Console.WriteLine();
}
Console.WriteLine();
}

static void GenerateArray()
{
int[] myArray = new int[5];
myArray[0] = 15;
myArray[1] = 464;
myArray[2] = 978;
myArray[3] = 6;
myArray[4] = 812;

PrintArray(myArray);
Console.WriteLine();

}
//arrays as arguments or return values
static void PrintArray(int[] myInts)
{
for (int i = 0; i < myInts.Length; i++)
Console.WriteLine("Item {0} is {1}", i, myInts[i]);
}

static string[] GetStringArray()
{
string[] theStrings = { "Hello", "from", "GetStringArray" };
return theStrings;
}

static void PassAndReceiveArrays()
{
Console.WriteLine("=> Arrays as params and return values.");
//pass array as parameter
int[] ages = { 20, 22, 23, 0 };
PrintArray(ages);

//get array as return value
string[] strs = GetStringArray();
foreach (string s in strs)
Console.WriteLine(s);

Console.WriteLine();
}

}

Wednesday, January 25, 2012

Wednesday 1-25-12

class Program
{
static void Main(string[] args)
{
ShowFolders();
Console.WriteLine();
ShowFolders(@"C:\");
}

static void ShowFolders(string root = @"C:\", bool showFullPath = false)
{
foreach (string folder in Directory.EnumerateDirectories(root))
{
string output = showFullPath ? folder : Path.GetFileName(folder);
Console.WriteLine(output);
}
}
}


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


namespace fromTheWeb
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("My machine name: {0}", Environment.MachineName);
Console.WriteLine();

//get drives availabe on local computer and form into a single character expression
string[] drives = Environment.GetLogicalDrives();
string driveNames = string.Empty;

foreach (string drive in drives)
driveNames += drive.Substring(0, 1);

//create regular expression pattern dynamically based on local machine information
string pattern = @"\\\\(?i:" + Environment.MachineName + @")(?:\.\w+)*\\((?i:[" + driveNames + @"]))\$";

string replacement = "$1:";

string[] uncPaths = { @"\\" + Environment.MachineName + @".domain1.mycompany.com\C$\Thingstodo.txt",
@"\\" + Environment.MachineName + @"\c$\ThingsToDo.txt",
@"\\" + Environment.MachineName + @"\d$\documents\mydocument.docx"};

foreach (string uncPath in uncPaths)
{
Console.WriteLine("Input String: " + uncPath);
Console.WriteLine("Returned String: " + Regex.Replace(uncPath, pattern, replacement));
Console.WriteLine();
}
}
}
}

Sunday, January 22, 2012

Sunday 1-22-12

static void Main(string[] args)
{
ShowFolders();
}


static void ShowFolders(string root = @"C:\", bool showFullpath = false)
{
foreach (string folder in Directory.EnumerateDirectories(root))
{
string output = showFullpath ? folder : Path.GetFileName(folder);
Console.WriteLine(output);
}
}

Saturday, January 21, 2012

Saturday 1-21-12

namespace GeneralCoding
{
class Program
{
static void Main(string[] args)
{
DeferType();
ConditionalOperator();
}

class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Address {get; set;}
}

class Company
{
public int Id {get; set;}
public string Name { get; set; }
public bool isBig {get; set;}
}

static void DeferType()
{
//declare three types that have nothing to do with each other
//but all have an Id and name property

Person p = new Person() { Id = 1, Name = "Ben", Address="Redmond, WA"};
Company c = new Company() { Id = 1313, Name="Microsoft", isBig = true};
var v = new {Id = 13, Name="Widget", Silly = true};

PrintInfo(p);
PrintInfo(c);
PrintInfo(v);

}

static void PrintInfo(dynamic data)
{
//will print anythign that has an Id and Name property
Console.WriteLine("ID: {0}, Name: {1}", data.Id, data.Name);
}

//declare an array of objects
static void ArrayDeclaration()
{
//these are all equivalent
int[] array1 = new int[4];
array1[0] = 13; array1[1] = 15; array1[2] = 15; array1[3] = 16;

int[] array2 = new int[4] {13, 14, 15, 16};

int[] array3 = new int[] {13, 14, 15, 16};

int[] array4 = {13, 14, 15, 16};
}

static void ConditionalOperator()
{
bool condition = true;

int x = condition ? 13 : 14;
Console.WriteLine("x is {0}", x);

//you can also embed the condition in other statements
Console.WriteLine("Condition is {0}", condition ? "TRUE" : "FALSE");
}
}
}


class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 100; ++i)
{
if (i.IsPrime())
{
Console.WriteLine(i);
}
}
Console.ReadKey();
}
}

static class IntMethods
{
//extension methods must be static
//the this keyword tells C# that this is an extension method
public static bool IsPrime(this int number)
{
//check for evenness
if (number % 2 == 0)
{
if (number == 2)
return true;
return false;
}

//don't need to check past the square
int max = (int)Math.Sqrt(number);
for (int i= 3; i <= max; i += 2)
{
if ((number % i) == 0)
{
return false;
}
}
return true;
}
}

Thursday, January 19, 2012

Thursday 1-19-12

class Program
{
static void Main(string[] args)
{
DeclareImplicitArrays();
ArrayOfObjects();
}

static void DeclareImplicitArrays()
{
//a is really int[]
var a = new[] { 1, 10, 100, 1000 };
Console.WriteLine("a is a: {0}", a.ToString());

//b is really double[]
var b = new[] { 1, 1.4, 2, 2.5 };
Console.WriteLine("b is a: {0}", b.ToString());

//c is really string[]
var c = new[] { " hello", null, " world" };
Console.WriteLine("c is a: {0}", c.ToString());
Console.WriteLine();

}

static void ArrayOfObjects()
{
Console.WriteLine("=> Array of Objects.");

//An array of objects can be anything at all.

object[] myObjects = new object[4];
myObjects[0] = 10;
myObjects[1] = false;
myObjects[2] = new DateTime(1969, 3, 24);
myObjects[3] = "Form & Void";

foreach (object obj in myObjects)
{
//print the type and value for each item in the array
Console.WriteLine("Type: {0}, Value: {1}", obj.GetType(), obj);
}
Console.WriteLine();

}


}

Wednesday, January 18, 2012

Wednesday 1.18.12

class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Arrays *****");
SimpleArrays();
ArrayInitialization();
Console.ReadLine();
}

static void SimpleArrays()
{
Console.WriteLine("=> Simple Array Creation.");
//assign an array of ints containing 3 elements {0, 1, 2}
int[] myInts = new int[3];


myInts[0] = 100;
myInts[1] = 200;
myInts[2] = 300;

//now print each value
foreach (int i in myInts)
Console.WriteLine(i);

Console.WriteLine();

//initialize a 100 item string array, indexed {0 - 99}
string[] booksOnDotNet = new string[100];
Console.WriteLine();
}

static void ArrayInitialization()
{
Console.WriteLine("=> Array Initialization.");
//array initialization syntax using the new keyword
string[] stringArray = new string[] { "one", "two", "three" };
Console.WriteLine("stringArray has {0} elements", stringArray.Length);

//array initialization sytnax without using the new keyword
bool[] boolArray = { false, false, true };
Console.WriteLine("boolArray has {0} elements", boolArray.Length);

//array intialization with new keyword and size
int[] intArray = new int[4] { 20, 22, 23, 0 };
Console.WriteLine("intArry has {0} elements", intArray.Length);
Console.WriteLine();

}
}

Monday, January 16, 2012

Monday 1-16-12

namespace VertexDemo
{
//format a type with ToString()
struct Vertex3d : IFormattable, IEquatable, IComparable
{
private int _id;

private double _x;
private double _y;
private double _z;

public int Id
{
get
{
return _id;
}

set
{
_id = value;
}
}

public double X
{
get { return _x; }
set { _x = value; }
}

public double Y
{
get { return _y; }
set { _y = value; }
}

public double Z
{
get { return _z; }
set { _x = value; }
}

public Vertex3d(double x, double y, double z)
{
this._x = x;
this._y = y;
this._z = z;

_id = 0;

}

public int CompareTo(Vertex3d other)
{
if (_id < other._id)
return -1;
if (_id == other._id)
return 0;
return 1;
}

public double this[int index]
{
get
{
switch (index)
{
case 0: return _x;
case 1: return _y;
case 2: return _z;
default: throw new ArgumentOutOfRangeException("index", "Only indexes 0-2 valid!");
}
}
set
{
switch (index)
{
case 0: _x = value; break;
case 1: _y = value; break;
case 2: _z = value; break;
default: throw new ArgumentOutOfRangeException("index", "Only indexes 0-2 valid!");
}
}

}

public double this[string dimension]
{
get
{
switch (dimension)
{
case "x":
case "X": return _x;
case "y":
case "Y": return _y;
case "z":
case "Z": return _z;
default: throw new ArgumentOutOfRangeException("dimension", "Only dimensions X, Y, and Z are valid!");
}
}
set
{
switch (dimension)
{
case "x":
case "X": _x = value; break;
case "y":
case "Y": _y = value; break;
case "z":
case "Z": _z = value; break;
default: throw new ArgumentOutOfRangeException("dimension", "Only dimensions X, Y, and Z are valid!");
}
}
}

public string ToString(string format, IFormatProvider formatProvider)
{
//"G" is .Net's standard for general formatting
//all times should support it
if (format == null) format = "G";

//is the user providing their own format provider?
if (formatProvider != null)
{
ICustomFormatter formatter = formatProvider.GetFormat(this.GetType()) as ICustomFormatter;

if (formatter != null)
{
return formatter.Format(format, this, formatProvider);
}
}

//formatting is up to us, so let'd do it
if (format == "G")
{
return string.Format("({0}, {1}, {2})", X, Y, _z);
}

StringBuilder sb = new StringBuilder();
int sourceIndex = 0;

while (sourceIndex < format.Length)
{
switch (format[sourceIndex])
{
case 'X':
sb.Append(X.ToString());
break;
case 'Y':
sb.Append(Y.ToString());
break;
case 'Z':
sb.Append(X.ToString());
break;
default:
sb.Append(format[sourceIndex]);
break;
}
sourceIndex++;
}
return sb.ToString();
}

public override bool Equals(object obj)
{
if (obj == null)
return false;
if (obj.GetType() != this.GetType())
return false;
return Equals((Vertex3d)obj);
}

public bool Equals(Vertex3d other)
{
return this._x == other._x
&& this._y == other._y
&& this._z == other._z;
}
}


class TypeFormatter : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter)) return this;
return Thread.CurrentThread.CurrentCulture.GetFormat(formatType);
}

public string Format(string format, object arg, IFormatProvider formatProvider)
{
string value;
IFormattable formattable = arg as IFormattable;
if (formattable == null)
{
value = arg.ToString();
}
else
{
value = formattable.ToString(format, formatProvider);
}
return string.Format("Type: {0}, Value: {1}", arg.GetType(), value);
}
}

class Program
{
static void Main(string[] args)
{
Vertex3d v = new Vertex3d(1.0, 2.0, 3.0);
Vertex3d v2 = new Vertex3d(4.0, 5.0, 6.0);
Vertex3d v3 = new Vertex3d(1.0, 2.0, 3.0);
TypeFormatter formatter = new TypeFormatter();
StringBuilder sb = new StringBuilder();
sb.AppendFormat(formatter, "{0:(X Y)}; {1:[X, Y, Z]}", v, v2);
Console.WriteLine(sb.ToString());
Console.WriteLine("v == v3 : {0}", v.Equals(v3));
Console.WriteLine("v == v2: {0}", v.Equals(v2));

Vertex3d vNew = new Vertex3d(1, 2, 3);
Console.WriteLine(vNew[0]);
Console.WriteLine(vNew["Z"]);
Console.WriteLine(vNew["y"]);
vNew.Id = 15;


}
}
}

Saturday, January 14, 2012

Saturday 1/14/2012

namespace MoreCSharpCoreConst
{
class Program
{
static void Main(string[] args)
{
DeclareExplicitVars();
DeclareImplicitVars();
ForLoop();
ForAndForEachLoop();
ExecuteWhileLoop();
ExecuteDoWhileLoop();
ExecuteSwitch();
ExecuteSwitchOnString();
}

//explicit variables
static void DeclareExplicitVars()
{
//explicitly typed local variables
//are declared as follows:
//datatype variableName = initialValue;
int myInt = 0;
bool myBool = true;
string myString = "Time, marches on...";
}

//implicitly typed variables
static void DeclareImplicitVars()
{
//implicitly typed local variabels are declared as follows:
//var variableName = initialValue;
var myInt = 0;
var myBool = true;
var myString = "time, marches on...";

//print out the underlying type
Console.WriteLine("myInt is a: {0}", myInt.GetType().Name);
Console.WriteLine("myBool is a: {0}", myBool.GetType().Name);
Console.WriteLine("myString is a: {0}", myString.GetType().Name);
}

//-------------Iteration Constructs---------------------------------

//for loop
static void ForLoop()
{
//note 'i' is only visible within the scope of the for loop
for (int i = 0; i < 4; i++)
{
Console.WriteLine("Number is {0} ", i);
}
}

//iterate array items using foreach
static void ForAndForEachLoop()
{
string[] carTypes = { "Ford", "BMW", "Yugo", "Honda" };
foreach (string c in carTypes)
Console.WriteLine(c);

int[] myInts = { 10, 20, 30, 40 };
foreach (int i in myInts)
Console.WriteLine(i);
}

static void ExecuteWhileLoop()
{
string userIsDone = "";
//test on a lower-class copy of the string
while (userIsDone.ToLower() != "yes")
{
Console.WriteLine("Area you done? [yes] [no]: ");
userIsDone = Console.ReadLine();
Console.WriteLine("in while loop");
}
}

static void ExecuteDoWhileLoop()
{
string userIsDone = "";

do
{
Console.WriteLine("In do/while loop");
Console.Write("Are you done? [yes] [no]: ");
userIsDone = Console.ReadLine();
} while (userIsDone.ToLower() != "yes"); //note the semicolon!
}

//switch on a numerical value
static void ExecuteSwitch()
{
Console.WriteLine("1 [C#], 2 [VB]");
Console.WriteLine("Please pick your language preference: ");
string langChoice = Console.ReadLine();
int n = int.Parse(langChoice);

switch (n)
{
case 1:
Console.WriteLine("Good choice, C# is a fine language.");
break;
case 2:
Console.WriteLine("VB: OOP, multithreading, and more!");
break;
default:
Console.WriteLine("well...good luck with that!");
break;
}
}

static void ExecuteSwitchOnString()
{
Console.WriteLine("C# or VB");
Console.Write("Please pick your language preference: ");
string langChoice = Console.ReadLine();
switch (langChoice)
{
case "C#":
Console.WriteLine("Good choice, C# is a fine language.");
break;
case "VB":
Console.WriteLine("VB: OOP, multithreading and more!");
break;
default:
Console.WriteLine("Well... good luck with that!");
break;

}
}

}
}


namespace CoreConstructsPt2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Fun with Methods");
string s1 = "Flip";
string s2 = "Flop";
Console.WriteLine("Before: {0}, {1} ", s1, s2);
SwapStrings(ref s1, ref s2);
Console.WriteLine("After: {0}, {1} ", s1, s2);
Console.WriteLine();
//pass in a comma-delimited list of doubles
double average;
average = CalcAverage(4.0, 3.2, 5.8, 64.22, 87.2);
Console.WriteLine("Average of data is: {0}", average);

//or pass an array of doubles
double[] data = { 4.0, 3.2, 5.7 };
average = CalcAverage(data);
Console.WriteLine("Average of data is: {0}", average);
Console.WriteLine();
DisplayFancyMessage(Message: "Wow! Very fancy indeed!", textColor: ConsoleColor.DarkRed, backgroundColor: ConsoleColor.White);

DisplayFancyMessage(backgroundColor: ConsoleColor.Green, Message: "Testing...", textColor: ConsoleColor.DarkBlue);

//calls int version of add()
Console.WriteLine(add(10, 10));

//calls long version of Add()
Console.WriteLine(add(9000000, 120000000000000000));

//calls double version of Add()
Console.WriteLine(add(4.3, 4.4));

Console.ReadLine();
}


public static void SwapStrings(ref string s1, ref string s2)
{
string tempStr = s1;
s1 = s2;
s2 = tempStr;
}

static double CalcAverage(params double[] values)
{
Console.WriteLine("You sent me {0} doubles.", values.Length);
double sum = 0;
if (values.Length == 0)
return sum;

for (int i = 0; i < values.Length; i++)
sum += values[i];
return (sum / values.Length);
}


//invoking methods using named parameters
static void DisplayFancyMessage(ConsoleColor textColor, ConsoleColor backgroundColor, string Message)
{
//store old colors to restore once message is printed
ConsoleColor oldTextColor = Console.ForegroundColor;
ConsoleColor oldbackgroundColor = Console.BackgroundColor;

//set new colors and print message
Console.ForegroundColor = textColor;
Console.BackgroundColor = backgroundColor;

Console.WriteLine(Message);

//resore previous colors
Console.ForegroundColor = oldTextColor;
Console.BackgroundColor = oldbackgroundColor;
}

static int add(int x, int y)
{ return x + y; }

static double add(double x, double y)
{ return x + y; }

static double add(long x, long y)
{ return x + y; }
}
}


@autoreleasepool {
//create three NSDate objects
NSDate *now = [NSDate date];
NSDate *tomorrow = [now dateByAddingTimeInterval:24.0 * 60.0 * 60.0];
NSDate *yesterday = [now dateByAddingTimeInterval:-24.0 * 60.0 * 60.0];
//create an array containing all three (nil terminates the list);
NSArray *dateList = [NSArray arrayWithObjects:now, tomorrow, yesterday, nil];

//how many dates are there?
NSLog(@"There are %lu dates", [dateList count]);

//print a couple
NSLog(@"The first date is %@", [dateList objectAtIndex:0]);
NSLog(@"The third date is %@", [dateList objectAtIndex:2]);
}



@autoreleasepool {
//create three NSDate objects
NSDate *now = [NSDate date];
NSDate *tomorrow = [now dateByAddingTimeInterval:24.0 * 60.0 * 60.0];
NSDate *yesterday = [now dateByAddingTimeInterval:-24.0 * 60.0 * 60.0];

//create an array containg all three (nil terminates the list)
NSArray *dateList = [NSArray arrayWithObjects:now, tomorrow, yesterday, nil];

NSUInteger dateCount = [dateList count];
for (int i = 0; i < dateCount; i++)
{
NSDate *d = [dateList objectAtIndex:i];
NSLog(@"Here is a date: %@", d);
}

for (NSDate *d in dateList){
NSLog(@"Here is a date: %@", d);
}
}

Friday, January 13, 2012

Friday 1-13-12

Imports System
Imports System.Threading

Namespace Apress.VisualBasicRecipes.Chapter04

Class Recipe04_01
'a private class used to pass data to the Display Message
'method when it is executed using the thread pool
Private Class MessageInfo
Private m_Iterations As Integer
Private m_Message As String

'a constructor that takes configuration settings for the thread
Public Sub New(ByVal iterations As Integer, ByVal message As String)
m_Iterations = iterations
m_Message = message
End Sub

'properties to retrieve configuration settings
Public ReadOnly Property Iterations() As Integer
Get
Return m_Iterations
End Get
End Property

Public ReadOnly Property Message() As String
Get
Return m_Message
End Get
End Property

End Class


'a method that conforms to the System.Threading.WaitCallback delegate signature
'displays a message to the console
Public Shared Sub DisplayMessage(ByVal state As Object)
'Safely case the state argument to a messageinfo object
Dim config As MessageInfo = TryCast(state, MessageInfo)

'if the config argument is Nothing, no arguments were passed to the threadPool.QueueUserWorkItem method; use default values
If config Is Nothing Then
'display a fixed message to the console three times
For count As Integer = 1 To 3
Console.WriteLine("A thread pool example.")
'sleep for the purpose of demonstration avoid sleeping (of course) on thread-pool threads in real applications
Thread.Sleep(1000)
Next

Else
'display the specified message the specified number of times
For count As Integer = 1 To config.Iterations
Console.WriteLine(config.Message)
'seep for the purpose of demonstration, don't do this in real life lol
Thread.Sleep(1000)
Next
End If
End Sub


Public Shared Sub Main()
'execute DisplayMessage using the thread pool and no arguments
ThreadPool.QueueUserWorkItem(AddressOf DisplayMessage)

'create a MessageInfo object to pass to the DisplayMessage method
Dim info As New MessageInfo(5, "A thread pool example with arguments.")

'execute a DisplayMesage using the thread pool and providing an argument
ThreadPool.QueueUserWorkItem(AddressOf DisplayMessage, info)

Dim otherinfo As New MessageInfo(7, "Another example with arguments.")
ThreadPool.QueueUserWorkItem(AddressOf DisplayMessage, otherinfo)
'wait to continue
Console.WriteLine("Main method complete. Press Enter")
Console.ReadLine()
End Sub

End Class

End Namespace


using System.Numerics;

namespace CSharpPrac
{
class Program
{
static void Main(string[] args)
{
UseBigInteger();
BasicStringFunctionality();
StringConcatenation();
}

static void UseBigInteger()
{
Console.WriteLine("=> Use BigInteger:");
BigInteger biggy = BigInteger.Parse("999999999999999999999999999999999999999999999999999999999");
Console.WriteLine("Value of biggy is {0}", biggy);
Console.WriteLine("Is biggy an even value?: {0}", biggy.IsEven);
Console.WriteLine("Is biggy a power of two?: {0}", biggy.IsPowerOfTwo);
BigInteger reallyBig = BigInteger.Multiply(biggy, BigInteger.Parse("88888888888888888888888888888888888888888888888888888888888"));
Console.WriteLine("Value of reallyBig is {0}", reallyBig);
}

static void BasicStringFunctionality()
{
Console.WriteLine("=> Basic String functionality:");
string firstName = "Freddy";
Console.WriteLine("Value of firstName: {0}", firstName);
Console.WriteLine("firstName has {0} characters.", firstName.Length);
Console.WriteLine("firstName in uppercase: {0}", firstName.ToUpper());
Console.WriteLine("firstName in lowercase: {0}", firstName.ToLower());
Console.WriteLine("firstName contains the letter y?: {0}", firstName.Contains("y"));
Console.WriteLine("firstName after replace: {0}", firstName.Replace("dy", ""));
Console.WriteLine();
}

static void StringConcatenation()
{
Console.WriteLine("=> String concatentation:");
string s1 = "Programming the ";
string s2 = "PsychoDrill (PTP)";
string s3 = s1 + s2;
//string s3 = String.Concat(s1, s2);
Console.WriteLine(s3);
Console.WriteLine();
}
}
}



namespace CSharpStrings
{
class Program
{
static void Main(string[] args)
{
EscapeChars();
StringEquality();
StringsAreImmutable();
FunWithStringBuilder();
}

static void EscapeChars()
{
Console.WriteLine("=> Escape characters:\a");
string strWithTabs = "Model\tColor\tSpeed\tPet Name\a ";
Console.WriteLine(strWithTabs);

Console.WriteLine("Everyone loves \"Hello World\"\a ");
Console.WriteLine("C:\\MyApp\\bin\\Debug\a ");

//adds a total of 4 blank lines (then beep again!)
Console.WriteLine("All finished.\n\n\n\a ");
Console.WriteLine();
}

static void StringEquality()
{
Console.WriteLine("=> String equality:");
string s1 = "Hello!";
string s2 = "Yo!";
Console.WriteLine("s1 = {0}", s1);
Console.WriteLine("s2 = {0}", s2);
Console.WriteLine();

//test these strings for equality
Console.WriteLine("s1 == s2: {0}", s1 == s2);
Console.WriteLine("s1 == Hello!: {0}", s1 == "Hello!");
Console.WriteLine("s1 = HELLO!: {0}", s1 == "HELLO!");
Console.WriteLine("s1 == hello!: {0}", s1 == "hello!");
Console.WriteLine("s1.Equals(s2): {0}", s1.Equals(s2));
Console.WriteLine("Yo.Equals(s2): {0}", "Yo!".Equals(s2));
}

static void StringsAreImmutable()
{
//set initial string value
string s1 = "This is my string.";
Console.WriteLine("s1 = {0}", s1);

//uppercase s1?
string upperString = s1.ToUpper();
Console.WriteLine("upperString = {0}", upperString);

//nope! s1 is in the same format
Console.WriteLine("s1 = {0}", s1);
}

static void FunWithStringBuilder()
{
Console.WriteLine("=> Using the StringBuilder:");
StringBuilder sb = new StringBuilder("*** Fantastic games ****");
sb.Append("\n");
sb.AppendLine("Half Life");
sb.AppendLine("Beyond Good and Evil");
sb.AppendLine("Deus Ex 2");
sb.AppendLine("System Shock");
Console.WriteLine(sb.ToString());

sb.Replace("2", "Invisible War");
Console.WriteLine(sb.ToString());
Console.WriteLine("sb has {0} chars.", sb.Length);
Console.WriteLine();
}
}
}



class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Type Conversions *****");
//add two shorts and print the result
short numb1 = 9, numb2 = 10;
Console.WriteLine("{0} + {1} = {2}", numb1, numb2, Add(numb1, numb2));
Console.WriteLine();

numb1 = 30000;
numb2 = 30000;

//explicitly cast the int into a short (and allow loss of data)
short answer = (short)Add(numb1, numb2);

Console.WriteLine("{0} + {1} = {2}", numb1, numb2, answer);
NarrowingAttempt();
Console.ReadLine();
}

//widing is the term used to define an implicit upward cast that does not result in a loss of data
static int Add(int x, int y)
{
return x + y;
}

static void NarrowingAttempt()
{
byte myByte = 0;
int myInt = 200;

//explicitly cast the int into a byte (no loss of data)
myByte = (byte)myInt;
Console.WriteLine("Value of myByte: {0}", myByte);
}

static void ProcessBytes()
{
byte b1 = 100;
byte b2 = 250;

//this time tell the compiler to add CIL code to throw an exception if overflow /underflow
//takes place
try
{
byte sum = checked((byte)Add(b1, b2));
Console.WriteLine("sum = {0}", sum);

}
catch (OverflowException ex)
{
Console.WriteLine(ex.Message);
}
}
}



@autoreleasepool {
double value1, value2;
char operator;

Calculator *deskCalc = [[Calculator alloc] init];
NSLog(@"Type in your expression.");
scanf("%lf %c %lf", &value1, &operator, &value2);

[deskCalc setAccumulator: value1];

if (operator == '+')
[deskCalc add: value2];
else if (operator == '-')
[deskCalc subtract: value2];
else if (operator == '*')
[deskCalc multiply: value2];
else if (operator == '/')
if (value2 == 0)
NSLog(@"Division by zero.");
else
[deskCalc divide: value2];
else
NSLog(@"Unknown operator");

NSLog(@"%.2f", [deskCalc accumulator]);
}



@autoreleasepool {
double value1, value2;
char operator;

Calculator *deskCalc = [[Calculator alloc] init];

NSLog(@"Type in your expression.");
scanf("%lf %c %lf", &value1, &operator, &value2);

[deskCalc setAccumulator: value1];

switch (operator) {
case '+':
[deskCalc add: value2];
break;
case '-':
[deskCalc subtract: value2];
break;
case '*':
[deskCalc multiply: value2];
break;
case '/':
[deskCalc divide: value2];
break;
default:
NSLog(@"Unkown operator.");
break;
}
NSLog(@"%.2f", [deskCalc accumulator]);
}

@autoreleasepool {
int p, d, isPrime;

for (p = 2; p <= 200; ++p){
isPrime = 1;

for (d = 2; d < p; ++d){
if (p % d == 0)
isPrime = 0;

}
if (isPrime != 0)
NSLog(@"%i ", p);
}
}

Thursday, January 12, 2012

Thursday 1-12-12

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
Photo *photo1 = [[Photo alloc] init];
NSLog(@"photo1 caption: %@", photo1.caption);
NSLog(@"photo1 photographer: %@", photo1.photographer);

photo1.caption = @"Overlooking the Golden Gate Bridge";
photo1.photographer = @"(Your name here)";

NSLog(@"photo1 caption: %@", photo1.caption);
NSLog(@"photo1 photographer: %@", photo1.photographer);

[photo1 release];

Photo* photo2 = [Photo photo];

NSLog(@"photo2 caption: %@", photo2.caption);
NSLog(@"photo2 photographer: %@", photo2.photographer);

photo2.caption = @"Moffett Field";
photo2.photographer = @"(Your Name Here)";

NSLog(@"photo2 caption: %@", photo2.caption);
NSLog(@"photo2 photographer: %@", photo2.photographer);
}



#import

@interface Photo : NSObject
{
NSString *caption;
NSString *photographer;
}

+(Photo*) photo;

- (NSString*) caption;
- (NSString*) photographer;

- (void) setCaption: (NSString*)input;
- (void) setPhotographer: (NSString*)input;
@end




#import "Photo.h"

@implementation Photo
-(id) init {
if (self = [super init]){
[self setCaption:@"Default Caption"];
[self setPhotographer:@"Default Photographer"];
}
return self;
}

+ (Photo*) photo{
Photo* newPhoto = [[Photo alloc] init];
return [newPhoto autorelease];
}

-(NSString*) caption {
return caption;
}

-(NSString*) photographer {
return photographer;
}

- (void) setCaption: (NSString*) input {
[caption autorelease];
caption = [input retain];
}

-(void) setPhotographer: (NSString*)input {
[photographer autorelease];
photographer = [input retain];
}

- (void) dealloc {
[self setCaption:nil];
[self setPhotographer:nil];

[super dealloc];
}

@end




namespace NewBase
{


class Base
{
public virtual void DoSomethingVirtual()
{
Console.WriteLine("Base.DoSomethingVirtual");
}

public void DoSomethingNonVirtual()
{
Console.WriteLine("Base.DoSomethingNonVirtual");
}
}

class Derived : Base
{
public override void DoSomethingVirtual()
{
Console.WriteLine("Derived.DoSomethingVirtual");
}

public new void DoSomethingNonVirtual()
{
Console.WriteLine("Derived.DoSomethingNonVirtual");
}
}

class Program
{
static void Main(string[] args)
{
Console.WriteLine("Derived via Base reference:");

Base baseRef = new Derived();
baseRef.DoSomethingVirtual();
baseRef.DoSomethingNonVirtual();

Console.WriteLine();
Console.WriteLine("Derived via Derived reference:");

Derived derivedRef = new Derived();
derivedRef.DoSomethingVirtual();
derivedRef.DoSomethingNonVirtual();
}
}
}


namespace CA2
{
public struct Point
{
private Int32 _x;
private Int32 _y;

public Int32 X
{
get { return _x; }
set { _x = value; }
}

public Int32 Y
{
get { return _y; }
set { _y = value; }
}

public Point(int x, int y)
{
_x = x;
_y = y;
}


}

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


Point p2 = new Point();
p2.X = 15;
p2.Y = 23;
Console.WriteLine("{0} / {1}", p2.X, p2.Y);
}
}
}

Wednesday, January 11, 2012

Wednesday 1-11-12

#include

int main (int argc, const char * argv[])
{
int *numbers;
numbers = malloc(sizeof(int) *10);

//create a second variable to always point
//at the beginning of the same memory block
int *numbersStart = numbers;

*numbers = 100;
numbers++;
*numbers = 200;
printf("%i", *numbers);
numbers = numbersStart;
printf("%i", *numbers);
//use the numbersStart variable to free the memory instead
free(numbersStart);
}



int main (int argc, const char * argv[])
{
char *fullname;
asprintf(&fullname, "Albert Einstein");
printf("%s\n", fullname);
free(fullname);

int total = 81;
float ratio = 1.618;

//declare a string pointer and use asprintf() to
//format the string and reserve dynamic memory
char *result;
asprintf(&result, "total: %i, ratio: %f", total, ratio);

//display the 'result' string and free the memory
printf("%s \n", result);
free(result);
myFunction();

return 0;
}




typedef struct {
char *title;
int lengthInSeconds;
int yearRecorded;
} Song;

Song CreateSong(int length, int year);

void displaySong(Song theSong);

int main (int argc, const char * argv[])
{
Song song1;
song1.title = "Hey Jude";
song1.lengthInSeconds = 425;
song1.yearRecorded = 1968;

Song song2;
song2.title = "Let It Be";
song2.lengthInSeconds = 243;
song2.yearRecorded = 1970;

Song mySong1 = CreateSong(324, 2004);
displaySong(mySong1);
return 0;
}

Song CreateSong(int length, int year){
Song mySong;
mySong.lengthInSeconds = length;
mySong.yearRecorded = year;
return mySong;
}

void displaySong (Song theSong){
printf("The song is %i seconds long ", theSong.lengthInSeconds);
printf("and was recorded in %i.\n", theSong.yearRecorded);
}




#include

int main (int argc, const char * argv[])
{
int wholeNumbers[5] = {2, 3, 5, 7, 9};
int theSum = sum(wholeNumbers, 5);
printf("THe sum is: %i ", theSum);

float fractionalNumbers[3] = {16.9, 7.86, 3.4};
float theAverage = average(fractionalNumbers, 3);
printf("and the average is: %f \n", theAverage);
return 0;
}

int sum(int values[], int count)
{
int i;
int total = 0;

for(i = 0; i < count; i++)
{
//add each value in the array to the total
total = total + values[i];
}
return total;
}

float average(float values[], int count)
{
int i;
float total = 0.0;

for(i=0; i < count; i++)
{
//add each value in the array to the total
total = total + values[i];

}
//calculate the average
float average = (total / count);
return average;
}

Tuesday, January 10, 2012

Tuesday 1-10-12

@autoreleasepool {
int number_to_test, remainder;

NSLog(@"Enter your number to be tested: ");
scanf("%i", &number_to_test);

remainder = number_to_test % 2;

if (remainder == 0)
{
NSLog(@"The number is even.");
}
if (remainder != 0)
{
NSLog(@"The number is odd.");
}
}


@autoreleasepool {
int number_to_test, remainder;

NSLog(@"Enter your number to be tested:");
scanf("%i", &number_to_test);

remainder = number_to_test % 2;

if(remainder == 0)
NSLog(@"The number is even.");
else
NSLog(@"The number is odd.");
}

@autoreleasepool {
int year, rem_4, rem_100, rem_400;
NSLog(@"Enter the year to be tested: ");
scanf("%i", &year);

rem_4 = year % 4;
rem_100 = year % 100;
rem_400 = year % 400;

if ((rem_4 == 0 && rem_100 != 0) || rem_400 == 0)
NSLog(@"It's a leap year.");
else
NSLog(@"Nope, it's not a leap year.");
}

@autoreleasepool {
int number, sign;

NSLog(@"Please type in a number: ");
scanf("%i", &number);

if(number < 0)
sign = -1;
else if (number == 0)
sign = 0;
else //must be positive
sign = 1;
NSLog(@"Sign = %i", sign);

}

@autoreleasepool {
char c;
NSLog(@"Enter a single character:");
scanf(" %c", &c);

if((c>='a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
NSLog(@"It's an alphabetic characer.");
else if (c >= '0' && c <= '9')
NSLog(@"It's a digit");
else
NSLog(@"It's a special character.");

}


#import

@interface Calculator: NSObject
//accumulator methods
-(void) setAccumulator: (double) value;
-(void) clear;
-(double) accumulator;

//arithmetic methods
-(void) add: (double) value;
-(void) subtract: (double) value;
-(void) multiply: (double) value;
-(void) divide: (double) value;
@end

@implementation Calculator
{
double accumulator;
}
-(void) setAccumulator:(double) value
{
accumulator = value;
}

-(void) clear
{
accumulator = 0;
}

-(double) accumulator
{
return accumulator;
}

-(void) add: (double) value
{
accumulator += value;
}

-(void) subtract:(double) value
{
accumulator -= value;
}

-(void) multiply:(double) value
{
accumulator *= value;
}

-(void) divide:(double) value
{
accumulator /= value;
}
@end


int main (int argc, const char * argv[])
{

@autoreleasepool {
double value1, value2;
char operator;
Calculator *deskCalc = [[Calculator alloc] init];
NSLog(@"Type in your expression.");
scanf("%lf %c %lf", &value1, &operator, &value2);
[deskCalc setAccumulator: value1];
if (operator=='+')
[deskCalc add:value2];
else if (operator == '-')
[deskCalc subtract: value2];
else if (operator == '*')
[deskCalc multiply: value2];
else if (operator == '/')
[deskCalc divide: value2];

NSLog(@"%.2f", [deskCalc accumulator]);

}
return 0;
}


#include
int main(void)
{
int num;
num = 1;
printf("I am a simple ");
printf("computer.\n");
printf("My favorite number is %d because it is first.\n", num);

return 0;
}


class Program
{
static void Main(string[] args)
{
LocalVarDeclarations();
NewingDataTypes();
ObjectFunctionality();
DataTypeFunctionality();
BooleanFunctionality();
CharFunctionality();
}

static void LocalVarDeclarations()
{
Console.WriteLine("=> Data Declarations:");
//local variables are delcared and initialized as follows:
//dataType varName = initialValue;
int myInt = 0;

//You can also declare and assign on two lines
string myString;
myString = "This is my character data";
Console.WriteLine("{0}", myInt);
Console.WriteLine("{0}", myString);
Console.WriteLine();
}

static void NewingDataTypes()
{
Console.WriteLine("=> Using new to create variables:");
bool b = new bool();
int i = new int();
double d = new double();
DateTime dt = new DateTime();
Console.WriteLine("{0}, {1}, {2}, {3}", b, i, d, dt);
Console.WriteLine();
}

static void ObjectFunctionality()
{
Console.WriteLine("=> System.Object functionality:");
//a C# int is really a shorthand for System.Int32
//which inherits the following members from System.Object
Console.WriteLine("12.GetHashCode() = {0}", 12.GetHashCode());
Console.WriteLine("12.Equals(23) = {0}", 12.Equals(23));
Console.WriteLine("12.ToString() = {0}", 12.ToString());
Console.WriteLine("12.GetType() = {0}", 12.GetType());
Console.WriteLine();
}

static void DataTypeFunctionality()
{
Console.WriteLine("=> Data type Functionality: ");
Console.WriteLine("Max of int: {0}", int.MaxValue);
Console.WriteLine("Min of int: {0}", int.MinValue);
Console.WriteLine("Max of double: {0}", double.MaxValue);
Console.WriteLine("Min of double: {0}", double.MinValue);
Console.WriteLine("double.Epsilon: {0}", double.Epsilon);
Console.WriteLine("double.PositiveInfinity: {0}", double.PositiveInfinity);
Console.WriteLine("double.NegativeInfinity: {0}", double.NegativeInfinity);
Console.WriteLine();

}

static void BooleanFunctionality()
{
Console.WriteLine("bool.FalseString: {0}", bool.FalseString);
Console.WriteLine("bool.TrueString: {0}", bool.TrueString);
}

static void CharFunctionality()
{
Console.WriteLine("=> char type Functionality:");
char myChar = 'a';
Console.WriteLine("char.IsDigit('a'): {0}", char.IsDigit(myChar));
Console.WriteLine("char.IsLetter('a'): {0}", char.IsLetter(myChar));
Console.WriteLine("char.IsWhiteSpace('Hello There', 5): {0}", char.IsWhiteSpace("Hello There", 5));
Console.WriteLine("char.IsWhiteSpace('Hello There', 6): {0}", char.IsWhiteSpace("Hello There", 6));
Console.WriteLine("char.IsWhiteSpace('A Person', 0): {0}", char.IsWhiteSpace("A Person", 0));
Console.WriteLine("char.IsWhiteSpace('A Person'), 1): {0}", char.IsWhiteSpace("A Person", 1));
Console.WriteLine("char.IsPunctuation('?'): {0}", char.IsPunctuation('?'));
Console.WriteLine();
}
}

Monday, January 9, 2012

Monday 1-9-12

@interface Rectangle: NSObject
{
int w;
int h;
}

-(void) setWidth: (int) w;
-(void) setHeight: (int) h;
- (int) width;
- (int) height;
- (int) area;
- (int) perimeter;
@end

@implementation Rectangle


-(void) setWidth:(int)width
{
w = width;
}

-(void) setHeight:(int)height
{
h = height;
}

-(int) width
{
return w;
}

-(int) height
{
return h;
}

-(int) area
{
return w * h;
}

-(int) perimeter
{
return (2 * w) + (2 * h);
}

@end


int main (int argc, const char * argv[])
{

@autoreleasepool {
Rectangle *rec = [[Rectangle alloc] init];
[rec setWidth:11];
[rec setHeight: 12];
NSLog(@"The height is %i", [rec height]);
NSLog(@"The width is %i", [rec width]);
NSLog(@"The perimeter is %i", [rec perimeter]);
NSLog(@"THe area is %i", [rec area]);

}
return 0;
}

@autoreleasepool {

int n, triangularNumber;
triangularNumber = 0;

for (n = 1; n <= 200; n = n + 1)
triangularNumber += n;
NSLog(@"The 200th triangular number is %i", triangularNumber);

}


@autoreleasepool {
int n, triangularNumber;
NSLog(@"Table of triangular numbers");
NSLog(@" n Sum from 1 to n");
NSLog(@"-- ------");

triangularNumber = 0;

for(n = 1; n <=10; ++n)
{
triangularNumber += n;
NSLog(@" %i %i", n, triangularNumber);
}


@autoreleasepool {
int n, number, triangularNumber;

NSLog(@"What traingular number do you want?");
scanf("%i", &number);
triangularNumber = 0;
for(n=1;n<=number;++n)
triangularNumber += n;

NSLog(@"Triangular number %i is %i\n", number, triangularNumber);
}


@autoreleasepool {
int n, number, triangularNumber, counter;
for (counter = 1; counter <= 5; ++counter)
{
NSLOg(@"What triangular number do you want?");
scanf("%i", &number);
triangularNumber = 0;

for(n=1; n<=number; ++n)
triangularNumber += n;

NSLog(@"Triangular number %i is %i", number, triangularNumber);
}
}

@autoreleasepool {
int n, number, triangularNumber, counter;
for (counter = 1; counter <= 5; ++counter)
{
NSLog(@"What triangular number do you want?");
scanf("%i", &number);
triangularNumber = 0;

for(n=1; n<=number; ++n)
triangularNumber += n;

NSLog(@"Triangular number %i is %i", number, triangularNumber);
}
}




#include

//global variables. these are visible fromo any function.

int totalItems = 0;
float totalCost = 0.0;
float salesTax = 0.0925;

//declare the functions we're going to use
//we don't need to declare main() because it's built in.

void addToTotal (float cost, int quantity);
float costWithSalesTax(float price);

//this is where the program starts when it runs.

main(){
float budget = 10000.00;
//make a new line
printf("\n");

//set the prices of each item
float laptopPrice = 1799.00;
float monitorPrice = 499.80;
float phonePrice = 199.00;

//for each line item, call the addToTotal() function
//specifying the item and quantity

addToTotal(laptopPrice, 2);
addToTotal(monitorPrice, 1);
addToTotal(phonePrice, 4);

//display a line and then the final total
printf("----------------------\n");
printf("TOTAL for %i items: $%5.2f\n\n", totalItems, totalCost);

if(totalCost < budget)
{
printf("You came in under budget!\n\n");
} else
{
printf("You're over budget. Time to talk to finance.\n\n");
}
}

void addToTotal(float cost, int quantity){
printf("Adding %i items of cost $%4.2f\n", quantity, cost);
//find the cost for this item by multiple cost by quantity
//then get the real cost by applying sales tax
float calculatedCost = cost * quantity;
float realCost = costWithSalesTax(calculatedCost);

//add this amount to the total and increase the total number
//of items purchased
totalCost = totalCost + realCost;
totalItems = totalItems + quantity;

}


float costWithSalesTax(float price)
{
//remember 'salesTax' is a global variable
float taxAmount = price * salesTax;
float subtotal = price + taxAmount;

return subtotal;
}


Friday, January 6, 2012

Friday 1-6-12

objective C, using NSDate class

int main (int argc, const char * argv[])
{

@autoreleasepool {

NSDate *now = [[NSDate alloc] init];
NSLog(@"The date is %@", now);

double seconds = [now timeIntervalSince1970];
NSLog(@"It has been %f seconds since the start of 1970.", seconds);

NSDate *later = [now dateByAddingTimeInterval:10000];
NSLog(@"In 10,000 seconds it will be %@", later);

NSDate *evenLater = [now dateByAddingTimeInterval:100000];
NSLog(@"In 100,000 seconds it will be %@", evenLater);

NSCalendar *cal = [NSCalendar currentCalendar];
NSUInteger day = [cal ordinalityOfUnit:NSDayCalendarUnit
inUnit:NSMonthCalendarUnit
forDate:now];
NSLog(@"This is day %lu of the month", day);


}
return 0;
}