Showing posts with label C# Example. Show all posts

Bài tập minh họa về toán tử dịch bit trong C-Sharp. (Program to Illustrate LeftShift Operations in C-Sharp.)

Bài tập này minh họa về toán tử LeftShift (<<) tạm dịch là phép toán dịch bit trong ngôn ngữ lập trình C-Sharp.

Left Shift Example


C-Sharp Source Example:
-------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpExample
{
    class LeftShiftexample
    {

        static void Main(string[] args)
        {

            int x = 1024 * 1024 * 1024;
            uint p = 1024 * 1024 * 1024;
            int y = -42;

            Console.WriteLine("LEFT SHIFT OPERATIONS :");
            Console.WriteLine("{0},{1},{2}", x, x * 2, x << 1);
            Console.WriteLine("{0},{1},{2}", p, p * 2, p << 1);
            Console.WriteLine("{0},{1},{2}", x, x * 4, x << 2);
            Console.WriteLine("{0},{1},{2}", p, p * 4, p << 2);
            Console.WriteLine("{0},{1},{2}", y, y * 1024 * 1024 * 64, x << 26);

            Console.ReadLine();

        }

    }

}
-----------------------------------









Bài tập sử dụng vòng lập lồng nhau để in hình kim cương. (How to print a diamond using nested loop?)

Đây cũng là một trong nhưng bài tập thường gặp khi ta học về vòng lập (loop) trong ngôn ngữ lập trình C#, bài nhập yêu cầu bạn nhập vào một nửa số dòng của viên kim cương và sử dụng dung các vòng lập lồng nhau để in ra một viên kim cương hoàn chỉnh.

How to print a diamond using nested loop


C# Example Source Code:
------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpExample
{
    class nestedloopexample
    {

        static void Main(string[] args)
        {


            int number, i, k, count = 1;

            Console.Write("Enter number of rows\n");
            number = int.Parse(Console.ReadLine());

            count = number - 1;

            for (k = 1; k <= number; k++)
            {
                for (i = 1; i <= count; i++)
                {
                    Console.Write(" ");
                }

                count--;

                for (i = 1; i <= 2 * k - 1; i++)
                {
                    Console.Write("*");
                }

                Console.WriteLine();
            }

            count = 1;

            for (k = 1; k <= number - 1; k++)
            {
                for (i = 1; i <= count; i++)
                {
                    Console.Write(" ");
                }

                count++;

                for (i = 1; i <= 2 * (number - k) - 1; i++)
                {
                    Console.Write("*");
                }

                Console.WriteLine();
            }

            Console.ReadLine();
        }
    }

}
------------------










Chương trình minh họa cách sử dụng chỉ định quyền hạn truy cập (Access Specifiers) trong C-Sharp. (Program to Illustrate the Use of Access Specifiers in C-Sharp.)

Đây là một chương trình dùng để minh họa cách sử dụng các chỉ định quyền hạn truy cập trong tiếng anh gọi là Access Specifiers trong ngôn ngữ lập trình C-Sharp bào gồm: private, protected, internal, public, protected internal.

Program to Illustrate the Use of Access Specifiers in C-Sharp


C-Sharp Basic Example:
--------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpExample
{
    class accessspecifier
    {

        static void Main(string[] args)
        {
            two B = new two();
            B.show();
        }

        class one
        {
            private int a;
            protected int b;
            internal int c;
            public int d;
            protected internal int e;
        }


        class two : one
        {

            public void show()
            {
                Console.WriteLine("Values are : ");

                //a=10; //it's private.
                b = 20; //it's protected
                c = 30; //it's internal
                d = 40; //it's public
                e = 50; //it's protected internal


                //Console.WriteLine(a); // Error x is not accessible
                Console.WriteLine("Priveate a is not accessible: ");
                Console.WriteLine("Protected: " + b);
                Console.WriteLine("Internal: " + c);
                Console.WriteLine("Public: " + d);
                Console.WriteLine("Protected Internal: " + e);
                Console.ReadLine();
            }


        }
    }
}
--------------------------













Làm thế nào để chuyển đổi giá trị của hai số bằng toán tử bit XOR trong C-Sharp? (How to swap the contents of two numbers using bitwise XOR operation in C-Sharp?)

Đây là một bài khá hay, bạn sẽ học hỏi và hiểu rõ hơn về toán tử bit XOR trong C-Sharp, và đây cũng là một lời giải khác cho bài tập chuyển đổi hai số mà không sử dụng biến thứ ba mà ta thường gặp khi học cơ bản về ngôn ngữ lập trình C#.



