Showing posts with label CSharp Basic Programs. Show all posts
Showing posts with label CSharp Basic Programs. Show all posts

Friday, 15 February 2013

TestMath.cs

To test the below, add a new class TestMath.cs and write the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpConsole
{
    class TestMath
    {
        static void Main()
        {
            Math m = new Math(100,50);
            m.Add(100, 50);
            m.Sub(60, 30);
            m.Mul(10, 20);
            m.Div(50, 25);
            Console.ReadLine();
           
        }
    }
}

What is the need of defining a Constructor explicitly?

 We are already aware that if we don't define a constructor in the class, still a implicit constructor comes  into picture and initializes some variables of class but we explicitly defines constructor under class so we have a chance of initializing variables of class with desired values.

Each and every class requires some initialization values foe execution so if we defined a constructor under the class we have a chance of sending our own initialization values for the class to execute and this values can be changed whenever wee create a new object for the class.

In the below below case, the four methods of the class requires the values for x and y to execute and those two variables are being initialized under the constructor so when and where we want to consume this class we can send values for x and y while creating the objects and then call all the four methods:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpConsole
{
    class Math
    {
        int x, y;
        public Math(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
        public void Add(int x, int y)
        {
            Console.WriteLine(x + y);
        }
        public void Sub(int x, int y)
        {
            Console.WriteLine(x - y);
        }
        public void Mul(int x, int y)
        {
            Console.WriteLine(x * y);
        }
        public void Div(int x, int y)
        {
            Console.WriteLine(x / y);
        }
       
     }
}

Thursday, 14 February 2013

When ever an object of class is created the constructor of that class gets called and the required memory get allocated. While creating the object of a class we are explicitly calling the constructor as following

  ConDemo cd = new ConDemo();  (Calling the constructor)

Constructors are of two types
  • Parameter-less  (zero argument) Constructor.
  •  Parametrized Constructor.

  •   Parameter-less  (zero argument) Constructor:   A constructor without any parameter is a parameter-less constructor which can be either defined implicitly provided there is no explicit constructor or else can be defined explicitly.
  •  Parametrized Constructor: A constructor with parameters is a Parametrized Constructor and can be defined only explicitly. if the constructor of a class is  Parametrized values to the parameter are sent while calling the constructor.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApps
{
    class ConParam
    {
        int a;   // a is a class variable
        public ConParam(int a)   // a is a block variable
        {
            this.a = a;
        }
        public void display()
        {
            Console.WriteLine("Values of a is{0}", a);
        }
        static void Main()
        {
            ConParam p1 = new ConParam(10);
            ConParam p2 = new ConParam(20);
            ConParam p3 = new ConParam(30);
            p1.display();
            p2.display();
            p3.display(); 
            Console.ReadLine();
        }
     }
}
Constructors:

      It is a special method present under a class which is responsible for initializing the variables of class. The name of constructor method will b same as the class name and more ever it is a non value returning method.

Syntax to define a constructor:
[<modifiers>] <name> ([<parameter defination>])
   {
        Statements;
   }

      Every class requires a constructor to be present in it, if we want to create an object of that class.

Note: As the constructor is mandatory for creating the object of a class, it must be defined by the programmer explicitly, or else while compiling the program compiler takes the responsibility of defining a constructor implicitly under that class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApps
{
    class ConDemo
    {
        public ConDemo()
        {
            Console.WriteLine("Constructor is called");
        }
        public void demo()
        {
            Console.WriteLine("Method is called");
        }
        static void Main()
        {
            ConDemo cd1 = new ConDemo();
            ConDemo cd2 = new ConDemo();
            ConDemo cd3 = cd2;
            Console.ReadLine();
        }
    }
}

Tuesday, 12 February 2013

Calling members of another class


//calling methods of another class by creating object

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

namespace CSharpConsole
{
    class Testclasses
    {
        static void Main()
        {
            Method_ex m1= new Method_ex();     // m1 is a object created
            Params p1=new Params();            // p1 is a object created
            m1.Test1();                        // calling methods
            m1.Test2(6, 12);
            Console.WriteLine(m1.Test3());
            Console.WriteLine(m1.Test4("Hello"));
            p1.AddNums(100, 75, 50);

            int x = 0, y = 0;
            p1.Math1(100, 25, ref x, ref y);
            Console.WriteLine(x + "   " + y);
            p1.Math2(100, 50, out x, out y);
            Console.WriteLine(x+ "   "+y);
            Console.ReadLine();              // waiting to key press
        }

    }
}

Operator Overloading



// Write a prorram to print the sum of complex numbers


using System;

public struct Complex
{
    public int real;
    public int imaginary;

    public Complex(int real, int imaginary)
    {
        this.real = real;
        this.imaginary = imaginary;
    }

    // Declare which operator to overload (+), the types 
    // that can be added (two Complex objects), and the 
    // return type (Complex):
    public static Complex operator +(Complex c1, Complex c2)
    {
        return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
    }
    // Override the ToString method to display an complex number in the suitable format:
    public override string ToString()
    {
        return (String.Format("{0} + {1}i", real, imaginary));
    }

    public static void Main()
    {
        Complex num1 = new Complex(2, 3);
        Complex num2 = new Complex(3, 4);

        // Add two Complex objects (num1 and num2) through the
        // overloaded plus operator:
        Complex sum = num1 + num2;

        // Print the numbers and the sum using the overriden ToString method:
        Console.WriteLine("First complex number:  {0}", num1);
        Console.WriteLine("Second complex number: {0}", num2);
        Console.WriteLine("The sum of the two numbers: {0}", sum);
        Console.ReadKey();

    }
}

Parameters in CSharp

      Parameters are defined so that the methods can be made more dynamic. Parameters of a methods can be of 2 types.
  •  Input parameters.
  • Output parameters.
       Input parameters are used for bringing values in the method for execution. Whereas output parameters are used for carrying a value ouut of the method after execution of the method
       By default every parameter we pass to a method is an input parameter and if we want to define a parameter as output parameter we need to prefix the parameter with ref or out keyword.

      public void test (int x,ref int y,out int z)

       Here x is an input parameter and y& z are output parameters.

Note: By using return types also we can send results out of a method, but only a single result whereas if we are sending results out of a method using output parameters we have a chance of sending more than 1 result at the time of execution.

Monday, 11 February 2013

Using Parameters


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

namespace CSharpConsole
{
    class Params
    {
        //method with default value to parameterss
        public void AddNums(int x, int y = 50, int z = 25)
        {
            Console.WriteLine(x + y + z);

        }
        //method with both input and output parameterss
        public void Math1(int a, int b, ref int c, ref int d)
        {
            c = a + b;
            d = a * b;
        }
        public void Math2(int a, int b, out int c, out int d)
        {
            c = a + b;
            d = a * b;
        }
        static void Main()
        {
            Params p = new Params();
            // Calling method with default values to parameters
            p.AddNums(100);
            p.AddNums(100, 100);
            p.AddNums(100,z: 100);
            p.AddNums(100, 100, 100);

            // Calling methods with input and output parameters
            int x = 0, y = 0;
            p.Math1(100, 50, ref x, ref y);
            Console.WriteLine(x + "   " + y);

            int m, n;
            p.Math2(200, 25, out m, out n);
            Console.WriteLine(m + "   " + n);
            Console.ReadLine();

        }
    }
}

// Program to print the following pattern
//   *****
//   *****
//   *****
//   *****
//   *****


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

namespace pattern_4
{
    class Program
    {
        static void Main(string[] args)
        {
            int i,j, k;

            for (i = 1; i <= 5; i++)
            {
                for (j = 1; j <= i; j++)
                {
                    Console.Write("");
                }
                for (k = 1; k <= 5; k++)
                {
                    Console.Write("*");
                }
                Console.WriteLine();

            }
            Console.ReadKey();
        }
    }
}
  

Sunday, 10 February 2013


// Write a program to print the binary format of a number

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

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            int num;
            Console.Write("Enter a Number : ");
            num = int.Parse(Console.ReadLine());
            int quot;

            string rem = "";

            while (num >= 1)
            {
                quot = num / 2;
                rem += (num % 2).ToString();
                num = quot;
            }

            // Reversing the  value
            string bin = "";
            for (int i = rem.Length - 1; i >= 0; i--)
            {
                bin = bin + rem[i];

            }

            Console.WriteLine("The Binary format for given number is {0}", bin);


            Console.Read();

        }
    }
}

