C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,305 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
As you can see the image above, they have random [02 04 01 03 05] numbers. Now if I click the button count it will count how many even number or odd number in textbox.
I have a code but it not working properly.
private void button2_Click(object sender, EventArgs e)
{
int num = ConvertToInt32(textBox1.Text);
int len_num = textBox1.Text.Length;
int[] arn = new int[len_num];
int cEv = 0;
int pOd = 0;
int s = 0;
for (int i = len_num - 1; i >= 0; i--)
{
arn[i] = broj % 10;
if (arn[i] % 2 == 0)
{
cEv++;
}
else
{
if (pOd == 0) pOd++;
pOd *= arn[i];
}
num /= 10;
s += arn[i];
}
txteven.Text = "is: " + Convert.ToString(cEv);
txtodd.Text = "is: " + Convert.ToString(pOd);
txtsum.Text = "is: " + Convert.ToString(s);
}
For example:
int[] numbers = textBox1.Text.Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries ).Select( p => int.Parse( p ) ).ToArray( );
int cEv = numbers.Where( n => ( n % 2 ) == 0 ).Count( );
int cOd = numbers.Where( n => ( n % 2 ) != 0 ).Count( );
int s = numbers.Sum( );
txteven.Text = "is: " + cEv;
txtodd.Text = "is: " + cOd;
txtsum.Text = "is: " + s;
It is possible to detect bad numbers.
In such cases, convert the contents of the text box into an array of strings and then convert it to a number.
private void button2_Click(object sender, EventArgs e)
{
string[] args = textBox1.Text.Split(
new char[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);
int cEv = 0;
int pOd = 0;
int s = 0;
for (int i = 0; i < args.Length; i++)
{
string str = args[i];
if (int.TryParse(str, out int tmp))
{
if (tmp % 2 == 0)
{
cEv++;
}
else
{
pOd++;
}
s += tmp;
}
else
{
System.Diagnostics.Debug.WriteLine($"Error! {str}");
}
}
txteven.Text = "is: " + Convert.ToString(cEv);
txtodd.Text = "is: " + Convert.ToString(pOd);
txtsum.Text = "is: " + Convert.ToString(s);
}