How to add elements to an array based on a condition? - c#

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 + " ");

Related

calculator computing multiple numbers

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.

return and while in function

This function accepting input and telling the user whether the input is number or not a number.
static string isnum()
{
Console.WriteLine("Write a number please");
string a = Console.ReadLine();
string nums = "123456789";
int cnt = 0;
for (int i = 0; i < a.Length; i++)
{
for (int j = 0; j < nums.Length; j++)
{
if (a[i] == nums[j])
{
cnt++;
break;
}
}
}
if (cnt == a.Length)
{
Console.WriteLine(a + " is a number");
return a;
}
else
{
Console.WriteLine(a + " is not a number");
return "";
}
}
isnum();
I would like this function to repeat herself if the input is not a number, till the input will be a number, and then to stop.
This function working now, but she's working only one time.
When I'm trying to add a while block to the function to make her run again and again till the input is number I'm getting the "not all code paths return a value" error.
is it because a "return" statement ends a function, and therefore prevent her to run again?
how can I solve that?
Thank you very much!
You can fix this with creating a loop arround it and do not return when it's not a number.
static string isnum()
{
// just loop forever.
while (true)
{
Console.WriteLine("Write a number please");
string a = Console.ReadLine();
string nums = "123456789";
int cnt = 0;
for (int i = 0; i < a.Length; i++)
{
for (int j = 0; j < nums.Length; j++)
{
if (a[i] == nums[j])
{
cnt++;
break;
}
}
}
if (cnt == a.Length)
{
Console.WriteLine(a + " is a number");
return a;
}
else
{
Console.WriteLine(a + " is not a number");
// don't return here
}
}
}
In this case the best approach is to use do while because you want your code to at least run once.
you have one problem in your code which is returning when variable is not a number. see these modifications:
static string isnum()
{
do{
Console.WriteLine("Write a number please");
string a = Console.ReadLine();
string nums = "123456789";
int cnt = 0;
for (int i = 0; i < a.Length; i++)
{
for (int j = 0; j < nums.Length; j++)
{
if (a[i] == nums[j])
{
cnt++;
break;
}
}
}
if (cnt == a.Length)
{
Console.WriteLine(a + " is a number");
return a;
}
else
{
Console.WriteLine(a + " is not a number");
}
}while(true);
}
Call it in a while loop, and loop until the result is a number:
string result = "";
while (result == "")
{
result = isnum();
}
Console.WriteLine("result is a number: " + result);
Instead of looping you can try querying the a string with a help of Linq:
using System.Linq;
...
static string isnum() {
// Keep asking user until he/she provides a number
while (true) {
Console.WriteLine("Write a number please");
string a = Console.ReadLine();
// Number is
// 1. Has at least one character
// 2. All characters of number are digits
if (a.Length > 0 && a.All(c => c >= '0' && c <= '9')) {
Console.WriteLine($"{a} is a number");
// we have a proper number, let's return int
return a;
}
Console.WriteLine($"{a} is not a number");
}
}

Splitting Array into new arrays and printing them with spaces

This program will sort numbers and depending if they are greater than or less than 100, put them into their own array.
The problem I have is printing this array. I would like the last number on the line, to not be followed by a space. I have tried many many times to get this to work now and figured I'd ask here.
I know of Console.Write("\b"); but I prefer to find a way of editing the loop so I don't have to do this. Here is the code:
using System;
using System.Linq;
class SplitArray
{
public static void Main(string[] args)
{
int[] myArray = GetNumbersFromConsole();
int[] smallNumbers = new int[myArray.Length];
int[] bigNumbers = new int[myArray.Length];
int bigIndex = 0;
int littleIndex = 0;
for (int i = 0; i < myArray.Length; i++)
{
if(myArray[i] > 100)
{
bigNumbers[bigIndex++] = myArray[i];
}
else if(myArray[i] < 100)
{
smallNumbers[littleIndex++] = myArray[i];
}
}
Console.Write("Big: ");
for (int i = 1; i < bigIndex; ++i)
{
Console.Write(bigNumbers[i]);
Console.Write(" ");
}
Console.WriteLine();
//Console.WriteLine($"{bigNumbers[0]}");
Console.Write("Little: ");
for (int i = 0; i < littleIndex; i++)
{
Console.Write($"{smallNumbers[i]}");
Console.Write(" ");
}
Console.ReadLine();
}
static int[] GetNumbersFromConsole()
{
int count = int.Parse(Console.ReadLine());
int[] result = new int[count];
for (int i = 0; i < count; ++i)
{
result[i] = int.Parse(Console.ReadLine());
}
return result;
}
}
You could just capture your Console.Write(" "); in an if statement.
if(i != littleIndex - 1)
{
Console.Write(" ");
}
littleIndex - 1 is the last time your loop executes, so this will just prevent it from adding the trailing white space. Just do the same for your big numbers as you're printing them out.
There is a builtin utility string.Join
var str = string.Join(" ",bigNumbers);
Console.WriteLine("Big: " + str);
I was playing around some more and just thought I'd try posting the first object in the array before running this loop (also changed loop so the first item didn't get printed twice).
Thank you everyone - I solved it! :)
using System;
using System.Linq;
namespace Arrays
{
class SplitArray
{
public static void Main(string[] args)
{
int[] myArray = GetNumbersFromConsole();
int[] smallNumbers = new int[myArray.Length];
int[] bigNumbers = new int[myArray.Length];
int bigIndex = 0;
int littleIndex = 0;
for (int i = 0; i < myArray.Length; i++)
{
if(myArray[i] > 100)
{
bigNumbers[bigIndex++] = myArray[i];
}
else if(myArray[i] < 100)
{
smallNumbers[littleIndex++] = myArray[i];
}
}
Console.Write("Big: ");
Console.Write($"{bigNumbers[0]} ");
for (int i = 1; i < bigIndex; i++)
{
Console.Write(bigNumbers[i]);
if (i != bigIndex - 1)
{
Console.Write(" ");
}
}
Console.WriteLine();
Console.Write("Little: ");
Console.Write($"{smallNumbers[0]} ");
for (int i = 1; i < littleIndex; i++)
{
Console.Write($"{smallNumbers[i]}");
if (i != littleIndex - 1)
{
Console.Write(" ");
}
}
Console.ReadLine();
}
static int[] GetNumbersFromConsole()
{
int count = int.Parse(Console.ReadLine());
int[] result = new int[count];
for (int i = 0; i < count; ++i)
{
result[i] = int.Parse(Console.ReadLine());
}
return result;
}
}
}

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;
}

Array Duplicate Elimination with c#?

I have a program here that need some improvements. This Program inputs 5 elements in an Array and Removes if any duplicates. It works but the problem is that it sets every duplicate to zero. I don't want to display zero. I want it completely destroyed and eliminated. I don't want that duplicate element to appear. This is what I have so Far! Could Use some help. Thank You.
// Gurpreet Singh
// Duplicate Program
using System;
class duplicate
{
static void Main()
{
const int Array_Size = 5;
int [] number = new int [Array_Size];
int i;
for ( i = 0; i < Array_Size; i++)
{
Console.Write("Element " + i + ": ");
number[i] = Int32.Parse(Console.ReadLine());
if (number[i] < 9 || number[i] > 101)
{
Console.WriteLine("Enter Number between 10 - 100");
number[i] = Int32.Parse(Console.ReadLine());
}
}
for (i = 0; i < Array_Size; i++)
{
for (int j = 0; j < Array_Size; j++)
{
if (i != j)
{
if (number[j] == number[i])
number[j] = 0;
}
}
}
Console.WriteLine("Duplicate Removed:");
for (i = 0; i < Array_Size; i++)
{
Console.WriteLine("Element " + i + " " + number[i]);
}
Console.ReadLine();
}
}
The easiest way is to use Linq's Distinct method:
number = number.Distinct().ToArray();
This will return a new array without any duplicates.
The duplicate is displayed as zero, since you assign the value of the duplicate to be zero, in the line,
if(number[j]==number[i])
number[j]=0
to delete the element from the array, use the following code:
if(number[j]==number[i])
{
int k=j;
while(k<Array_Size-1)
{
number[k]=number[k+1];
k++;
}
Array_Size--;
}
the statement Array_Size--; is done so that the last element is not repeated twice
This is my complete code in which I put some double-for-loop statement to
prevent it from inserting the duplicated integers in an array.
Have a look.
class Program
{
static void Main(string[] args)
{
const int ARRAY_SIZE = 5;
int[] ArrayTable = new int[ARRAY_SIZE];
int Element=0;
int a;
for(a=0; a<ArrayTable.Length;a++)
{
Console.Write("Please Enter an integer (between 10-100): ");
Element = Int32.Parse(Console.ReadLine());
while (Element < 10 || Element > 100)
{
Console.Write("Try again (between 10-100): ");
Element = Int32.Parse(Console.ReadLine());
}
ArrayTable[a] = Element;
for (int b = 0; b < a; b++)
{
while (ArrayTable[a] == ArrayTable[b])
{
Console.Write("Integer Duplicated!\nTry again: ");
Element = Int32.Parse(Console.ReadLine());
ArrayTable[a] = Element;
Console.WriteLine();
while (Element < 10 || Element > 100)
{
Console.Write("Try again (between 10-100): ");
Element = Int32.Parse(Console.ReadLine());
ArrayTable[a] = Element;
}
}
}
}
for (int c = 0; c < ArrayTable.Length; c++)
{
Console.Write("{0} ", ArrayTable[c]);
}
}

Categories