Updating a list using a method? - c#

This is a really simple question concerning a method. I'm pretty new to C# and am testing lists. How do I call the method "addTwo" so that it updates every element in the "Marks" list by two? Please note that I've already created this method (scroll down further below the main method). I just want to know how to call it in the main method.
namespace ParallelLists
{
class Program
{
static void Main(string[] args)
{
//create an list of 4 student names
List<string> names = new List<string>(4);
names.Add("Matt");
names.Add("Mark");
names.Add("Luke");
names.Add("John");
//create a list of 4 integers representing marks
List<decimal> marks = new List<decimal>(4);
marks.Add(88m);
marks.Add(90m);
marks.Add(55m);
marks.Add(75m);
Console.WriteLine("the mark of " + names[0] + " is : " + marks[0]);
Console.ReadLine();
//Upgrade everyone by 2 marks
...
}
public List<decimal> addTwo(List<decimal> mark)
{
List<decimal> temp = mark;
for (int i = 0; i < temp.Count; i++)
{
temp[i] += 2m;
}
return temp;
}
}
}

You need to make your method static, since you are accessing on a non object. also you need to update your marks collection with the returned value. You dont actually need to return the List because list is mutable.
class Program
{
static void Main(string[] args)
{
//create an list of 4 student names
List<string> names = new List<string>(4);
names.Add("Matt");
names.Add("Mark");
names.Add("Luke");
names.Add("John");
//create a list of 4 integers representing marks
List<decimal> marks = new List<decimal>(4);
marks.Add(88m);
marks.Add(90m);
marks.Add(55m);
marks.Add(75m);
marks = addTwo(marks);
Console.WriteLine("the mark of " + names[0] + " is : " + marks[0]);
Console.ReadLine();
Console.Read();
}
public static List<decimal> addTwo(List<decimal> mark)
{
List<decimal> temp = mark;
for (int i = 0; i < temp.Count; i++)
{
temp[i] += 2m;
}
return temp;
}
}
if you dont want to return the list, you can do the following:
class Program
{
static void Main(string[] args)
{
//create an list of 4 student names
List<string> names = new List<string>(4);
names.Add("Matt");
names.Add("Mark");
names.Add("Luke");
names.Add("John");
//create a list of 4 integers representing marks
List<decimal> marks = new List<decimal>(4);
marks.Add(88m);
marks.Add(90m);
marks.Add(55m);
marks.Add(75m);
addTwo(marks);
Console.WriteLine("the mark of " + names[0] + " is : " + marks[0]);
Console.ReadLine();
Console.Read();
}
public static void addTwo(List<decimal> mark)
{
List<decimal> temp = mark;
for (int i = 0; i < temp.Count; i++)
{
temp[i] += 2m;
}
}
}

Your list is already getting a reference to 'mark' why return anything when any operation you are doing will operate on that same list.
instead of:
public List<decimal> addTwo(List<decimal> mark)
{
List<decimal> temp = mark;
for (int i = 0; i < temp.Count; i++)
{
temp[i] += 2m;
}
return temp;
}
I would do:
public void addTwo(List<decimal> mark)
{
for (int i = 0; i < mark.Count; i++)
{
temp[i] += 2m;
}
}
Then in your code call is just as
addTwo(mark);
I would rename it to AddTwo to fit normal c# conventions as well.

//Upgrade everyone by 2 marks
var plustwo = addTwo(marks);
Console.WriteLine("the mark of " + names[0] + " is : " + plustwo[0]);
Console.ReadLine();
Note, that you will also need to make AddTwo a static method:
public static List<decimal> addTwo(List<decimal> mark)

Related

Function that writes out the sum only writes out 0

