C# 0 The Complete Reference


foreach  cycles through an array in sequence from the lowest index to  the highest. Although the  foreach



Download 4,07 Mb.
Pdf ko'rish
bet219/1096
Sana23.01.2022
Hajmi4,07 Mb.
#402171
1   ...   215   216   217   218   219   220   221   222   ...   1096
Bog'liq
C-Sharp 3 The Complete Reference Herbert Schildt

foreach

 cycles through an array in sequence from the lowest index to 

the highest.

Although the 



foreach

 loop iterates until all elements in an array have been examined, it 

is possible to terminate a 

foreach

 loop early by using a 



break

 statement. For example, this 

program sums only the first five elements of 

nums

:

// Use break with a foreach.



using System;

class ForeachDemo {

  static void Main() {

    int sum = 0;

    int[] nums = new int[10];

    // Give nums some values.

    for(int i = 0; i < 10; i++)

      nums[i] = i;

    // Use foreach to display and sum the values.

    foreach(int x in nums) {

      Console.WriteLine("Value is: " + x);

      sum += x;

      if(x == 4) break; // stop the loop when 4 is obtained

    }


    Console.WriteLine("Summation of first 5 elements: " + sum);

  }


}

This is the output produced:

Value is: 0

Value is: 1

Value is: 2

Value is: 3

Value is: 4

Summation of first 5 elements: 10

As is evident, the 

foreach

 loop stops after the fifth element has been obtained.

The

foreach

 loop also works on multidimensional arrays. It returns those elements in 

row order, from first to last.

// Use foreach on a two-dimensional array.

using System;

class ForeachDemo2 {

  static void Main() {

    int sum = 0;

    int[,] nums = new int[3,5];

www.freepdf-books.com




Download 4,07 Mb.

Do'stlaringiz bilan baham:
1   ...   215   216   217   218   219   220   221   222   ...   1096




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©hozir.org 2024
ma'muriyatiga murojaat qiling

kiriting | ro'yxatdan o'tish
    Bosh sahifa
юртда тантана
Боғда битган
Бугун юртда
Эшитганлар жилманглар
Эшитмадим деманглар
битган бодомлар
Yangiariq tumani
qitish marakazi
Raqamli texnologiyalar
ilishida muhokamadan
tasdiqqa tavsiya
tavsiya etilgan
iqtisodiyot kafedrasi
steiermarkischen landesregierung
asarlaringizni yuboring
o'zingizning asarlaringizni
Iltimos faqat
faqat o'zingizning
steierm rkischen
landesregierung fachabteilung
rkischen landesregierung
hamshira loyihasi
loyihasi mavsum
faolyatining oqibatlari
asosiy adabiyotlar
fakulteti ahborot
ahborot havfsizligi
havfsizligi kafedrasi
fanidan bo’yicha
fakulteti iqtisodiyot
boshqaruv fakulteti
chiqarishda boshqaruv
ishlab chiqarishda
iqtisodiyot fakultet
multiservis tarmoqlari
fanidan asosiy
Uzbek fanidan
mavzulari potok
asosidagi multiservis
'aliyyil a'ziym
billahil 'aliyyil
illaa billahil
quvvata illaa
falah' deganida
Kompyuter savodxonligi
bo’yicha mustaqil
'alal falah'
Hayya 'alal
'alas soloh
Hayya 'alas
mavsum boyicha


yuklab olish