@作者: 风不停息丶
练习1:for循环打印正三角图案
# 1
## 2
### 3
#### 4
class Program
{
static void Main(string[] args)
{
for (int r = 0; r < 4; r++) // 0 1 2 3
{
for (int i = 0; i <= r; i++)//0 01 012 0123
{
Console.Write("#");
}
Console.WriteLine();
}
}
}
练习2:for循环打印倒三角图案
#### 4
### 3
## 2
# 1
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 4; i++)
{
for (int c = 0; c < i; c++)
{
Console.Write(" ");
}
for (int a = 4; a > i; a--)
{
Console.Write("#");
}
Console.WriteLine();
}
}
}
练习3:冒泡排序
输入一段数字进行排序
//冒泡排序
private static int[] OrderBy(int[] array)
{
//需要与后面比较的元素索引
//只需要对比到倒数第二位,array。Length-1
for (int currentIndex = 0; currentIndex < array.Length - 1; currentIndex++)
{
for (int i = currentIndex + 1; i < array.Length; i++)//
{
if (array[currentIndex] > array[i])//第二位和第一位比较,如果大于就交换
{
//交换方法
int temp = array[currentIndex];//定义一个变量 将array[currentIndex]里的数据赋值给变量temp
array[currentIndex] = array[i];//将array[currentIndex]里的数据换成array[i]的数据
array[i] = temp;//将变量temp的数据赋值给array[i]
}
}
}
return array;
}
练习4:选择冒泡排序
private static int[] OrderBy(int[] array)//定义数组方法int[]
{
//需要与后面比较的元素索引
//比较3次 0 1 2
//当前指数,第0个数拿去初始比较,所以array.length-1
for (int currentIndex=0;currentIndex<array.Length-1;currentIndex++)
{
int minIndex = currentIndex;//设置一个变量 = currentIndex
for (int i=currentIndex+1;i<array.Length;i++)
{
if (array[currentIndex] > array[i])//比较 交换
{
//需要记录的索引
if (array[minIndex] > array[i])
{
minIndex = i;
}
}
}
if (minIndex != currentIndex)//如果上面循环结束之后没有相同,那么就执行
{
int temp = array[currentIndex];
array[currentIndex] = array[minIndex];
array[minIndex] = temp;
}
}
return array;
}
练习5:冒泡查重
定义检查数组中是否存在相同元素的方法
private static bool IsRepeating1(int[] array)
{
//定义检查数组中是否存在相同元素的方法int[]
//5 3 1 3 8
for (int i=0;i<array.Length-1;i++)
{
for (int a=i+1;a<array.Length;a++)
{
if (array[a] == array[i])
{
return true;
}
}
}
return false;
}