Showing posts with label Beginner in C#. Show all posts
Showing posts with label Beginner in C#. Show all posts

Thursday, September 27, 2012

Beginner in C#: Helper methods

What's a helper method?

Well, a helper method is a statement that carries with it a big or small piece of code, created by you, to execute them easily in your program

Why to use helper methods in C#?

Using helper method can help you to save time, for example if you need to get the factorial of an integer more than one time in your code, it's better for  you to create a method and call it something like getFact(uint n), with a parameter an unsigned integer.

What are the types of helper methods?

  1. Methods that don't return a value (of type void).
  2. Methods that returns value (of type int, string, Button, bool, etc... it depends on your needs)

Example on C# helper methods:


Number factorial function C#

You can do this function in two ways , using a recursive method or not.

Recursive method C#:

        public static uint getFact(uint n)
        {
            if (n <2) 
                return 1;
           //you don't have to use 'else' here
            return n * getFact(n - 1);
        }

Non-recursive method C#:

        public static uint getFact(uint n)
        {
            uint ans=1;
            for (uint i = 2; i <= n; i++)
                ans *= i;
            return ans;
        }
So now you are ready to create your own helper methods! have a question? Comment on this post.

Tuesday, September 25, 2012

Beginner in C#: using fixed one dimensional Arrays

What is an Array?

An array is simply a place to store an amount of items, that can be used later easily.

Defining a fixed Array

First, you must specify the type of items to store in your array, lets say for example you want to store a list of integers. Then, the number of items (integers) you want to store.
The following code snippet creates an array of 4 integers.
int[] myFirstIntArray = new int[4];

Storing items in your array

In C#, an array index starts at 0, and ends at the array length minus one.
To store data in a predefined array, the basic way, just set the value of each item in your array, using the equal sign!
Let's consider our previous example. we want to store in it the following information:
  1. my age.
  2. my birth-year.
  3. my birth-month.
  4. my birth-day.
The code below will do the task.

myFirstIntArray[0] = 19 ; //19 years old
myFirstIntArray[1] = 1993 ;
myFirstIntArray[2] = 7 ; //July
myFirstIntArray[3] = 21 ;

Of course, you may need to store a big amount of items and you're not gonna put them all one by one, so in this case we usually use the Loops.

A good example: Let's say we want to get the list of the first 100 prime numbers. Here we are going to use a do-While loop.

            int[] primeNbrs = new int[100];
            int number = 2;
            int index=0;
            do
            {
                int i = 2;
                while ((i < number) && (number % i != 0)) i++;
                if (i == number)
                {
                    primeNbrs[index] = number;
                    index++;
                }
                number++;
            } while (index < 100);
If you have any questions, COMMENT!

Friday, September 21, 2012

Beginner in C#: using StreamReader and StreamWriter

Brief Definition

StremReader: used to Read data from a file, such as .txt files.
StremWriter: used to Write data on a file, or even create a new file.

Example

To make things simple lets consider a simple example.
We want to write a C# console application that will EDIT a text file.
The process is as the following:
  1. Reading the old text file
  2. Writing a new one (edited one)
  3. Deleting the original.
Before you start make sure you've added this line above the namespace:
using System.IO;
In the following we suppose that you have a text file in the Debug directory of your project with name "file.txt".

Declarations:
            StreamReader sR = new StreamReader("file.txt");
            StreamWriter sW = new StreamWriter("new.txt");

Writing data in the new.txt file while reading from the file.txt file at the same time.
            while (sR.Peek() != -1) // stops when it reachs the end of the file
            {
                string line = sR.ReadLine();
                // "line" EDITING GOES HERE
                sW.WriteLine(line); // writing the edited line as a new line in the new.txt file
            }

Deleting the old file and rename the new file as the old file's name.
            File.Delete("file.txt");
            File.Move("new.txt", "file.txt");

Finally close the initially declared StreamReader and StreamWriter.
                sR.Close();
                sW.Close();
And that's it! leave your comments.

Beginner in C#: The if statement

The if statement is one of the most important statement in almost all programming languages and in C#.

The main use of it is to specify an action to do but only when a condition of type bool is true.


For example lets make a simple console application that asks the user for an integer number and determines if the number given is an even number or an odd number.

        static void Main(string[] args)
        {
            Console.Write("Enter a number: ");//asking the user to enter a number
            int number = int.Parse(Console.ReadLine());//reading the given number
            if (number % 2 == 0)//if 'number' is a multiple of two
                Console.WriteLine("It's an even number");//Writing the result
            else //this means "if not, do the following.."
                Console.WriteLine("It's an odd number");//Writing the result
            Console.Read();
        }

If (you have a question)
    Leave a comment and I'll answer!

Wednesday, September 19, 2012

Beginner in C#: Understanding loops


What is a loop in programming?


A loop is as statement that helps you to execute a piece of code repeatedly, a known number of times or until a certain condition become true.
For example, if I said I'm going to walk exactly 500 steps, I'm making a loop about one step repeated 500 times. But if I said I'm going to walk until my dad calls me, here I don't know when exactly my dad will calls me, so this is a loop depending on a particular condition: "my dad is calling me", when it becomes true I will stop walking.

Loops in C#


The 3 most frequently used loops in C# are the following:

the "for" loop

The for loop is usually used to repeat a code N times, N could be a variable or a fixed integer (int).
here's how you write it:

int i; // Declaring an integer with the name 'i'
for(i=0;i<N;i++)
{
// YOUR CODE HERE
}

the "while" loop

The while loop is used to repeat an action until the condition (of type bool) becomes true. 
usage:
while(!condition)
{
// YOUR CODE HERE
}

the "do-while" loop

The do-while loop is just like the while, the only difference is that by its usage we ensure that your CODE is executed at least once.
usage:
do
{
// CODE
}while(!condition);
Its equivalent to:
// CODE
while(!condition)
{
// CODE
}