Separate functions without duplicating code - c#

I am currently working on a program to traverse through a list of numbers with two different functions to find the sum and a specific value. Here is the code that I have implemented
class Program
{
static int i, sum;
static List<int> store = new List<int>();
static void Main(string[] args)
{
for (i = 0; i < 100; i++)
{
store.Add(i);
}
i = 0;
TraverseList();
Console.ReadLine();
}
static void TraverseList()
{
while (i < store.Count)
{
FindValue();
FindSum();
i++;
}
Console.WriteLine("The sum is {0}", sum);
}
static void FindValue()
{
if (store[i] == 40)
{
Console.WriteLine("Value is 40");
}
}
static void FindSum()
{
sum = sum + store[i];
}
}
I was thinking of separating FindSum and FindValue into two different functions and not calling them in TraverseList. Is there any other way of doing it rather the duplicating the common code of list traversal in those two functions as I have done here
class Program
{
static int i, sum;
static List<int> store = new List<int>();
static void Main(string[] args)
{
for (i = 0; i < 100; i++)
{
store.Add(i);
}
i = 0;
FindValue();
i = 0;
FindSum();
Console.ReadLine();
}
static void FindValue()
{
while (i < store.Count)
{
if (store[i] == 40)
{
Console.WriteLine("Value is 40");
}
i++;
}
}
static void FindSum()
{
while (i < store.Count)
{
sum = sum + store[i];
i++;
}
Console.WriteLine("The sum is {0}", sum);
}
}

To find the sum of a series of numbers you can use the simple LINQ function:
List<int> numbers = new List<int>();
int sum = numbers.Sum();
I am not sure what you mean by find a value. If you want to check if one of the numbers in a series is equal to a certain value you can use the LINQ function Any:
int myValue = 40;
bool hasMyValue = numbers.Any(i => i == myValue);
This uses a lambda expression which executes a function and passes each element in the collection to the function. The function returns true or false to indicate that the element is a match for the Any test.
If instead you want to check for how many numbers in a sequence match a certain value you can instead use the Count function like so:
int numberOfMatches = numbers.Count(i => i == myValue);

First thing - I would use foreach instead of while, regarding the duplicate code (assuming you are not using Linq) - I think it's fine
A taste how Linq can simplify your code:
var FindSum = store.Sum();
var FindValue = store.FindAll(x => x == 40);

I cannot stress enough how bad it is to have i and sum as class members. Especially i. It will make your code very fragile, and hard to work with. Try to make each method as isolated from the rest of the code as possible.
Try something like this instead:
static void Main( string[] args )
{
List<int> store = new List<int>();
for( int i = 0; i < 100; i++ )
store.Add( i );
FindValue( store );
FindSum( store );
Console.ReadLine();
}
static void FindValue( List<int> list )
{
for( int i = 0; i < list.Count; i++ )
{
if( list[i] == 40 )
Console.WriteLine( "Value is 40" );
}
}
static void FindSum( List<int> list )
{
int sum = 0;
for( int i = 0; i < list.Count; i++ )
sum += list[i];
Console.WriteLine( "The sum is {0}", sum );
}
It is perfectly fine (and normal) to duplicate the looping, it's just a single line. You could also use a foreach here.
Also, disregard everyone telling you to use LINQ. You're obviously new to programming and you should learn the basics first.

Related

how to get any number of inputs from user and put it into a "params" method in c#?