Problem: The sum writes out as 0. How do i make it so that the function Summa() writes out the actual sum out of the 10 numbers that user writes in?
This is probably extremely simple but im new to this :P
All of the things in the code weren't separate before but i wanted if i could move the sum part to it's own function
using System;
namespace Array
{
class Program
{
static void Main(string[] args)
{
int number;
int[] vektor = new int[10];
for (int i = 0; i < vektor.Length; i++)
{
Console.WriteLine("Enter a number");
number = Convert.ToInt32(Console.ReadLine());
vektor[i] = number;
}
Summa();
}
static void Summa()
{
int sum = 0;
int[] vektor = new int[10];
int i = 0;
sum = sum + vektor[i];
Console.WriteLine("The amount is " + sum);
}
}
}
You are creating a new array called vektor in the Summa() function, instead of using the one created in the main() function. Also you've to iterate through the array to find the sum
Change Summa to :
static void Summa(int[] vektor)
{
int sum = 0;
for(int i=0; i < vektor.Length; i++)
{
sum = sum + vektor[i];
}
Console.WriteLine("The amount is " + sum);
}
And change the function call in the main() to:
Summa(vektor);
You are summing a different array; you'd need to pass the array in:
static void Summa(int[] vektor)
{
int sum = 0;
foreach (var val in vektor)
sum += val;
// ^^^ or just use: var sum = vektor.Sum();
Console.WriteLine("The amount is " + sum);
}
/// ...
Summa(vektor);
So, you're not passing any information to your method "Summa", but you're instead creating a new Array.
So you need to pass the Array from your main method to you "summa" method.
namespace Array
{
class Program
{
static void Main(string[] args)
{
int number;
int[] vektor = new int[3];
for (int i = 0; i < vektor.Length; i++)
{
Console.WriteLine("Enter a number");
number = Convert.ToInt32(Console.ReadLine());
vektor[i] = number;
}
Summa(vektor);
}
static void Summa(int[] vektor)
{
int sum = 0;
foreach (var item in vektor)
{
sum += vektor[item];
}
Console.WriteLine("The amount is " + sum);
}
}
}
Also, using foreach loops will make your life much easier in the future.
https://www.w3schools.com/cs/cs_for_loop.asp
When you're unsure what your program is doing and don't know why it isn't working like it should. Try using the debug feature.
If you're using Visual Studio you can access it by pressing F11.
Lycka till med studierna!

Pass variables between methods

