Retrieve data from arrays - c#

I want to enter students' Id and Marks into an array. Problem statement is that if user enters the Id of student then Mark of that student should be displayed. Below is my code so far. Could you please help me?
int [] mark = new int [5] ;
string [] studentsid = new string [5];
string userInput = "";
bool found = false;
int i = 0;
string[] answer = new string[5];
for (i = 0; i < answer.Length; i++)
{
Console.WriteLine("Enter Student " + (i + 1) + " 's ID Number: ");
studentsid[i] = Console.ReadLine();
Console.WriteLine("Enter student" + (i + 1) + "'s mark: ");
mark[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Enter one of you student's id number");
userInput = Console.ReadLine();
if (studentsid[i].ToUpper() == userInput.ToUpper())
{
found = true;
Console.WriteLine(mark[i]);
}
if (mark[i] >=85 && mark[i] <= 100 )
{
Console.WriteLine("Distinction");
}
Console.ReadKey();

You need to put a second loop around the block of code that checks if the student's ID matches.
Right now, you are only checking if one student (the last student in the array) matches the user's input. You are also using a for-loop's control variable outside of the loop, which is generally considered bad practice.
Consider something like this:
Console.WriteLine("Enter one of you student's id number");
userInput = Console.ReadLine();
for (int i = 0; i < studentsid.length; i++)
{
if (studentsid[i].ToUpper() == userInput.ToUpper())
{
found = true;
Console.WriteLine(mark[i]);
}
}
Also, your "answers" array serves no purpose. You only create it to check its hard-coded length of 5. Use the length of studentsid instead.
Finally, two arrays aren't really the ideal way to store this type of data.
A map, using the student ID as the key and the mark as the value, would be a much more efficient way to store and access this data.

Related

How to output data in a certain form?

I have a homework problem that I need help with.
This is the assignment question
So I have the following code for my class:
public Tests(String firstName, String lastName, int[] testScores)
{
this.firstName = firstName;
this.lastName = lastName;
this.testScores = testScores;
}
//First Name getter and setter
public String GetFirstName()
{
return firstName;
}
public void SetFirstName(String firstName)
{
this.firstName = firstName;
}
//Last Name getter and setter
public String GetLastName()
{
return lastName;
}
public void SetLastName(String lastName)
{
this.lastName = lastName;
}
//Test Scores getter and setter
public int[] GetTestScores()
{
return testScores;
}
public void SetTestScores(int[] testScores)
{
this.testScores = testScores;
}
//This method calculates the average of the test scores for each student.
public double CalculateAverage(int[] testScores)
{
int sum = 0;
for (int i = 0; i < testScores.Length; i++)
{
sum = sum + testScores[i];
}
double average = sum / testScores.Length;
return average;
}
//This method returns the letter grade from the test average.
public char WhatIsGrade(double avgTestScore)
{
char grade;
if (avgTestScore >= 90)
{
grade = 'A';
return grade;
}
else if (avgTestScore >= 80 && avgTestScore < 90)
{
grade = 'B';
return grade;
}
else if (avgTestScore >= 70 && avgTestScore < 80)
{
grade = 'C';
return grade;
}
else if (avgTestScore >= 60 && avgTestScore < 70)
{
grade = 'D';
return grade;
}
else
{
grade = 'F';
return grade;
}
}
//Updates the score of a test
public void modifyGrade(int testNumber, int newScore)
{
testScores[testNumber] = newScore;
}
So once I did the class, I thought it would be pretty simple with writing the driver code in the main method.
Here is what I have so far in my main method:
static void Main(string[] args)
{
int[] scores = new int[5];
Console.WriteLine("Student 1 First Name: ");
String student1First = Console.ReadLine();
Console.WriteLine("Student 1 Last Name: ");
String student1Last = Console.ReadLine();
for (int i = 0; i < scores.Length; i++)
{
Console.WriteLine("Enter score: ");
scores[i] = Convert.ToInt32(Console.ReadLine());
}
The only thing I can think of is to write this code for each student. But then I run into the problem of finding the sum for each student's scores. I also run into the problem of how to store each student's data so that I can print it out at the end in a table form. I am guessing that I have to import the class so I did so like this:
Tests t1 = new Tests(firstName, lastName, arrayName)
But I get confused as to how it will be for each one and how to actually store anything in these. Can somebody explain step by step? Also if I have done anything wrong in my class, can somebody point it out?
Alright lets start with your class. So looks like you're missing 2 things in your Tests constructor, you're gonna wanna add the logic to set the value of the average and the letter grade to the constructor. Gonna want to make a getter and setter for each of those as well. In the CalculateAverage() and WhatIsGrade() you dont need the arguments since you've already pass that data to the class, so you can get rid of those and change the logic to reference the data you set in your constructor. So the constructor should look something like this now:
public Tests(String firstName, String lastName, int[] testScores)
{
this.firstName = firstName;
this.lastName = lastName;
this.testScores = testScores;
average = CalculateAverage();
grade = WhatIsGrade();
}
Now onto the main class, unless your teacher wants all the data entered manually you can just hardcode all the data. If not you can just take all the user input in a loop. And according to your assignment you need to store each Tests object into an array of objects. So hardcoded it would look something like this
Tests[] testArray = new Tests[]
{
new Tests(your data here),
new Tests(your data here),
etc
};
For output you'll want to make a method that overrides the default ToString method, you can read more about that here: https://learn.microsoft.com/en-us/dotnet/api/system.object.tostring?view=netframework-4.8
That'll be where you do the formatting your teacher requested, then its just as simple as running through that array of objects with a loop and calling the ToString method on each object in the array.
Alright so outside of the loop go ahead and make an empty array of objects. Then within the loop you can do what you've already done in your main, just within the loop. You'll want to store each of the user inputs into a temporary variable just like you've already got in your main then at the very end of the loop you'll just need to add each object to your array of objects. Loop should look something like this:
for(int i = 0; i < testArray.Length; i++)
{
int[] scores = new int[5];
Console.WriteLine("Student First Name: ");
String studentFirst = Console.ReadLine();
Console.WriteLine("Student Last Name: ");
String studentLast = Console.ReadLine();
for (int j = 0; j < scores.Length; j++)
{
Console.WriteLine("Enter score: ");
scores[j] = Convert.ToInt32(Console.ReadLine());
}
testArray[i] = new Tests(studentFirst, studentLast, scores);
}
So in your overridden ToString method, before the return statement you'll want to declare a temporary string variable to hold the scores the iterate through the scores array in a for loop and add each element to the string. It'll look something like this:
string scores = "";
for(int i = 0; i < testScores.Length; i++)
{
scores = scores + testScores[i] + " ";
}
return GetFirstName() + " " + GetLastName() + " " + scores + GetAverage() + " " + GetGrade();

Find the index of an object in an array with unknown objects

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?
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!");
}
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");
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.
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)

no same numbers in array

I'm making a program that accepts values into an array, but if you attempt to input the same value twice, it rejects, if the value is unique, go on.
using System;
public class Program
{
public static void Main()
{
char[] charray = new char[7];
Console.WriteLine("Enter 7 unique alphabetic characters: ");
for (int i = 0; i < charray.Length; i++)
{
charray[i] = Convert.ToChar(Console.ReadLine());
for (int j = 0; j < charray.Length; j++)
{
if (charray[i] == charray[j])
{
Console.WriteLine("Please enter a unique alphabetic character.");
}
}
}
Console.WriteLine(charray);
}
}
Can someone tell me what's wrong?
you're comparing every element in your array with what you just assigned to an element in your array, so of course you'll always find a duplicate... with the item you just entered.
What you actually want is:
void Main()
{
char[] charray = new char[7];
Console.WriteLine("Enter 7 unique alphabetic characters: ");
for (int i = 0; i < charray.Length; i++)
{
var x = Convert.ToChar(Console.ReadLine());
if (charray.Contains(x))
{
Console.WriteLine("Please enter a unique alphabetic character.");
i--;
}
else
{
charray[i] = x;
}
}
Console.WriteLine(charray);
}
By the way this approach is quite slow specially if you extend your array, 7 is fine but the level of optimization is very poor, you might want to look at concept of Hash map. And like the others said, since you first insert the input inside your array, the for will always find your input inside and return duplicated, you might want to check the duplication before insertion operation.
I would like to propose the following implementation:
char[] charArray = new char[7];
Console.WriteLine("Enter {0} unique alphabetic characters: ", charArray.Length);
int i = 0;
while (i < charArray.Length)
{
char inputChar = Console.ReadKey().KeyChar;
Console.WriteLine();
if (charArray.Contains(inputChar))
{
Console.WriteLine("Please enter a unique alphabetic character.");
}
else
{
charArray[i] = inputChar;
++i;
}
}
Console.WriteLine(charArray);

Outputting a string array

I have 3 methods to 1. Take in strings as an array [zipCodes], 2. Output a menu for the user and 3. display the string array back to the user. The first 2 options are working and after testing I can say that the array is working and taking in strings, however I am having bother displaying them back to the user.
I have used this method with ints, it makes me think that the [i] is only for 1 character, an explanation would be greatly appreciated.
// Here is the code so far
static void Main(string[] args)
{
string[] zipCodes = new string[10];
string zCounter;
for (int i = 0; i < zipCodes.Length; i++)
{
Console.WriteLine("Please enter 10 destinations:");
zCounter = Convert.ToString(Console.ReadLine());
zCounter = zipCodes[i];
}
int sentinalNo;
Console.Clear();
Console.WriteLine("Please enter from the following options: ");
Console.WriteLine("1. Display order zipcodes.");
Console.WriteLine("2. Search zipcode.");
Console.WriteLine("3. Exit.");
sentinalNo = Convert.ToInt32(Console.ReadLine());
while (sentinalNo != 3)
{
switch (sentinalNo)
{
case 1:
DisplayZips(zipCodes);
break;
}
}
}
private static void DisplayZips(string[] zipCodes)
{
for (int i = 0; i < zipCodes.Length; i++)
{
// Why doesnt this work?
Console.WriteLine(zipCodes[i]);
}
You should assign input into the array items:
// array of 10 strings each of them is null
string[] zipCodes = new string[10];
...
for (int i = 0; i < zipCodes.Length; i++)
{
Console.WriteLine("Please enter 10 destinations:");
// Convert.ToString is redundant here
zCounter = Convert.ToString(Console.ReadLine());
// swapped: user input is assigned to array items
zipCodes[i] = zCounter;
}

C# basic school project SOS

I am new to programming and I would be delighted if someone could help me with the following question: "Write a program that ask for the class and number of students. after asking for the name of student, ask for the grades by the Name of student, show average and show highest grade". I am stuck at part 3, and can't the link the names to next part. This is what I got so far:
static void Main(string[] args)
{
// 1 give a name and number of students
Console.Write("Class = ");
Convert.ToString(Console.ReadLine());
Console.Write("Number of students = ");
int aantalStudenten = Convert.ToInt32(Console.ReadLine());
Console.WriteLine();
// 2 ask for the names
int[] aantal = new int[aantalStudenten];
Random RandomNumber = new Random();
for (int i = 0; i < aantalStudenten; i++)
{
Console.Write("Geef naam van de {0}e student : ", i + 1);
string studentNaam = Convert.ToString(Console.ReadLine());
}
Console.WriteLine();
// 3 give the grade of each student by the name
for (int j = 0; j < aantalStudenten; j++)
{
Console.Write("Cijfer van {0} : "); // here i need the students name)//
int cijfers = Convert.ToInt32(Console.ReadLine());
}
//class avarege here
//highest grade of the class
int hoogste = stuCijfer.Max();
Console.WriteLine("De hoogste cijfer is {}," hoogste;
//name and grade of each student
Console.WriteLine();
Console.WriteLine("Press any key to stop");
Console.ReadKey();
}
Console.Write("Class = ");
Convert.ToString(Console.ReadLine());
Console.Write("Number of students = ");
int aantalStudenten = Convert.ToInt32(Console.ReadLine());
Console.WriteLine();
// 2 ask for the names
string[] namen = new string[aantalStudenten];
int[] cijfers = new int[aantalStudenten];
Random RandomNumber = new Random();
for (int i = 0; i < aantalStudenten; i++){
Console.Write("Geef naam van de {0}e student : ", i + 1);
namen[i] = Convert.ToString(Console.ReadLine());
}
Console.WriteLine();
// 3 give the grade of each student by the name
for (int i = 0; i < aantalStudenten; i++){
Console.Write("Cijfer van {0} : ", namen[i]); // here i need the students name)//
cijfers[i] = Convert.ToInt32(Console.ReadLine());
}
double gemiddeld = 0;
//class avarege here
for (int i = 0; i < cijfers.Count(); i++) {
gemiddeld += cijfers[i];
}
gemiddeld = gemiddeld / cijfers.Count();
Console.WriteLine("Het gemiddelde van de klas is: {0}", gemiddeld);
//highest grade of the class
int hoogste = 0;
for (int i = 0; i < cijfers.Count(); i++) {
if (cijfers[i] > hoogste) {
hoogste = cijfers[i];
}
}
Console.WriteLine("De hoogste cijfer is {0}",hoogste);
//name and grade of each student
Console.WriteLine();
Console.WriteLine("Press any key to stop");
Console.ReadKey();
You should put the names of the students in a list the way you are working now you are overwriting each time the user enters a new name. and then u can loop over the names storing the score in an array in this case u can use two separate one's but it would be better to use a dictionary or a 2D array.
but good luck further
It looks like your trying to get a string where you're picking out the name but it might have been converted to an int. Change the part where you converted it to a int when you received the name.
It also looks like you have for int j. Before you named it int i. Make sure it references back to the exact same name for what you identified each time.
on a side note you could try to store the names into an array and pull them out be referencing the array. That might help.
If I were to code such a program properly I would create a new Student class to contain a name and a score, then create a list or array to contain multiple instances of Student. Hopefully you're familiar with the concepts of creating new classes, and with lists or arrays. If you need help understanding any of those, let me know.

Categories