FAQ: Loops - Review

This community-built FAQ covers the “Review” exercise from the lesson “Loops”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Learn C#

FAQs on the exercise Review

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in #get-help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to #get-help and #community:tips-and-resources. If you are wanting feedback or inspiration for a project, check out #project.

Looking for motivation to keep learning? Join our wider discussions in #community

Learn more about how to use this guide.

Found a bug? Report it online, or post in #community:Codecademy-Bug-Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

For the third suggested practice program (a choose your own adventure game) how do I get the console to accept input from the player? (i.e. Console.Readline())

In previous lessons there was a reference to a “regular console” that requires “dotnet run” to run the program. How do I get one of those so I can have the player put stuff in?

Thanks!

Hello, @data1382960316, and welcome to the forums.

You could google C# IDE’s, and find several options, but for a sandbox type environment where you can practice things you’re learning, repl.it works quite well.

1 Like

I need help with this: Loops through a piece of text and only prints words that start with the letter “a” to the console to create a poem.

Hello, @elab234. What have you got so far? I would start by writing a short poem using only words that start with “a”, and then sprinkle those words into a string in the order they appear in the poem. Use a loop to iterate through each word in the string, and print only the words that start with “a”. The resulting printed output would be the poem I had written.

I think I’m hitting the same problem. I’ve done something like you’ve suggested but kind of boiled it down in the hopes to just get the basics of what I/we are trying to accomplish. So made a string consisting of a sentence that contains several words that begin with “a”… and that’s as far as I’ve got.

I figured from there I could use IndexOf to search through the string for the letter “a”, but then realised that could come back with the index of that letter at any point in a word. So changed it to search for " a" (an “a” with a space before it), but that’s when I hit my next block. I’ve no idea what to write to get the code to take that information and somehow pick out the the word that is starting at that point in the string, and only that word. I did think of doing so kind of double index check to find a space following where the " a" was found, but after that I don’t know how to get it to print out the information between those two points.

I’ve tried Googling around and found things about checking to see what a string starts with, or if it starts with a particular character/word. Or the same but at the end of the string.

The closest I found to make a string for the poem/sentence, another for the what we’re looking for (the start - it would be “a” but again we need to be sure its the start of a word, so this is " a"), and what we’re looking for after that (a space to indicate the end of the word). Then make an if statement with a condition looking at the sentence containing the start, when that’s true AND when it’s also true that it finds in the sentence what we’ve declared is the end.
Then to declare start and end points and create a substring using them. Most of this is actually doable with what we’ve previously been taught, EXCEPT the if condition uses this: String.Contains. I don’t remember seeing this - I may be wrong, and there may be another way around it but this is all I’ve found so far.

So what I have is:

strSource = the poem;
strStart = " a";
strEnd = " ";

if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
int Start, End;
Start = (strSource.IndexOf(strStart, 0) - 1) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
Console.WriteLine(strSource.Substring(Start, End - Start));
}

I’ve then tried putting this inside a ‘for’ loop, with the thought that I’d assign a boolean value to, say, ‘i’. Set it to ‘true’, then in the ‘if’ statement put “i = strSource…”. Also pop “continue;” at the end of the ‘if’ section. My thinking here is that it would loop through until it got to the end of the poem/sentence and then I’d have it stop. But sadly on trying this I just kept getting errors about my ‘for’ condition.

Consider what you need to do here. Ideally, you’d loop through each word of the string. If the word starts with the letter ‘a’ or ‘A’ (presumably), you print it. If it doesn’t start with ‘a’ or ‘A’, you move on to the next word. There is a much easier way to iterate through the string one word at a time, but you likely aren’t familiar with it. Look into String.Split().

If you’d rather not use String.Split() which would return an array containing each word as elements of the array, you could use a for loop to iterate through each character of the string. If the character is ‘a’ or ‘A’, you could test the characters before and after looking for " " (a space) to see if the ‘a’ or ‘A’ is the beginning of a word. This would be way more work, and you’d have to account for edge cases like if the string started with a word beginning with ‘a’ or ‘A’ (There would be no character before it to check).

In either case, remember that you can access parts of a string by index:

string word = "about";
Console.WriteLine(word[0]); //prints: a

Here’s an example of using Split():

      string blah = "Hello there, fellow. How are you today?";
      string[] blahArray = blah.Split(' '); //splits the string using a single space as the delimiter
      Console.WriteLine(blahArray); //shows us that blahArray is an array
      foreach(string word in blahArray)
      {
        Console.WriteLine(word); //print each element of the array
      }

Output:

System.String[]
Hello
there,
fellow.
How
are
you
today?
3 Likes

I understand what you’ve put and your explaination, and thank you for the help.

The only problem I have is that this has not been touched on yet. I’ve sure a lot of people that go through these courses are people looking to expand their coding knowledge from other languages or re-up after not using it for a while. Sadly I am a complete noob. I am happy to put in some extra work; looking around to try and find answers (which is how I came by the stuff I previously posted). But otherwise I’ve no idea what I’m looking for to be able to search for what can help, and assume that I should be able to use the stuff that’s been previously taught in the course to provide the solution.

BTW this isn’t meant in any way as shouting/having a go/otherwise being aggressive. There have been a few times not going through the lessons where by the end it suggests using what you’ve learned to do certain things, but the answer seems to include stuff that hasn’t been taught.

2 Likes

Hello! Complete newbie here. I’m not sure if I’m answering question 1 here.

Yeah, don’t mind the poem used for the practice. :sweat_smile:

      string poem = "A duck walked up to a lemonade stand and he said to the man, running the stand. Hey! Bum bum bum. Got any grapes?";

string[] poemConvert = poem.Split(' ');

foreach (string a in poemConvert)
{
  if(a.Substring(0,1) != "a" && a.Substring(0,1) !="A")
  {
  continue;
  }
  Console.WriteLine($"{a}.");
}

Console output:
A.
a.
and.
any.

1 Like

Just a couple of observations.

  1. Perhaps an easier way to access the first letter of a string is to use its index: a[0]

  2. How could you make the code inside your for loop more concise? Would you for example ask someone to:

    1. Check each bedroom in the house.
    2. If the light is off and the ceiling fan is off, don’t do anything, otherwise turn off the switch.

    Or:

    1. Check each bedroom in the house.
    2. If the light is on or the ceiling fan is on, turn off the switch.

I’m also attempting the 1st poem activity here and can’t understand why what I have isn’t working. I have just entered my string into an array rather than using split (i should have used split, yes).

static void Main(string[] args)

    {

      string[] poem = { "Curtains", "are", "forcing", "their", "will", "against", "the", "wind", "and", "children"};

      foreach (string word in poem)

      {

        if (word[0] == "a")

        {


          Console.WriteLine(word);

        }      

      }

    }

I’m getting the error “Operator ‘==’ cannot be applied to operands of type ‘char’ and ‘string’”

Is it because word[0] is actually a char and “a” is a string? How would I compare it to a char rather than a string?

I have managed to fix my code but it doesn’t feel right. I assigned “a” to a string called A. Then i compared word[0] == A[0]. Doesn’t feel like how I’m meant to do this but I don’t know how to assign a character to a variable instead of a string or directly compare to the character “a”.

Hello, @py7970378822, and welcome to the forums.

In C#, ' and " aren’t interchangable like in some other languages. 'a' is of type Char, while "a" is of type String. When you get the first character of word using word[0] it is a Char, so you can’t compare it to the String "a", but you could compare it to the Char 'a'.

Here’s my solution for the program that loops through a list of numbers and if it is even, prints even and if it’s odd, prints odd.

using System;

namespace LoopsReview
{
  class Program
  {
    static void Main(string[] args)
    {
      int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};

      foreach (int number in numbers)
      {
        if (number % 2 == 0)
        Console.WriteLine($"{number} is even.");
        else
        {
          Console.WriteLine($"{number} is odd.");
        }
      }

    }
  }
}

Here is the solution I found:

using System;
namespace LoopsReview
{
class Program
{
static void Main(string args)
{
Console.WriteLine(“This program will find all a’s inside of a string and print them in the console.” + “\n”); //I deciseded not to make it so the result was a poem but rather a word finder. string poem = " In all chaotic beauty lies a wounded work of art. \nBeautiful but torn, wreaking havoc on my heart. \nCamouflaged by insecurities, blinded by it all.\nI love the way you sit there and barely notice me at all. \n";
//This indicates the desired letter to find.
string toFind = “a”;
//Prints the poem
Console.WriteLine(poem);
//This line divides every word into an indivdual array each time that an space (’ ‘) is found.
string poemArray = poem.Split(’ ');
//This uses the foreach loop to check every element.
foreach (string word in poemArray)
{
//This IF statement prints any word that gets passed by the foreach loop that meats the requirements, in this case its that it startes with the letter/word indicated in toFind
if (word.StartsWith(toFind))
{
Console.WriteLine(word);
}
}
}
}
}

Do not worry if you do not get it at first. There are certain methods, and tools you have not learned yet, Also if you separate your sentences with \n make sure to put a space, since I notices that the program would print “art. Beautiful” if I wrote “art.\nBeautiful” without spaces. It seems it reads it as one line.

I found an easy solution; but:

string text = “I had a baby one day, and it crashed into a park all around smack down yes sir a cat ate a pig and ran down town as the day flew by always.”;

string newArray = text.Split(" ");
foreach (string s in newArray)
{
if (s[0] == ‘a’)
{
Console.WriteLine(s);
}
}
Console.Write(newArray[0]);

I could use some help with the first challenge. In my first solution I get an error that says:‘nullable reference types’ is not available in C# 7.3. Please use language version 8.0 or greater.
I’m not sure why this doesn’t work:

static void Main(string[] args)

    {

      string text = "I had a baby one day, and it crashed into a park all around smack down yes sir a cat ate a pig and ran down town as the day flew by always.";

      //Console.Write(text[0]);

      for (int i = 0; i < (text.Length - 1); i++)

      {

        if (text[i] == 'a')

        {

          do

          {

            Console.Write(text[i]);

          } while (text[i] ! ' ');

          Console.Write(" ");

        }

      } 

      /* 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! */

    }

Here’s my solution to the Poem Program:

using System;

namespace poem

{

  class Program

  {

    static void Main(string[] args)

    {

      string origText = "I am naturally observant, as you may have remarked, Mr. Holmes, and I soon had a pretty good plan of the whole house in my head. There was one wing, however, which appeared not to be inhabited at all. A door which faced that which led into the quarters of the Tollers opened into this suite, but it was invariably locked. One day, however, as I ascended the stair, I met Mr. Rucastle coming out through this door, his keys in his hand, and a look on his face which made him a very different person to the round, jovial man to whom I was accustomed. His cheeks were red, his brow was all crinkled with anger, and the veins stood out at his temples with passion. He locked the door and hurried past me without a word or a look.";

     

      /// Split the original text string into an array of strings, using spaces, commas and full stops as 'string seperators'

      string[] stringSeparators =  new string[] {" ", ",", "."};

      string[] textResult = origText.Split(stringSeparators, StringSplitOptions.None);

      Console.WriteLine("What's your favourite letter?");

      string userLetter = Console.ReadLine();

      // Find all strings in the array that being with the users chosen letter and make an array

      string[] poemResult = Array.FindAll(textResult, (ele) => {

        return ele.StartsWith(userLetter, StringComparison.InvariantCultureIgnoreCase);

      });

      

      /// Loop through the new array and write each word to the console 

      Console.WriteLine($"\nMy {userLetter} Poem");

      Console.WriteLine($"");

      for (int it = 0; it < poemResult.Length; it++){

          Console.WriteLine("{0}", poemResult[it]);

          }

    }

    }

}

I agree with you 100%. That’s been my experience in 5 of the 6 courses I’ve taken on this site. In “reviewing what you’ve learned,” they ask you to do something, and when either using ‘View Solution’ or checking these forums, you find that the solution hasn’t yet been presented in the material.