Thao tác trên mảng bằng C#
Thao tác trên mảng bằng C#, nhập xuất, thêm và xóa phần tử x ở vị trí thứ k
Code:
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mang1
{
class Program
{
static void Main(string[] args)
{
int[] a = new int[100];
int n, i, j, tg;
Console.WriteLine("Nhap vao tong so cua mang:");
n = Int32.Parse(Console.ReadLine());
for (i = 0; i < n; i++) {
Console.Write("Nhap vao so {0}: ",i+1);
a[i] = Int32.Parse(Console.ReadLine());
}
for (i = 0; i < n; i++ ) {
Console.Write("{0} ",a[i]);
}
for (i = 0; i < n; i++) {
for (j = i; j < n; j++) {
if (a[i] > a[j]) {
tg = a[i];
a[i] = a[j];
a[j] = tg;
}
}
}
Console.WriteLine("\n-------\n");
for (i = 0; i < n; i++) {
Console.Write("{0} ",a[i]);
}
int k,x;
Console.WriteLine("\nNhap so va vi tri can them vao mang:");
x = Int32.Parse(Console.ReadLine());
k = Int32.Parse(Console.ReadLine());
k--;
for (i = n; i >= k; i--) {
a[i] = a[i-1];
}
a[k] = x;
n++;
Console.WriteLine("\n-------\n");
for (i = 0; i < n; i++)
{
Console.Write("{0} ", a[i]);
}
Console.WriteLine("\nNhap vao so va vi tri can xoa:");
x = Int32.Parse(Console.ReadLine());
k = Int32.Parse(Console.ReadLine());
k--;
for (i = k; i < n - 1; i++) {
a[i] = a[i+1];
}
n--;
Console.WriteLine("\n-------\n");
for (i = 0; i < n; i++)
{
Console.Write("{0} ", a[i]);
}
Console.ReadLine();
}
}
}

Post a Comment