Javatpoint Logo
Javatpoint Logo

For?ach loop in C#

Th? for?ach loop in C# is d?sign?d to simplify th? proc?ss of it?rating ov?r th? ?l?m?nts of a coll?ction, such as arrays, lists, dictionari?s, and oth?r data structur?s that impl?m?nt th? IEnum?rabl? or IEnum?rabl? int?rfac?. It offers a conv?ni?nt and ?ffici?nt way to acc?ss and proc?ss ?ach it?m in th? coll?ction. To und?rstand th? th?ory b?hind th? for?ach loop in C#, consid?r th? following k?y points:

Enum?ration: At its cor?, th? for?ach loop is an ?num?rator-bas?d it?ration m?chanism. It us?s an ?num?rator, which is an obj?ct that k??ps track of th? curr?nt position within th? coll?ction and allows you to r?tri?v? ?l?m?nts on? by on?. Th? ?num?rator is obtain?d from th? coll?ction using th? G?tEnum?rator() m?thod.

R?ad-Only: Th? for?ach loop is r?ad-only, meaning that it provid?s r?ad-only acc?ss to th? ?l?m?nts in th? coll?ction. You can r?tri?v? and ?xamin? th? ?l?m?nts but cannot modify th?m directly within th? loop. Att?mpting to modify ?l?m?nts will result in a compilation ?rror.

Automatic Initialization and Cl?anup: Th? for?ach loop automatically initializ?s th? ?num?rator, it?rat?s through th? coll?ction, and cl?ans up r?sourc?s wh?n th? loop is finish?d or wh?n an ?xc?ption occurs. This automatic management simplifi?s th? it?ration proc?ss and r?duc?s th? risk of r?sourc? l?aks.

Typ? Inf?r?nc?: Th? var k?yword is oft?n us?d in th? for?ach loop d?claration to l?t th? compil?r inf?r th? typ? of th? curr?nt ?l?m?nt.

Syntax:

It has the following syntax:

for?ach: It is th? k?yword that starts th? loop.

var it?m: It is th? d?claration of a local variabl? (it?m in this cas?) that r?pr?s?nts th? curr?nt ?l?m?nt in th? coll?ction during ?ach it?ration. Th? var k?yword is us?d for implicit typing, allowing C# to inf?r th? data typ? of it?m bas?d on th? typ? of th? ?l?m?nts in th? coll?ction.

in coll?ction: It sp?cifi?s th? coll?ction ov?r which you want to it?rat?. Coll?ction should b? an obj?ct that impl?m?nts th? IEnum?rabl? or IEnum?rabl? int?rfac?, which includ?s most coll?ction typ?s in C# such as arrays, lists, dictionari?s, and mor?.

Th? cod? block ?nclos?d in curly brac?s {}: It is th? body of th? for?ach loop, wh?r? you plac? th? cod? that you want to ?x?cut? for ?ach ?l?m?nt in th? coll?ction.

Program: Working with Generics

Output:

Stud?nt: Alic?
Ent?r grad?s (comma-s?parat?d): 2,3
Av?rag? Grad?: 2.50
Stud?nt: Bob
Ent?r grad?s (comma-s?parat?d):6,8
Av?rag? Grad?: 8.00
Stud?nt: Charli?
Ent?r grad?s (comma-s?parat?d): 5,6,8
Av?rag? Grad?: 6.33

Explanation:

For?ach Loop (Out?r Loop):

Th? out?r for?ach loop it?rat?s through ?ach stud?nt in th? stud?nts list.

For ?ach stud?nt, it performs the following tasks:

Stud?nt Information Input:

  • It displays th? stud?nt's nam?.
  • Prompts th? us?r to ?nt?r grad?s for th? stud?nt (comma-s?parat?d).
  • R?ads th? ?nt?r?d grad?s as a string and splits it using Split(',') to obtain an array of strings.

Inn?r For?ach Loop (Grad? Input):

  • Th? inn?r for?ach loop it?rat?s through ?ach grad? string ?nt?r?d by th? us?r.
  • It tri?s to pars? ?ach grad? string to an int?g?r using int.TryPars?.
  • If th? parsing is successful, it adds th? pars?d grad? to th? stud?nt's list of grad?s using th? AddGrad? m?thod.

Av?rag? Grad? Calculation:

  • Aft?r ?nt?ring all grad?s for th? stud?nt, it calculat?s th? av?rag? grad? using th? G?tAv?rag?Grad? m?thod.
  • After that, th? av?rag? grad? is display?d to th? us?r with two d?cimal plac?s ({av?rag?Grad?:F2}).

R?p?at for Each Stud?nt:

Th? out?r for?ach loop continu?s until all stud?nts in th? list hav? b??n proc?ss?d.

Compl?xity Analysis:

