ต่อไปนี้เป็นอาร์เรย์และองค์ประกอบ -
int[] arr = { 10, 20, 15 }; ตั้งค่าลบเป็นองค์ประกอบบวก
if (arr[i] > 0) arr[i] = -arr[i];
วนซ้ำด้านบนจนถึงความยาวของอาร์เรย์
for (int i = 0; i < arr.Length; i++) {
Console.WriteLine(arr[i]);
if (arr[i] > 0)
arr[i] = -arr[i];
} เรามาดูตัวอย่างฉบับสมบูรณ์กัน
ตัวอย่าง
using System;
public class Demo {
public static void Main(string[] args) {
int[] arr = { 10, 20, 15 };
Console.WriteLine("Displaying elements...");
for (int i = 0; i < arr.Length; i++) {
Console.WriteLine(arr[i]);
if (arr[i] > 0)
arr[i] = -arr[i];
}
Console.WriteLine("Displaying negated elements...");
for (int i = 0; i < arr.Length; i++) {
Console.WriteLine(arr[i]);
}
}
} ผลลัพธ์
Displaying elements... 10 20 15 Displaying negated elements... -10 -20 -15