In C# the program is supposed to count how many valid and invalid values were entered by comparing them to the array and then give a total of the correct and incorrect inputs, but when I enter numbers that are outside of the bounds of the if statement the code from the if statement still runs. I've gone back and reviewed videos and the textbook and I cannot see where my if else statement is lacking.
int[] values = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, };
int count = 0;
Console.WriteLine("Enter a value between 0 and 10");
foreach (int v in values)
{
Console.ReadLine();
if (values[v] >= 0 || values[v] <= 10)
{
Console.WriteLine("Enter a value");
count++;
}
else
{
Console.WriteLine("Invalid Entry");
count++;
}
}
Console.WriteLine("You entered {0} correct values", count);
Console.WriteLine("You entered {0} incorrect values", count);
Console.ReadKey();
}
}
(values[v] >= 0 || values[v] <= 10) will always return true, all numbers are either less than 10 or greater than zero. Presumably you want an and (&&) operator to grab values between 0 and 10 inclusive
Also, foreach iterates through the values of an array, not the index, so you don't need to reference values[v], you can just reference v directly (although in your case values[v]==v). Calling values[v] in a foreach runs a huge risk of indexOutOfBounds exceptions. If you want to iterate through the index a straight for loop is more appropriate:
for(int i = 0; i< values.Length; i++)
var myVal = values[i];
Final Edit, you aren't actually checking the user's input
var input = Console.ReadLine();
//you never bothered capturing the user's input with a variable
decimal myNum;
if (decimal.TryParse(input, out myNum)) //did the user give a number?
{
//use myNum instead of values[v]
}
else
{
//process bad input
}
There's a bunch of stuff you can do to make things cleaner, (like removing your array altogether and using for(int i = 0; i< 10; i++) instead, for example), but good code doesn't happen on day 1 (my first few projects make me wanna throw up now), you got this friend.
You have a foreach loop, you do not need to use
if (values[v] >= 0 || values[v] <= 10)
instead, use
if(v >= 0 || v <= 10)
plus your if statement will always return true because the value you have in your array of int is greater than or equals to 0 or less than or equals to 10.
Try to change the array from
int[] values = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, };
to
int[] values = { -5, 1, 2, 3, 11, 5, 6, 13, 8, 9, 15, };
and you should have 4 incorrect count, provided you separate the correct count and incorrect count instead of adding them together using the count.
Separate them into validCount and invalidCount
Related
static void PrintPartOfArray(int[] array, int from, int to)
{
int x = array.Length;
if (from > x && from < 0)
{
Console.WriteLine("there is an exeption!");
}
if (to > x && to < 0)
{
Console.WriteLine("there is an exeption!");
}
else
{
for (int i = from; i <= to; i++)
{
Console.WriteLine(array[i]);
}
}
}
static void Main(string[] args)
{
int[] array2 = new int[] { 3, 6, 54, 24, -90, 7, 4 };
PrintPartOfArray(array2,2,7);
}
it supposes to show the "exception error when the function receives a number outside the length of the array, for some reason it not working, when I checked with the debugger it simply skipped the if loops, what have I done wrong?
Consider "early return" for things like this.
if (from > array.Length - 1 || to > array.Length - 1 || from < 0 || to < 0)
{
Console.WriteLine("One of your arguments is out of range.");
return;
}
// Normal, error-free code goes here.
If from and to are greater than x, they can't possibly also be less than 0. Recall that x is the length of an array, which can't be negative. That being said, it's literally impossible for either of your if statements to evaluate to true. Did you mean || instead?
Also, the last index of the array is array.Length - 1, not array.Length. Similarly, the first item in the array is at index 0, not index 1. I think that your array indices are off by 1 here.
I have this code. I would like to only display the parts of the array that are greater than 0.
For example... A bunch of numbers are entered and stored as a variable. But not all of the variables in the array will be used. The ones that aren't are stored as 0. So when I display the array, the numbers are displayed as:
"140, 180, 298, 130, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, " etc.
I don't want the zeros to be displayed.
int[] scores = {score1, score2, score3, score4, score5, score6, score7, score8, score9, score10, score11, score12, score13, score14, score15};
Console.WriteLine("Your scores as you entered them: " + (string.Join(", ", scores)));
Console.ReadKey();
Use linq's Where:
string.Join(", ", scores.Where(x => x != 0))
In the description above you also said the parts of the array that are greater than 0. So if that is the case you can change it to:
string.Join(", ", scores.Where(x => x > 0))
For a non linq solution use a List<int> and a simple foreach (or for) loop:
List<int> result = new List<int>();
foreach(int item in scores)
{
if(item != 0)
result.Add(item);
}
If you don't understand LINQ yet, you can look into this piece of code:
int[] scores = { 1, 2, 3, 0, 0, 4, 5, 0, 0, 6};
int[] withoutZeros = WithoutZeros (scores);
And the core method:
public static int[] WithoutZeros (int[] input)
{
int zerosCount = 0; // we need to count how many zeros are in the input array
for (int i = 0; i < input.Length; i++)
{
if (input[i] == 0) zerosCount = zerosCount + 1;
}
// now we know number of zeros, so we can create output array
// which will be smaller than then input array (or not, if we don't have any zeros in the input array)
int[] output = new int[input.Length - zerosCount]; // can be smaller, equal, or even empty
// no we need to populate non-zero values from the input array to the output array
int indexInOutputArray = 0;
for (int i = 0; i < input.Length; i++)
{
if (input[i] != 0)
{
output[indexInOutputArray] = input[i];
indexInOutputArray = indexInOutputArray + 1;
}
}
return output;
}
To get the answer of your question have a look at Gilad Green's answer.
I just wanted to give you a little feedback about the code I see.
Since, I dont see all your code I am making a lot of assumptions here, so sorry if I am wrong.
If you want to fill an array with 15 values, you should consider refactoring your code to use a loop.
In the following example I will use a for loop but it could be solved with different loops.
int[] scores = new int[15]; //initialize an array of ints with a length of 15
for (int i = 0; i < scores.Length; i++) //loop from 0 till smaller than the length of the array (0-14 = 15 iterations)
scores[i] = int.Parse(Console.ReadLine()); //fill the scores array with the index of i with the console input
Say I have an an array of numbers:
int[] that = new [] {1, 2, 3, 2, 4, 8, 9, 7};
I'm trying to display them so that the numbers that are increasing have their own line.
For example the result would be:
1 2 3
2 4 8 9
7
I'm able to do the first row using,
for (int i = 1; i < that.Length; i++)
{
if (that[i-1] < that[i])
{
Console.Write(that[i-1] + " ");
}
}
The thing is this works for the first row because 1-3 are increasing but stops after that.
I'm not exactly sure how to continue so that 2 4 8 9, then 7 are written.
I have a feeling this is homework so I'm going to leave the actual coding to you. But here's how to do it in plain language:
Have a variable where we store the previous value. Let's call it oldValue, and start it with zero (if you're only using positive numbers in your array).
Go through the array one item at a time.
Check to see if that number is larger than oldValue.
If FALSE, print the new line character. "\n" in C#.
Print that number and make oldValue equal that number.
Unless your numbers are finished get the next number and go to step 3.
You never create a new line.
int[] arr = new[] {1, 2, 3, 2, 4, 8, 9, 7};
for(var i = 0; i < arr.Length; i++){
if(i == 0 || ((i < arr.Length - 1) && arr[i] < arr[i + 1])){
Console.Write(arr[i]);
} else {
Console.Write("{0}\n", arr[i]);
}
}
Output:
123
2489
7
Couple of remarks:
Avoid the usage of this as a variable name. It's a reserved
keyword.
Use \n as a newline character.
There are a number of ways you can do this, either by appending a string with characters until a lesser one is reached and then using the Console.WriteLine() command to write the entire string at once, or (the easier way given your code) which is to simply test for the new value being lesser than the previous and inserting a newline character into your text.
// Start at zero
for (int i = 0; i < this.Length; i++)
{
// If this is not the first element in the array
// and the new element is smaller than the previous
if (i > 0 && this[i] < this[i-1])
{
// Then insert a new line into the output
Console.Write(Environment.NewLine);
}
Console.Write(this[i] + " ");
}
int[] numbers = new int[] { 1, 2, 3, 2, 4, 8, 9, 7 };
String orderedNumbers = String.Empty;
for (int i = 0; i < numbers.Length; i++)
{
if (i == 0 || numbers[i] > numbers[i - 1])
{
orderedNumbers += numbers[i].ToString();
}
else
{
orderedNumbers += System.Environment.NewLine + numbers[i].ToString();
}
}
MessageBox.Show(orderedNumbers);
i am writing a code in c# to sort an array, i want all the negative values in the right side and all the positive values in the left side, the should not be in decreasing order
namespace SortApp
{
class Program
{
static void Main(string[] args)
{
int[] newInt = new int[] { 5, -2, -1, -4, -20, 6, 7, -14, 15, -16, 8, 9, 10 };
int size = 12, i= 0; // or newInt.Length
for (i = 0; i < newInt.Length; i++)
{
if (newInt[i] < 0 && newInt[size] > 0)
{
int temp = newInt[i];
newInt[i] = newInt[size];
newInt[size] = temp;
size--;
}
}
for (i = 0; i < newInt.Length; i++)
{
Console.Write(newInt[i]);
Console.Write(" ");
}
}
}
}
but the output is something like this (-20 is on wrong side):
5 10 9 8 -20 6 7 -14 15 -16 -4 -1 -2
but the intended output is:
5 10 9 8 15 6 7 -14 -20 -16 -4 -1 -2
Why is my code not producing my intended output?
Your solution incorrectly decides when to finish the loop. Also, it unconditionally increments i in the loop header, and never decrements size even when it points to a negative number.
Here is how you fix it:
for (i = 0; i < size ; ) {
if (newInt[i] < 0 && newInt[size] >= 0) {
int temp = newInt[i];
newInt[i] = newInt[size];
newInt[size] = temp;
size--;
i++;
continue;
}
if (newInt[i] >= 0) {
i++;
}
if (newInt[size] < 0) {
size--;
}
}
Here is a demo on ideone.
You can rewrite this loop using a more readable identifiers for your left and right pointers, rather than using i and size. This would make your algorithm look more "symmetric" in the code, to recognize the symmetry in its design:
int left = 0, right = newInt.Length-1;
while (left < right) {
if (newInt[left] < 0 && newInt[right] >= 0) {
int temp = newInt[left];
newInt[left] = newInt[right];
newInt[right] = temp;
right--;
left++;
continue;
}
if (newInt[left] >= 0) {
left++;
}
if (newInt[right] < 0) {
right--;
}
}
Here is an ideone link to the alternative implementation.
Try this solution:
var newInt = new[] {5, -2, -1, -4, -20, 6, 7, -14, 15, -16, 8, 9, 10};
var solution = newInt.GroupBy(i => i > 0).
SelectMany(g => g).
ToArray();
The problem with your algorithm is that when you decrease size, you end up having newInt[size] point at a negative value, and the if block is not entered.
The general idea for a pretty easy easy solution would be to start one index, call it left at the beginning of the array, and another, called right at the end of the array.
Increment left until you find a negative number, or until left == right. When you hit a negative number, decrement right until you find a positive number, or until right == left.
If left is indexing a negative number and right is indexing a positive number, swap the two items and start incrementing left again.
The general idea, not tested:
int left = 0;
int right = a.Length-1;
while (left < right)
{
if (a[left] < 0)
{
while (right > left)
{
if (a[right] >= 0)
{
// swap here
int temp = a[left];
a[left] = a[right];
a[right] = temp;
break;
}
--right;
}
}
++left;
}
This yields the desired order with a minimum of loops
int[] newInt = new int[] { 5, -2, -1, -4, -20, 6, 7, -14, 15, -16, 8, 9, 10 };
int lt = 0;
int rt = newInt.Length - 1;
while (true) {
// Find first negative number
while (newInt[lt] >= 0 && lt < rt) {
lt++;
}
// Find last positive number
while (newInt[rt] < 0 && rt > lt) {
rt--;
}
if (lt == rt) {
break; // Finished
}
// Swap
int temp = newInt[lt];
newInt[lt] = newInt[rt];
newInt[rt] = temp;
}
//TODO: Print result
if you can use generics and linq than the easiest solution would be :
int[] newInt = new int[] { 5, -2, -1, -4, -20, 6, 7, -14, 15, -16, 8, 9, 10 };
newInt.ToList().Sort();
newInt.Reverse();
newInt = newInt.ToArray();
Hope this will help !!
I have a series of number as such: [1 2 4 8 16 32 64 128], if I input a number, i.e. 66, then the output should be 64 and 2. If I input 87, then the output should be 64, 16, 4, 2, 1.
(Basically, it first divide by the largest possible number, find the remainder, then keep dividing by the largest number possible, until the remainder is 0. Or another way maybe just to subtract the largest possible number and keep subtracting like that until it reaches 0.)
I'm thinking of a recursive function, but not really sure. Any help?
Thanks.
class Program
{
[Flags]
enum Bits
{
_1 = 1,
_2 = 2,
_4 = 4,
_8 = 8,
_16 = 16,
_32 = 32,
_64 = 64,
_128 = 128
}
static void Main(string[] args)
{
var b = (Bits)87;
Console.WriteLine(b);
Console.ReadKey();
}
}
Here's the iterative version
public static IEnumerable<int> FindIndex(int input)
{
var power = 0;
while (input > 0)
{
var digit = input % 2;
if (digit == 1)
{
yield return (int)Math.Pow(2, power);
}
input /= 2;
power++;
}
}
and here's the recursive version
public static void FindIndexRec(int input, int power, ICollection<int> numbers)
{
if (input == 0)
{
return;
}
var digit = input % 2;
if (digit == 1)
{
numbers.Add((int)Math.Pow(2, power));
}
FindIndexRec(input / 2, ++power, numbers);
}
and you can call it like
var numbers = new List<int>();
FindIndexRec(input, 0, numbers);
You could use bit masks. In fact, scratch that - you should use bit masks! That is almost certainly how the error code was created, and it's how it should be picked apart. Anything else is highly likely to confuse your audience of other programmers.
I make no claims to represent all programmers, nor do I claim to be any good, but I am a programmer, and all the other answers confused me. It's obviously a bitwise "problem", so why obfuscate?
There's no need to even store the result anywhere, since it's as quick to recompute it every time, like so:
for(int i=0;i<8;++i) {
if((error&(1<<i))!=0 {
// 1<<i is in the resulting list.
}
}
List<int> additives = new List<int>()
List<int> sourceNumbers = new List<int> { 1, 2, 4, 8, 16, 32, 64, 128 };
int sourceNumber = 87;
foreach(var number in sourceNumbers.Reverse())
{
if(sourceNumber % number > 0)
{
additives.Add(number);
sourceNumber -= number;
}
else
{
additives.Add(number);
break;
}
}
Here's a pretty naive iterated solution in pseudocode. Try to take it somewhere more interesting from here. You can do it recursively, you can convert the integer to binary representation and iterate on that string, id imagine theres a clever way to do it with LINQ very concisely, etc.
v = inputNumber
while(v > 0):
temp = greatest power of 2 less than v
print temp
v -= temp
PS - this does not explictly store the series in question - it presumes powers of 2.
string calculate(int input)
{
string output = string.Empty;
int[] series = new int[] { 1, 2, 4, 8, 16, 32, 64, 128 };
foreach (int i in series.Reverse<int>())
{
if (input >= i)
{
output += i.ToString() + " ";
input -= i;
}
}
return output;
}
This one will work with input numbers greater than 256:
int[] calculate(int input)
{
List<int> retVal = new List<int>();
string output = string.Empty;
int[] series = new int[] { 1, 2, 4, 8, 16, 32, 64, 128 };
foreach (int i in series.Reverse<int>())
{
while (input >= i)
{
retVal.Add(i);
input -= i;
}
}
return retVal.ToArray();
}
Ex:
var result = calculate(284);
// result = 128, 128, 16, 8, 4
IEnumerable<int> GetFlags(int input,IEnumerable<int> series)
{
foreach (int value in series)
if ((input & value)==value)
yield return value;
}
Or LINQ solution to the problem.
IEnumerable<int> GetFlags(int input, IEnumerable<int> series)
{
return series.Where(x => (x & input) == x);
}
Programming aside, you can also look at it mathematically. It's basically 2 to the power of (integer value of) log(2, input)
Putting this in a recursive function would be easy ofcourse, it would even look simple and smooth, but I doubt it being less computationally complex and it sure doesn't help with your homework, just thought I would throw it here.