Advertisement
karlakmkj

List - for & foreach loop

Nov 27th, 2020
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.06 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace LearnLists
  5. {
  6.   class Program
  7.   {
  8.     static void Main()
  9.     {
  10.       List<string> runners = new List<string> { "Jemima Sumgong", "Tiki Gelana", "Constantina Tomescu", "Mizuki Noguchi" };
  11.       Random rand = new Random();
  12.      
  13.       Console.WriteLine("In reverse chronological order, the gold medalists are...");
  14.      
  15.       // First loop
  16.       for (int i = 0; i < runners.Count; i++)
  17.       {
  18.         Console.WriteLine($"{i+1}: {runners[i]}");
  19.       }
  20.      
  21.       Console.WriteLine("\nPrinting runner bibs...");
  22.      
  23.       // Second loop - using for loop and foreach loop to achieve the same result
  24.       for (int i = 0; i < runners.Count; i++)
  25.       {
  26.           string name = runners[i].ToUpper();
  27.           int id = rand.Next(100, 1000);
  28.           Console.WriteLine($"{id} - {name}");
  29.       }
  30.       foreach(string runner in runners){
  31.         string name = runner.ToUpper();
  32.         int id = rand.Next(100, 1000);
  33.         Console.WriteLine($"{id} - {name}");
  34.       }
  35.     }
  36.   }
  37. }
  38.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement