Below is my code in C# to get 10 int inputs and and store them in either evennum or oddnum array, then output the arrays, in my output it all works but it displays the empty values in EvenNum and OddNum as 0 which makes sense, but is there anyway to avoid it displaying them?
Code:
usingSystem;
usingSystem.Linq;
class Program {
publicstaticvoid Main (string[] args) {
int[] num = newint[10];
int[] EvenNum = newint[10];
int[] OddNum = newint[10];
//Loop 10 times:
for (int i=0; i < num.Length; ) {
//Get numbers as input
Console.WriteLine("Enter a number: ");
num[i] = Convert.ToInt32(Console.ReadLine());
if (num[i] % 2 == 0) {
//If number is even, store in an array called EvenNum.
EvenNum[i] = num[i];
} else {
//If number is odd, store in an array called OddNum.
OddNum[i] = num[i];
}
i++;
if(i==10) {
//Display EvenNum array in ascending order
Console.WriteLine("EvenNumbers in ascending order: ");
//Find sum of EvenNum array and display sum.
Console.WriteLine("Sum of EvenNumbers= " + EvenNum.Sum());
foreach (int e in EvenNum) {
Array.Sort(EvenNum);
Console.WriteLine(e);
}
//Display OddNum array in descending order
Console.WriteLine("OddNumbers in descending order: ");
//Find sum of OddNum array and display sum.
Console.WriteLine("Sum of OddNumbers= " + OddNum.Sum());
foreach (int o in OddNum) {
Array.Sort(OddNum);
Array.Reverse(OddNum);
Console.WriteLine(o);
}
}
}
}
}
Thanks to Format for answering and below is updated code for anyone interested. Also needed to move the Array.Sort's out of the foreach statements to avoid the obvious
Code:
usingSystem;
usingSystem.Linq;
class Program {
publicstaticvoid Main (string[] args) {
int[] num = newint[10];
int[] EvenNum = newint[10];
int[] OddNum = newint[10];
//Loop 10 times:
for (int i=0; i < num.Length; ) {
//Get numbers as input
Console.WriteLine("Enter a number: ");
num[i] = Convert.ToInt32(Console.ReadLine());
if (num[i] % 2 == 0) {
//If number is even, store in an array called EvenNum.
EvenNum[i] = num[i];
} else {
//If number is odd, store in an array called OddNum.
OddNum[i] = num[i];
}
i++;
if(i==10) {
//Display EvenNum array in ascending order
Array.Sort(EvenNum);
Console.WriteLine("EvenNumbers in ascending order: ");
//Find sum of EvenNum array and display sum.
Console.WriteLine("Sum of EvenNumbers= " + EvenNum.Sum());
foreach (int e in EvenNum) {
if (e != 0) {
Console.WriteLine(e);
}
}
//Display OddNum array in descending order
Array.Sort(OddNum);
Array.Reverse(OddNum);
Console.WriteLine("OddNumbers in descending order: ");
//Find sum of OddNum array and display sum.
Console.WriteLine("Sum of OddNumbers= " + OddNum.Sum());
foreach (int o in OddNum) {
if (o != 0) {
Console.WriteLine(o);
}
}
}
}
}
}