Monday, 28 January 2013



// Write a program to print the area of a circle.

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

namespace areaofcircle
{
    class Program
    {
        static void Main(string[] args)
        {
            int r;
            double a, p;
            p = 3.14;
            Console.WriteLine("Enter the value of radius");
            r = Convert.ToInt32(Console.ReadLine());
            a = p * r * r;
            Console.WriteLine("area" + a);
            Console.ReadLine();

        }
    }
}


// Write a program to print the fibonacci series

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

namespace fibo
{
    class Program
    {
        static void Main(string[] args)
        {
            int n, i, pre = 0;
            int next = 1;
            Console.WriteLine("Enter the value of n:  ");
            n = Convert.ToInt32(Console.ReadLine());
            for (i = 2; i <= n; i++)
            {
                int a = pre + next;
                Console.WriteLine(" " + a);
                pre = next;
                next = a;
            }
            Console.ReadKey();
            }
        }
    }


// Write a program to print the table of a number

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

namespace Table
{
    class Program
    {
        static void Main(string[] args)
        {
            int i,a,n;
            Console.WriteLine("Enter the number");
            n= Convert.ToInt32(Console.ReadLine());
            for(i=1;i<= 10;i++)
            {
                a=n*i;
                Console.WriteLine(a);
            }
            Console.ReadKey();
        }
    }
}


