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;
using System.Threading;
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( "" );
Console.WriteLine( "Press esc to exit." );
while ( !keyPressHandler( Console.ReadKey( true ) ) )
{
Thread.Sleep( 250 );
/* no op */
}
}
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 ] + " " );
}
}
protected static Boolean keyPressHandler( ConsoleKeyInfo input )
{
if ( input.Key == ConsoleKey.Escape )
return true;
return false;
}
}
}
posted by dharh 12:47 AM Nov 29th, 2009