C-Sharp Basic Example:
---------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpExample
{
    class swap_the_contents_of_two_numbers
    {

        static void Main(string[] args)
        {

            int i, k;

            Console.WriteLine("Enter two integers \n");
            i = int.Parse(Console.ReadLine());
            k = int.Parse(Console.ReadLine());

            Console.WriteLine("\n Before swapping i= {0} and k = {1}", i, k);
            i = i ^ k;
            k = i ^ k;
            i = i ^ k;

            Console.WriteLine("\n After swapping i= {0} and k = {1}", i, k);
            Console.ReadLine();

        }

    }
}
---------------------------------











C-Sharp Tìm số lần lập lại của mạo thừ 'the' xuất hiện trong câu. (C-Sharp how to find the frequency of the word in a given sentence?)

Đây là một trong những bài tập cơ bản của C-Sharp khi mới bắt đầu học ngôn ngữ lập trình này, bài tập yêu cầu bạn phải tìm số lần xuất hiện của mạo từ 'the' trong câu.

C-Sharp how to find the frequency of the word in a given sentence


C-Sharp Example:
-----------------------
    using System;
    class program
    {
        public static void Main()
        {
            string s1;
            Console.WriteLine("Enter the String : ");
            s1 = Console.ReadLine();
            Console.WriteLine(counting.CountStringOccurrences(s1, "the"));
            Console.ReadLine();
        }
    }

    public static class counting
    {
        public static int CountStringOccurrences(string text, string pattern)
        {

            int count = 0;
            int i = 0;
            while ((i = text.IndexOf(pattern, i)) != -1)
            {
                i += pattern.Length;
                count++;
            }

            return count;
        }

    }

---------------------------------





Bài tập C-Sharp phân loại chiều cao của người.

Một bài tập C-Sharp cũng khá thực tế nhất trong trong việc khám sức khẻo, bài tập yêu cầu là người dùng sẽ nhập vào chiều cao của mình rùi chương trình sẽ cho biết chiều cao của họ đang là cao, lùn hay trung bình từ đó sẽ có chế độ ăn uống tập luyện để cao hơn chút. Để phân loại ta có các tiêu chuẩn sau:
  • Đơn vị dùng để đo chiều cao là centimeters.
  • Nếu người đó có chiều cao nhỏ hơn 150 centimeters thì người đó lùn.
  • Nếu người đó có chiều cao trong khoảng 151 đến 165 centimeter thì người đó cao trung bình.
  • Nếu người đó có chiều cao trong khoảng 165 đến 195 centimeter thì người đó cao.
  • Nếu người đó có chiều cao lơn hơn 195 centimeter thì người đó cao bất thường :)).


C-Sharp Example:
----------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpExample
{
    class PersonHeight
    {

        static void Main(string[] args)
        {
            float height;
            Console.WriteLine("Enter  the Height (in centimeters) \n");
            height = int.Parse(Console.ReadLine());

            if (height < 150.0)
                Console.WriteLine("Dwarf \n");
            else if ((height >= 150.0) && (height <= 165.0))
                Console.WriteLine(" Average Height \n");
            else if ((height >= 165.0) && (height <= 195.0))
                Console.WriteLine("Taller \n");
            else
                Console.WriteLine("Abnormal height \n");

            Console.Read();


        }

    }

}-----------










Làm thế nào để lấy một con số ngẫu nhiên trong C-Sharp? (How to get random number in C-Sharp?).

Bài viết này hướng dẫn cách để lấy một số ngẫu nhiên bắt kỳ trong C#, số ngẫu nhiên này được lấy bởi lớp Random (random class) và hàm next().



C-Sharp Source Code:
----------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpExample
{
    class RandomNumber
    {

        static void Main(string[] args)
        {
            Console.WriteLine("Some Random Numbers that are generated are : ");
            for (int i = 1; i < 10; i++)
            {
                Randfunc();
            }

        }

        static Random r = new Random();

        static void Randfunc()
        {
            int n = r.Next();
            Console.WriteLine(n);
            Console.ReadLine();
        }

    }

}

----------------------








Bài tập hiển thị một số giao dịch ATM đơn giản trong C-Sharp.

Đây có thể xem là một bài tập khá thú vụ và rất thức tế khi chúng ta mới bắt đầu học cơ bản về về C-Sharp. Bài tập yêu cầu bạn hiển thị một số qui trình giao dịch thông thình trong cỗ máy ATM, và tất nhiên bài tập chỉ yêu cầu một cách thể hiện các giao dịch này rất cơ bản thôi. Các giao dịch(transaction ) này bao gồm:
  • Balance checking - Kiểm tra tiền dư.
  • Cash withdrawal - Rút tiền mặt.
  • Cash deposition - Gửi tiền.