// Write a program that prints

//*
//**
//***
//****

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

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 1; i <= 4; i++)
            {
              
                for (int j = 1; j <= i; j++)
                {
                    Console.Write("*");
                }

                Console.WriteLine();
            }
            Console.ReadKey();
        }
    }
}


// Write a program to take as input your name and print “Hello name”.

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            
            string name = string.Empty;
            Console.WriteLine("Enter your Name:");
            name = Console.ReadLine();
            Console.Clear();
            Console.Write("\n");
            Console.WriteLine("Hello " + name);
            Console.ReadKey();
        }  
    }
}

// Write a program to find out m % n without using the % operator.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace prog7
{
    class Program
    {
        static void Main(string[] args)
         {
            int n = 0, m = 0, def=0;
 
            Console.WriteLine("Enter M value");
 
            m = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter Nvalue");
            n = int.Parse(Console.ReadLine());
            if (n == 1)
                Console.WriteLine("Result   " +def);
            else
            {
                while (m > 1)
                {
                    m = m - n;
                    //Once it meet such a condition that m become lesser then n that's mean now we can't devide m number through n
                    if (m < n)
                        break;
                }
 
                //Moving to the next line 
                Console.WriteLine();
 
                //Printing the biggest number from n number 
                Console.WriteLine(" Result: " + m);
 
            }
 
            //Waiting for any keypress 
            Console.ReadKey();
        }
       }
     }

// Write a program to find out m / n without using the / operator
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace prog6
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = 0, m = 0, d = 0;
            Console.WriteLine("Enter M value");
            m = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter Nvalue");
            n = int.Parse(Console.ReadLine());
            if (n == 1)
                Console.WriteLine("Result" + m);
            else
            {
                while (m > 1)
                {
                    m = m - n;
                    d++;
                }
                //Moving to the next line 
                Console.WriteLine();
                //Waiting for any keypress 
                Console.ReadKey();

            }
        }
    }
}

// Write the programs to print the even numbers between 1 to 100. 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace evennum
{
    class Program
    {
        static void Main(string[] args)
        {
            int n ;
            {
                Console.WriteLine("the even numbers between 1 to 100 are :");
                for (n = 1; n <= 100; n++)
                    if(n%2==0)
                    //while (n <= 100)
              
                Console.WriteLine(n);
                Console.ReadKey();
             }
        }
    }
}

Sunday, 27 January 2013


//Write a program to find the biggest number in n numbers without using arrays.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace biggestnumber
{
    class Program
    {
        static void Main(string[] args)
       {
            int ntimes = 0,biggest_number=0,num=0;
            Console.Write("How many times you want to enter the number : ");
            ntimes = int.Parse(Console.ReadLine());
            for (int i = 1; i <= ntimes; i++)
            {
                Console.Write("Enter {0} Number    ",i);
                num = int.Parse(Console.ReadLine());
                    if (biggest_number< num)
                    biggest_number = num;
            }
            Console.WriteLine();
            Console.WriteLine("The biggest Number : " + biggest_number);
           Console.ReadKey();
        } } }

//Write a program to take as input a number n and find the sum of all numbers from 1 to n.
//Eg. If input is 6 then output should be 1+2+3+4+5+6 = 21 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace addtwonos
{
    class Program
    {
       
        static void Main(string[] args)
        {
            int n = 0, total = 0, temp = 0;
            Console.Write("Enter the n number :  ");
            n = int.Parse(Console.ReadLine());

            for (int i = 1; i <= n; i++)
            {
                Console.Write("Enter the {0} number ", i);
                temp = int.Parse(Console.ReadLine());

                total = total + temp;
            }

            Console.WriteLine("The total of a number u entered is : " + total);
            //total = Int32.Parse(Console.ReadLine());
            Console.ReadKey();
        }
    }
}