Để biết một số có chia hết cho 2 hay không, hãy kiểm tra điều gì sẽ xảy ra khi số đó chia hết cho 2.
Nếu phần dư là 0 thì số đó chia hết cho 2, còn lại sai -
if (num % 2 == 0) {
Console.WriteLine("Divisible by 2 ");
} else {
Console.WriteLine("Not divisible by 2");
} Sau đây là mã hoàn chỉnh -
Ví dụ
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo {
class Test {
static void Main(string[] args) {
int num;
num = 18;
// checking if the number is divisible by 2 or not
if (num % 2 == 0) {
Console.WriteLine("Divisible by 2 ");
} else {
Console.WriteLine("Not divisible by 2");
}
Console.ReadLine();
}
}
} Đầu ra
Divisible by 2