numbers and csharp progs.docx

35
C# Fibonacci Sequence Fibonacci numbers are a fascinating sequence. This sequence models and predicts financial markets and natural phenomena. We can compute Fibonacci numbers with recursion. This can be slow. It is also possible to use iteration. Example First, this is an iterative method. Conceptually, an iterative Fibonacci method stores the result of the previous Fibonacci number before computing the next

Upload: rameshctlatp

Post on 02-Oct-2015

222 views

Category:

Documents


0 download

TRANSCRIPT

C# Fibonacci Sequence

Fibonaccinumbers are a fascinating sequence. This sequence models and predicts financial markets and natural phenomena. We can compute Fibonacci numbers with recursion. This can be slow. It is also possible to use iteration.Example

First, this is an iterative method. Conceptually, an iterative Fibonacci method stores the result of the previous Fibonacci number before computing the next one. This reduces the time required.Note:To compute a Fibonacci number at a certain position N, we have to loop through all previous numbers starting at position 0.ForBased on:

.NET 4.5

C# program that computes Fibonacci iteratively

using System;

class Program{ public static int Fibonacci(int n) {int a = 0;int b = 1;// In N steps compute Fibonacci sequence iteratively.for (int i = 0; i < n; i++){ int temp = a; a = b; b = temp + b;}return a; }

static void Main() {for (int i = 0; i < 15; i++){ Console.WriteLine(Fibonacci(i));} }}

Output

01123581321345589144233377

If you just wantto list Fibonacci numbers, you could change Fibonacci() to simply use Console.WriteLine(a). This would make the method print out each number as it is computed, which would reduce the total amount of computation required.But:The time spent printing to the Console would dominate the program's real-world runtime.Console.WriteLineOverflow

One problem with this implementation is that the int types will overflow past the 47th Fibonacci number. To solve this problem, you can change Fibonacci() to return double. Also change a, b, and temp to be of type double.IntDoubleDiscussion

The Fibonacci sequence begins with zero. Fibonacci himself, in 1202, began it with 1, but modern scientists just use his name, not his version of the sequence. I tested the output of the program and it is correct.Fibonacci began the sequence not with 0, 1, 1, 2, as modern mathematicians do but with 1, 1, 2.Fibonacci: WikipediaSummary

Fibonacci numbers don't just reveal some interesting aspects of the world. They also teach us about computer programming. By storing the previous value in a loop iteration, we avoid a tremendous amount of computational work.And:In the rare cases where Fibonacci numbers are critical, an iterative solution dramatically improves software.

An other style of the same program01namespacefabi

02{

03classfab

04{

05publicstaticintfibonacci(intn)

06{

07intprevious = -1;

08intnext = 1;

09for(inti = 0; i < n; i++)

10{

11intsum = next + previous;

12previous = next;

13next = sum;

14Console.WriteLine(next);

15}

16returnnext;

17}

18

19

20staticvoidMain(string[] a)

21{

22intnum;

23Console.WriteLine("Enter a number:");

24num = Convert.ToInt32(Console.ReadLine());

25Console.WriteLine("\n");

26Console.WriteLine("The first "+ num +" number(s) in the fibonacci series are: ");

27fibonacci(num);

28

29Console.Read();

30}

31}

32}

Non Recursion

01// non recursion

02voidShowNumsLoopy(intn) {

03for(inti = 0; i < n; i++) {

04Console.WriteLine(i);

05}

06}

07

08// recursion

09// in recursion, there's usually some kind of setup before the thing gets started.

10voidShowNumsRecusion(intn) {

11ShowNumsRecusion(n, 0);

12}

13// the work is here

14voidShowNumsRecusion(intn,inti) {

15if(i < n) {

16Console.WriteLine(i);

17ShowNumsRecusion(n, i - 1);

18}

19}

A more elegant example was this:

1voidShowNumsRecusion(intn) {

2if(n max) {return true; } char a = value[min]; char b = value[max]; if (char.ToLower(a) != char.ToLower(b)) {return false; } min++; max--;} }

static void Main() {string[] array ={ "civic", "deified", "deleveled", "devoved", "dewed", "Hannah", "kayak", "level", "madam", "racecar", "radar", "redder", "refer", "repaper", "reviver", "rotator", "rotor", "sagas", "solos", "sexes", "stats", "tenet",

"Dot", "Net", "Perls", "Is", "Not", "A", "Palindrome", ""};

foreach (string value in array){ Console.WriteLine("{0} = {1}", value, IsPalindrome(value));} }}

