Thursday, August 18, 2011

Thursday 8.18.11


//modulus
#include
#define SEC_PER_MIN 60
int main(void)
{
int sec, min, left;

printf("Convert seconds to minutes and seconds!\n");
printf("Enter the number of seconds (<=0 to quit):\n");
scanf("%d", &sec);
while (sec>0)
{
min = sec / SEC_PER_MIN; //truncated number of minutes
left = sec % SEC_PER_MIN; //number of seconds left over
printf("%d seconds is %d minutes, %d seconds.\n", sec, min, left);
printf("Enter next value (<=0 to quit):\n");
scanf("%d", &sec);
}
printf("Done!\n");

return 0;
}





#include
int main(void)
{
int ultra = 0, super = 0;

while (super < 5)
{
super++;
++ultra;
printf("super = %d, ultra = %d \n", super, ultra);
}

return 0;
}





#include
int main(void)
{
int a = 1, b = 1;
int aplus, plusb;

aplus = a++;
plusb = ++b;
printf("a aplus b plusb \n");
printf("%1d %5d %5d %5d\n", a, aplus, b, plusb);

return 0;
}




#include
int main(void)
{
int count, sum; //declaration statement

count = 0; //assignment statement
sum = 0; //assignment statement
while (count++ < 20) //while statement (structured statement)
{
sum = sum + count;
printf("sum = %d\n", sum); //function statement
}
return 0

}




#include
int main(void)
{
char ch;
int i;
float f1;

f1 = i = ch = 'C';
printf("ch = %c, i = %d, f1 = %2.2f\n", ch, i, f1);
ch = ch + 1;
i = f1 + 2 * ch;
f1 = 2.0 * ch + i;
printf("ch = %c, i = %d, f1 = %2.2f\n", ch, i, f1);
ch = 5212205.17;
printf("Now ch = %c\n", ch);

return 0;
}




#include
void pound(int n);

int main(void)
{
int times = 5;
char ch = '!'; //ASCII code is 33
float f = 6.0;

pound(times); //int argument
pound(ch); //char automatically -> int
pound((int) f); //cast forces f -> int

return 0;
}

void pound(int n)
{
while (n-- > 0)
{
printf("#");
}
printf("\n");
}




#include
const int S_PER_M = 60;
const int S_PER_H = 3600;
const double M_PER_K = 0.62137;

int main(void)
{
double distk, distm; //distance run in km and in miles
double rate; //average speed in mph
int min, sec; // minutes and seconds of running time
int time; //running time in seconds only
double mtime; //time in seconds for one mile
int mmin, msec; //minutes and seconds for one mile

printf("This program converts your time for a metric race\n");
printf("to a time for running a mile and to your average\n");
printf("speed in miles per hour.\n");
printf("Please enter, in kilometeres, the distance run.\n");
scanf("%lf", &distk); //%lf for type double
printf("Next, enter the time in minutes and seconds.\n");
printf("Begin by entering the minutes.\n");
scanf("%d", &min);
printf("Now enter the seconds.\n");
scanf("%d", &sec);
//converts time to pure seconds
time = S_PER_M * min + sec;
//convers kilometers to miles
distm = M_PER_K * distk;
//miles per sec x sec per hour = mph
rate = distm / time * S_PER_H;
// time/distance - time per mile
mtime = (double) time / distm;
//using the cast operator
mmin = (int) mtime / S_PER_M; //find whole minutes
msec = (int) mtime % S_PER_M; //find remain seconds
printf("Your ran %1.2f km (%1.2f miles) in %d min, %d sec.\n", distk, distm, min, sec);
printf("That pace corresponds to running a mile in %d min, ", mmin);
printf("%d sec.\n Your average speed was %1.2f mph.\n", msec, rate);

return 0;
}




using System;
using System.Windows.Forms;

public class MainClass : System.Windows.Forms.Form
{
public MainClass()
{
Console.WriteLine("Company: " + Application.CompanyName);
Console.WriteLine("App Name: " + Application.ProductName);
Console.WriteLine("I live here: " + Application.StartupPath);
}
[STAThread]
static void Main()
{
Application.Run(new MainClass());
}
}




Imports System
Namespace InterfaceDemo
Interface IStorable
Sub Read()
Sub Write(ByVal obj As Object)
Property Status() As Integer
End Interface 'IStorable

'here's the new interface
Interface ICompressible
Sub Compress()
Sub Decompress()
End Interface 'ICompressible

'Document implements both interfaces
Public Class Document
Implements ICompressible, IStorable

'hold teh data for IStorable's Status property
Private myStatus As Integer = 0

