0

In a program that asks the name, surname and age of 10 student, at the end we have to enter the name of one of them and the program has to give their place in the array. It always tells me that the place is 0. Here is the code:

public class Program_pinakes
{
    public static void Main(string[] args)
    {
        int i; 
        string[] a = new string[10]; 
        string[] b = new string[10]; 
        int[] c = new int[10]; 
        int index = 0;

        for (i = 0; i < 10; i++)
        {  
            Console.Write("Name: ");
            a[i] = Console.ReadLine();
            Console.Write("Surname: ");
            b[i] = Console.ReadLine();
            Console.Write("Age: ");
            c[i] = Int32.Parse(Console.ReadLine());
        }

        Console.Write("Name of student you are looking for: ");
        string name = Console.ReadLine();
        if (name == a[i])
            index = i;

        Console.Write("Student"+a[i]+" is located at"+index+" place.");
    }       
}

Edit: Thank you all for your answers. I found out about the IndexOutOfRange problem and solved it easily. The main problem was about the index returning 0. Now, after I put it on the loop to search the array again, it returns 0 for the first name, 1 for the second and so on. Is this the right way, or it should be returning 1 for the first name, 2 for second etc?

5
  • 2
    actually it should exit with an IndexOutOfRange exception. after the for loop i has the value of 10 and your array has only 10 positions. so the last one would be a[9] Commented Apr 18, 2018 at 12:34
  • 1
    You need to loop through the array to find the index if(name == a[i]) is just a comparison to one of the values and honestly that should give an exception because at that point i would be 10 and out of the range of the array. Commented Apr 18, 2018 at 12:34
  • 2
    My guess is that the intention of the exercise was to teach you how to define your own classes, not to teach you how to define parallel arrays (a not-so-good practice when you can avoid it). Commented Apr 18, 2018 at 12:36
  • 1
    Also for doing look ups you might what to consider using a dictionary instead of an array. Commented Apr 18, 2018 at 12:39
  • "It always tells me that the place is 0." How can this be? either explain please how this is possible or remove this information, because your code tells a different story Commented Apr 18, 2018 at 12:50

4 Answers 4

3

At the end of the loop i has the value of 10. (This is the reason why the cancel condition: i < 10 becomes true and the loop exits).

So when you try to access a[i] after the loop it will throw an IndexOutOfRange exception. Because you have not enough elements in your array.

Solution: To find an element you need to loop again through the array and compare each value with the search-name:

 for(int i = 0; i < 10; i++ )
 {
    if (name == a[i])
    {
       index = i;
       break; // finish the loop, you have found the first occurence
    }
 }
 Console.Write("The first occurence of Student: "+name+" is located at"+index+" place.");

Edit: There can be a case of course that the search-name is not in the list. You can handle such a case by initializing the index value with -1 and check for it after the search loop:

int index = -1;

// search loop here

if (index > -1)
{
    Console.Write("The first occurence of Student: " + name + " is located at" + index + " place.");
}
else
{
    Console.Write("Student: "+ name +" could not be found!");
}
Sign up to request clarification or add additional context in comments.

2 Comments

what about the name doesn't exist in the list, It will throw an exception again plus if we ignore exception case, it will show wrong information in that case as it will show 0th position.
@Amit thank you for the comment. copy paste strikes again... I corrected it and added the handling of the not-found case.
2

This code you have posted is not working, as it will throw an exception System.IndexOutOfRangeException.

However apart from this exeption, my answer would be: becuase,

       if (name == a[i])
            index = i;
         Console.Write("Student"+a[i]+" is located at"+index+" place.");

by doing this you are checking if ith entry of the array is the one you desired or not, if yes then you are setting index with i.

But what about it doesn't match? index will stay with the value as it was initialized with. Here it is zero what you are getting in output.

you should be doing like below.

             index = -1;
             for(int j = 0; i < a.Length; j++ )
             {
                if (name == a[j])
                {
                   index = j;
                   break;
                }
             }
             if(index != -1)
                Console.Write("Student" + name + " is located at" + (index + 1) + " place.");
             else
               Console.Write("Student" + name + " is not in list");

Comments

1

Consider creating a Student object which holds all your student specific data:

class Student
{
   public string Name { get; set; }
   public string Surename { get; set; }
   public int Age { get; set; }
}

Now create a list of Student:

var students = new List<Student>();

And in your loop create a new Student object for every repetition:

for (i = 0; i < 10; i++)
{  
   Console.Write("Name: ");
   var name = Console.ReadLine();
   Console.Write("Surname: ");
   var surname = Console.ReadLine();
   Console.Write("Age: ");
   var age = Int32.Parse(Console.ReadLine());

   students.Add(new Student {Name = name, Surname = surname, Age = age});
}

After the loop you ask for the name of the student you want the index for and use LINQ to find him in the list:

Console.Write("Name of student you are looking for: ");
string name = Console.ReadLine();
var foundStudent = students.FirstOrDefault(s => s.Name.Equals(name));
if(foundStudent != null)
{
   var index = students.IndexOf(foundStudent);
   Console.Write($"Student {foundStudent.Name} is located at {index} place.");
}
else
{
   Console.WriteLine($"No student for name {name} found");
}

NOTE:
Check out C#'s string interpolation feature for building strings with variables. I find it way more cleaner.

Comments

0

The index always is 0 because your if (name == a[i]) statement is not in a lopp. So you do not actually search in the array but only check if it is like the 11th (array starts to count at 0) element. (i is set to 10 after your for loop)

1 Comment

Actually at the end of the loop i should be 10.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.