foreach和for

1、foreach循环与for循环输出结果比较,能达到一样的输出效果。

 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace ForeachApplication
7 {
8 class Program
9 {
10 static void Main(string[] args)
11 {
12 int[] a = { 1,5,9,20,16};
13 Console.WriteLine("使用foreach ....结果");
14 foreach (int i in a)
15 {
16 Console.WriteLine("{0}",i);
17 }
18 Console.WriteLine("使用for ....结果");
19 for (int j = 0; j < 5; j++)
20 Console.WriteLine("{0}",a[j]);
21 }
22 }
23 }

2、foreach与 for 的主要区别在于 foreach 循环对数组内容进行只读访问,所以不能改变任何元素的值。而for 循环可以,看下面代码:

foreachfor
 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace ForeachApplication
7 {
8 class Program
9 {
10 static void Main(string[] args)
11 {
12 int[] a = { 1,5,9,20,16};
13 Console.WriteLine("使用foreach ....结果");
14 foreach (int i in a)
15 {
16 Console.WriteLine("{0}",i);
17 }
18 Console.WriteLine("使用for ....结果");
19 for (int j = 0; j < 5; j++)
20 // Console.WriteLine("{0}",a[j]);
21 {
22 if (a[j] > 10)
23 {
24 a[j] = 7;
25 }
26
27 }
28 Console.WriteLine("把数组中的大于10的数,修改成7后....输出结果");
29 foreach (int i in a)
30 {
31 Console.WriteLine("{0}", i);
32 }
33 }
34 }
35 }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值