I have code which consists of Array in doubles, but right now I am trying to check how to detect if there is two similar MAX in the array. The number MAX that I have set is 100. So if there is two or more 100, I would like to display output: Multiple MAX value. Hence I thought of using IF-ELSE, but I am not sure on how to check for Multiple MAX value.
This is my code:
double num1 = 100;
double num2 = 100;
double num3 = 70;
double num4 = 65;
double[] array1 = { num1, num2, num3, num4 };
double text = array1.Max();
if()
{
}
else
{
}
You can use the Count extension method, Try this code:
if(array1.Count(x=>x == text) > 1){
//...
} else {
//...
}
int count=0;
bool maxreached=false;
for(int i=0;i<array1.Length;i++)
{
if(array1[i]==text)
count++;
if(count>1)
{
maxreached=true;
break;
}
}
if(maxreached)
Console.WriteLine("Max value = "+ text +" found multiple times");
Related
The task is to allow the user to enter values between 0 and 100. If the user enters -99 the program should stop. Once the program has exited, the average must be computed. However, the average should include all the entered values, except the lowest value entered (minimum) and the greatest value entered (maximum). I have written a fairly good-looking code, but it throws an IndexOutOfRangeException.
Here is that code:
class Program
{
static void Main(string[] args)
{
DisplayApp();
Calculate();
}
static void DisplayApp()
{
Console.WriteLine("Grade Calculator: ");
Console.WriteLine();
}
static double Calculate()
{
Console.WriteLine("Enter grades (-99 to exit): ");
string input = Console.ReadLine();
int[] array1 = new int[] { };
int iInput = int.Parse(input);
int min = 100;
int max = 0;
int i = 0;
int sum = 0;
double average = 0;
while(iInput != 99)
{
if(iInput < min)
{
array1[i] = min;
}
else if(iInput > max)
{
array1[i] = max;
}
sum += iInput - (min + max);
i++;
}
average = (double)sum / i;
return average;
}
}
What do you think could be improved in order for the program to work?
As I mentioned in the comments, you create an array of size zero. I don't see why you need an array at all, since you are only summing the values:
static double Calculate()
{
Console.WriteLine("Enter grades (-99 to exit): ");
int min = Int32.MaxValue;
int max = Int32.MinValue;
int sum = 0;
int i = 0;
while (true)
{
// TODO: Change to TryParse and handle input errors.
int iInput = int.Parse(Console.ReadLine());
if (iInput == -99) break;
if (iInput > 0 && iInput < 100) {
if (iInput < min)
{
min = iInput;
}
if (iInput > max)
{
max = iInput;
}
sum += iInput;
i += 1;
}
}
// TODO: Ensure no division by zero
return (double)(sum - max - min) / (i - 2);
}
I used Visual Studio to create an application that features 3 fields where 3 numbers can be added together. Now, I need to validate all 3 fields so that negative numbers cannot be added. If a negative number is entered, each field has also to return a unique message like: "please enter a positive first number."
I figured out how to do that for one field, but how do I set it up for all 3 fields to not accept negative numbers (and display a unique message)?
Here is what I have:
{
int num = int.Parse(txtNum1.Text);
if (num <0)
{
MessageBox.Show("Please enter a positive first number");
}
else
{
int num1 = int.Parse(txtNum1.Text);
int num2 = int.Parse(txtNum2.Text);
int num3 = int.Parse(txtNum3.Text);
int sum = num1 + num2 + num3;
txtResult.Text = sum.ToString();
}
Hopefully this makes sense.
This might help you
int num = 0;
bool atLeastOneisNegative = false;
foreach (Control x in this.Controls)
{
if (x is TextBox)
{
num = 0;
num = int.Parse(((TextBox)x).Text);
if(num < 0)
{
atLeastOneisNegative = true;
MessageBox.Show("Please enter a positive first number");
}
}
}
if(!atLeastOneisNegative)
{
int num1 = int.Parse(txtNum1.Text);
int num2 = int.Parse(txtNum2.Text);
int num3 = int.Parse(txtNum3.Text);
int sum = num1 + num2 + num3;
txtResult.Text = sum.ToString();
}
Whereas the question is not stating whether you are using WPF or WinForms. But the logic might help you to achieve to iterate all your TextBoxes and see the value is Positive.
It can be easier with NumericUpDown control or handling the TextBox.Validating event, but anyway:
int i1, i2, i3;
if (!int.TryParse(txtNum1.Text, out i1) || i1 < 0) { MessageBox.Show("Please enter a positive first number" ); return; }
if (!int.TryParse(txtNum2.Text, out i2) || i2 < 0) { MessageBox.Show("Please enter a positive second number"); return; }
if (!int.TryParse(txtNum3.Text, out i3) || i3 < 0) { MessageBox.Show("Please enter a positive third number" ); return; }
int sum = i1 + i2 + i3;
txtResult.Text = sum.ToString();
I have to write 2 different numbers in two textboxes, and with a button calculate the GCD, but when I run it, the button does nothing.
int x = Convert.ToInt16(txtNum1.Text);
int y = Convert.ToInt16(txtNum2.Text);
int num1, num2;
int residuo;
if (x < y)
{
num1 = y;
num2 = x;
}
else
{
num1 = x;
num2 = y;
}
do
{
residuo = num1 % num2;
if (residuo == 0)
{
txtMCD.Text = num2.ToString();
}
else
{
num1 = num2;
num2 = residuo;
}
} while (residuo == 0);
X and y are both numbers writen in the textboxes, I use num1 and num2 to save the value of x and y in order that num1 is the higher, and num2 the lesser. Any ideas?
Your termination condition is incorrect. It should be while (residuo != 0). As it is, you either terminate the loop after one iteration, or you are in an infinte loop.
I have this code I'm using to create a program that takes a a range and outputs to the Console the prime numbers. I have one problem, I'm trying to iterate through the array I built so the loop should only write to the console the values that are prime using my method's return value. The problem I'm having is that I have the second condition set to numArray.Length but it seems to give me the Index out of Range Exception. I just want the loop to iterate through all values in the numArray and stop when it's done figuring out whether the last value is prime or not.
public struct Prime
{
public int x;
// constructor for Prime
public Prime(int x1)
{
x = x1;
}
public int IsPrime(int number)
{
int i;
for (i = 2; i * i <= number; i++)
{
if (number % i == 0) return 0;
}
return 1;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter an Integer");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter a Second Integer of Greater Value");
// int num2 = 0;
int num2 = Convert.ToInt32(Console.ReadLine());
/* if (num2temp > num1)
{
num2temp = num2;
}
else
{
Console.WriteLine("You Did Not Enter An Integer Greater Than the First Integer, Please Enter Your Integers Again.");
Environment.Exit(0);
}
*/ int index = 1;
int[] numArray = new int[num2];
for (int i = num1; i <= num2; i++)
{
numArray[index] = i;
Console.WriteLine(" index: {0} assignment: {1}", index, i);
index++;
Console.WriteLine("index: {0}",index);
}
Console.WriteLine("value: {0}", numArray[40]);
/* Prime myprime = new Prime();
if (myprime.IsPrime(numArray[12]) == 1)
{
Console.WriteLine("true");
}
else
{
Console.WriteLine("False");
} */
Prime myprime = new Prime();
int value = 0;
for (int y = 1; y <= num2; y++)
{
if (myprime.IsPrime(numArray[y]) == 1)
{
value = numArray[y];
Console.Write("{0} \t", value);
}
}
You're currently trying to iterate up to and including the size of the array. Arrays are 0-indexed in C#. So this:
int[] numArray = new int[num2];
for (int i = num1; i <= num2; i++)
should be:
for (int i = num1; i < num2; i++)
And note that to get at the first element array, num1 would have to be 0, not 1.
Likewise, your initial assignment of index as 1 should be 0 instead. Basically you need to go through all your code (it's confusing at the moment with lots of bits commented out) and check everywhere that you're assuming arrays are 1-based, and instead change your code as they're 0-based.
(In some cases you may just want to make the array one bigger, of course. If you want an array which logically contains the values 1 to x inclusive, you can either create an array of size x and subtract one from each index all the time, or create an array of size x + 1.)
Your index starts from 1 but should start from 0:
int index = 0; //CHANGE HERE
int[] numArray = new int[num2];
for (int i = num1; i <= num2; i++)
{
numArray[index] = i;
Console.WriteLine(" index: {0} assignment: {1}", index, i);
index++;
Console.WriteLine("index: {0}",index);
}
and then here y should also be 0 and check should if it is less than num2:
for (int y = 0; y < num2; y++)
{
if (myprime.IsPrime(numArray[y]) == 1)
{
value = numArray[y];
Console.Write("{0} \t", value);
}
}
because array indexing in C# start from 0.
This is a problem statement.
Consider a number 2345. If you multiply its digits then you get the number 120. Now if you again multiply digits of 120 then you will get number 0 which is a one digit number. If I add digits of 2345 then I will get 14. If I add digits of 14 then I will get 5 which is a one digit number.
Thus any number can be converted into two one digit numbers in some number of steps. You can see 2345 is converted to 0 by using multiplication of digits in 2 steps and it is converted to 5 by using addition of digits in 2 steps. Now consider any number N. Let us say that it can be converted by multiplying digits to a one digit number d1 in n1 steps and by adding digits to one digit number d2 in n2 steps.
Your task is to find smallest number greater than N and less than 1000000000 which can be converted by multiplying its digits to d1 in less than or equal to n1 steps and by adding its digits to d2 in less than or equal to n2 steps.
How to solve it in C#...
I think you're simply approaching / interpreting the problem incorrectly; here's a stab in the dark:
using System;
using System.Diagnostics;
static class Program
{
static void Main()
{
// check our math first!
// You can see 2345 is converted to 0 by using multiplication of digits in 2 steps
int value, steps;
value = MultiplyToOneDigit(2345, out steps);
Debug.Assert(value == 0);
Debug.Assert(steps == 2);
// and it is converted to 5 by using addition of digits in 2 steps
value = SumToOneDigit(2345, out steps);
Debug.Assert(value == 5);
Debug.Assert(steps == 2);
// this bit is any random number
var rand = new Random();
for (int i = 0; i < 10; i++)
{
int N = rand.Next(0, MAX);
int result = Execute(N);
Console.WriteLine("For N={0}, our answer is {1}", N, result);
}
}
const int MAX = 1000000000;
//Now consider any number N.
static int Execute(int N)
{
// Let us say that it can be converted by multiplying digits to a one digit number d1 in n1
// steps and by adding digits to one digit number d2 in n2 steps.
int n1, n2;
int d1 = MultiplyToOneDigit(N, out n1),
d2 = SumToOneDigit(N, out n2);
// Your task is to find smallest number greater than N and less than 1000000000
for (int i = N + 1; i < MAX; i++)
{
int value, steps;
// which can be converted by multiplying its digits to d1 in less than or equal to n1 steps
value = MultiplyToOneDigit(i, out steps);
if (value != d1 || steps > n1) continue; // no good
// and by adding its digits to d2 in less than or equal to n2 steps.
value = SumToOneDigit(i, out steps);
if(value != d2 || steps > n2) continue; // no good
return i;
}
return -1; // no answer
}
static int MultiplyToOneDigit(int value, out int steps)
{
steps = 0;
while (value > 10)
{
value = MultiplyDigits(value);
steps++;
}
return value;
}
static int SumToOneDigit(int value, out int steps)
{
steps = 0;
while (value > 10)
{
value = SumDigits(value);
steps++;
}
return value;
}
static int MultiplyDigits(int value)
{
int acc = 1;
while (value > 0)
{
acc *= value % 10;
value /= 10;
}
return acc;
}
static int SumDigits(int value)
{
int total = 0;
while (value > 0)
{
total += value % 10;
value /= 10;
}
return total;
}
}
There are two memory problems I can see; the first is the generation of lots of strings - you might want to approach that something like:
static int SumDigits(int value)
{
int total = 0;
while (value > 0)
{
total += value % 10;
value /= 10;
}
return total;
}
(which is completely untested)
The second problem is the huge list; you don't need to store (in lstString) every value just to find a minimum. Just keep track of the best you've done so far. Or if you need the data for every value, then: don't store them as a string. Indeed, the i can be implied anyway (from the position in the list/array), so all you would really need would be an int[] of the cnt values for every value. And int[1000000000] is 4GB just by itself, so would require the large-array support in recent .NET versions (<gcAllowVeryLargeObjects>). But much better would be: just don't store it.
But it's throwing System.OutOfMemoryException .
That simply mean you're running out of memory. Your limit is 1,000,000,000 or roughly 1G. Times 4 bytes for a string reference that's already too large for a 32 bit system. Even without the actual strings.
You can store your answers more compactly in an int[] array but that would still show the same problem.
So, lower your limit or compile and run on a 64 bit PC.
A for effort :)
Now doing together. You can of course do refactoring.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _17082903_smallest_greatest_number
{
class Program
{
static void Main(string[] args)
{
int N = 2344;
int n1 = 0;
int n2 = 0;
int d1 = SumDigits(N, ref n1);
int d2 = ProductDigits(N, ref n2);
bool sumFound = false, productFound = false;
for (int i = N + 1; i < 1000000000; i++)
{
if (!sumFound)
{
int stepsForSum = 0;
var res = SumDigits(i, ref stepsForSum);
if (res == d1 && stepsForSum <= n1)
{
Console.WriteLine("the smallest number for sum is: " + i);
Console.WriteLine(string.Format("sum result is {0} in {1} steps only", res, stepsForSum));
sumFound = true;
}
stepsForSum = 0;
}
if (!productFound)
{
int stepsForProduct = 0;
var res2 = ProductDigits(i, ref stepsForProduct);
if (res2 == d2 && stepsForProduct <= n2)
{
Console.WriteLine("the smallest number for product is: " + i);
Console.WriteLine(string.Format("product result is {0} in {1} steps only", res2, stepsForProduct));
productFound = true;
}
stepsForProduct = 0;
}
if (productFound && sumFound)
{
break;
}
}
}
static int SumDigits(int value, ref int numOfSteps)
{
int total = 0;
while (value > 0)
{
total += value % 10;
value /= 10;
}
numOfSteps++;
if (total < 10)
{
return total;
}
else
{
return SumDigits(total, ref numOfSteps);
}
}
static int ProductDigits(int value, ref int numOfSteps)
{
int total = 1;
while (value > 0)
{
total *= value % 10;
value /= 10;
}
numOfSteps++;
if (total < 10)
{
return total;
}
else
{
return ProductDigits(total, ref numOfSteps);
}
}
}
}