'the Document constructor
Public Sub New(ByVal s As String)
Console.WriteLine("Creating document with: {0}", s)
End Sub 'new

Public Sub Compress() Implements ICompressible.Compress
Console.WriteLine("Implementing Compress")
End Sub

Public Sub Decompress() Implements ICompressible.Decompress
Console.WriteLine("Implementing Decompress")
End Sub

Public Sub Read() Implements IStorable.Read
Console.WriteLine("Implementing the Read Method for IStorable")
End Sub

Public Property Status As Integer Implements IStorable.Status
Get
Return myStatus
End Get
Set(ByVal value As Integer)
myStatus = value
End Set
End Property

Public Sub Write(ByVal obj As Object) Implements IStorable.Write
Console.WriteLine("Implementing the Write Method for IStorable")
End Sub
End Class

Class Tester
Public Sub Run()
Dim doc As New Document("Test Document")
doc.Status = -1
doc.Read()
doc.Compress()
Console.WriteLine("Document Status: {0}", doc.Status)
End Sub 'Run

Shared Sub Main()
Dim t As New Tester()
t.Run()
End Sub 'Main
End Class 'Tester

End Namespace




Imports System
Namespace InterfaceDemo
Interface IStorable
Sub Read()
Sub Write(ByVal obj As Object)
Property Status() As Integer
End Interface 'IStorable

'the compressible interface is now the base for ICompressible2
Interface ICompressible
Sub Compress()
Sub Decompress()
End Interface 'ICompressible

'extend ICompressible to log the bytes saved
Interface ICompressible2
Inherits ICompressible
Sub LogSavedBytes()
End Interface 'ICompressible2


'Document implements both interfaces
Public Class Document
Implements ICompressible2, IStorable

Public Sub New(ByVal s As String)
Console.WriteLine("Creating document with: {0}", s)
End Sub 'New

Public Sub LogSavedBytes() Implements ICompressible2.LogSavedBytes
Console.WriteLine("Implementing LogSavedBytes")
End Sub


Public Sub Decompress() Implements ICompressible2.Decompress
Console.WriteLine("Implementing decompress for ICompresible")
End Sub

Public Sub Compress() Implements ICompressible2.Compress
Console.WriteLine("Implementing compress for ICompressible")
End Sub


Public Sub Read() Implements IStorable.Read
Console.WriteLine("Implementing the Read Method for IStorable")
End Sub

Public Property Status As Integer Implements IStorable.Status
Get
Return myStatus
End Get
Set(ByVal value As Integer)
myStatus = value
End Set

End Property

Public Sub Write(ByVal obj As Object) Implements IStorable.Write
Console.WriteLine("Implementing the Write Method for IStorable")
End Sub

Private myStatus As Integer = 0

End Class

Class Tester
Public Sub Run()
Dim doc As New Document("Test Document")
If TypeOf doc Is IStorable Then
Dim isDoc As IStorable = doc
isDoc.Read()
Else
Console.WriteLine("Could not cast to IStorable")
End If

If TypeOf doc Is ICompressible2 Then
Dim ilDoc As ICompressible2 = doc
Console.Write("Calling both ICOmpressible And ")
Console.WriteLine("ICompressible2 methods...")
ilDoc.Compress()
ilDoc.LogSavedBytes()
Else
Console.WriteLine("Could not cast to ICompressible2")
End If
End Sub

Shared Sub Main()
Dim t As New Tester()
t.Run()
End Sub 'Main

End Class
End Namespace




Imports System
Imports System.Text

Namespace Apress.VisualBasicRecipes.Chapter02

Public Class Recipe02_01

Public Shared Function ReverseString(ByVal str As String) As String

'Make sure we have a reversible string.
If str Is Nothing Or str.Length <= 1 Then
Return str
End If

'create a stringBuilder object with the required capacity.
Dim revStr As StringBuilder = New StringBuilder(str.Length)

'Convert the string to a character array so we can easily loop through it
Dim chars As Char() = str.ToCharArray()

'Loop backward through the soruce string one character ata time
'and append each characer to the StringBuilder
For count As Integer = chars.Length - 1 To 0 Step -1
revStr.Append(chars(count))
Next

Return revStr.ToString()

End Function

Public Shared Sub Main()
Console.WriteLine(ReverseString("Madam Im Adam"))

Console.WriteLine(ReverseString("The quick brown fox jumped over the lazy dog."))

'wait to continue
Console.WriteLine(vbCrLf & "Main method complete. Press Enter.")
Console.ReadLine()
End Sub


End Class

End Namespace




Imports System
Imports System.IO
Imports System.Text.Encoding

Namespace Apress.VisualBasicRecipes.Chapter02

Public Class Recipe02_02