Và người dùng có thể chọn bất kỳ giao dịch nào họ muốn.



C-Sharp Source Code:
--------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpExample
{
    class ATMTransaction
    {

        static void Main(string[] args)
        {

            int amount = 1000, deposit, withdraw;
            int choice, pin = 0, x = 0;

            Console.WriteLine("Enter Your Pin Number ");
            pin = int.Parse(Console.ReadLine());

            while (true)
            {
                Console.WriteLine("********Welcome to ATM Service**************\n");
                Console.WriteLine("1. Check Balance\n");
                Console.WriteLine("2. Withdraw Cash\n");
                Console.WriteLine("3. Deposit Cash\n");
                Console.WriteLine("4. Quit\n");
                Console.WriteLine("*********************************************\n\n");
                Console.WriteLine("Enter your choice: ");

                choice = int.Parse(Console.ReadLine());
                switch (choice)
                {
                    case 1:
                        Console.WriteLine("\n YOUR BALANCE IN Rs : {0} ", amount);
                        break;
                    case 2:
                        Console.WriteLine("\n ENTER THE AMOUNT TO WITHDRAW: ");
                        withdraw = int.Parse(Console.ReadLine());
                        if (withdraw % 100 != 0)
                        {
                            Console.WriteLine("\n PLEASE ENTER THE AMOUNT IN MULTIPLES OF 100");
                        }
                        else if (withdraw > (amount - 500))
                        {
                            Console.WriteLine("\n INSUFFICENT BALANCE");
                        }

                        else
                        {
                            amount = amount - withdraw;
                            Console.WriteLine("\n\n PLEASE COLLECT CASH");
                            Console.WriteLine("\n YOUR CURRENT BALANCE IS {0}", amount);
                        }
                        break;
                    case 3:
                        Console.WriteLine("\n ENTER THE AMOUNT TO DEPOSIT");
                        deposit = int.Parse(Console.ReadLine());
                        amount = amount + deposit;
                        Console.WriteLine("YOUR BALANCE IS {0}", amount);
                        break;
                    case 4:
                        Console.WriteLine("\n THANK U USING ATM");
                        Environment.Exit(0);
                        break;
                    default:
                        Console.WriteLine("Default case");
                        break;
                }

            }


        }


    }
}

-------------------------












Làm thế nào để so sánh hai ngày tháng năm trong C-Sharp? (How to compare two dates in C-Sharp?).

Đây là một bài tập đơn giản khi ta bắt đầu làm quen với kiểu dữ liệu date(ngày) trong ngôn ngữ lâp trình C#, bài tập yêu cầu bạn so sánh hai ngày cho trước và in ra ngày nào xảy ra trước và ngày nào xảy ra sau.



C-Sharp Example Source Code:
--------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpExample
{
    class CompareTwoDates
    {

        static void Main(string[] args)
        {

            DateTime sd = new DateTime(2010, 10, 12);
            Console.WriteLine("Starting Date : {0}", sd);

            DateTime ed = sd.AddDays(10);
            Console.WriteLine("Ending Date   : {0}", ed);


            if (sd < ed)
            {
                Console.WriteLine("{0} Occurs Before {1}", sd, ed);
            }

            Console.Read();

        }


    }
}
---------------------








Làm thế nào để hiển thị ngày tháng trong C-Sharp với nhiều định dạng khác nhau? (How to Display the Date in Various Formats in C-Sharp?)

Đây là một bài tập, ví dụ, thường gặp khi học C-Sharp tới phần kiểu dữ liệu dạng ngày tháng (Date). Bài ví dụ này sẽ mô tả cách để hiển thị ngày tháng (Date) trong C-Sharp với nhiêu định dạng khác nhau ví dụ như DD/MM/YYYY, YYYY/MM/DD, ...



C-Sharp Date Example:
------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpExample
{
    class DisplayDateTime
    {

        static void Main(string[] args)
        {

            DateTime date = new DateTime(2013, 6, 23);

            Console.WriteLine("Some Date Formats : ");
            Console.WriteLine("Date and Time:  {0}", date);
            Console.WriteLine(date.ToString("yyyy-MM-dd"));
            Console.WriteLine(date.ToString("dd-MMM-yy"));
            Console.WriteLine(date.ToString("M/d/yyyy"));
            Console.WriteLine(date.ToString("M/d/yy"));
            Console.WriteLine(date.ToString("MM/dd/yyyy"));
            Console.WriteLine(date.ToString("MM/dd/yy"));
            Console.WriteLine(date.ToString("yy/MM/dd"));
            Console.Read();


        }


    }
}

---------------------------------