Output

civic = Truedeified = Truedeleveled = Truedevoved = Truedewed = TrueHannah = Truekayak = Truelevel = Truemadam = Trueracecar = Trueradar = Trueredder = Truerefer = Truerepaper = Truereviver = Truerotator = Truerotor = Truesagas = Truesolos = Truesexes = Truestats = Truetenet = TrueDot = FalseNet = FalsePerls = FalseIs = FalseNot = FalseA = TruePalindrome = False = True

The IsPalindrome methodis case-insensitive. Instead of converting the input string with ToLower, which would require an allocation, we check the lowercased versions of all the characters. This makes it faster.Tip:If your input strings are always lowercase, it would be better to remove the char.ToLower transformations.char.ToLowerAlso,the method throws an exception if the parameter string is null. If the parameter string is empty, it will consider that a palindrome. This is correct by the definition of palindrome specified by the method.Null StringsExceptionSentences

This program is the same as the simpler palindrome method except for some small changes. The important change is inside IsPalindrome. There are two additional while-loops. These loops have additional logic.WhileIf either charis determined to be a non-letter non-digit character, we begin skipping forward or backward to one that should be checked. This means that punctuation and spaces do not affect the palindromicity of a phrase.char.IsLetterOrDigitC# program that checks for palindromic sentences

using System;

class Program{ /// /// Determines whether the string is a palindrome. /// public static bool IsPalindrome(string value) {int min = 0;int max = value.Length - 1;while (true){ if (min > max) {return true; } char a = value[min]; char b = value[max];

// Scan forward for a while invalid. while (!char.IsLetterOrDigit(a)) {min++;if (min > max){ return true;}a = value[min]; }

// Scan backward for b while invalid. while (!char.IsLetterOrDigit(b)) {max--;if (min > max){ return true;}b = value[max]; }

if (char.ToLower(a) != char.ToLower(b)) {return false; } min++; max--;} }

static void Main() {string[] array ={ "A man, a plan, a canal: Panama.", "A Toyota. Race fast, safe car. A Toyota.", "Cigar? Toss it in a can. It is so tragic.", "Dammit, I'm mad!", "Delia saw I was ailed.", "Desserts, I stressed!", "Draw, O coward!", "Lepers repel.", "Live not on evil.", "Lonely Tylenol.", "Murder for a jar of red rum.", "Never odd or even.", "No lemon, no melon.", "Senile felines.", "So many dynamos!", "Step on no pets.", "Was it a car or a cat I saw?",

"Dot Net Perls is not a palindrome.", "Why are you reading this?", "This article is not useful.", "...", "...Test"};

foreach (string value in array){ Console.WriteLine("{0} = {1}", value, IsPalindrome(value));} }}

Output

A man, a plan, a canal: Panama. = TrueA Toyota. Race fast, safe car. A Toyota. = TrueCigar? Toss it in a can. It is so tragic. = TrueDammit, I'm mad! = TrueDelia saw I was ailed. = TrueDesserts, I stressed! = TrueDraw, O coward! = TrueLepers repel. = TrueLive not on evil. = TrueLonely Tylenol. = TrueMurder for a jar of red rum. = TrueNever odd or even. = TrueNo lemon, no melon. = TrueSenile felines. = TrueSo many dynamos! = TrueStep on no pets. = TrueWas it a car or a cat I saw? = TrueDot Net Perls is not a palindrome. = FalseWhy are you reading this? = FalseThis article is not useful. = False... = True...Test = False

Performance.What is the advantage of using two sub-loops to skip forward and back? This approach means you do not need to allocate any new strings. You can check the original string data without converting it.Info:A slower approach strips all spaces and punctuation from the source string. Then, you could use the simpler palindrome method.Summary

We introduced a simple method that tests for palindromes in the C# language. Many palindromes are composed of multiple words and have spaces and punctuation. These can be tested with a separate method that accounts for these charact

Top of Form

C#:.NET:NumberBottom of FormC# Prime Number

This method checks forprimenumbers fast. We see how prime numbers are computed in the .NET Framework. Primes are used in many programsthey are used in the Dictionary class. The Framework provides a method for testing primes.DictionaryExampleThe algorithm here is an efficient way to determine if a specific number is a prime number. It can be found in the System.Core assembly in the .NET Framework, in the HashHelpers class.

Note:It contains several optimizations that improve the performance of the computation.Next:This program shows the results on the primes between 0 and 100, and between 10000 and 10100, proving correctness.Program.cs, C# program that tests IsPrime

