im new to programming and we have our first activity which is to write a program that will accept a number then display its incrementing values using an array and loop statement. I tried but my code does not meet the corret way so i hope anyone can help mwle btw this is my code...
Console.WriteLine("Please input a number: ");
int put = Convert.ToInt32(Console.ReadLine());
int[] array = new int[put];
Console.WriteLine("Incremented number: ");
for (int j = 1; j <= array.Length; j++)
{
// put = put + 1;
Console.WriteLine(j);
}
Console.ReadKey();
Unless you haven't specified all the requirements, it's not completely clear what you need to do, but I assume you're asking how to populate the array and then output numbers from the array?
The typical pattern would be something like:
Console.Write("Enter the number of times to increment: ");
int put = Convert.ToInt32(Console.ReadLine()); // Not the best way to do it, but ok
// Initialize an array with the specified number of elements
int[] array = new int[put];
Console.WriteLine("\nIncremented numbers: ");
// Since arrays are 0-based, start with 0 in our loop
for (int j = 0; j < array.Length; j++)
{
// Add 1 to the current index and assign it to the appropriate array index
array[j] = j + 1;
// Output the number from the array to the console
Console.WriteLine(array[j]);
}
Console.ReadKey();
Related
So, I'm trying to first make an array consisting of, let's say 5 integers.
Going through the for loop so the user will enter each integer separately.
However, the Array.Sort() function causes the array to be incomplete and it also replaces the last integers in the array.
This happens only when I try to Sort inside the 'for' loop, but sorting outside the loop works, and I can't tell why. Thanks.
Console.WriteLine("\nLive Array Sort\n\n");
Console.Write("Write number of elements to sort: ");
int max = Convert.ToInt32(Console.ReadLine());
int[] array = new int[max];
for (int i = 1; i <= max; i++)
{
int index = i - 1;
Console.Write($"\nEnter Element [{i}] Index [{index}]: ");
array[index] = Convert.ToInt32(Console.ReadLine());
Console.Write("Sorted Array Elements: ");
Console.ForegroundColor = ConsoleColor.Yellow;
Array.Sort(array);
for (int j = 0; j < array.Length; j++)
{
if (array[j] != 0)
Console.Write("\t" + array[j]);
}
Console.ResetColor();
Console.Write("\n");
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("\nSuccessfully completed!");
Console.Read();
The problem, of course, is that you're always inserting each new element into array[index]. However, the sort operation is re-ordering your array, and array[index] isn't always the next unset element!
Let's take an example:
Index: 0
Input number: 1
Array: [1, 0, 0]
Sorted array: [0, 0, 1]
Index: 1
Input number: 2
Array: [0, 2, 1]
Sorted array: [0, 1, 2]
Index: 2
Input number: 3
Array: [0, 2, 3]
Sorted array: [0, 2, 3]
See what happened on that last iteration? The sort operation on the previous iteration left the array containing [0, 1, 2] in that (sorted) order, but our logic said that we needed to insert the new element at index 2, which overwrite the last element in the array (giving [0, 1, 3])!
The key to debugging these sorts of problems is to work through your code step-by-step. Preferably in a debugger, as this lets you look at all of your variables in each loop iteration, but you can also do it by printing out the contents of your variables and then inspecting them.
One solution is not to sort your array until after your loop, as you found.
Another it to use a list, rather than an array. A list lets you add elements one-by-one, so you never have a situation where you're trying to sort a collection which contains some elements which have been correctly set, and some which are still waiting to be set.
Console.WriteLine("\nLive Array Sort\n\n");
Console.Write("Write number of elements to sort: ");
int max = Convert.ToInt32(Console.ReadLine());
List<int> list = new List<int>();
for (int i = 1; i <= max; i++)
{
int index = i - 1;
Console.Write($"\nEnter Element [{i}] Index [{index}]: ");
list.Add(Convert.ToInt32(Console.ReadLine()));
Console.Write("Sorted List Elements: ");
Console.ForegroundColor = ConsoleColor.Yellow;
list.Sort();
for (int j = 0; j < list.Count; j++)
{
Console.Write("\t" + list[j]);
}
Console.ResetColor();
Console.Write("\n");
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("\nSuccessfully completed!");
Console.Read();
Notice how this also let us get rid of the if (array[j] != 0) check, since our list only contains elements which we've added so far.
I am trying to make a linear search where the user inputs a selection of numbers and then they input a random number and the program shows if it is in the list or not.
int[] list = new int[10];
bool found = false;
for (int i = 0; i < 12;)
{
Console.WriteLine("Enter number to be stored.");
list[i] =Convert.ToInt16(Console.ReadLine());
i++;
}
Console.WriteLine("Enter number you want to find.");
int n1 = Convert.ToInt16(Console.ReadLine());
for (int i = 0; i <= 10;)
{
if (list[i] == n1)
{
Console.WriteLine(n1 + " is in the list.");
found = true;
Console.ReadKey();
}
else i++;
}
if (found == false)
{
Console.WriteLine("Element not in this list.");
}
Console.ReadKey();
I am pretty sure that the problem lies in this snippet of code.
int[] list = new int[10];
bool found = false;
for (int i = 0; i < 12;)
{
Console.WriteLine("Enter number to be stored.");
list[i] =Convert.ToInt16(Console.ReadLine());
i++;
}
An array beings with 0 so there are 11 element spaces right?
So when i run it, i go past entering the 10th number and when i enter the 11th, it breaks and says
System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'
Firstly I'd recommend you read up on for loops and arrays in C#.
Secondly you don't want to hardcode the length in the for loop - let the framework do it for you using list.Length. You're seeing the crash because you're trying to assign a value to your array, but the index within your array doesn't exist.
int[] list = new int[10];
bool found = false;
for (int i = 0; i < list.Length; i++)
{
// Do work with list[i]
}
When you say int[10]; you tell it to have 10 entries. They are counting from zero, yes, but that just means that your array has the indices 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
Your loop goes from i = 0 up to i = 11 before it stops because it's no longer smaller than twelve. But the index for the array can at most be 9.
If you set a breakpoint, you should be able to look at the array contents in a debugger. This way, you could also test such things yourself.
It should be i < 10 or i <= 9 if your array only holds 10 objects. The 10 indices will be 0-9.
I want to create an algorithm that would identify if the user input is repeating or not. If it is repeating it will prompt the user a message if its not repeating it will continue the process.
public static class Program
{
public static void Main()
{
Console.WriteLine("input array of numbers: );
int[] array = new int[4];
for(int i=0; i<3; i++)
{
array[i] = int.Parse(Console.ReadLine());
if(array[i] == array[0])
{
Console.WriteLine("repeating inputs")
}
}
Console.WriteLine("Highest number is:" + array.MaxLenght);
Console.ReadLine();
}
}
Explanation: The user will be prompted by message "inter array of numbers:" then the user will now input the numbers. If the user inputs the same number or if the number was already inputted, the user will be prompted by a message something like "repeating inputs! Input another number". After the user input another number unique to the previously interred the program will continue and print out the largest number base on the inputs.
i'm not sure if I understood you correctly but this is what i can extrapolated from your post :
you want to get input from the user and check if it's repeating or not and then print the highest number (based on your Console.WriteLine("Highest number is:" + array.MaxLenght); )
this is how i'd approach it
Console.WriteLine("input array of numbers: ");
List<int> uniqueInts = new List<int>();
int[] array = new int[4];
for (int i = 0; i < 3; i++)
{
array[i] = int.Parse(Console.ReadLine());
if (!uniqueInts.Contains(array[i]))
uniqueInts.Add(array[i]);
}
//getting the max number
//assuming the first number is the max
int max = uniqueInts[0];
for (int i = 1; i < uniqueInts.Count; i++)
{
if (max < uniqueInts[i])
max = uniqueInts[i];
}
Console.WriteLine("The highest number is : " + max);
There are a lot of assumptions that I'm making with this answer. I'm assuming you're struggling to get the value of the item prior to the current iteration considering you have if(array[i] == array[0]).
If that's the case, then simply change array[0] to array[i-1].
Wait! Before you do that, you need to add a check to make sure you aren't on the first iteration. If you don't, you'll get an exception thrown on the first iteration, because you'll be trying to grab array[-1], which isn't valid.
for(int i=0; i<3; i++)
{
array[i] = int.Parse(Console.ReadLine());
if(i > 0)
{
if (array[i] == array[i-1])
Console.WriteLine("repeating inputs")
}
}
Make these few changes, and I think you'll get what you're after.
as you can read from the title I'm trying to store all the numbers between two numbers in an array.
For example store the numbers between 21 and 43 (22,23,24,25,26,27,28,29...) in an array.
This is the code, I don't know why but it prints only the higher number minus one.
class Program
{
static void Main(string[] args)
{
int higher = 43;
int lower = 21;
int[] numbers = new int[22]; //the numbers between 21 and 43 are 22
for (int i = lower; i < higher;i++)
{
for (int a = 0; a < 22; a++)
{
numbers[a] = i;
}
}
for (int c = 0; c < 22; c++)
{
Console.WriteLine(numbers[c]);
}
Console.ReadLine();
}
}
This is the code, I don't know why but it prints only the higher number minus one.
This question will attract answers giving you a half dozen solutions you can cut and paste to do your assignment.
I note you did not ask a question in your question -- next time, please format your question in the form of a question. The right question to ask here is how do I learn how to spot mistakes in code I've written? because that is the vital skill you lack. Answers that give you the code will not answer that question.
I already gave you a link to a recent answer where I explain that in detail, so study that.
In particular, in your case you have to read the program you wrote as though you had not written it. As though you were coming fresh to the program that someone else wrote and trying to figure out what it does.
The first thing I would do is look at the inner loop and say to myself "what does this do, in words?"
for (int a = 0; a < 22; a++)
{
numbers[a] = i;
}
That is "put the value i in every slot of the array. Now look at the outer loop:
for (int i = lower; i < higher;i++)
{
put the value i in every slot of the array
}
Now the technique to use here is to logically "unroll" the loop. A loop just does something multiple times so write that out. It starts with lower, it goes to higher-1, so that loop does this:
put the value lower in every slot of the array
put the value lower+1 in every slot of the array
…
put the value higher-1 in every slot of the array
What does the third loop do?
print every item in the array
And now you know why it prints the highest number minus one multiple times. Because that's what the program does. We just reasoned it out.
Incidentally the answers posted so far are correct, but some are not the best.
You have a technique that you understand for "do something to every member of an array, and that is:
loop an indexer from 0 to the array size minus one
do something to the array slot at the indexer
But the solutions the other answers are proposing are the opposite:
loop an indexer from the lower to the higher value
compute an index
do something to the array slot at that index
It's important to understand that both are correct, but my feeling is that for the beginner you should stick with the pattern you know. How would we
loop an indexer from 0 to the array size minus one
do something to the array slot at the indexer
for your problem? Let's start with giving you a much better technique for looping the indexer:
for (int i = 0; i < numbers.Length; ++i)
That's a better technique because when you change the size of the array, you don't have to change the loop! And also you are guaranteed that every slot in the array is covered. Design your loops so that they are robust to changes and have good invariants.
Now you have to work out what the right loop body is:
{
int number = i + lower;
numbers[i] = number;
}
Now you know that your loop invariant is "when the loop is done, the array is full of consecutive numbers starting at lower".
For everytime you loop through i, you put that number in every slot of the array. The inner loop is what is causing your issue. A better solution would be:
int higher = 43;
int lower = 21;
int[] numbers = new int[21];
int index = 0;
for (int i = lower + 1; i < higher; i++) // if you want to store everything
// between 21 and 43, you need to
// start with 22, thus lower + 1
{
numbers[index] = i;
index++;
}
for (int c = 0; c < 21; c++)
{
Console.WriteLine(numbers[c]);
}
Console.ReadLine();
Replace a with a direct translation of i
for (int i = lower; i < higher;i++)
{
numbers[i-lower] = i;
}
Use below
int higher = 43;
int lower = 21;
int[] numbers = new int[22]; //the numbers between 21 and 43 are 22
for (int i = lower+1; i < higher; i++)
{
numbers[i-lower] = i;
}
for (int c = 1; c < 21; c++)
{
Console.WriteLine(numbers[c]);
}
Console.ReadLine();
I think higher & lower are variables so following will give you output
for any higher and lower numbers
class Program
{
static void Main(string[] args)
{
int higher = 43;
int lower = 21;
int numDiff = higher - lower - 1;
int[] numbers = new int[numDiff]; //the numbers between 21 and 43 are 22
for(int i = 0; i<numbers.Length; i++)
{
numbers[i] = numDiff + i + 1;
}
for(int b = 0; b<numbers.Length; b++)
{
Console.WriteLine(numbers[b]);
}
Console.ReadLine();
}
}
I am initializing array size to 1 but I am updating it in the subsequent lines. It is not even storing the first element in the array as the array size is 1 initially but I expected it would. Could someone provide me with an explanation? Here is the code:
class Program
{
static void Main(string[] args)
{
int num = int.Parse(Console.ReadLine());
Console.Write("The binary number for " + num + " is ");
int size = 1;
int[] binary = new int[size];
size = 0;
while(num>=1)
{
if (num % 2 == 0)
binary[size++] = 0;
else
binary[size++] = 1;
//size += 1;
num = num / 2;
}
for (int i = size - 1; i >= 0; i--)
{
Console.Write(binary[i]);
}
Console.WriteLine();
Console.Write("The Compliment of this number is ");
for (int i = size - 1; i >= 0; i--)
{
if (binary[i] == 0)
binary[i] = 1;
else
binary[i] = 0;
}
for (int i = size - 1; i >= 0; i--)
{
Console.Write(binary[i]);
}
Console.WriteLine();
Console.ReadKey();
}
}
You cannot resize an array, it always has the length you gave it to during initialization (1 in your case).
I think the problem is specifically in your expectation that you can update an array size "in the subsequent lines."
When you make the array here:
int[] binary = new int[size];
Then the size is set in stone
When you call something like:
binary[size++] = 0;
This will not actually increase the number of slots in your array. In fact, that code is only changing the index where you are looking to read or write values. I can see that your code is going to quickly go out of bounds of the array (if you ask for anything but binary[0]
It turns out this array is a tricky data type to use; arrays have a fixed size on creation. You want something that can grow!
So you can either:
-Use an array, but declare that it's size is Math.Ciel(logbase2(yourNumber)) to make sure you will have enough space
-Use a data structure that can grow, like a string or list
-You can create a new array every time you need it bigger and assign it like:
binary = new int[++size];
binary[size-1]=whatever
Good luck, hope this helps!