以特定模式交换数组
问题描述:
我的数组如下:
My array is like:
11 22 33 44 55 66 77 88 99 110
和交换就像这样完成
and the swapping is to be done like this
22 11 44 33 66 55 88 77 110 90
ASP.NET C#控制台应用程序,
所以有人可以帮我这个
ASP.NET C# console application,
so can anyone please help me for this
class Program
{
static void Main()
{
int i,n;
//Enter Number of elements in an array
Console.WriteLine("Enter no array elements : ");
n = Convert.ToInt32(Console.ReadLine());
// Enter elements to an array
int[] arr = new int[n];
Console.WriteLine("Enter the array elements : ");
for(i=0; i<arr.length;> {
arr[i] = Convert.ToInt32(Console.ReadLine());
}
//Display Array Elements
Console.WriteLine("Array Elements are :");
for (i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i] + "\t");
}
//Logic Starts From Here
if (arr.Length == 1)
{
Console.WriteLine("Too Les Items to be shorted");
}
else
{
int start, end, mid;
start = arr[0];
end = arr[n-1];
Console.WriteLine("Start and End are " + start + "\t and \t" + end);
for (i = 0; i < n - 1; i++)
{
arr[n - 1] = arr[i];
}
Console.WriteLine(" NEWArray Elements are :");
for (i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i] + "\t");
}
;
}
Console.ReadKey();
}
}
我的尝试:
ASP.NET C#控制台应用程序,
所以任何人都可以帮我这个
What I have tried:
ASP.NET C# console application,
so can anyone please help me for this
答
试试这个
Try this
// swap
int tmp;
for (i = 0; i < arr.Length- 1; i+=2)
{
tmp= arr[i + 1];
arr[i + 1] = arr[i];
arr[i]= tmp;
}
int [] arr = new int [10];
int i;
Console.WriteLine(输入数组元素:);
for(i = 0; i< arr.length;> {
Console.WriteLine (arr [i] +\t);
}
====================
然后
start = a [0];
end = a [n-1];
for(i = 0; i< n-1;> {
a [n-1] = a [i];
}
这是正确的方式..?
int[] arr = new int[10];
int i;
Console.WriteLine("Enter the array elements : ");
for(i=0; i<arr.length;> {
Console.WriteLine(arr[i] + "\t");
}
====================
then after
start = a[0];
end = a[n-1];
for(i=0; i<n-1;>{
a[n-1] = a[i];
}
is it the right way..?
试试这个
try this
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
class Program
{
static void Main(string[] args)
{
int[] input = { 11, 22, 33, 44, 55, 66, 77, 88, 99, 110 };
int[] output = new int[10];
int count = 0;
for (int i = 0; i < input.Length; i++)
{
count++;
if (count == 2)
{
output[i - 1] = input[i];
output[i] = input[i - 1];
count = 0;
}
}
Console.WriteLine(" Output :");
for (int i = 0; i < output.Length; i++)
Console.WriteLine(output[i] + "\t");
Console.ReadKey();
}
}