calculator computing multiple numbers - c#

static void Main(string[] args)
{
string again;
do
{
Console.Write("Enter size to compute: ");
int size = Convert.ToInt32(Console.ReadLine());
int[] numbers = new int[size];
float[] numberS = new float[size];
Console.Write("Pick one of the operation \"(+) (-) (*) (/)\": ");
string operation = Console.ReadLine();
if (operation == "+")
{
for (int i = 0; i < size; i++)
{
Console.Write("Enter numbers: ");
numbers[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The sum is:" + add(numbers));
}
else if (operation == "-")
{
for (int i = 0; i < size; i++)
{
Console.Write("Enter numbers: ");
numbers[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The subtraction is:" + subtract(numbers));
}
else if (operation == "*")
{
for (int i = 0; i < size; i++)
{
Console.Write("Enter numbers: ");
numbers[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The mulplication is:" + multiply(numbers));
}
else if (operation == "/")
{
for (int i = 0; i < size; i++)
{
Console.Write("Enter numbers: ");
numberS[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The division is:" + division(numberS));
}
else Console.WriteLine("Invalid Input");
Console.Write("Do you want to compute again Y/N: ");
again = Console.ReadLine().ToUpper();
Console.Clear();
} while (again == "Y");
}
static int add(int[] numbers)
{
int total = 0;
for (int i = 0; i < numbers.Length; i++)
{
total += numbers[i];
}
return total;
}
static int subtract(int[] numbers)
{
int total = 0;
for (int i = 0; i < numbers.Length; i++)
{
total += numbers[i] - numbers[i];
}
return total;
}
static int multiply(int[] numbers)
{
int total = 0;
for (int i = 0; i < numbers.Length; i++)
{
total += numbers[i] * numbers[i];
}
return total;
}
static float division(float[] numbers)
{
float total = 0;
for (int i = 0; i < numbers.Length; i++)
{
total += numbers[i] / numbers[i];
}
return total;
}
I was expecting the same results in my phones calculator but no

Your code itself is fine. However your subtract, multiply and division methods are wrong. They are calculating something totally different than intended.
The multiply-method sums the squares of the entered numbers.
The subtract-method always subtracts the current number of itself which equals 0 and always results with a total of 0.
The division method always divides the current number by itself which is 1 and results with a total which equals the number of numbers entered.
Try these methods instead:
static int subtract(int[] numbers)
{
if (numbers.Length == 0)
return 0;
int total = numbers[0];
for (int i = 1; i < numbers.Length; i++)
{
total -= numbers[i];
}
return total;
}
static int multiply(int[] numbers)
{
if (numbers.Length == 0)
return 0;
int total = numbers[0];
for (int i = 1; i < numbers.Length; i++)
{
total *= numbers[i];
}
return total;
}
static float division(float[] numbers)
{
if (numbers.Length == 0)
return 0;
float total = numbers[0];
for (int i = 1; i < numbers.Length; i++)
{
total /= numbers[i];
}
return total;
}
In all of these methods the program first checks if there are any numbers passed. Otherwise it just returns 0.
If there are any numbers you set the first entered number to the total variable because it will be used anyway. The temporary result is always stored in the total variable.
Because the first element is already used the for-loop starts from index 1 instead of 0.
Then the operations are applied to the variable with all remaining numbers.

Related

How to add elements to an array based on a condition?

I'm working on this simple C# program adding elements to an array. I allow the user to enter 5 numbers, and if the user enters an INVALID valid I have a message for that. My issue is that whether the users enters an invalid number or not I still want to add 5 numbers to my array.
My code works, but let's say the user enters 3 numbers and then 2 words and I end up having ONLY 3 numbers, but I want the 5 numbers no matter what. What am I doing wrong?
Here's my code:
int[] numbers = new int[5];
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Enter a number: ");
string c = Console.ReadLine();
int value;
if (int.TryParse(c, out value))
{
numbers[i] = value;
}
else
{
Console.WriteLine("You did not enter a number\n");
}
}
for (int i = 0; i < numbers.Length; i++ )
{
Console.Write(numbers[i] + " ");
}
You can reduced increment count by 1, when user inputs wrong/no number.
Also note, you are code currently reading input only for 4(not 5 as question description says.) numbers.
int[] numbers = new int[4];
for (int i = 0; i < 4; i++)
{
Console.WriteLine("Enter a number: ");
string c = Console.ReadLine();
int value;
if (int.TryParse(c, out value))
{
numbers[i] = value;
}
else
{
i--;
Console.WriteLine("You did not enter a number\n");
}
}
for (int i = 0; i < numbers.Length; i++ )
{
Console.Write(numbers[i] + " ");
}
try using do-while
int[] numbers = new int[4];
int i = 0;
do
{
Console.WriteLine("Enter a number: ");
string c = Console.ReadLine();
int value;
if (int.TryParse(c, out value))
{
numbers[i] = value;
i++;
}
else
{
Console.WriteLine("You did not enter a number\n");
}
} while (i < 5);
Console.WriteLine("\nYour entered numbers are\n");
for (int j = 0; j < numbers.Length; j++ )
{
Console.Write(numbers[j] + " ");
}
You could use while loop here. See the below code
int[] numbers = new int[5];
int i = 0;
while (i < 5) {
Console.WriteLine ("Enter a number: ");
string c = Console.ReadLine ();
int value;
if (int.TryParse (c, out value)) {
numbers[i] = value;
i++;
} else {
Console.WriteLine ("You did not enter a number\n");
}
}
for (i = 0; i < numbers.Length; i++) {
Console.Write (numbers[i] + " ");
}
You can reduce the code using while loop. Also its better to change the last for loop to foreach
int[] numbers = new int[5];
int i = 0;
while (i < 5)
{
Console.WriteLine("Enter a number: ");
string c = Console.ReadLine();
int value;
if (!int.TryParse(c, out value)) continue;
numbers[i] = value;
i++;
}
foreach (int t in numbers)
Console.Write(t + " ");

Extra zero in final out put where does it come from?

I wrote this code to order any set of numbers from biggest to smallest, but for whatever reason, the output always has a zero at the end. My question is, where did it come from? (new to coding)
Console.WriteLine("Please enter set of numbers");
int input = Convert.ToInt16(Console.ReadLine());
int counter= 1;
int temp1;
int temp2;
int[] array = new int[input+1];
for (int i = 0; i <=input-1; i++)
{
Console.WriteLine("Please enter entry number " + counter);
int number = Convert.ToInt16(Console.ReadLine());
array[i] = number;
counter++;
}
for (int x = 0; x <= input; x++)
{
for (int i = 1; i <=input; i++)
{
if (array[i - 1] <= array[i])
{
temp1 = array[i - 1];
temp2 = array[i];
array[i - 1] = temp2;
array[i] = temp1;
}
}
}
Console.WriteLine();
for (int i = 0; i<=input; i++)
{
Console.Write(array[i] + " ");
}
Console.ReadLine();
You're inconsistent between whether you're trying to handle input + 1 or input elements. For example:
int[] array = new int[input+1];
for (int i = 0; i <=input-1; i++)
{
Console.WriteLine("Please enter entry number " + counter);
int number = Convert.ToInt16(Console.ReadLine());
array[i] = number;
counter++;
}
You're creating an array with input + 1 elements, but only populating input of them.
In general, it's much more common to use exclusive upper boundaries for loops. For example:
int[] array = new int[input];
for (int i = 0; i < input; i++)
{
// No need for the counter variable at all
Console.WriteLine("Please enter entry number " + (i + 1));
int number = Convert.ToInt16(Console.ReadLine());
array[i] = number;
}

Find the average. largest, smallest number and mode of a int array

Hi I am trying to make a program where the user can enter up to 25 numbers and then it tells the user the average, smallest and largest number and the mode of the numbers entered but I am not sure on how to do this.
Any Guidance would be appreciated
here is what I have so far
static void Main(string[] args)
{
Console.WriteLine("enter the amount of numbers you would like to use of: ");
int arraylength = Int32.Parse(Console.ReadLine());
int[] AverageArray = new int[25];
//filling the array with user input
for (int i = 0; i < AverageArray.Length; i++)
{
Console.Write("enter the numbers you wish to find the average for: ");
AverageArray[i] = Int32.Parse(Console.ReadLine());
}
//printing out the array
Console.WriteLine("here is the average: ");
for (int i = 0; i < AverageArray.Length; i++)
{
Console.WriteLine(AverageArray[i]);
}
Console.WriteLine(FindAverage(AverageArray));
}
public static double FindAverage(int[] averageNumbers)
{
int arraySum = 0;
for (int i = 0; i < averageNumbers.Length; i++)
arraySum += averageNumbers[i];
return arraySum / averageNumbers.Length;
}
public static double LargestNumber(int[] Nums, int Count)
{
}
public static double SmallestNumber(int[] Nums, int Count)
{
}
public static double Mode(int[] Nums, int Count)
{
}
}
var smallest = AverageArray.Min();
var largest = AverageArray.Max();
var mode = AverageArray.GroupBy(v => v)
.OrderByDescending(g => g.Count())
.First()
.Key;
If you don't know how to use linq
/*Assign Initial Value*/
int highestNum = numberArray[0];
int lowestNum = numberArray[0];
int sum = 0;
foreach (int item in numberArray)
{
/*Get The Highest Number*/
if (item > highestNum)
{
highestNum = item;
}
/*Get The Lowest Number*/
if (item < highestNum)
{
lowestNum = item;
}
//get the sum
sum = item + sum;
}
//display the Highest Num
Console.WriteLine(highestNum);
//display the Lowest Num
Console.WriteLine(lowestNum);
//Display The Average up to 2 decimal Places
Console.WriteLine((sum/numberArray.Length).ToString("0.00"));
public static double LargestNumber(int[] Nums, int Count)
{
double max = Nums[0];
for (int i = 1; i < Count; i++)
if (Nums[i] > max) max = Nums[i];
return min;
}
public static double SmallestNumber(int[] Nums, int Count)
{
double min = Nums[0];
for (int i = 1; i < Count; i++)
if (Nums[i] < min) min = Nums[i];
return min;
}
public static double Mode(int[] Nums, int Count)
{
double mode = Nums[0];
int maxCount = 1;
for (int i = 0; i < Count; i++)
{
int val = Nums[i];
int count = 1;
for (int j = i+1; j < Count; j++)
{
if (Nums[j] == val)
count++;
}
if (count > maxCount)
{
mode = val;
maxCount = count;
}
}
return mode;
}

Finding minimum of several integers

In a program that requires the user to input the number of integers, I cannot find out how to display the minimum of all the values.
static void Main(string[] args)
{
Console.WriteLine("\n Number of values:");
int num = Convert.ToInt32(Console.ReadLine());
int[] number = new int[num];
int i;
for (i = 0; i < number.Length; i++)
{
Console.WriteLine("\n Enter value:");
number[i] = Convert.ToInt32(Console.ReadLine());
}
for (i = 0; i < number.Length; i++)
{
int Min = number[0];
if (number[i + 1] < Min)
{
Min = number[i + 1];
}
}
Console.WriteLine("Smallest is {0}", Min);
}
Declare Min outside for loop
int Min = number[0];
for (i = 1; i < number.Length; i++)
{
if (number[i] < Min)
{
Min = number[i];
}
}
There are methods that do this for you:
int[] number = new int[num];
int min = number.Min();
Use this:
int minNumber = numbers.Min();
You can use the Min method to calculate this.
int min = number.Min();
public static int FindMinimum(int[] values)
{
int result = int.MaxValue;
foreach (int value in values)
result = Math.Min(result, value);
return result;
}
Your current code will overflow the array. You should check index 0 first and then check the rest.
Replace
for (i = 0; i < number.Length; i++)
{
int Min = number[0];
if (number[i + 1] < Min)
{
Min = number[i + 1];
}
}
with
int Min = number[0];
for (i = 1; i < number.Length; i++)
{
if (number[i] < Min)
{
Min = number[i];
}
}
However, you could simply use Enumerable.Min() as int Min = number.Min(x => x)
how about this?!
int[] Numbers = new int[5] { 3, 5, 7, 9, 11, 15 };
var q = (from Num in Numbers
select Num).Min();
Have a look at LINQ samples from MSDN: http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b
you can use linq to object.
use Min method
sort your data in descending and take the first one
Declare Min as global static for example - public static int Min
Change the loop condition to for (i = 0; i < number.Length -1 ; i++) you exceed by one index range
Put Console.ReadLine on the end.
Or you don't have to store all numbers
static void Main(string[] args)
{
int min = int.MaxValue;
Console.WriteLine("\n Number of values:");
int num = Convert.ToInt32(Console.ReadLine());
var enteredValue = 0;
for (var i = 0; i < num; i++)
{
Console.WriteLine("\n Enter value:");
enteredValue = Convert.ToInt32(Console.ReadLine());
if (min>enteredValue) min = enteredValue;
}
Console.WriteLine("Smallest is {0}", min);
Console.ReadLine();
}

infinite loop in C#

This simple program take an input of integers and print them , but stop printing if it sees 60
string input = string.Empty;
int intValue = 0;
int[] numbers = new int[5];
for (int i = 0; i < 4; i++)
{
input = Console.ReadLine();
if (int.TryParse(input, out intValue))
numbers[i] = intValue;
}
for (int i = 0; i < numbers.Length; i++)
{
while (numbers[i] != 60)
{
Console.WriteLine(intValue);
}
}
the program go on an infinite loop after the 4th input
like that
Input:
1
2
3
4
4
4
4
4
4 ........ and so on
and i don't know the reason .... ^_^
while (numbers[i] != 60)
{
Console.WriteLine(intValue);
}
should be:
if (numbers[i] != 60)
{
Console.WriteLine(intValue);
}
string input = string.Empty;
int intValue = 0;
int[] numbers = new int[5];
for (int i = 0; i < 4; i++)
{
input = Console.ReadLine();
if (int.TryParse(input, out intValue))
numbers[i] = intValue;
}
for (int i = 0; i < numbers.Length; i++)
{
/*while (numbers[i] != 60)*/
if (numbers[i] != 60) // it should be if condition, while statement made it infinite
{
Console.WriteLine(intValue);
}
}

Categories