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.
Related
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();
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.
In my class i have to create a method that will find multiple maximum numbers within an array. the user will input how many maximum numbers they are wanting and then the code should display all those numbers. if i select 2 this code will show me the 2 maximum numbers but if im wanting more it just doesnt work. i was trying to search the array for the maximum number and then have it display the outcome and then change that element to 0 and than repeat the loop until it hits that number (userinput). im soo frustrated can someone help me please
public static int FindingMaxNum(int[] arr, int max)
{
int userinput;
Console.Write("Enter the number of maximum values: ");
userinput = Convert.ToInt32(Console.Read());
int i = 0;
int c = 0;
for (i = 0; i < arr.Length; i++)
{
if (arr[i] >= max)
{
max = arr[i];
c++;
while (c <= userinput)
{
Console.WriteLine(max);
arr[i] = 0;
break;
}
}
}
return -1;
}
If I understand correctly, you want to get some number of items from an array whose values are greater than all the others in the array.
If so, something like this modified version of your method may do the trick:
public static void WriteMaxNum(int[] arr)
{
if (arr == null)
{
Console.WriteLine("The array is null");
return;
}
if (arr.Length == 0)
{
Console.WriteLine("The array is empty");
return;
}
int count = arr.Length;
int numMaxValues;
// Get number of max values to return from user
do
{
Console.Write("Enter the number of maximum values (1 - {0}): ", count);
} while (!int.TryParse(Console.ReadLine(), out numMaxValues) ||
numMaxValues < 1 ||
numMaxValues > count);
// Output the max values
Console.Write("The {0} max values are: ", numMaxValues);
Console.WriteLine(string.Join(", ", arr.OrderByDescending(i => i).Take(numMaxValues)));
}
Usage
static void Main(string[] args)
{
var myArray = new[] { 1, 9, 4, 8, 2, 5, 0, 7, 6, 3 };
WriteMaxNum(myArray);
Console.Write("\nDone!\nPress any key to exit...");
Console.ReadKey();
}
Output
Simple solution with average complexity O(nlogn):
Sort the array first then print the last N nos.
int[] arr = new int[]{-5,-69,1250,24,-96,32578,11,124};
Array.Sort(arr);
int n=3;
for(int i=arr.Length-1;i>=0 && n>0 ;--i){
n--;
Console.WriteLine(arr[i]);
}
Now coming to your code, there are multiple problems. First there is no need to take 'max' as parameter in your function. Second you are looping only arr.Length times once. There should be nested loop, outer one of which has to run userInput times and inner on has to iterate over all the values. Third you should initialize to extracted value position to minimum value so that the method works for negative numbers too.
Refined code:
for(int i=0;i<userinput;++i){
int max = int.MinValue,pos=-1;
for(int j=0;j<arr.Length;++j){
if(max<arr[j]){
pos = j;
max = arr[j];
}
}
arr[pos] = int.MinValue;
Console.Write(max+",");
}
I just barely understood how to use if statement and "for loop." In addition right now I have to do this
Sort the integer elements within the array from lowest (element 0) to highest (element 4). Do not use the preexisting Array.Sort method; code your own.
This is a homework problem and I don't even know where to start. Can somebody walk me through this?
class Program
{
static void Main(string[] args)
{
int i;
double power = 0, sum = 0;
int[] mArray = new int[5];
Console.WriteLine("Please Enter Number Between 10 and 50 \nMake sure all of your Number entered correctly \notherwise you will need to enter everything again ");
for (i = 0; i < mArray.Length; i++)
{
Console.WriteLine("Please enter your Number.");
mArray[i] = Convert.ToInt32(Console.ReadLine());
if (mArray[i] >= 50 || mArray[i] <= 10)
{
i--;
Console.WriteLine("Please enter numbers only between 10 and 50.");
}
}
for (i = 0; i < mArray.Length; i++)
{
sum = sum + (mArray[i]);
}
double mean = sum / mArray.Length;
for (i = 0; i < mArray.Length; i++)
{
power += Math.Pow((mArray[i] - mean), 2);
}
double rMean = power / (mArray.Length - 1);
Console.WriteLine("Mean {0}", mean);
Console.WriteLine("Variance {0}", rMean);
Console.WriteLine("Here is sorted numbers");
Console.ReadKey();
}
}
There are many sorting algorithms you can try like Insertion Sort
Selection Sort,
Bubble Sort,
Shell Sort,
Merge Sort,
Heap Sort,
Quick Sort,
And many Others.
I have developed a program in c# which is doing "Insertion Sort", the code takes in a max value for the elements and the values of the elements and then one by one shows the steps of sorted values.
Code:
static void insertionSort(int[] ar)
{
for (int i = 1; i < ar.Length; i++)
{
int temp = ar[i];
int j = i - 1;
while (j >= 0 && ar[j] > temp)
{
ar[j + 1] = ar[j];
foreach (int val in ar)
Console.Write(val + " ");
Console.WriteLine();
j--;
}
}
}
static void Main(String[] args)
{
int ar_size;
ar_size = Convert.ToInt32(Console.ReadLine());
int[] ar = new int[ar_size];
for (int i = 0; i < ar_size; i++)
{
ar[i] = Convert.ToInt32(Console.Read());
}
insertionSort(ar);
Console.ReadKey();
}
The Sample Input That I Give:
5
2 4 6 8 3
The Output That Comes:
Can anyone explain me why is this happening!
Any help would be greatly appreciated! :)
Apart from the problems with your sort itself, the reason for the strange numbers in your result is that you use Console.Read very wrong. It returns the ASCII value of the character entered by the user. Furthermore, it will return the ASCII values for all entered characters, not only for the numbers.
So, the first call to Console.Read() will return 50 (ASCII value of '2').
The second call will return 32 (ASCII value of a space).
The third call will return 52 (ASCII value of '4').
etc.
To fix this, initialize ar like this:
var numbers = Console.ReadLine().Split(' ');
for (int i = 0; i < ar_size; i++)
ar[i] = Convert.ToInt32(numbers[i]);
Please note that this code lacks error handling. It will throw an exception in the followin circumstances:
The user entered anything besides spaces and numbers
The user entered less numbers than he specified in the first line