using System;

class Program{ static void Main() {//// Write prime numbers between 0 and 100.//Console.WriteLine("--- Primes between 0 and 100 ---");for (int i = 0; i < 100; i++){ bool prime = PrimeTool.IsPrime(i); if (prime) {Console.Write("Prime: ");Console.WriteLine(i); }}//// Write prime numbers between 10000 and 10100//Console.WriteLine("--- Primes between 10000 and 10100 ---");for (int i = 10000; i < 10100; i++){ if (PrimeTool.IsPrime(i)) {Console.Write("Prime: ");Console.WriteLine(i); }} }}

Class that contains IsPrime: PrimeTool.cs, C#

using System;

public static class PrimeTool{ public static bool IsPrime(int candidate) {// Test whether the parameter is a prime number.if ((candidate & 1) == 0){ if (candidate == 2) {return true; } else {return false; }}// Note:// ... This version was changed to test the square.// ... Original version tested against the square root.// ... Also we exclude 1 at the end.for (int i = 3; (i * i) = min) {return num2; }}for (int j = min | 1; j < 2147483647; j += 2){ if (PrimeTool.IsPrime(j)) {return j; }}return min; }}Dictionary

Whenever you add an element to Dictionary or initialize it with a specific capacity, the private instance Initialize method is called. This method uses the HashHelpers class, which contains the GetPrime method.When the Dictionarymust resize to have a capacity of more than 7199369 buckets, the IsPrime method is used in a loop. This code is not run on smaller Dictionaries but is part of all Dictionary instances.Dictionary Initialize method: C#

private void Initialize(int capacity){ int prime = HashHelpers.GetPrime(capacity); this.buckets = new int[prime]; // ... // ...}Summary

Here we looked at how the .NET Framework determines whether a number is a prime number. We described the basic algorithmic design of the IsPrime method, which provides optimized logic for testing number factors.Further:We saw how these methods are applied in the Dictionary class, making them a part of every program that uses Dictionary.

C# - Read Number and Check ODD or EVEN

I have given here a C# program to read number and check ODD or EVEN. It uses mod (%) operator with 2. If the remainder is 1, then it would be an ODD number otherwise EVEN Number.

usingSystem;usingSystem.Collections.Generic;usingSystem.Text;namespaceOddEven{classOddOREven {staticboolReadInteger(outintn) {stringinput=System.Console.ReadLine();n= 0;try {n=Convert.ToInt32(input);returntrue; }catch(System.Exceptionex) {System.Console.WriteLine("Error in the input format\n\n");returnfalse; } }staticvoidMain(string[]args) {System.Console.Write("Enter a Number to Check ODD or EVEN: ");intnumber= 0;ReadInteger(outnumber);if((number% 2) == 0)System.Console.WriteLine("{0} is an EVEN number",number);elseSystem.Console.WriteLine("{0} is an ODD number",number); } }}

Enter a Number to Check ODD or EVEN: 1515 is an ODD numberPress any key to continue . . .Enter a Number to Check ODD or EVEN: 2222 is an EVEN numberPress any key to continue . . .

An OtherStyle of this program

Qu 1:Write a program in which accept a number from the user and identify whether the number is even or odd.usingSystem;namespaceexample1{classProgram{ staticvoidMain(string[] args) { intnum; Console.Write("Enter your number:\t"); num =Convert.ToInt32(Console.ReadLine()); if(num % 2 == 0) { Console.WriteLine("{0} is Even Number", num); } else { Console.WriteLine("{0} is Odd number", num); } Console.ReadLine(); }}}

Qu2:Write a program in which accept a number from the user between 1 to 7 and display corresponding days starting with Monday.Hint:Use switch case

usingSystem;namespaceexample2{classProgram{ staticvoidMain(string[] args) { intopt; label: Console.Write("\n\nEnter your option (1-7) for days. 1 for Monday:\t"); opt =Convert.ToInt32(Console.ReadLine()); switch(opt) { case1: Console.WriteLine("Monday"); break; case2: Console.WriteLine("Tuesday"); break; case3: Console.WriteLine("Wednesday"); break; case4: Console.WriteLine("Thursday"); break; case5: Console.WriteLine("Friday"); break; case6: Console.WriteLine("Saturday"); break; case7: Console.WriteLine("Sunday"); break; default: Console.WriteLine("Invalid option. Please try again\n"); gotolabel; } Console.ReadLine(); }}}