I am trying to create a method that sums and outputs integers in an array. I understand how to sum the integers, however I am having trouble producing the desired output.
If I pass into the method 8, 3, 3
I need the output to look as follows.
For the list = <8, 3, 3> the sum is: 14
Once again I am familiar with how to sum, I am unfamiliar with how to format this.
Here is my method so far...
public static void Sum(params int[] number)
{
int total = 0;
for (int i = 0; i < number.Length; ++i)
{
total = total + number[i];
}
Console.Write("For the list =, the sum of its elements is : {0}.", total);
Console.Write("\n");
}
Use the String.Join method to make a string with the values in the array:
string values = String.Join(", ", number);
Then just add it to the output:
Console.Write("For the list = <{0}> the sum of its elements is : {1}.", values, total);
Prior to framework 4 there is no overload of String.Join that can take an array of anything other than string, so if you are using an older framwork you need to turn the integers to strings:
string values = String.Join(", ", number.Select(n => n.ToString()));
public static void Sum(params int[] number)
{
int total=0;
for (int i = 0; i < number.Length; ++i) total = total + number[i];
string ext = String.Format ("<{0}>", String.Join (",", number));
Console.Write("For the list ={0} the sum is: {1}.",ext, total);
Console.Write("\n");
}
There are several ways you could go to produce the desired output, one would be:
public static void Sum(params int[] number)
{
int total=0;
StringBuild tmp="For the list =
for (int i = 0; i < number.Length; ++i)
{
total = total + number[i];
}
Console.Write("For the list =, the sum of its elements is : {0}.", total);
Console.Write("\n");
}
This will do it:
using System;
using System.Linq;
public class Test
{
public static void Main()
{
Sum(8,3,3);
}
public static void Sum(params int[] number)
{
Console.WriteLine("For the list <{0}>, the sum of its elements is: {1}",
string.Join(", ", number),
number.Sum());
}
}
outputs:
For the list <8, 3, 3>, the sum of its elements is: 14
Click here for a working sample
Related
Searching for a "magic digit" among the integers elements of array and summing of all integers that contain the "magic digit".
For example :
1, 2, 3, 4, 5, 55
and magic Digit is 5
1, 2, 3, 4, 5, 55
The sum of numbers that contain the magic digit "5" is: 60
(thank you in advance for your help)
so far I have :
int[] arrayOfUserInput = new int[10];
int i;
//------------------------------- Array and variable declaration
Console.WriteLine("Please enter 10 integers : ");
for (i = 0; i < 10; i++)
{
Console.Write("array element = {0} : ", i);
arrayOfUserInput[i] = Convert.ToInt32(Console.ReadLine());
}
//-------------------------------- User input of 10 integers
Console.Write("Please enter your magic number : ");
int magicNumberInput = Convert.ToInt32(Console.ReadLine());
if (magicNumberInput >= 0 && magicNumberInput <= 9)
{
Console.WriteLine($"Your magic number is : {magicNumberInput}");
}
else
{
Console.WriteLine("Sorry, but please enter single digit number!");
}
//-------------------------------- User input & displaying of magic number
Console.WriteLine("Your integers are : ");
for (i = 0; i < 10; i++)
{
Console.Write("{0} ", arrayOfUserInput[i]);
}
Console.WriteLine("");
//--------------------------------- Displaying user input of 10 integers
You can use Linq .Where() and .Sum() to calculate total of all numbers containing magic numbers.
using System;
using System.Linq;
using System.Collections.Generic;
...
var arrayOfUserInput = new int[] {1, 2, 3, 4, 5, 55};
var magicNumberInput = 5;
var sumOfNumbers = arrayOfUserInput
.Where(x => x.ToString().Contains(magicNumberInput.ToString())) //Filter by Magic numbers
.Sum(); //Calculate sum of filtered numbers.
.Net Fiddle
If you don't want to use Linq then you can do it using foreach or for loop with string.Contains() function.
...
var sumOfNumbers = 0;
foreach(var input in arrayOfUserInput)
{
if(input.ToString().Contains(magicNumberInput.ToString()))
sumOfNumbers += input;
}
Console.WriteLine(sumOfNumbers);
I would strongly suggest you to read more about LINQ and basics of C#.
Code refactoring note:
If you store input data in string format, then you need not to convert it again into string. At the time of addition convert it into int and add it to sumOfNumbers. Like,
Using Linq,
var sumOfNumbers = arrayOfUserInput
.Select(x => x.Contains(magicNumberInput) && int.TryParse(x, out int number) ? number : 0)
.Sum();
using for loop,
...
var sumOfNumbers = 0;
foreach(var input in arrayOfUserInput)
{
if(input.Contains(magicNumberInput) && int.TryParse(input, out int number))
sumOfNumbers += number;
}
Currently I have an array of 13 values and I want to find all the permutations of it and exclude the ones that summations that exceed a given threshold. The problem is that there are so many values it never finishes. Is there a way to optimize what I have?
public class formPermut
{
public void swapTwoNumber(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
public void prnPermut(int[] list, int k, int m)
{
int i;
if (k == m)
{
for (i = 0; i <= m; i++)
Console.Write("{0}", list[i]);
Console.Write(" ");
}
else
for (i = k; i <= m; i++)
{
swapTwoNumber(ref list[k], ref list[i]);
prnPermut(list, k + 1, m);
swapTwoNumber(ref list[k], ref list[i]);
}
}
}
public static void RecExercise11()
{
int n, i;
formPermut test = new formPermut();
int[] arr1 = new int[13];
Console.WriteLine("\n\n Recursion : Generate all possible permutations of an array :");
Console.WriteLine("------------------------------------------------------------------");
Console.Write(" Input the number of elements to store in the array [maximum 13 digits ] :");
n = Convert.ToInt32(Console.ReadLine());
Console.Write(" Input {0} number of elements in the array :\n", n);
for (i = 0; i < n; i++)
{
Console.Write(" element - {0} : ", i);
arr1[i] = Convert.ToInt32(Console.ReadLine());
}
Console.Write("\n The Permutations with a combination of {0} digits are : \n", n);
test.prnPermut(arr1, 0, n - 1);
Console.Write("\n\n");
}
}
}
So the problem is that you need to exclude the permutations whose sum is greater than a threshold is a perfect candidate for backtracking (don't search this term yet), think about a way to speed this up (there's n! permutations so it won't finish in a while).
Imagine this like a tree were the leaves are the permutations themselves and answer:
Do you need to know the full permutation before being able to exclude it?
What calculations can you make in a non-leaf node?
I would suggest you look at using the Permutation library from here
https://www.codeproject.com/Articles/26050/Permutations-Combinations-and-Variations-using-C-G
and then write your filtering on top of that.
I was asked to solve a problem in C# to get the sum of 'n' user inputs from console, which is separated by space, in a single line.
int n = Convert.ToInt32(Console.ReadLine());
int[] arr = new int[n];
int sum = 0;
for(int i = 0; i < n; i++) {
arr[i] = Convert.ToInt32(Console.ReadLine());
sum += arr[i];
}
Console.WriteLine("{0}",sum);
How can I modify this code to get the expected output from the space separated input?
Also the values need to be stored in array.
Input:
5
1 2 3 4 5
Output:
15
int result = Console.ReadLine().Split().Select(int.Parse).Sum();
You'll of course have to handle any bad user input as needed.
Per your added requirements:
int[] items = Console.ReadLine().Split().Select(int.Parse).ToArray();
int sum = items.Sum();
You could do something like this:
int result = input.Split(' ').Take(n).Select(int.Parse).Sum();
But it seems to me that you could avoid asking the user for the count, and just add together all the lines that they typed in:
string input = Console.ReadLine();
int result = input.Split(' ').Select(int.Parse).Sum();
Console.WriteLine(result);
(Note that this code does no error checking.)
EDIT: It seems that you want to have an array of ints. In that case, you can do it like this (again, with no error checking):
using System;
using System.Linq;
namespace Demo
{
internal class Program
{
private static void Main()
{
int n = int.Parse(Console.ReadLine());
int[] arr = Console.ReadLine().Split(' ').Take(n).Select(int.Parse).ToArray();
int sum = arr.Sum();
Console.WriteLine("{0}", sum);
}
}
}
You need to use the split function in C#. When you read the line, you get the whole line. This means you're attempting to say "sum = 0 plus Convert.ToInt32('5 1 2 3 4 5')" which doesn't work.
You need an array of integers equal to
Console.ReadLine().Split(" ");
String.Split function:
https://msdn.microsoft.com/en-us/library/b873y76a.aspx
using arr[i] = Convert.ToInt32(Console.ReadLine()) inside the loop will cause the program to expect an input on a different line and not on a single line.
What you can do is to take the input as a string and then split based on space, which produces an array of the inputed values. You can then sum them
Considering the fact that Naveen seems a student, I think some more code can explain better and let him learn some more from this exercise:
I've made a sample that gets some numbers separated by space or an enter and when the user enters a T calculates the sum in a traditional way using a loop and using Linq. I'm sure there are plenty of better ways to do the same, but maybe something a little bit more structured can be better to begin understanding C#.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SumTheNumbers
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Insert the numbers separated by a space or [Enter]> key, when finished write T and press [Enter] and you will have the result");
List<int> values = new List<int>();
while (true)
{
string inputData = Console.ReadLine();
if (inputData.ToUpper().StartsWith("T")) break;
string[] svals = inputData.Split(' ');
for (int i = 0; i < svals.Length; i++)
{
int x = 0;
int.TryParse(svals[i], out x);
if (x != 0) values.Add(x);
}
}
//Traditional mode
int total = 0;
for (int i = 0; i < values.Count; i++)
{
total = total + values[i];
}
//Linq mode
int totalLinq = values.Sum();
Console.WriteLine("The sum is");
Console.Write("Total: ");
Console.WriteLine(total.ToString());
Console.Write("Total linq: ");
Console.WriteLine(totalLinq.ToString());
Console.WriteLine("Press a key to end...");
Console.ReadKey();
}
}
}
I have a method that needs to do a calculation based upon the length of an array. I am using the .length method for the calculation, but the method is doing arithmetic with the max length of the array (which I have declared as 10). This is the loop I am using to get data from the user. I know it isn't the ideal way to sort array data, but this is for a homework assignment, and it revolves around using the .Split method correctly (which isn't the problem I'm having).
for (int i = 0; i < MAX; i++)
{
Console.Write("Enter a name and a score for player #{0}: ", (i + 1));
string input = Console.ReadLine();
if (input == "")
{
// If nothing is entered, it will break the loop.
break;
}
// Splits the user data into 2 arrays (integer and string).
string[] separateInput = input.Split();
name [i] = separateInput[0];
score [i] = int.Parse(separateInput[1]);
}
Here is the method I am using to calculate the average score:
static void CalculateScores(int[] score)
{
int sum = 0;
int average = 0;
for (int i = 0; i < score.Length; i++)
{
sum += score[i];
average = sum / score.Length;
}
Console.WriteLine("The average score was {0}", average);
I am calling the method like this:
CalculateScores(score);
Edit: My arrays are declared:
int[] score = new int[MAX]; //MAX == 10.
string[] name = new string[MAX];
The CalculateScores method is doing the math as though score.Length is always 10, no matter how many different combinations of scores I input to the console. I can't figure out if it's because my loop to gather input has been done incorrectly, or my CalculateScores method is flawed. Thanks in advance.
Edit: to clarify, I am just confused at why I can't get the correct value out of CalculateScores.
Length always represents the size of the array, which if you've instantiated as 10, then it will always be 10, regardless of how many items you've filled.
There are lots of ways of solving your problem, but I'd go with the simple one of not using length in your calculation, but rather just storing the number of items in a separate variable:
int numItems = 0;
for(int i=0;i<MAX;i++)
{
Console.Write("Enter a name and a score for player #{0}: ", (i + 1));
string input = Console.ReadLine();
if (input == "")
{
break; // if nothing is entered, it will break the loop
}
numItems++;
...
}
static void CalculateScores(int[] score, int numItems)
{
// don't use Length at all, use numItems instead
}
Arrays are generally used for fixed sized data, so the Length property reflects how many items the array can hold rather than the amount of elements in the array. The simplest fix would be to use a List(T), which is used for variadic data, instead.
// A nice abstraction to hold the scores instead of two separate arrays.
public class ScoreKeeper
{
public string Name { get; set; }
public int Score { get; set; }
}
var scores = new List<ScoreKeeper>();
for (int i = 0; i < MAX; i++)
{
Console.Write("Enter a name and a score for player #{0}: ", (i + 1));
string input = Console.ReadLine();
if (input == "")
{
// If nothing is entered, it will break the loop.
break;
}
// Splits the user data into 2 arrays (integer and string).
string[] separateInput = input.Split();
scores.Add(new ScoreKeeper { Name = separateInput[0], Score = int.Parse(separateInput[1]) });
}
static void CalculateScores(ICollection<ScoreKeeper> scores)
{
// We take advantage of Linq here by gathering all the
// scores and taking their average.
var average = scores.Select(s => s.Score).Average();
Console.WriteLine("The average score was {0}", average);
}
checking maually:
int sum = 0;
int average = 0;
int length;
for (int i = 0; i < MAX; i++) {
if(name[i]!=string.empty) {
sum += score[i];
length=i+1;
}
}
average = sum / length;
Console.WriteLine("The average score was {0}", average);
I need to define two methods for returning the sum and average of an int array. The method defining is as follow:-
public int Sum(params int[] customerssalary)
{
// I tried the following but it fails return customerssalary.sum();
}
Another question is, how can I return the average of these int values?
customerssalary.Average();
customerssalary.Sum();
This is the way you should be doing it, and I say this because you are clearly new to C# and should probably try to understand how some basic stuff works!
public int Sum(params int[] customerssalary)
{
int result = 0;
for(int i = 0; i < customerssalary.Length; i++)
{
result += customerssalary[i];
}
return result;
}
with this Sum function, you can use this to calculate the average too...
public decimal Average(params int[] customerssalary)
{
int sum = Sum(customerssalary);
decimal result = (decimal)sum / customerssalary.Length;
return result;
}
the reason for using a decimal type in the second function is because the division can easily return a non-integer result
Others have provided a Linq alternative which is what I would use myself anyway, but with Linq there is no point in having your own functions anyway. I have made the assumption that you have been asked to implement such functions as a task to demonstrate your understanding of C#, but I could be wrong.
Using ints.sum() has two problems:
The variable is called customerssalary, not ints
C# is case sensitive - the method is called Sum(), not sum().
Additionally, you'll need a using directive of
using System.Linq;
Once you've got the sum, you can just divide by the length of the array to get the average - you don't need to use Average() which will iterate over the array again.
int sum = customerssalary.Sum();
int average = sum / customerssalary.Length;
or as a double:
double average = ((double) sum) / customerssalary.Length;
Though the answers above all are different flavors of correct, I'd like to offer the following solution, which includes a null check:
decimal sum = (customerssalary == null) ? 0 : customerssalary.Sum();
decimal avg = (customerssalary == null) ? 0 : customerssalary.Average();
You have tried the wrong variable, ints is not the correct name of the argument.
public int Sum(params int[] customerssalary)
{
return customerssalary.Sum();
}
public double Avg(params int[] customerssalary)
{
return customerssalary.Average();
}
But do you think that these methods are really needed?
If you are using visual studio 2005 then
public void sumAverageElements(int[] arr)
{
int size =arr.Length;
int sum = 0;
int average = 0;
for (int i = 0; i < size; i++)
{
sum += arr[i];
}
average = sum / size; // sum divided by total elements in array
Console.WriteLine("The Sum Of Array Elements Is : " + sum);
Console.WriteLine("The Average Of Array Elements Is : " + average);
}
i refer so many results and modified my code its working
foreach (var rate in rateing)
{
sum += Convert.ToInt32(rate.Rate);
}
if(rateing.Count()!= 0)
{
float avg = (float)sum / (float)rateing.Count();
saloonusers.Rate = avg;
}
else
{
saloonusers.Rate = (float)0.0;
}