I have 2 methods in my program.
1. Start Exam
2. Mark Exam
as you see,
in first method i calculated how many questions are correct or wrong.
in second, i want to show the result.
PROBLEM:
How can i pass the correctlyAnswers and wrongAnswers and LIST between methods?
this is what i have:
static void Main(string[] args)
{
int menuChoice = 99;
Question[] questions = new Question[30];
do
{
Console.Clear();
DisplayMenu();
menuChoice = InputOutput_v1.GetValidInt("Option");
switch (menuChoice)
{
case 1:
InputOutput_v1.DisplayTitle("Start Exam");
CreateQuestion(questions);
break;
case 2:
InputOutput_v1.DisplayTitle("Mark Exam");
DisplayAllQuestions(questions);
break;
}
} while (menuChoice != '0') ;
}
public static void StartExam(Question[] questions)
{
char[] studentAnswers = new char[30];
int[] wrongAnswers = new int[30];
int correctlyAnswered = 0;
int falselyAnswered = 0;
string list = "";
Console.Clear();
Console.WriteLine("== DO NOT CHEAT! ==\n");
Console.WriteLine("----------------");
for (int i = 0; i < studentAnswers.Length; i++)
{
Console.WriteLine("\nQuestion {0}", i + 1);
Console.WriteLine("------------");
questions[i].DisplayQuestion();
studentAnswers[i] = InputOutput_v1.GetValidChar("Your Answer (A, B, C, D)");
if (studentAnswers[i] == questions[i].correctAnswer)
{
correctlyAnswered = correctlyAnswered + 1;
}
else
{
falselyAnswered = falselyAnswered + 1;
wrongAnswers[i] = i + 1;
list += i + 1 + ", ";
}
}
}
public static void MarkExam(Question[] questions)
{
if (correctlyAnswered >= 15)
{
Console.WriteLine("Passed with {0} correct answers", correctlyAnswered);
}
else
{
Console.WriteLine("Failed with {0} incorrect answers. Incorrect answers are: {1} ", falselyAnswered, list.Remove(list.Length - 2));
}
Console.ReadLine();
}
Well, why can't you call your MarkExam() method passing those variables like
public static void StartExam(Question[] questions)
{
char[] studentAnswers = new char[30];
int[] wrongAnswers = new int[30];
int correctlyAnswered = 0;
int falselyAnswered = 0;
string list = "";
........
MarkExam(questions, wrongAnswers, correctlyAnswered);
In which case you will have to change your method signature accordingly
Make the correctlyAnswers, wrongAnswers, and LIST defined as global variables outside your methods, e.g.
private int correctlyAnswered;
private int falselyAnswered;
private Question[] questions;
First, why are you using an array instead of a list? And inside this class your methods don't really need to be static.
Second, create private variables to the class and they can be used in all methods.
public class ExamClass
{
private List<Question> questions = new List<Question>();
private List<Question> incorrect = new List<Question>();
private List<Question> correct = new List<Question>();
...
}

Method being run through twice when it should only run once

class Myclass
{
public string Driver1()
{
string a = "";
Console.Write("Please enter drivers name: ");
a = Console.ReadLine();
return a;
}
public int numberOfTrips()
{
int a = 0;
{
Console.Write("Enter the number of trips: ");
a = Convert.ToInt32(Console.ReadLine());
}
return a;
}
public List<float> Payments()
{
List<float> a = new List<float>();
float input;
for (int i = 0; i<numberOfTrips(); i++)
{
Console.Write("Enter payment {0}: ", (1 + i));
input = float.Parse(Console.ReadLine());
Console.WriteLine("Payment added");
a.Add(input);
}
return a;
}
}
class Program
{
static void Main(string[] args)
{
Myclass a = new Myclass();
string name = a.Driver1();
int trip = a.numberOfTrips();
float total = a.Payments().Sum();
Console.WriteLine("\nDriver: {0}\n" + "Number of trips: {1}\n" + "Total payment: {2}\n", name, trip, total);
}
}
The issue i am having is that the "public int numberOfTrips()" method is running twice before it gets to the method containing the for loop. I think this is to do with the fact i am using it within the for loop to specify when the loop should stop. I am guessing i have done this wrong so how would i correct this? I need the user to be able to set the how many times it will ask for payment.
Any help is appreciated.
Just pass the number from numberOfTrips as a parameter to Payments:
public List<float> Payments(int tripCount)
{
List<float> a = new List<float>();
float input;
for (int i = 0; i < tripCount; i++)
{
Console.Write("Enter payment {0}: ", (1 + i));
input = float.Parse(Console.ReadLine());
Console.WriteLine("Payment added");
a.Add(input);
}
return a;
}
In your Main method:
Myclass a = new Myclass();
string name = a.Driver1();
int trip = a.numberOfTrips();
float total = a.Payments(trip).Sum();
Instead of calling numberOfTrips() in Main() as well as in Payments() you might try creating an instance variable or static variable in MyClass. Then you can fetch the number of trips from that variable after all payments are calculated.
That is correct. The first time it runs is in Main to set the 'trip' variable. The second time it runs is in Payments, inside the for loop declaration.

How do I create a subset of an array?

I have 1 array with many string lines.
For every line in that array, if a condition is met,
I have a console app that displays the line from the array, with some modifications (I call this the outputLine).
How do I make an array from the list of outputLines ?
class Program
{
static void Main(string[] args)
{
string[] linesArray = File.ReadAllLines(#"C:\Users\AK1\Desktop\CC2_B.TXT");
int linecount = File.ReadAllLines(#"C:\Users\AK1\Desktop\CC2_B.TXT").Length;
for (int i = 0; i < linecount; i++)
{
if (linesArray[i].Contains("2008/12"))
{
string[] outputArray = linesArray;
string outputLine = "yes " + outputArray[i];
Console.WriteLine(outputLine);
}
}
Console.ReadLine();
}
}
Rather than an array, which has to define its size at declaration in C#, you're looking for a List<string>. You might want to refer to this answer about adding elements to an array to better understand the difference between List and array
Add using System.Collections.Generic at the top of your file and modify your code as such:
class Program
{
static void Main(string[] args)
{
string[] linesArray = File.ReadAllLines(#"C:\Users\AK1\Desktop\CC2_B.TXT");
int linecount = File.ReadAllLines(#"C:\Users\AK1\Desktop\CC2_B.TXT").Length;
List<string> outputLines = new List<string>();
for (int i = 0; i < linecount; i++)
{
if (linesArray[i].Contains("2008/12"))
{
string outputLine = "yes " + linesArray[i];
outputLines.Add(outputLine);
Console.WriteLine(outputLine);
}
}
Console.ReadLine();
}
}
Then if you really need it to be an array (like to pass it to another function), you can call outputLines.ToArray()
why not first filter your lines with desired condition by using linq? then you can output in console.
string[] lines = File.ReadAllLines(#"C:\Users\AK1\Desktop\CC2_B.TXT");
string[] filteredLines = lines.Where(line => line.Contains("2008/12")).ToArray();
foreach(string line in filteredLines){
Console.WriteLine("yes " + line);
}
Declare an array with a capacity of linecount, in case you need to add every single line.
I suppose this is c++? so you can not increase an array size in runtime.
static void Main(string[] args)
{
int outputCounter=0;
.......
if (linesArray[i].Contains("2008/12"))
{
string outputLine = "yes " + outputArray[i];
outputArray[outputCounter]= outputLine;
outputCounter++;
Console.WriteLine(outputLine);
}
}
Update:
For c# just do something like this
static void Main(string[] args)
{
List<string> outputList = new List<string>();
.......
if (linesArray[i].Contains("2008/12"))
{
string outputLine = "yes " + outputArray[i];
outputList.Add(outputLine);
Console.WriteLine(outputLine);
}
}
Try working with Lists instead of arrays if you're wanting to make dynamic additions. For example;
class Program
{
static void Main(string[] args)
{
string[] linesArray = File.ReadAllLines(#"C:\Users\AK1\Desktop\CC2_B.TXT");
int linecount = File.ReadAllLines(#"C:\Users\AK1\Desktop\CC2_B.TXT").Length;
// Delcare your list here
List<string> outputList = new List<string>();
for (int i = 0; i < linecount; i++)
{
if (linesArray[i].Contains("2008/12"))
{
// You can "Add" to lists easily like this
outputList.Add(linesArray[i]);
// This will return you the last item in the list
string outputLine = "yes " + outputList.Last();
Console.WriteLine(outputLine);
}
}
// Then if you specifically want it back to an Array
string[] outputArray = outputList.ToArray();
Console.ReadLine();
}
}
Hope this helps :)

C# - For vs Foreach - Huge performance difference

i was making some optimizations to an algorithm that finds the smallest number that is bigger than X, in a given array, but then a i stumbled on a strange difference. On the code bellow, the "ForeachUpper" ends in 625ms, and the "ForUpper" ends in, i believe, a few hours (insanely slower). Why so?
class Teste
{
public double Valor { get; set; }
public Teste(double d)
{
Valor = d;
}
public override string ToString()
{
return "Teste: " + Valor;
}
}
private static IEnumerable<Teste> GetTeste(double total)
{
for (int i = 1; i <= total; i++)
{
yield return new Teste(i);
}
}
static void Main(string[] args)
{
int total = 1000 * 1000*30 ;
double test = total/2+.7;
var ieTeste = GetTeste(total).ToList();
Console.WriteLine("------------");
ForeachUpper(ieTeste.Select(d=>d.Valor), test);
Console.WriteLine("------------");
ForUpper(ieTeste.Select(d => d.Valor), test);
Console.Read();
}
private static void ForUpper(IEnumerable<double> bigList, double find)
{
var start1 = DateTime.Now;
double uppper = 0;
for (int i = 0; i < bigList.Count(); i++)
{
var toMatch = bigList.ElementAt(i);
if (toMatch >= find)
{
uppper = toMatch;
break;
}
}
var end1 = (DateTime.Now - start1).TotalMilliseconds;
Console.WriteLine(end1 + " = " + uppper);
}
private static void ForeachUpper(IEnumerable<double> bigList, double find)
{
var start1 = DateTime.Now;
double upper = 0;
foreach (var toMatch in bigList)
{
if (toMatch >= find)
{
upper = toMatch;
break;
}
}
var end1 = (DateTime.Now - start1).TotalMilliseconds;
Console.WriteLine(end1 + " = " + upper);
}
Thanks
IEnumerable<T> is not indexable.
The Count() and ElementAt() extension methods that you call in every iteration of your for loop are O(n); they need to loop through the collection to find the count or the nth element.
Moral: Know thy collection types.
The reason for this difference is that your for loop will execute bigList.Count() at every iteration. This is really costly in your case, because it will execute the Select and iterate the complete result set.
Furthermore, you are using ElementAt which again executes the select and iterates it up to the index you provided.

Categories