|
8. Open a text file and convert it into HTML file. (File operations/Strings)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace lrn2csharp8
{
class Program
{
static void Main( string[ ] args )
{
string file = "";
string html = "<html><head><title></title></head><body>{0}</body></htm>";
string textFile = "";
Console.WriteLine( "Input name of a file in the current directory to convert into an HTML document." );
Console.Write( ":" );
try
{
file = Console.ReadLine( );
FileStream fs = new FileStream( file, FileMode.Open, FileAccess.Read );
StreamReader sr = new StreamReader( fs );
while(!sr.EndOfStream)
{
string line = sr.ReadLine( );
if ( line.Length != 0 )
textFile += "<p>" + line + "</p>";
}
sr.Close( );
StreamWriter sw = new StreamWriter( fs.Name + ".html" );
sw.Write( string.Format( html, textFile ) );
sw.Close( );
}
catch ( Exception e )
{
Console.WriteLine( "WTF?!?" );
}
}
}
}
posted by dharh 2:14 AM Jan 30th
7. Printing output in different formats (say rounding up to 5 decimal places, truncating after 4 decimal places, padding zeros to the right and left, right and left justification)(Input output operations)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace lrn2csharp7
{
class Program
{
static void Main( string[ ] args )
{
double theNumber;
Console.WriteLine( "Input a number to be formatted" );
Console.Write( ":" );
try
{
theNumber = Convert.ToDouble( Console.ReadLine( ) );
Console.WriteLine( "Original number: {0}", theNumber );
Console.WriteLine( "Rounded up to the 5th decimal place: {0}", Math.Round( theNumber, 5 ) );
Console.WriteLine( "Truncating after the 4th decimal place: {0}", Decimal.Truncate( Convert.ToDecimal( theNumber * 10000 ) ) / 10000 );
Console.WriteLine( "Padding 7 zeroes on each side: {0}", String.Format( "{0:0000000.0000000}", theNumber ) );
Console.WriteLine( "Here is a box with 20 spaces: | |" );
Console.WriteLine( "Here is the number left justified: |{0,-20}|", theNumber );
Console.WriteLine( "Here is the number right justified: |{0,20}|", theNumber );
}
catch ( FormatException fe )
{
Console.WriteLine( "You did not enter a valid number fool." );
}
}
}
}
posted by dharh 9:56 PM Dec 5th
6. Scientific calculator supporting addition, subtraction, multiplication, division, square-root, square, cube, sin, cos, tan, Factorial, inverse, modulus
This is a fairly simple implementation of a console calculator. It only takes 2 number expressions ( ex: 1 + 1 ) as well as / commands for most other functions, except factorial ( n! ). Very little error checking is being done. All sorts of invalid inputs will cause this to throw exceptions. using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace lrn2csharp6_console
{
class Program
{
private static String Version = "0.0";
static void Main( string[ ] args )
{
Console.WriteLine( "neSP: Calc v" + Version );
Console.WriteLine( "---------------------------------" );
Console.WriteLine( "Enter Command. ( example: /help )" );
int end = 0;
while ( end == 0 )
{
String exp = "";
Console.Write( ":" );
try
{
exp = Console.ReadLine( );
}
catch ( InvalidOperationException )
{
Console.WriteLine( "Not a valid command." );
exp = "";
}
if ( exp.Length == 0 )
{
// empty command
}
else if ( exp.ToCharArray( ).First( ) == '/' )
{
if ( exp.Split( ' ' ).ToString( )[ 0 ].Equals( "/help" ) )
{
Console.WriteLine( "You are being helped:" );
Console.WriteLine( "/help - bring up this help system." );
Console.WriteLine( "/quit or /q - quit program." );
Console.WriteLine( "/prime n - generate prime numbers from 2 to n." );
Console.WriteLine( "/factor numerator/denominator - factors fraction." );
Console.WriteLine( "/sqrt n - finds the square root of n." );
Console.WriteLine( "/cbrt n - finds the cube root of n." );
Console.WriteLine( "/sin n - finds sine of n." );
Console.WriteLine( "/cos n - finds cosine of n." );
Console.WriteLine( "/tan n - finds tangent of n." );
Console.WriteLine( "/inv numerator/denominator - finds inverse of fraction." );
Console.WriteLine( "n! - finds factorial of n." );
}
else if ( exp.Split( ' ' )[ 0 ].Equals( "/quit" ) || exp.Split( ' ' )[ 0 ].Equals( "/q" ) )
{
end = 1;
}
else if ( exp.Split( ' ' )[ 0 ].Equals( "/primes" ) )
{
Console.Write( "primes:" );
prime( Convert.ToInt32( exp.Split( ' ' )[ 1 ] ) );
Console.WriteLine( );
}
else if ( exp.Split( ' ' )[ 0 ].Equals( "/factor" ) )
{
}
else if ( exp.Split( ' ' )[ 0 ].Equals( "/sqrt" ) )
{
Console.WriteLine( Math.Sqrt( Convert.ToDouble( exp.Split( ' ' )[ 1 ] ) ) );
}
else if ( exp.Split( ' ' )[ 0 ].Equals( "/cbrt" ) )
{
double power = 1.0 / 3.0;
Console.WriteLine( Math.Pow( Convert.ToDouble( exp.Split( ' ' )[ 1 ] ), power ) );
}
else if ( exp.Split( ' ' )[ 0 ].Equals( "/sin" ) )
{
Console.WriteLine( Math.Sin( Convert.ToDouble( exp.Split( ' ' )[ 1 ] ) ) );
}
else if ( exp.Split( ' ' )[ 0 ].Equals( "/cos" ) )
{
Console.WriteLine( Math.Cos( Convert.ToDouble( exp.Split( ' ' )[ 1 ] ) ) );
}
else if ( exp.Split( ' ' )[ 0 ].Equals( "/tan" ) )
{
Console.WriteLine( Math.Tan( Convert.ToDouble( exp.Split( ' ' )[ 1 ] ) ) );
}
else if ( exp.Split( ' ' )[ 0 ].Equals( "/inv" ) )
{
String fraction = exp.Replace( "/inv ", "" );
double numer = Convert.ToDouble( fraction.Split( '/' )[ 0 ] );
double denom = Convert.ToDouble( fraction.Split( '/' )[ 1 ] );
Console.WriteLine( denom / numer );
}
else
{
Console.WriteLine( "Invalid command ( " + exp + " ) supplied." );
}
}
else if ( exp.Contains( '!' ) )
{
int f = Convert.ToInt32( exp.Split( '!' )[ 0 ] );
Console.WriteLine( f );
int total = 1;
for ( int i = 0; i < f; i++ )
{
total = total * ( i + 1 );
}
Console.WriteLine( total );
}
else
{
calc( exp );
}
}
}
static void calc( String expression )
{
String[ ] stack = expression.Split( ' ' );
Console.WriteLine( doCalc( Convert.ToDouble( stack[ 0 ] ), Convert.ToChar( stack[ 1 ] ), Convert.ToDouble( stack[ 2 ] ) ) );
}
static double doCalc( double left, char theOperator, double right )
{
double total = 0.0;
if ( theOperator == '+' )
{
total = add( left, right );
}
else if ( theOperator == '-' )
{
total = subtract( left, right );
}
else if ( theOperator == '*' )
{
total = multiply( left, right );
}
else if ( theOperator == '/' )
{
total = divide( left, right );
}
else if ( theOperator == '^' )
{
total = Math.Pow( left, right );
}
else if ( theOperator == '%' )
{
total = mod( Convert.ToInt32( left ), Convert.ToInt32( right ) );
}
return total;
}
static double add( double num, double num2 )
{
return ( num + num2 );
}
static double subtract( double num, double num2 )
{
return ( num - num2 );
}
static double multiply( double num, double num2 )
{
return ( num * num2 );
}
static double divide( double num, double num2 )
{
if ( num2 == 0 )
{
Console.WriteLine( "ERROR: Division by zero." );
return num;
}
else
{
return ( num / num2 );
}
}
static int mod( int num, int num2 )
{
return ( num % num2 );
}
static void prime( int num )
{
int count = 0;
for ( int _i = 2; _i < num; _i++ )
{
if ( !isPrime( _i ) )
{
if ( ( count % 10 ) == 0 ) Console.WriteLine( );
Console.Write( " {0,6}", _i );
count++;
}
}
}
static bool isPrime( int num )
{
bool notPrime = false;
for ( int k = num - 1; k > 1 && !notPrime; k-- )
{
if ( num % k == 0 ) notPrime = true;
}
return notPrime;
}
}
}
posted by dharh 8:46 PM Nov 29th
4. Reynolds number is calculated using formula (D*v*rho)/mu Where D = Diameter, V= velocity, rho = density mu = viscosity Write a program that will accept all values in appropriate units (Don't worry about unit conversion) If number is < 2100, display Laminar flow, If it's between 2100 and 4000 display 'Transient flow' and if more than '4000', display 'Turbulent Flow' (If, else, then...)
5. Modify the above program such that it will ask for 'Do you want to calculate again (y/n), if you say 'y', it'll again ask the parameters. If 'n', it'll exit. (Do while loop) While running the program give value mu = 0. See what happens. Does it give 'DIVIDE BY ZERO' error? Does it give 'Segmentation fault..core dump?'. How to handle this situation. Is there something built in the language itself? (Exception Handling) using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace lrn2csharp4_5
{
class Program
{
static void Main( string[ ] args )
{
char answer = 'y';
Console.WriteLine( "Today we are going to calculate Reynolds Number (D*v*rho)/mu" );
while ( answer.Equals( 'y' ) )
{
try
{
calcReynolds( );
}
catch ( System.DivideByZeroException dbze )
{
Console.WriteLine( dbze.Message );
}
Console.Write( "Do you want to calculate again (y/n): " );
try
{
answer = Convert.ToChar( Console.ReadLine( ) );
}
catch ( System.FormatException )
{
answer = 'n';
}
}
}
static void calcReynolds( )
{
Console.Write( "Enter Diameter: " );
double d = Convert.ToDouble( Console.ReadLine( ) );
Console.Write( "Enter Velocity: " );
double v = Convert.ToDouble( Console.ReadLine( ) );
Console.Write( "Enter Density: " );
double rho = Convert.ToDouble( Console.ReadLine( ) );
Console.Write( "Enter Viscosity: " );
double mu = Convert.ToDouble( Console.ReadLine( ) );
// C# actually handles divide by zero well and wont throw an exception automatically, so do it manually
if ( mu.Equals( 0 ) )
throw new System.DivideByZeroException( "Cannot divide by zero. Viscosity was zero. You erred." );
double reynolds = ( d * v * rho ) / mu;
if ( reynolds < 2100 )
Console.WriteLine( "Laminar flow (" + reynolds + ")" );
else if ( reynolds >= 2100 && reynolds <= 4000 )
Console.WriteLine( "Transient flow (" + reynolds + ")" );
else
Console.WriteLine( "Turbulent flow (" + reynolds + ")" );
}
}
}
posted by dharh 3:01 AM Nov 29th
3. Accepting series of numbers, strings from keyboard and sorting them ascending, descending order.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace lrn2csharp3
{
class Program
{
static void Main( string[ ] args )
{
Console.Write( "Please enter the number of items you wish to enter: " );
int num_item = Convert.ToInt32( Console.ReadLine( ) );
int[ ] nums = new int[ num_item ];
for ( int i = 0; i < num_item; i++ )
{
Console.Write( "Item " + i + ": " );
nums[ i ] = Convert.ToInt32( Console.ReadLine( ) );
}
qsort( nums );
foreach ( int num in nums ) Console.Write( num.ToString( ) + " " );
Console.WriteLine( "" );
nums = reverse( nums );
foreach ( int num in nums ) Console.Write( num.ToString( ) + " " );
Console.WriteLine( "" );
}
static void swap<T>( ref T lhs, ref T rhs )
{
T temp;
temp = lhs;
lhs = rhs;
rhs = temp;
}
static void qsort( int[ ] nums )
{
qs( nums, 0, nums.Length - 1 );
}
static void qs( int[ ] items, int left, int right )
{
int i, j;
int x;
i = left;
j = right;
x = items[ ( left + right ) / 2 ];
do
{
while ( ( items[ i ] < x ) && ( i < right ) ) i++;
while ( ( x < items[ j ] ) && ( j > left ) ) j--;
if ( i <= j )
{
swap<int>( ref items[ i ], ref items[ j ] );
i++;
j--;
}
} while ( i <= j );
if ( left < j ) qs( items, left, j );
if ( i < right ) qs( items, i, right );
}
static int[ ] reverse( int[ ] items )
{
int[ ] reversed = new int[ items.Length ];
int j = 0;
for ( int i = items.Length - 1; i >= 0; i-- )
{
reversed[ j ] = items[ i ];
j++;
}
return reversed;
}
}
}
posted by dharh 1:40 AM Nov 29th
2. Fibonacci series, swapping two variables, finding maximum/minimum among a list of numbers.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace lrn2csharp2
{
class Program
{
static void Main( string[ ] args )
{
int fibs = 21;
int[ ] fib_series = new int[ fibs ];
Console.WriteLine( "Outputing Fib 0 through " + fibs );
for ( int i = 0; i < fib_series.Length; i++ )
{
fib_series[ i ] = fibonacci( i );
}
printArray( fib_series );
Console.WriteLine( "" );
Console.WriteLine( "Max in Fib Series: " + max( fib_series ) );
Console.WriteLine( "Min in Fib Series: " + min( fib_series ) );
Console.WriteLine( "Swapping front with end: " );
swap<int>( ref fib_series[ 0 ], ref fib_series[ fib_series.Length - 1 ] );
printArray( fib_series );
Console.WriteLine( "" );
}
static void swap<T>( ref T lhs, ref T rhs )
{
T temp;
temp = lhs;
lhs = rhs;
rhs = temp;
}
public static int fibonacci( int n )
{
if ( n <= 1 )
{
return n;
}
else
{
return fibonacci( n - 1 ) + fibonacci( n - 2 );
}
}
public static int max( int[ ] n )
{
int max = n[ 0 ];
for ( int _i = 0; _i < n.Length; _i++ )
{
if ( n[ _i ] > max ) max = n[ _i ];
}
return max;
}
public static int min( int[ ] n )
{
int min = n[ 0 ];
for ( int _i = 0; _i < n.Length; _i++ )
{
if ( n[ _i ] < min ) min = n[ _i ];
}
return min;
}
public static void printArray( int[ ] n )
{
for ( int _i = 0; _i < n.Length; _i++ )
{
Console.Write( n[ _i ] + " " );
}
}
}
}
posted by dharh 12:47 AM Nov 29th
1. Display series of numbers (1,2,3,4, 5....etc) in an infinite loop. The program should quit if someone hits a specific key (Say ESCAPE key).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace lrn2CSharp1
{
class Program
{
static void Main( string[ ] args )
{
for ( int i = 0; ; i++ )
{
if ( Console.KeyAvailable && keyPressHandler( Console.ReadKey( true ) ) ) break;
Console.Write( i + " " );
Thread.Sleep( 250 );
}
}
protected static Boolean keyPressHandler( ConsoleKeyInfo input )
{
if ( input.Key == ConsoleKey.Escape ) return true;
return false;
}
}
}
posted by dharh 7:13 PM Feb 10th, 2008
« Previous 1 Next »
|
airships america attention batteries blogs books browser c++ computers copyright CSharp dharh disaster DIY DRM drugs economy energy environment FCC gaming government history HTML humor idt internet interview java javascript linkjack linux MLP moving music nature neThing neTodo networking news opensource philosophy podcasts politics poverty programming projects radio religion science sick simple software space sparce tagging technology twitter unbirthday video wiki
|

- a little order in the chaos where the mind dwells



