FAQ: Loops - Review

Solution for the second problem:

using System;

namespace LoopsReview
{
  class Program
  {
    static void Main(string[] args)
    {
     //Declaring an array which hold numbers
     int[] numbers = { 10, 5, 12, 3421, 904, 84 };

     //Calling every numbers of the array via loop
     for (int i = 0; i < numbers.Length; i++)
     {
     //Checking if it's odd or not
     if (numbers[i] % 2 == 0)
        Console.WriteLine($"{numbers[i]} is an even number.");
     else
        Console.WriteLine($"{numbers[i]} is an odd number.");
     }
    }
  }
}

Second problem:

int[] numbers = new int[] {1,2,3,4,76,35,34,53,5,34,87,75,665};

    foreach(int number in numbers)

    {

      if(number % 2 == 0)

      {

        Console.WriteLine($"{number} is even");

      }

      else 

      {

         Console.WriteLine($"{number} is odd");

      }

    }

Here’s my attempt. I decided to also list the factors for each number and through that, work out if the number is a prime.

for (int i = 1; i <= 50; ++i)
{
    Console.WriteLine(i % 2 == 0 ? $"{i}: even": $"{i}: odd") ;
    // List factors or mark as prime
    string factors = "";
    for (int j = 1; j<i/2+1; ++j)
    {
        if (i % j == 0)
        {
factors = factors + $" {j}";
        }
    }
    if (i < 4) { factors = " 1"; };
    Console.WriteLine(factors == " 1" ? $"{i} is a prime number! \n": $"The factors of {i} are{factors}\n");

Second challenge. I confess that if I hadn’t peaked here and seen the split function, I’d have been stuck. With that, it was pretty straightforward. I made life difficult for myself as I wanted to get rid of the extra punctuation. This cost me the most time. I couldn’t find a Regex.Replace formula that would would go through the final string and take out the punctuation, but not the spaces. Any tips here appreciated. The formula I did use, I just found by googling, but it would be more efficient were it outside of the loop.

//String generated using "=rand(3)" in MS Word
string input = "Video provides a powerful way to help you prove your point. When you click Online Video, you can paste in ... (shortened here for space!)");
char wantedLetter = (char)Console.Read();
wantedLetter = char.ToLower(wantedLetter);
string output = "";
string[] indivWords = input.Split(' ');
foreach (string word in indivWords)
{
    if (word.Substring(0, 1).ToLower() == char.ToString(wantedLetter))
    {
        string subword = Regex.Replace(word, "[^a-zA-Z0-9]+", "", RegexOptions.Compiled);
        output = output + " " + subword;
    }
}
Console.WriteLine(output == "" ? $"Sorry, no words starting with {wantedLetter}" : output);

Why does this code run into an error:

using System; namespace LoopsReview { class Program { static void Main(string[] args) { /* use this space to write your own short program! Here's what you learned: while loop: while(){..} do...while loop: do{...}while(); for loop: for(int i=0; i<x; i++){} foreach loop: foreach(int item in list){} jump statements: break, continue, return Good luck! */ foreach (int item in int[] items = {1, 2, 3}) { Console.WriteLine(item); } } } }

?

So. I have been making the code for a first quizz (where it prints out only words starting with a). If someone needs it, here’s what I got:

using System; namespace LoopsReview { class Program { static void Main(string[] args) { string text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."; string[] textArray = text.Split(' '); foreach (string word in textArray) { if (word[0] == 'a' || word[0] == 'A') { Console.WriteLine(word); } } } } }

The output is going to be:

  • and
  • an
  • a
  • and
  • a
  • also
  • and
  • Aldus

It’s a pretty simple code. Not sure if that’s the best option but I hope this will help someone :slight_smile:

(Here is an explanation of how the code works) ==>
Make a variable that contains the text. ( string text = [something] )
Make a variable that sorts every single word in the text as an array. ( string textArray = text.Split(’ '); )
Make a loop that checks every single word in our array text. ( foreach (string word in textArray) {} )
And finally make an if statement inside of the loop, that checks if the word starts with a or A. ( (word[0] == ‘a’ || word[0] == ‘A’) )

Here’s my modified choose your own adventure. I used bits and pieces from the original choose your own adventure exercises and modified it. It’s a tad messy as I was really trying to play with my while loops, but it all worked out in the end.

using System;

namespace ChooseYourOwnAdventure
{
    class Program
    {
        static void Main(string[] args)
        {
            /* THE MYSTERIOUS NOISE */

            // Start by asking for the user's name:
            Console.Write("What is your name?: ");
            string name = Console.ReadLine();

            while (name == "")
            {
                Console.WriteLine("What is your name?:");
                name = Console.ReadLine();
            }
            Console.WriteLine($"Hello, {name}! Welcome to our story.");

            Console.WriteLine("It begins on a cold rainy night. You're sitting in your room and hear a noise coming from down the hall. Do you go investigate?");

            string noiseChoice = Console.ReadLine();


            while (noiseChoice == "no" || noiseChoice == "NO" || noiseChoice == "")
            {
                Console.WriteLine(noiseChoice.ToUpper());
                Console.WriteLine("You have decided to remain in the room. \n Do you want to change your mind?");
                noiseChoice = Console.ReadLine();
            }
            if (noiseChoice == "yes" || noiseChoice == "YES")
            {
                Console.WriteLine(noiseChoice.ToUpper());
                Console.WriteLine("You walk into the hallway and see a light coming from under a door down the hall. \n You walk towards it. Do you open it or knock? ");
                Console.WriteLine("Type OPEN or KNOCK");
            }
            


            string doorChoice = Console.ReadLine();

            while (doorChoice == "knock" || doorChoice == "KNOCK")
            {
                Console.WriteLine(doorChoice.ToUpper());
                Console.WriteLine("You knocked on the door. There was no answer. \n If you would like to open the door, type OPEN.");
                doorChoice = Console.ReadLine();

            }

            if (doorChoice == "open" || doorChoice == "OPEN")
            {
                Console.WriteLine(doorChoice.ToUpper());
                Console.WriteLine("The door is locked! You must answer the riddle.");
                Console.WriteLine("Answer the riddle (The answer is NOTHING)");
            }

            string riddleAnswer = Console.ReadLine();

            while (riddleAnswer != "nothing" || riddleAnswer != "NOTHING")
            {
                Console.WriteLine("You answered incorrectly. The door doesn't open. \nWould you like to try again?");
                riddleAnswer = Console.ReadLine();
                //You could use a newline here instead of multiple Console.WriteLines.

                if (riddleAnswer == "nothing" || riddleAnswer == "NOTHING")
                {
                    Console.WriteLine("You open the door and feel an immense terror. You go back to your room, turn the lights off and close the door.");
                    Console.WriteLine("THE END");
                    break;
                }
                

            }
            
        }
    }
}