Tim? Compl?xity:

  • Th? tim? compl?xity of cr?ating a list of n stud?nts is O(n), wh?r? n is th? numb?r of stud?nts.
  • Th? out?r for?ach loop it?rat?s through ?ach stud?nt in th? stud?nts list. Sinc? th?r? ar? n stud?nts, th? tim? compl?xity of this loop is O(n).
  • Th? inn?r for?ach loop it?rat?s through th? ?nt?r?d grad?s for ?ach stud?nt. In th? worst cas?, if a stud?nt has m grad?s, th? tim? compl?xity of this loop within th? out?r loop b?com?s O(m), wh?r? m r?pr?s?nts th? maximum numb?r of grad?s among all stud?nts.
  • Calculating th? av?rag? grad? for ?ach stud?nt involv?s it?rating through th?ir grad?s. If a student has m grad?s, this calculation has a tim? compl?xity of O(m).
  • Th? tim? compl?xity of th? ?ntir? program can b? ?xpr?ss?d as O(n * m), wh?r? n is th? numb?r of stud?nts, and m is th? maximum numb?r of grad?s among all stud?nts.

Spac? Compl?xity:

  • Th? spac? compl?xity of th? stud?nts list is O(n), wh?r? n is th? numb?r of stud?nts.
  • Th? program cr?at?s n instanc?s of th? Stud?nt class, wh?r? ?ach instanc? holds th? stud?nt's nam?, a list of grad?s, and som? additional ov?rh?ad for obj?ct r?f?r?nc?s. Th? spac? compl?xity for th?s? obj?cts is O(n).
  • Each student has a list of grades. Th? spac? compl?xity for all grad? lists is O(m), wh?r? m is th? maximum numb?r of grad?s among all stud?nts.
  • Th? program us?s som? t?mporary variabl?s lik? av?rag?Grad?, grad?StrArray, and grad?. Th? spac? compl?xity for th?s? variabl?s is r?lativ?ly small and can b? consid?r?d O(1).
  • Th? spac? compl?xity of th? program can b? approximat?d as O(n + m), wh?r? n is th? numb?r of stud?nts, and m is th? maximum numb?r of grad?s among all stud?nts.

Program: working with lists

Output:

Long?st word: banana
Short?st word: fig

Explanation:

  • The program starts by creating a list of strings called words. This list contains five words: "appl?," "banana," "ch?rry," "dat?," and "fig".
  • Two string variabl?s, long?st and short?st, ar? initializ?d. long?st, will stor? th? long?st word found, whil? short?st initially assum?s th? first word in th? list is th? short?st.
  • Th? program us?s a for?ach loop to it?rat? through ?ach word in th? words list. For ?ach it?ration, th? curr?nt word is r?pr?s?nt?d by th? variabl? word.
  • Insid? th? loop, th? program compar?s th? l?ngth of ?ach word to th? l?ngths of th? long?st and short?st words found so far. If th? curr?nt word is long?r than th? curr?nt long?st, long?st is updat?d. Similarly, if th? curr?nt word is short?r than th? curr?nt short?st, short?st is updat?d.
  • Aft?r th? for?ach loop finish?s, th? program prints th? long?st and short?st words to th? consol?.

Compl?xity Analysis:

Tim? Compl?xity:

  • Th? tim? compl?xity of cr?ating a list of n strings is O(n), wh?r? n is th? numb?r of words in th? list.
  • Initializing th? long?st and short?st variabl?s tak?s constant tim?, O(1).
  • Th? for?ach loop it?rat?s through ?ach word in th? words list onc?. Sinc? th?r? ar? n words, th? tim? compl?xity of this loop is O(n).
  • Insid? th? loop, th? program compar?s th? l?ngth of ?ach word. Th?s? comparisons ar? constant tim? op?rations, O(1). Printing th? r?sults involv?s constant tim? op?rations, O(1).
  • Th? tim? compl?xity of th? ?ntir? program is dominat?d by th? for?ach loop, making it O(n), wh?r? n is th? numb?r of words in th? list.

Spac? Compl?xity:

  • Th? spac? compl?xity of th? words list is O(n), wh?r? n is th? numb?r of words in th? list.
  • Th? spac? compl?xity for th?s? variabl?s is O(1), as th?y only hold r?f?r?nc?s to strings and do not d?p?nd on th? siz? of th? input.
  • Th? program us?s a small numb?r of t?mporary variabl?s, such as word, which hav? a constant spac? compl?xity, O(1).
  • The spac? compl?xity of th? program is O(n), primarily du? to th? spac? r?quir?d to stor? th? list of words. Th? oth?r variabl?s and t?mporary storag? do not significantly aff?ct th? ov?rall spac? compl?xity.

Program: Enum?rating Dictionari?s

Output:

Alic?: 25 y?ars old
Bob: 30 y?ars old
Charli?: 28 y?ars old

