Mô tả bài toán
Tạo ứng dụng Console, cho phép người dùng nhập 2 con số
A và
B. Yêu cầu in ra màn hình giá trị trước và sau khi thay đổi vị trí của
A và
B.
Cách giải quyết
Lấy giá trị người dùng nhập vào 2 biến
A và
B. Sử dụng 1 biến
temp để thay đổi giá trị của 2 biến
A và
B:
1temp = A;
2A = B;
3B = temp;
Source code
[su_spoiler title="Bài giải (Nên nhớ tự làm trước khi click vào đây)"]
1/*
2C# Program to Swap 2 Numbers
3This is a C# Program to swap 2 numbers.
4
5Problem Description
6This C# Program Swaps 2 Numbers.
7
8Problem Solution
9It obtains two numbers from the user and swaps the numbers using a temporary variable.
10*/
11using System;
12using System.Collections.Generic;
13using System.Linq;
14using System.Text;
15namespace Lession2
16{
17 class Program
18 {
19 static void Main(string[] args)
20 {
21 int num1, num2, temp;
22 Console.Write("\nEnter the First Number : ");
23 num1 = int.Parse(Console.ReadLine());
24 Console.Write("\nEnter the Second Number : ");
25 num2 = int.Parse(Console.ReadLine());
26 temp = num1;
27 num1 = num2;
28 num2 = temp;
29 Console.Write("\nAfter Swapping : ");
30 Console.Write("\nFirst Number : " + num1);
31 Console.Write("\nSecond Number : " + num2);
32 Console.Read();
33 }
34 }
35}
[/su_spoiler]
Github
https://github.com/kellyfire611/learning.nentang.vn-csharp/tree/master/src/Lession2