Public Shared Sub Main()

'Create a file to hold the output.
Using output As New StreamWriter("C:\inetpub\output.txt")
'Create and Write a string containing the symbol for pi.
Dim srcString As String = String.Format("Area = {0}r^2", ChrW(&H3A0))
output.WriteLine("Source Text: " & srcString)

'write the UTF-15 encoded bytes of the source string.
Dim utf16String As Byte() = Unicode.GetBytes(srcString)
output.WriteLine("UTF-16 Bytes: {0}", BitConverter.ToString(utf16String))

'Convert the UTF-15 encoded source string to UTF-8 and ASCII
Dim utf8String As Byte() = UTF8.GetBytes(srcString)
Dim asciiString As Byte() = ASCII.GetBytes(srcString)

'write teh UTF-8 and ASCII encoded byte arrays.
output.WriteLine("UTF-8 Bytes: {0}", BitConverter.ToString(utf8String))
output.WriteLine("ASCII Bytes: {0}", BitConverter.ToString(asciiString))

'Convert UTF-8 and ASCII encoded bytes back to UTF-16 encoded string
'and write to the output file
output.WriteLine("UTF-8 Text: {0}", UTF8.GetString(utf8String))
output.WriteLine("ASCII Text: {0}", ASCII.GetString(asciiString))

End Using

'Wait to continue
Console.WriteLine(vbCrLf & "Main method complete. Press enter.")
Console.ReadLine()

End Sub
End Class
End Namespace





Imports System
Imports System.IO

Namespace Apress.VisualBasicRecipes.Chapter02

Public Class Recipe02_03
Public Shared Function DecimalToByteArray(ByVal src As Decimal) As Byte()
'Create a MemoryStream as a buffer to holdthe binary data.
Using Stream As New MemoryStream
'Create a BinaryWriter to write binary data to the stream
Using writer As New BinaryWriter(Stream)
'write the decimal to the BinaryWriter/MemoryStream.
writer.Write(src)

'return the byte representation of the decimal.
Return Stream.ToArray
End Using
End Using

End Function

'create a decimal from a byte array.
Public Shared Function ByteArrayToDecimal(ByVal src As Byte()) As Decimal
'create a MemoryStream containing the byte array.
Using Stream As New MemoryStream(src)
'create a binaryReader to read the decimal from teh stream.
Using reader As New BinaryReader(Stream)
'read and return the decimal from teh BinaryReader/MemoryStream.
Return reader.ReadDecimal
End Using
End Using
End Function

Public Shared Sub Main()

Dim b As Byte() = Nothing

' Convert a boolean to a byte array and display.
b = BitConverter.GetBytes(True)
Console.WriteLine(BitConverter.ToString(b))

' Convert a byte array to a boolean and display
Console.WriteLine(BitConverter.ToBoolean(b, 0))

'convert an interger to a byte array and display
b = BitConverter.GetBytes(3678)
Console.WriteLine(BitConverter.ToString(b))

'convert a byte array to integer and display
Console.WriteLine(BitConverter.ToInt32(b, 0))

'convert a decimal to a byte array and display
b = DecimalToByteArray(28599834554.563846696D)
Console.WriteLine(BitConverter.ToString(b))

'convert a byte array to a decimal and display
Console.WriteLine(ByteArrayToDecimal(b))

'Wait to continue
Console.WriteLine(vbCrLf & "Main method complete. Press Enter.")
Console.ReadLine()

End Sub

End Class

End Namespace




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

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//remove a substring from a string
string name = "Doe, John";
Console.WriteLine(name);
name = name.Remove(3, 1);
Console.WriteLine(name);

string name2 = "Johnson, Don";
Console.WriteLine(name2);
name2 = name2.Remove(7, 5);
Console.WriteLine(name2);

//if performance is critical, and particularly if the string removal operation occurs in a loop
//so that the operation is performed multiple times, you can instead use the Remove method of the
//stringbuilder object

StringBuilder str = new StringBuilder("1234abc5678", 12);
str.Remove(4, 3);
Console.WriteLine(str);

//to replace a delimiting character within a string, use the following code

string commaDelimitedString = "100,200,300,400,500";
Console.WriteLine(commaDelimitedString);
commaDelimitedString = commaDelimitedString.Replace(',', ':');
Console.WriteLine(commaDelimitedString);
commaDelimitedString = commaDelimitedString.Replace(':', '-');
Console.WriteLine(commaDelimitedString);

string theName = "Mary";
string theObject = "car";
string ID = "This is the property of .";
ID = ID.Replace("", theObject);
ID = ID.Replace("", theName);
Console.WriteLine(ID);


}
}
}

No comments: