14 Replies - 466 Views - Last Post: 15 June 2013 - 06:30 AM Rate Topic: -----

#1 Semus  Icon User is offline

  • D.I.C Head

Reputation: 14
  • View blog
  • Posts: 126
  • Joined: 27-May 13

Linking entries in a 2 dimensional array

Posted 14 June 2013 - 07:53 AM

So here we are once again. It's a brand new challenge (the other 2 challenges in the book at the end of this chapter I absolutely breezed through) and I'm a bit confused.

I'll try to explain this one as simply as possible.

The challenge states to create a program to store the names of my five best friends (or any name for that matter) and their birthdays. Ask the user to enter a name, then look up that name in your list and display their birthday. It also says "HINT: Use a multi-dimensional array to keep the names and birthdays linked."

I know I'm probably over thinking this one, but I have at least gotten this far. Here's my code:

           string[,] friends1 = new string[5, 2];

            Console.WriteLine("Please enter the names and birthdays of your 5 closest friends:");

                Console.Write("\t\tFirst name: ");
                friends1[0, 0] = Console.ReadLine();
                Console.Write("\t\tNow their birthday: ");
                friends1[0, 1] = Console.ReadLine();
                Console.Write("\t\tSecond name: ");
                friends1[1, 0] = Console.ReadLine();
                Console.Write("\t\tNow their birthday: ");
                friends1[1, 1] = Console.ReadLine();
                Console.Write("\t\tThird name: ");
                friends1[2, 0] = Console.ReadLine();
                Console.Write("\t\tNow their birthday: ");
                friends1[2, 1] = Console.ReadLine();
                Console.Write("\t\tFourth name: ");
                friends1[3, 0] = Console.ReadLine();
                Console.Write("\t\tNow their birthday: ");
                friends1[3, 1] = Console.ReadLine();
                Console.Write("\t\tFifth name: ");
                friends1[4, 0] = Console.ReadLine();
                Console.Write("\t\tNow their birthday: ");
                friends1[4, 1] = Console.ReadLine();

                Console.ReadLine();


What I am trying to do is store the names and their birthdays in the 2 dimensional array. For example, the first name goes in row 0, column zero, and their birthday goes in row 0, column 1. And it continues on down the rows with each birthday directly below the name, in column 1.

This code works fine so far, but as far as linking the birthdays to the names, I think I screwed that part up with this code. I don't think I've actually linked anything at all.

The book is rather unclear about linking objects in an array, so I am a bit confused.

I know that you don't like to give out answers and I'm not looking for a solution, but am I even on the right track?

Is This A Good Question/Topic? 0
  • +

Replies To: Linking entries in a 2 dimensional array

#2 Momerath  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1010
  • View blog
  • Posts: 2,444
  • Joined: 04-October 09

Re: Linking entries in a 2 dimensional array

Posted 14 June 2013 - 08:09 AM

Other than not using a loop to enter the data (not sure if you are up to loops yet), you are doing fine. The names and dates are 'linked' because they are in the same row of the array.

Loop example:
string[,] friends1 = new string[5, 2];

Console.WriteLine("Please enter the names and birthdays of your 5 closest friends:");

for (int i = 0; i < friends1.GetLength(0); i++) {
    Console.Write("\t\tName #{0}: ", i+1);
    friends[i,0] = Console.ReadLine();
    Console.Write("\t\tNow their birthday: ");
    friends[i,1] = Console.ReadLine();
}

Was This Post Helpful? 0
  • +
  • -

#3 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4484
  • View blog
  • Posts: 7,812
  • Joined: 08-June 10

Re: Linking entries in a 2 dimensional array

Posted 14 June 2013 - 08:17 AM

When they say "linking", they just mean that you should put the two linked values at the same first index of the array. So, if my name goes at friends1[0,0], then my birthday should go at friends1[0,1].

It looks like you've basically done it right.

However, I'd suggest using a loop. That way, you can expand your functionality later.

I'm going to do something that I don't usually do; I'm going to give you some code.

//use this constant as our array length
const int maxLength = 5;
//make an array using our constant
string[,] friends = new string[maxLength, 2];
//loop. start at zero, go while i is less than our const
for (int i = 0; i < maxLength; i++)
{
    //Get values (btw, we're using i+1 because arrays start at zero,
    //but humans start at 1
    Console.Write("Please enter name {0}: ", i + 1);
    string name = Console.ReadLine();
    Console.Write("Enter his/her birthday: ");
    string bday = Console.ReadLine();
    //assign values to our array:
    friends[i, 0] = name;
    friends[i, 1] = bday;
}



I'll walk you through it. First, it's best to avoid magic numbers. Your length of 5 was a "magic number". We'll replace that with a constant. Now, if we changed the assignment to hold six people, we only have to change one value and the rest of the program already works!

Next, instead of writing code to ask for each number, we'll write a loop. We start at zero, and go as long as i is less than our constant.

Then, we just assign what we fetch.
Was This Post Helpful? 0
  • +
  • -

#4 Semus  Icon User is offline

  • D.I.C Head

Reputation: 14
  • View blog
  • Posts: 126
  • Joined: 27-May 13

Re: Linking entries in a 2 dimensional array

Posted 14 June 2013 - 08:30 AM

Your solutions seem very intuitive, AND I like the fact that you used a constant. I just learned about those and wanted to try something with constants soon. Now you've shown me one way to use them, so thank you.

I had a feeling that loops would be a part of the solution, but I just couldn't get my head around how to implement them. I really need to start thinking about loops more often because they really are used quite a bit for so many things.

Just a little FYI here... I didn't know you could substitute the first value in the array with a variable and then increment that variable. It seems logical, but I have just never seen it done before. It's great to know it can be done.

Now, as far as accessing the birthdays later after entering a name, I'll have to think about that for awhile. I'll repost when I have the full challenge done so I can track my progress.
Was This Post Helpful? 0
  • +
  • -

#5 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4484
  • View blog
  • Posts: 7,812
  • Joined: 08-June 10

Re: Linking entries in a 2 dimensional array

Posted 14 June 2013 - 08:33 AM

Well, as to that, you could take my code, and sort of flip it. Instead of writing to the array, you can just grab values from it.
Was This Post Helpful? 0
  • +
  • -

#6 tlhIn`toq  Icon User is online

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5512
  • View blog
  • Posts: 11,817
  • Joined: 02-June 10

Re: Linking entries in a 2 dimensional array

Posted 14 June 2013 - 08:34 AM

I might suggest you are getting to a stage where you could include methods. You want to get out of this bad habit of procedurally coding one massive main() method, as soon as you can.

Instead of 50 input lines, none of which do any kind of data validation, you could call an input method that at least confirms the user entered something.

friends[0,0] = GetUserInput("First Name");
friends[0,1] = GetUserInput("Birthday");
friends[0,3] = GetuserInput("Gender");


string GetUserInput(string Prompt)
{
   string result = string.Empty;
   while (string.isemptyorwhitespace(result)
   {  
      Console.Write(string.format("\t\t{0}: ",Prompt);
      result = Console.GetLine();
   }
}


Now you have a method that will continue to prompt until the user does more than just hit [ENTER]. They actually have to enter something.
Was This Post Helpful? 0
  • +
  • -

#7 Semus  Icon User is offline

  • D.I.C Head

Reputation: 14
  • View blog
  • Posts: 126
  • Joined: 27-May 13

Re: Linking entries in a 2 dimensional array

Posted 14 June 2013 - 09:14 AM

View PostCurtis Rutland, on 14 June 2013 - 08:33 AM, said:

Well, as to that, you could take my code, and sort of flip it. Instead of writing to the array, you can just grab values from it.


you're probably right, but your code has me a little more confused now. I've never seen this done before:

	    friends[i, 0] = name;
	    friends[i, 1] = bday;


Although, going through the debugger, I see what's happening.

Still, it's really confusing me. how can the variable "name" or "bday" be equal to multiple entries in an array. If I saw the entire code I'd be able to debug and perhaps see what was going on, but I don't want you to do that.

Perhaps you could explain what's going on in greater detail? flipping the code around even visually, I can't seem to understand how to access the data back out of the variables.


@tlhIn`toq

I haven't gotten to methods yet. I'm sure there are several, simpler ways to do this kind of thing, but the book expects me to handle it in a certain way and I'd like to stick to that for now. I appreciate the suggestion, though.

This post has been edited by Semus: 14 June 2013 - 09:16 AM

Was This Post Helpful? 0
  • +
  • -

#8 Witchking  Icon User is offline

  • D.I.C Head

Reputation: 68
  • View blog
  • Posts: 188
  • Joined: 17-February 13

Re: Linking entries in a 2 dimensional array

Posted 14 June 2013 - 09:46 AM

You're using a two dimensional array so unlike in a regular old array you can't simply represent the elements with a single number like first ([0]) and second ([1]). Instead the array is like a plane with two directions: x and y, or rows and columns. You can use each row to represent a person, where the first column is the name and the second is the birthday. MyArray[0,0] returns the first row, and first column.
friends[i, 0] = name;
friends[i, 1] = bday;
Similarly this sets the the first column (0) in the i:th row to the value of name and the second column (1) to the value of bday.
Spoiler


An array isn't limited to just two dimensions of course. A three dimensional array is like a box with x, y, and z dimensions. Going further, visualizing it becomes more difficult as we are inherently incapable of perceiving higher dimensional space, however the principle remains the same.

This post has been edited by Witchking: 14 June 2013 - 09:54 AM

Was This Post Helpful? 0
  • +
  • -

#9 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2262
  • View blog
  • Posts: 9,464
  • Joined: 29-May 08

Re: Linking entries in a 2 dimensional array

Posted 14 June 2013 - 10:25 AM

View PostSemus, on 14 June 2013 - 05:14 PM, said:

	    friends[i, 0] = name;
	    friends[i, 1] = bday;


Although, going through the debugger, I see what's happening.

Still, it's really confusing me. how can the variable "name" or "bday" be equal to multiple entries in an array. If I saw the entire code I'd be able to debug and perhaps see what was going on, but I don't want you to do that.


I think you are confusing yourself with the term "equal to", as = means assignment;-
You can think of assignment as taking the value on the righthand side is placed (assigned) to the location on the left hand side.
Where To Store = Value To Store .

Mathematically the symbol should be :=

The symbol for "equal to" is == (in C#).

This post has been edited by AdamSpeight2008: 14 June 2013 - 10:27 AM

Was This Post Helpful? 0
  • +
  • -

#10 tlhIn`toq  Icon User is online

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5512
  • View blog
  • Posts: 11,817
  • Joined: 02-June 10

Re: Linking entries in a 2 dimensional array

Posted 14 June 2013 - 10:42 AM

If you're only going two dimensions, had you considered a Dictionary<key, value> ? Its a lot more versatile. Or even a List<T> where the type is a Person class with properties of 'Name', Birthday, Gender and so on.

The generic array is limited compared to these types. There are places where it is the best choice - but not here where you have to pre-define the size and you don't know how many people the user is going to want to enter.
Was This Post Helpful? 0
  • +
  • -

#11 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2262
  • View blog
  • Posts: 9,464
  • Joined: 29-May 08

Re: Linking entries in a 2 dimensional array

Posted 14 June 2013 - 10:48 AM

Tutorial: Parallel Arrays, Array with Object (Class & Structure)
Was This Post Helpful? 0
  • +
  • -

#12 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4484
  • View blog
  • Posts: 7,812
  • Joined: 08-June 10

Re: Linking entries in a 2 dimensional array

Posted 14 June 2013 - 11:42 AM

View PostSemus, on 14 June 2013 - 11:14 AM, said:

View PostCurtis Rutland, on 14 June 2013 - 08:33 AM, said:

Well, as to that, you could take my code, and sort of flip it. Instead of writing to the array, you can just grab values from it.


you're probably right, but your code has me a little more confused now. I've never seen this done before:

	    friends[i, 0] = name;
	    friends[i, 1] = bday;


Although, going through the debugger, I see what's happening.

Still, it's really confusing me. how can the variable "name" or "bday" be equal to multiple entries in an array. If I saw the entire code I'd be able to debug and perhaps see what was going on, but I don't want you to do that.

Perhaps you could explain what's going on in greater detail? flipping the code around even visually, I can't seem to understand how to access the data back out of the variables.


I can clarify a bit. First, Adam is correct. You're confusing two concepts, equality and assignment. Remember that in C#, x = y; means "assign the value of y to x", and x == y means "return true if the value of y is the same as the value of x".

So, let's start with the loop. The code in the loop is able to be executed multiple times. So I'll explain it step by step.

First, when we enter the loop, i is set to 0. First we ask for the user name, then on the next line, we create a variable called name and read input from the console into it. We do the same thing for birthday, except we create a variable called bday.

Now, we have the data we want, but we need to store it long term. A topic your book may not have covered yet is called "scope", which is related to where and how long variables live for. Basically, since our name and bday variables were created in the loop, they only exist inside that loop. But we created the array outside the loop.

So, what we do is assign the values we stored into the array. Since i is 0, we're storing our values at [0,0] and [0,1] respectively. We're "assigning" the value of name to friends[0,1].

Then, we get to the end of the loop. The loop increases the value of i, checks to make sure i is still less than our constant, then begins again.

Since those variables were created in the loop, they expired at the end of the loop and are created again and again until the loop exits. Each time the loop loops, the variables are created again with new values read from the console.

Then, once we loop enough times that i is no longer less than our constant, the loop exits.

So, then if you wanted to turn around and output all those values, you could use a very similar loop. The difference would be that you wouldn't read anything from the console. You'd do nothing but outputting values.

You'd still want to loop the same, and you'd still refer to the specific indexes of the array as [i,0] and [i,1]. The difference is that you'll take values from the array instead of assigning to them. Some code that might help:

string name = friends[i,0];
string bday = friends[i,1];
Console.WriteLine("Friend {0}: {1}.  Friend {0}'s birthday: {2}", i + 1, name, bday);


P.S., if you don't understand how the Console.WriteLine code is working, remember that counting in a computer starts with zero. The {0} means "the first parameter after this one". {1} is "the second parameter" and so forth.
Was This Post Helpful? 0
  • +
  • -

#13 Semus  Icon User is offline

  • D.I.C Head

Reputation: 14
  • View blog
  • Posts: 126
  • Joined: 27-May 13

Re: Linking entries in a 2 dimensional array

Posted 15 June 2013 - 05:35 AM

So, I worked on this last night and part of this morning. I managed to get it to work as long as the name being entered matched one of the names in the array. If the name that the user entered (at the end after entering all the names and birthdays) did not match one of the names in the array, it wouldn't do anything. In fact, I think it threw an exception (can't remember).

I seem to have remedied that situation with this new code. This code checks to see if the name being entered matches one of the names in the array. If it does, it prints out a message saying "You entered **** and their birthday is ****". If the name does not match, it prints out "That name does not exist!".

Still, I think this program has it's flaws. For one, if you happen to enter the name, but forget to use the correct capitalization, it will probably tell you the name doesn't exist. Not sure how to fix that.

I'd like some feedback on how well I did. I tried to come up with some simple solutions. In the end I had to use some things I am not so familiar with, but they worked out OK.

Here's the code:

            const int maxLength = 5;
            string[,] friends1 = new string[maxLength, 2];

            Console.WriteLine("Please enter the names and birthdays of your 5 closest friends:");

            for (int x = 0; x < maxLength; x++)
            {
                Console.Write("\t\tYour friend's name #{0}: ", x + 1);
                string name = Console.ReadLine();
                Console.Write("\t\tNow their birthday: ");
                string bday = Console.ReadLine();

                friends1[x, 0] = name;
                friends1[x, 1] = bday;
            }
            string choice;
            Console.Write("Please enter a name: ");
            choice = Console.ReadLine();
            for (int x = 0; x < maxLength; x++)
            {
                string name2 = friends1[x, 0];
                if (!name2.Contains(choice) && x == 4)
                {
                    Console.WriteLine("That name does not exist!");
                }
            }
            for (int x = 0; x < maxLength; x++)
            {
                string name = friends1[x, 0];
                string bday = friends1[x, 1];
                if (name == choice)
                {
                    Console.WriteLine("You entered {0} and their birthday is {1}", choice, bday);
                }
            }
            Console.ReadLine();


In the first for loop I could have just used name instead of name2 because it was in the scope of the loop (started learning about scope the other day).

This post has been edited by Semus: 15 June 2013 - 05:38 AM

Was This Post Helpful? 0
  • +
  • -

#14 Witchking  Icon User is offline

  • D.I.C Head

Reputation: 68
  • View blog
  • Posts: 188
  • Joined: 17-February 13

Re: Linking entries in a 2 dimensional array

Posted 15 June 2013 - 06:20 AM

You could instead of using a two dimensional array where each row represents a person, create a class Person and use either a Person[] array or a List<Person>. For example:
void Main()
{
	List<Person> friends = new List<Person>();
	
	//add friends using friends.Add(new Person(name, bday));
	
	//then you can use LINQ to search for friend:
	GetBirthdayOf(Peter);
}

private string GetBirthdayOf(string name)
{
	foreach (Person p in friends)
	{
		if (p.Name = name) return p.Birthday;
	}
}

private string GetBirthdayOfUsingLinq(string name)
{
	return friends.Where(n => n.Name.ToLower() == name.ToLower()).Select(n => n.Birthday).First();
}

private string

class Person
{
	public Person(string name, string birthday)
	{
		this.name = name;
		this.birthday = birthday;
	}
	
	private string name, birthday;
	
	public string Name
	{
		get { return name; }
	}
	
	public string Birthday
	{
		get {return birthday; }
	}
}
Here i created a class called Person, with two properties: Name and Birthday. I also created two methods for getting the birthday of a person from the list using their name as argument. The first method uses a foreach loop to search through the list, whereas the second uses LINQ.

friends.Where(n => n.Name.ToLower() == name.ToLower()).Select(n => n.Birthday).First();
This might look intimidating, but is in fact quite simple. I use the Where() method on the list friends. The method returns all members of the list that match the predicate n => n.Name.ToLower() == name.ToLower(). This is a lambda expression where the n represents the member of the list. We then see if n.Name equals the name we are searching for. Using the ToLower() method, for the duration of the evaluation we change both strings to all lowercase. The Where method returns all matching members of the list, but this is not what we're looking for, instead we are looking for the Birthday property. So we use the Select method with the predicate n => n.Birthday again the n represents the member of the list, and n.Birthday is returned. We now have a collection of strings, even if the collection only has one member. Assuming the list had no duplicate names we can safely call the First() method to get the only member in the collection, which is the string Birthday from the Person with the matching name.

This post has been edited by Witchking: 15 June 2013 - 06:33 AM

Was This Post Helpful? 0
  • +
  • -

#15 Semus  Icon User is offline

  • D.I.C Head

Reputation: 14
  • View blog
  • Posts: 126
  • Joined: 27-May 13

Re: Linking entries in a 2 dimensional array

Posted 15 June 2013 - 06:30 AM

@Witchking

Your two suggestions seem awesome, except I haven't really gotten to LINQ or classes just yet. Still, I kinda get what's happening. I'm sure I'll understand more once I actually get to classes and LINQ related things. LINQ is one of those subjects that deserves it's own book. Are there any books on LINQ and C#? I'll have to do some searching for tutorials around the net.

Thanks for the suggestions, but they are a little over my head atm. Still, I will take your examples and go over them a bit to see if I can understand how they work.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1