Thursday March 29th, 2018

C# Methods (Functions)

By Ebubekir Sezer

In object-oriented programming languages, functions are called methods. We do everything same with when we doing something with functions using with the methods. Briefly methods and functions are same thing. Purpose of using methods is instead of coding same thing again and again, we just define method and call that method. Methods make the coding easier.

Firstly, I will use already existing method. This method is Random method. Program will be about decide the heads or tails. I will make a loop and that loop go on 5 times. If number come 1 it will be heads. If it’s come 2 it will be tail. Code Sequence;

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

namespace ConsoleApp2
{
    class Program
    {
        
          

            static void Main(string[] args)
            {
            Random number = new Random();
            for (int i = 0; i < 5; i++)
            {
                int headtail = number.Next(1, 3);
                if (headtail == 1)
                {
                    Console.WriteLine("Head");
                }
                else
                {
                    Console.WriteLine("Tail");
                }
            }
            Console.ReadKey();
        }
        }
    }

Screen Display;

Tail
Tail
Tail
Tail
Head

Now, I will make a method which is about the taking the power of the number. Program will ask a number and power by the user and then will send the these information to the method and program will press the result on the screen. Code Sequence;

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

namespace ConsoleApp2
{
    class Program
    {

            static int pow(int number, int power = 1)
            {
                if (power == 0)
                {
                    return 1;
                }
                else
                {
                    return number * pow(number, power - 1);
                    // I use the recursive function here
                }
            }
            static void Main(string[] args)
            {
                int number, power;
                Console.WriteLine("Enter the number:");
                number = int.Parse(Console.ReadLine());
                Console.WriteLine("Enter the power:");
                power = int.Parse(Console.ReadLine());
                Console.WriteLine(pow(number, power));
                Console.ReadKey();
            }
        }
    }

Screen Display;

Enter the number:
4
Enter the power:
3
64