如何为每个循环转换我的循环? [英] How Would I Convert My For Loops To For Each Loop?
本文介绍了如何为每个循环转换我的循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用for循环制作了一个菱形图案程序。我想用foreach循环来做。任何人都可以请帮助我如何将我的for循环转换为foreach循环。
这是代码:
I have made a diamond pattern program using for loop. I want to do it using foreach loop. Any one can please help me out how do i convert my for loops to foreach loop.
Here is code:
Console.WriteLine("Program for displaying pattern of *.");
Console.Write("Enter the maximum number of *: ");
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\nHere is the Diamond of Stars\n");
for (int i = 0; i <= (n - 1); i = i + 2)
{
for (int j = 0; j <= i; j++)
Console.Write("*");
Console.WriteLine();
}
for (int i = n - 1; i >= 1; i = i - 2)
{
for (int j = 0; j < (i - 1); j++)
Console.Write("*");
Console.WriteLine();
}
推荐答案
在这些情况下,尝试没有任何意义:你没有使用对象的集合,因此没有foreach循环的基础 - 这些仅在您通过实现IEnumerable或IEnumerable< T>的对象集合进行迭代时起作用。接口。
Int32
不这样做,所以你不能使用foreach
替换for
循环。
In those cases, it makes no sense to try: you aren't using a collection of objects, so there is no base for a foreach loop - these only work when you are iterating though a collection of objects that implements the IEnumerable or IEnumerable<T> interface.
Int32
doesn't do that, so you can't use aforeach
to replace yourfor
loops.
这篇关于如何为每个循环转换我的循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文