AllTheTimeWorld.com

csharp loopsNested Loops: generate a deck of cards

Nested Loops: generate a deck of cards

A loop for each suit with a nested loop for each card.
Also uses switch.

Nested Loops: generate a deck of cards

A loop for each suit with a nested loop for each card.
Also uses switch.


Text of video

Code to add a deck of cards to list using nested loops:

private void Form1_Load(object sender, EventArgs e)
{
   //A deck of cards has 4 suits: diamond,club, spade, heart
   //Each suit has cards from 0 to 10 plus Jack, Queen, King and Ace
   //We use a nested loop to add all 52 cards to the list box.
   for (int suit=0;suit<4;suit++)
   {
      String s = "";
      switch (suit)
      {
        case 0: s ="Diamond"+ (char)9826; break; 
        case 1: s = "Club" + (char)9827; break; 
        case 2: s = "Spade" + (char)9828; break; 
        case 3: s = "Heart" + (char)9829; break;
      }
      string c = "";
      for(int card=2;card<15;card++)
      {
        switch(card)
        {
          case 11: c = "Jack"; break;
          case 12: c = "Queen"; break;
          case 13: c = "King"; break;
          case 14: c = "Ace"; break;
          default: c= card.ToString(); break;
        }
        lstCards.Items.Add(c + " of " + s);
      }
    }
}