so we can give any number of parameters to a method, like this:
static int sumPrices(params int[] prices) {
int sum = 0;
for (int i = 0; i < prices.Length; i++) {
sum += prices[i];
}
return sum;
}
static void Main(string[] args)
{
int total = sumPrices(100, 50, 200, 350);
Console.WriteLine(total);
Console.ReadKey();
}
but ... what if we wanted to get the "100, 50, 200, 350" from the USER?
in above example it's the coder giving the sumPrices method its arguments/parameters.
i mean, it would be one solution to just pass the method an array.
static int sumPrices(int[] prices) {
int sum = 0;
for (int i = 0; i < prices.Length; i++) {
sum += prices[i];
}
return sum;
}
static void Main(string[] args)
{
//get up to 9999 inputs and sum them using a method
bool whileLoop = true;
int[] inputs = new int[9999];
int index = 0;
while (whileLoop == true)
{
Console.WriteLine("entering price #" + index + ", type 'stop' to sum prices");
string check = Console.ReadLine();
if (check == "stop") {
whileLoop = false;
break;
}
inputs[index] = int.Parse(check);
index++;
}
int[] prices = new int[index];
for (int i = 0; i < index; i++)
{
prices[i] = inputs[i];
}
Console.WriteLine("-----------------");
Console.WriteLine(sumPrices(prices));
Console.ReadKey();
}
BUT... longer code... and has limits.
our professor basically wanted the first code, however, i don't see how and where it's
supposed be used if we didn't know the user's inputs and if params arguments were coming from the coder (unless of course, coder using the same function multiple times for convenience)
i have tried to think of a solution and i'm not exactly sure how it could be done.
but it basically goes like this.
we could get inputs from the user separated by commas:
100,200,50
and the program would translate it into params arguments:
sumPrices("100,200,50");
but as you can see... it's a string. i wonder if there's a JSON.parse() thing like in js.
The code in the OP has some unnecessary code as well as some limitations such as 9999.
Let's examine the following code:
bool whileLoop = true;
while (whileLoop == true)
{
}
This could be re-written as:
while (true == true)
{
}
or
while (true)
{
}
Next, let's examine the following code:
if (check == "stop") {
whileLoop = false;
break;
}
You've set whileLoop = false; which is unnecessary because once break is executed, excution has moved to after the loop.
Since the input array has a hard-code size of 9999, you've limited yourself to 9999 values. You may consider using a List instead or resize the array.
Try the following:
using System;
using System.Collections.Generic;
using System.Linq;
namespace UserInputTest
{
internal class Program
{
static void Main(string[] args)
{
decimal price = 0;
List<decimal> _values = new List<decimal>();
if (args.Length == 0)
{
//prompts for user input
Console.WriteLine("The following program will sum the prices that are entered. To exit, type 'q'");
do
{
Console.Write("Please enter a price: ");
string userInput = Console.ReadLine();
if (userInput.ToLower() == "q")
break; //exit loop
else if (Decimal.TryParse(userInput, out price))
_values.Add(price); //if the user input can be converted to a decimal, add it to the list
else
Console.WriteLine($"Error: Invalid price ('{userInput}'). Please try again.");
} while (true);
}
else
{
//reads input from command-line arguments instead of prompting for user input
foreach (string arg in args)
{
if (Decimal.TryParse(arg, out price))
{
//if the user input can be converted to a decimal, add it to the list
_values.Add(price); //add
}
else
{
Console.WriteLine($"Error: Invalid price ('{arg}'). Exiting.");
Environment.Exit(-1);
}
}
}
Console.WriteLine($"\nThe sum is: {SumPrices(_values)}");
}
static decimal SumPrices(List<decimal> prices)
{
return prices.Sum(x => x);
}
static decimal SumPricesF(List<decimal> prices)
{
decimal sum = 0;
foreach (decimal price in prices)
sum += price;
return sum;
}
}
}
Usage 1:
UserInputTest.exe
Usage 2:
UserInputTest.exe 1 2 3 4 5
Resources:
Built-in types (C# reference)
Floating-point numeric types (C# reference)
Decimal.TryParse
Iteration statements - for, foreach, do, and while
String interpolation using $
List Class
Enumerable.Sum Method
Default values of C# types (C# reference)
Environment.Exit
The trick is input from the user always starts out as strings. You must parse those strings into integers. We can do it in very little code like this:
static int sumPrices(IEnumerable<int> prices)
{
return prices.Sum();
}
static void Main(string[] args)
{
int total = sumPrices(args.Select(int.Parse));
Console.WriteLine(total);
Console.ReadKey();
}
See it here (with adjustments for the sandbox environment):
https://dotnetfiddle.net/Pv6B6e
Note this assumes a perfect typist. There is no error checking if a provided value will not parse.
But I doubt using linq operations are expected in an early school project, so we can expand this a little bit to only use techniques that are more familiar:
static int sumPrices(int[] prices)
{
int total = 0;
foreach(int price in prices)
{
total += price;
}
return total;
}
static void Main(string[] args)
{
int[] prices = new int[args.Length];
for(int i = 0; i<args.Length; i++)
{
prices[i] = int.Parse(args[i]);
}
int total = sumPrices(prices);
Console.WriteLine(total);
Console.ReadKey();
}
If you're also not allowed to use int.Parse() (which is nuts, but sometimes homework has odd constraints) you would keep everything else the same, but replace int.Parse() with your own ParseInt() method:
static int ParseInt(string input)
{
int exponent = 0;
int result = 0;
for(int i = input.Length -1; i>=0; i--)
{
result += ((int)(input[i]-'0') * (int)Math.Pow(10, exponent));
exponent++;
}
return result;
}
Again: there's no error checking here for things like out-of-bounds or non-numeric inputs, and this particular implementation only works for positive integers.

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!

Cannot apply indexing with [] to an expression of type 'Array''

I am getting the "Cannot apply indexing with [] to an expression of type 'Array''" for the below code.. Aim is to create a calculator template and then call these methods to run the various operations.
Errors are coming in the areas marked //HERE.. Please help. I am a newbie when it comes to c# coding, so, all help is appreciated and I would like it if someone could explain me the issue too. Thanks
private static Array NumberFeedLengthDecider()
{
Console.WriteLine("Please enter how many numbers that you would like to add.");
int i = Convert.ToInt32(Console.ReadLine());
int[] numbers = new int[i];
return numbers;
}
private static int NumberFeed(Array numbers)
{
Console.WriteLine("Please enter the numbers one by one, each followed by the 'Enter' key.");
int i = numbers.Length;
for (int counter = 0; counter < i; counter++)
{
int temp = Convert.ToInt32(Console.ReadLine());
numbers[counter] = temp; //HERE
}
return i;
}
private static void NumberDisplay(Array numbers)
{
Console.WriteLine("The numbers you have entered are: ");
int i = (numbers.Length);
for (int x = 0; x < i; x++)
{
Console.WriteLine(numbers[x]); //HERE
}
}
Basically, I want to create a method for deciding the number of numbers the operations are to be run on which is the first one (numberFeedLengthDecider), then another method to feed the numbers into that array (NumberFeed), and then another method to display that group of numbers (NumberDisplay). but for some reason, I can't seem to get it to work
Array is the base class for arrays, its elements aren't "strongly typed"; you can put any object in it.
Since you seem to be dealing with int elements only, you should be using int[] where you now use Array. You can then access elements with the [] indexing, and you ensure that each element is an int to boot.
You could rewrite this code with something like this
Check the IEnumerable interface and List class
This code is cleaner and removes NumberFeedLengthDecider method, this method is making noise in the code. When you don't know how many inputs you will have use List class, it uses more memory than classic array, but gets the job done in situations like this. For better conversions check out TryParse and Parse method (ex. int.TryParse() and int.Parse()) and work more with exception handling.
public List<int> Insert()
{
//Output here something to the console
List<int> numbers = new List<int>();
while(true)
{
var input = Console.ReadLine();
if(input.ToLower() == "done") break;
try
{
numbers.Add(Convert.Int32(input));
}
catch(FormatException e)
{
Console.WriteLine(e.Message);
}
}
return numbers;
}
public void Print(IEnumerable<int> numbers)
{
foreach(var num in numbers)
{
Console.WriteLine(num);
}
}
Use "SetValue". Example:
Array? arr = Array.CreateInstance(arrayType, source.Count);
for (int i = 0; i < source.Count; i++)
{
arr.SetValue(source[i], i);
}
Or, in your case:
for (int counter = 0; counter < i; counter++)
{
int temp = Convert.ToInt32(Console.ReadLine());
numbers.SetValue[counter] = temp;
// to read back...
Console.WriteLine(arr.GetValue(counter));
}

Randomizing List with Guid

I have a problem about my c# project. In the program I have a list
private static void FillData(List<Question> questions)
{
AddQuestion(questions,
"DotA isimli MOBA oyununun açılımı nedir? ",
2,
"Defense of the Arkham",
"Defence of the Ancients",
"Defense of the Ancients",
"Dance of the Architectures"
);
like that and i wanna make that list randomizely showned in every opening with shuffle. In the example my teacher used
private static void Shuffle(Soru[] array)
{
int length = array.Length;
for (int i = 0; i < length; i++)
{
int index = i + ((int) (_random.NextDouble() * (length - i)));
Soru soru = array[index];
array[index] = array[i];
array[i] = soru;
}
this and i wanna make that in Guid.NewGuid(). Can anyone help me with replacing that with Guid?
(edited from comments) This is what I tried so far:
private static void Shuffle(List<Question> List)
{
List = List.OrderBy(o => Guid.NewGuid().ToString()).ToList();
foreach (Question question in ....) { Console.WriteLine(question);
}
but I can't fullfill foreach loop. And yes I want to use Guid instead of random.
The problem is that you only modified the input parameter to hold a reference of another List. As it is not passed as reference, in the place where you have called it will hold the reference of the original List.
You could try this way:
private static void Shuffle(List<Question> List)
{
var randomOrderList = List.OrderBy(o => Guid.NewGuid().ToString()).ToList();
for (int i = 0; i < List.Count; i++)
{
List[i] = randomOrderList[i];
}
}

mergesort - with an insignificant change throws SystemInvalidOperationException

A very strange thing occured in my program. Here is the simplified code.
class Program
{
static void Main(string[] args)
{
ArrayList numbers = new ArrayList();
numbers.Add(1);
numbers.Add(3);
numbers.Add(4);
numbers.Add(2);
var it = Sorts.MergeSort((ArrayList)numbers.Clone());
Sorts.PrintArray(it, "mergesort");
Console.WriteLine("DONE");
Console.ReadLine();
}
}
public static class Sorts
{
public static ArrayList BubbleSort(ArrayList numbers)
{
bool sorted = true;
for (int i = 0; i < numbers.Count; i++)
{
for (int j = 1; j < numbers.Count; j++)
{
if ((int)numbers[j - 1] > (int)numbers[j])
{
int tmp = (int)numbers[j - 1];
numbers[j - 1] = numbers[j];
numbers[j] = tmp;
sorted = false;
}
}
if (sorted)
{
return numbers;
}
}
return numbers;
}
public static ArrayList MergeSort(ArrayList numbers, int switchLimit = 3)
{
//if I use this if - everything works
if (numbers.Count <= 1)
{
// return numbers;
}
//the moment I use this condition - it throws SystemInvalidOperationException in function Merge in the line of a "for"-loop
if (numbers.Count <=switchLimit)
{
return Sorts.BubbleSort(numbers);
}
ArrayList ret = new ArrayList();
int middle = numbers.Count / 2;
ArrayList L = numbers.GetRange(0, middle);
ArrayList R = numbers.GetRange(middle, numbers.Count - middle);
L = MergeSort(L);
R = MergeSort(R);
return Merge(L, R);
}
private static ArrayList Merge(ArrayList L, ArrayList R)
{
ArrayList ret = new ArrayList();
int l = 0;
int r = 0;
for (int i = 0; i < L.Count + R.Count; i++)
{
if (l == L.Count)
{
ret.Add(R[r++]);
}
else if (r == R.Count)
{
ret.Add(L[l++]);
}
else if ((int)L[l] < (int)R[r])
{
ret.Add(L[l++]);
}
else
{
ret.Add(R[r++]);
}
}
return ret;
}
//---------------------------------------------------------------------------------
public static void PrintArray(ArrayList arr, string txt = "", int sleep = 0)
{
Console.WriteLine("{1}({0}): ", arr.Count, txt);
for (int i = 0; i < arr.Count; i++)
{
Console.WriteLine(arr[i].ToString().PadLeft(10));
}
Console.WriteLine();
System.Threading.Thread.Sleep(sleep);
}
}
There is a problem with my Sorts.MergeSort function.
When I use it normally (take a look at the first if-condition in a function - all works perfectly.
But the moment when I want it to switch to bubblesort with smaller input (the second if-condition in the function) it throws me an SystemInvalidOperationException. I have no idea where is the problem.
Do you see it?
Thanks. :)
Remark: bubblesort itself works - so there shouldn't be a problem in that sort...
The problem is with your use of GetRange:
This method does not create copies of the elements. The new ArrayList is only a view window into the source ArrayList. However, all subsequent changes to the source ArrayList must be done through this view window ArrayList. If changes are made directly to the source ArrayList, the view window ArrayList is invalidated and any operations on it will return an InvalidOperationException.
You're creating two views onto the original ArrayList and trying to work with both of them - but when one view modifies the underlying list, the other view is effectively invalidated.
If you change the code to create copies of the sublists - or if you work directly with the original list within specified bounds - then I believe it'll work fine.
(As noted in comments, I'd also strongly recommend that you use generic collections.)
Here's a short but complete program which demonstrates the problem you're running into:
using System;
using System.Collections;
class Program
{
static void Main()
{
ArrayList list = new ArrayList();
list.Add("a");
list.Add("b");
ArrayList view1 = list.GetRange(0, 1);
ArrayList view2 = list.GetRange(1, 1);
view1[0] = "c";
Console.WriteLine(view2[0]); // Throws an exception
}
}
on this line R = MergeSort(R); you alter the range of numbers represented by L. This invalidates L. Sorry I have to go so can't explain any further now.

Categories