Explanation:

  • The program starts by creating a Dictionary called ag?s. This dictionary is d?sign?d to stor? k?y-valu? pairs wh?r? th? k?ys ar? strings (r?pr?s?nting nam?s) and th? valu?s ar? int?g?rs (r?pr?s?nting ag?s).
  • Thr?? k?y-valu? pairs ar? add?d to th? ag?s dictionary using th? curly brac?s {} syntax within th? Dictionary initializ?r.
  • The main part of th? program is th? for?ach loop that it?rat?s through th? ag?s dictionary.
  • The for?ach loop is s?t up as follows: for?ach (var pair in ag?s).
  • In ?ach it?ration of th? loop, th? loop variabl? pair r?pr?s?nts a k?y-valu? pair from th? ag?s dictionary.
  • Th? loop continu?s to ?x?cut? until it has gon? through all th? k?y-valu? pairs in th? dictionary.
  • Insid? th? loop, w? ?xtract th? k?y (nam?) and valu? (ag?) from th? pair variabl?.
  • K?y r?tri?v?s th? k?y (nam?), which is a string, and assigns it to th? nam? variabl?.
  • Valu? r?tri?v?s th? valu? (ag?), which is an int?g?r, and assigns it to th? ag? variabl?.
  • Aft?r ?xtracting th? k?y (nam?) and valu? (ag?), th? program us?s Consol?.Writ?Lin? to display this information in a human-r?adabl? format.
  • It prints th? nam? and ag? of ?v?ryon? in th? format "Nam?: Ag? y?ars old" using th? nam? and ag? variabl?s.
  • Th? for?ach loop r?p?ats this proc?ss for ?ach k?y-valu? pair in th? ag?s dictionary.
  • In this ?xampl?, it will it?rat? thr?? tim?s (onc? for ?ach p?rson in th? dictionary).

Compl?xity Analysis:

Tim? Compl?xity:

  • Th? tim? compl?xity of initializing a dictionary with n k?y-valu? pairs is O(n), wh?r? n is th? numb?r of k?y-valu? pairs.
  • Th? for?ach loop it?rat?s through all th? k?y-valu? pairs in th? dictionary onc?. Sinc? th?r? ar? n k?y-valu? pairs, th? tim? compl?xity of this loop is O(n).
  • Acc?ssing th? k?y and valu? of ?ach k?y-valu? pair using K?y and pair.Valu? op?rations is a constant-tim? op?ration, O(1), because it doesn't d?p?nd on th? siz? of th? input.
  • Th? Consol?.Writ?Lin? op?ration for ?ach k?y-valu? pair is also a constant-tim? op?ration, O(1).
  • Th? tim? compl?xity of th? ?ntir? program is dominat?d by th? for?ach loop, making it O(n), wh?r? n is th? numb?r of k?y-valu? pairs in th? dictionary.

Spac? Compl?xity:

  • Th? spac? compl?xity of th? dictionary its?lf is O(n) b?caus? it stor?s n k?y-valu? pairs.
  • Th? spac? compl?xity for th?s? variabl?s is O(1) b?caus? th?y only hold r?f?r?nc?s to ?xisting data, and th? amount of m?mory th?y consum? do?s not d?p?nd on th? siz? of th? input.
  • Th? program prints strings to th? consol?, which r?quir?s t?mporary m?mory for th?s? strings. How?v?r, th? spac? us?d by th?s? strings is r?lativ?ly small and can b? consid?r?d O(1).
  • Th? spac? compl?xity of th? program can b? approximat?d as O(n), primarily du? to th? spac? r?quir?d to stor? th? dictionary. Th? oth?r variabl?s and t?mporary storag? do not significantly aff?ct th? ov?rall spac? compl?xity.

B?n?fits:

Th? for?ach loop in C# off?rs s?v?ral b?n?fits, making it a pr?f?rr?d choic? for it?rating ov?r coll?ctions, arrays, and ?num?rabl? data structur?s. H?r? ar? th? k?y advantag?s of using th? for?ach loop:

Optimization: Mod?rn C# compil?rs and runtim? ?nvironm?nts oft?n optimiz? for?ach loops for b?tt?r p?rformanc?. This optimization can l?ad to fast?r cod? ?x?cution compared to manually managing indic?s or it?rators.

R?duc?d Cod? Boil?rplat?: Compar?d to traditional for loops, for?ach loop ?liminat?s th? n??d for manual manag?m?nt of loop variabl?s, incr?m?nting, and bounds ch?cking. It r?duc?s cod? v?rbosity and boil?rplat?.

Improv?d Error Handling: The for?ach loop can h?lp improv? ?rror handling. By abstracting th? it?ration logic, it r?duc?s th? chanc?s of off-by-on? ?rrors and ind?x-r?lat?d bugs that ar? common with oth?r loop constructs.

Enhanc?d Cod? Maintainability: Th? concis? and ?xpr?ssiv? natur? of for?ach loops mak?s th? cod?bas? ?asi?r to maintain. D?v?lop?rs sp?nd l?ss tim? d?bugging it?ration-r?lat?d issu?s, allowing th?m to focus on high?r-l?v?l logic.

Functional Programming Support: for?ach loops align with th? principl?s of functional programming by promoting a d?clarativ? style of coding. It can l?ad to cl?an?r and mor? maintainabl? cod? that ?mphasiz?s what n??ds to b? don? rather than how to do it.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA