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.
Related
I've created a program that adds all input values from the user and prints the sum if the user entered 0 or greater than 101. Here's my code:
int n, sum = 0;
do
{
Console.Write("Enter a number:");
n = int.Parse(Console.ReadLine());
sum += n;
}
while (n != 0 && n < 101);
Console.WriteLine("Sum is:" + sum);
Console.ReadKey();
I'm trying to figure how to accepts numbers alternately. For example, Input values are: 4, 7, 8, 3, 6, 1. If the user input two consecutive odd or even number the system will not accept two consecutive odd or even or it will display the sum of all inputted numbers.
Taking the recomendation of Andrew an Peter you can add the list to save your previous inputs and do some checks to the current and prev data to do the logic.
the code that implements this is the following:
//save input list
List<int> inputNumbers = new List<int>();
int n, sum = 0;
do
{
Console.Write("Enter a number:");
n = int.Parse(Console.ReadLine());
//My Recomendation ==============================
//save previus input numbers
inputNumbers.Add(n);
//Check is there are previous input number
if(inputNumbers.Count>1){
//New control vars
Boolean previousNumberIsOdd= false,currentNumberIsOdd= false;
foreach (int item in inputNumbers)
{
Console.Write(item+",");
}
//check if previus number is odd
if((inputNumbers[inputNumbers.Count-2])%2 == 0){
previousNumberIsOdd = true;
}
//Check if current number is odd
if(n%2==0){
currentNumberIsOdd = true;
}
Console.WriteLine("Control vars:" + previousNumberIsOdd +"/"+currentNumberIsOdd);
//Check diferent scenarios and do the logic
//previous and current number are odds
if(previousNumberIsOdd && currentNumberIsOdd){
//break while and write the result
break;
}
//previous and current number are evens
if(!previousNumberIsOdd && !currentNumberIsOdd){
//break while and write the result
break;
}
}
//if there aren't numbers to break the cycle then do the original logic
//End of my recomendation =====================
sum += n;
}
while (n != 0 && n < 101);
Console.WriteLine("Sum is:" + sum);
Console.ReadKey();
}
You can do many optimizations to this code but a put it like that to be very clear in the logic.
By using two flag you can achieve the result.
int n, sum = 0;
bool previous = false, current;
bool init = true;
do
{
Console.Write("Enter a number:");
n = int.Parse(Console.ReadLine());
current = n % 2 == 0;
if( current == previous && !init)
break;
previous = current;
init = false;
sum += n;
}
while (n != 0 && n < 101);
Console.WriteLine("Sum is:" + sum);
Console.ReadKey();
Output
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.
So, I decided to have some fun and make a program that will come up with a number and you have to guess it with it telling you if you're too high/too low. However, I decided it would be more fun if the computer could come up with the random numbers itself.
I use a simple method here which basically has the program check if a value is in an array, and if it is, come up with another random number. And when a number is too high, start from the size of how large the number can be and go down to that number (that way if it's too high of a number, it never guesses that high or higher again).
So, this works great for small numbers. I think when doing a number like 1,000 or something, it guessed it within 15 tries. However, when I did a 10,000,000 (I know, it's a bit extreme, but I wanted to see C#'s power since I'm fairly new to the language).
The program got about 10 guesses in and it started slowing down incredibly. I had put in a 250ms sleep timer to make it look more like it was guessing (since it is instant for things like 1,000 or 10,000), but when taking it out, it still slowed down. I think this is probably because if it guesses a number like 3 million, it has to add 7 million values to an array (I'm using a List so that it has an "infinite" value).
So what exactly can I do at this point? I want it to be able guess big numbers, but it doesn't really seem possible at this point. How could I do this?
Here's my code:
using System;
using System.Collections.Generic;
using System.Linq;
namespace Program {
class Program {
static void Main(string[] args) {
Random random = new Random();
int selectedNumber = random.Next(1, 101);
int maxNumber;
int guessNumber = 0;
int inputNumber = 0;
// Intro
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.WriteLine("Welcome to the High Low - Computer version program!");
System.Threading.Thread.Sleep(4000);
Console.WriteLine("\n--------------------------------------------------------");
Console.ForegroundColor = ConsoleColor.DarkYellow;
// This way the computer guesses rather than you
char who = 'C';
Console.Write("\nHow high do you want the computer's number to be max > ");
maxNumber = Convert.ToInt32(Console.ReadLine());
List<int> guessedNumbers = new List<int>();
selectedNumber = random.Next(1, maxNumber);
do {
// System.Threading.Thread.Sleep(250);
Console.ForegroundColor = ConsoleColor.DarkYellow;
if (who == 'M') {
Console.Write("\nPlease enter your guess > ");
guessNumber = Convert.ToInt32(Console.ReadLine());
}
else {
while (true) {
guessNumber = random.Next(1, maxNumber);
if (!(guessedNumbers.Contains(guessNumber))) {
guessedNumbers.Add(guessNumber);
inputNumber++;
break;
}
}
Console.WriteLine("Please enter your guess > {0}", guessNumber);
}
Console.ForegroundColor = ConsoleColor.DarkGreen;
if (guessNumber < selectedNumber) {
Console.WriteLine("\nYou're guessing too low!\n");
for (int i = 0; i < guessNumber; i++) {
guessedNumbers.Add(i);
inputNumber++;
}
}
else if (guessNumber > selectedNumber) {
Console.WriteLine("\nYou're guessing too high!\n");
for (int i = maxNumber; i > guessNumber; i--) {
guessedNumbers.Add(i);
inputNumber++;
}
}
} while (guessNumber != selectedNumber);
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.WriteLine("\nCongratulations! You correctly guessed that {0} is the computer's number!", selectedNumber);
Console.ReadKey();
}
}
}
Edit: I think I'll try a way to make it so that it only adds the numbers that are higher or lower if they aren't already in there, to keep from having duplicate numbers.
The way you're trying to find the number using the computer's power isn't really efficient, why don't you just change the ranges of the possible guessing numbers based on if the previously guessed number is higher or lower than the correct number like so:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Highest number:");
int maxNumber = Convert.ToInt32(Console.ReadLine());
Random rand = new Random();
int correctNumber = rand.Next(0, maxNumber);
Console.WriteLine("Trying to guess number now..");
int guessedNumber = 0;
int lowBound = 0;
int highBound = maxNumber;
int guesses = 0;
while(guessedNumber != correctNumber)
{
guessedNumber = rand.Next(lowBound, highBound);
if(guessedNumber > correctNumber)
{
highBound /= 2;
lowBound /= 2;
}
else if(guessedNumber < correctNumber)
{
lowBound *= 2;
highBound *= 2;
}
++guesses;
}
Console.WriteLine($"Took me {guesses} guesses.");
Console.ReadKey();
}
}
This takes less than a second for 10,000,000 entries on my machine.
for (int i = 0; i < guessNumber; i++)
{
guessedNumbers.Add(i);
inputNumber++;
}
Everytime you enter these types of loops, you add 'guessnumber' items to the list, possibly millions.
Consider re-reading your code and understanding what it does.
Also, you should consider encapsulating your code to avoid making a behemoth of your main()
Another way is to use a Binary Search approach to guess the number and avoid the additional overhead caused by writing and searching for guess values.
This should run in O(log n).
int minGuess = 0;
int maxGuess = 1000000;
Random random = new Random();
int selectedNumber = random.Next(minGuess, maxGuess);
Console.WriteLine($"Selected number: {selectedNumber}");
int guess;
int count = 0;
do
{
count++;
guess = (minGuess + maxGuess) / 2;
Console.WriteLine($"Guess: {guess}");
if (selectedNumber < guess)
maxGuess = guess - 1;
else
minGuess = guess + 1;
} while (guess != selectedNumber);
Console.WriteLine($"Guessed it in {count} tries");
Console.ReadLine();
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+",");
}
In C# how do i ask user for starting and stopping point within the array?
Below is my code so far:
class Program
{
static void Main(string[] args)
{
double[] num = { 10, 20, 30, 40, 50 };
double n = num.Length;
Console.Write("Elements of, arrary are:" + Environment.NewLine);
for (int i = 0; i < n; i++)
{
Console.WriteLine(num[i]);
}
double sum = 0;
for (int i = 0; i < n; i++)
{
sum = sum + num[i];
}
Console.WriteLine("The sum of elements:" + sum);
Console.ReadKey();
}
}
You'll take the sum of the elements between starting and stopping point, as I guess. Take two inputs from the user and assign them to starting and ending points to the for-loop. Such as:
int startingPoint = Convert.ToInt32(Console.ReadLine());
int endingPoint = Convert.ToInt32(Console.ReadLine());
for(int i = startingPoint; i <= endingPoint; i++)
{
//take sum etc.
}
Don't forget to inform the user about the element values in the array and what input value they are entering at that moment.
Another important thing here is to control the inputs. They should be numeric and between 0-n, starting point should be smaller than ending point.
For numeric control you can write like follows:
if (int.TryParse(n, out startingPoint))
{
// operate here
}
else
{
Console.WriteLine("That's why I don't trust you, enter a numeric value please.");
}
startingPoint should be between 0-n and cannot be n. To control it:
if (startingPoint >= 0 && startingPoint < n)
{
// operate here
}
else
{
Console.WriteLine("Please enter a number between 0 and " + n + ".");
}
After taking startingPoint successfully, you should control if endingPoint. It should be between startingPoint-n. After controlling for being numeric you can write as follows:
if (endingPoint >= startingPoint && endingPoint < n)
{
// operate here
}
else
{
Console.WriteLine("Please enter a number between " + startingPoint + " and " + n + ".");
}
I don't know what can I explain more for this question. Please let me know for further problems.
If you want to prompt the user for the start and end indexes:
Console.WriteLine("Please enter start index");
string startIndexAsString = Console.ReadLine();
int startIndex = int.Parse(startIndexAsString);
Console.WriteLine("Please enter end index");
string endIndexAsString = Console.ReadLine();
int endIndex = int.Parse(endIndexAsString);
var sum = num.Skip(startIndex).Take(endIndex - startIndex + 1).Sum();