My task is to let a user input numbers, and when they input 0, the loop will end and should display the lowest number. However since they're inputting 0, that becomes the lowest number. I have tried using the OrderBy to skip the first number in the array, but that doesn't seem to be working.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Task 7\n");
int[] numbers = new int[100];
for(int i = 0; i < numbers.Length; i++)
{
Console.WriteLine("Input any number. Once you enter 0, the application will end");
numbers[i] = int.Parse(Console.ReadLine());
if(numbers[i] == 0)
{
break;
}
}
int lowest = numbers.OrderBy(num => num).Skip(1).First();
Console.WriteLine($"The lowest number was: {lowest}");
Console.ReadLine();
}
}
Maybe there's a smarter way overall to end the loop when the user inputs 0
Any ideas?
Use a temporary variable to store the output from int.Parse() before adding it to your array:
var temp = int.Parse(Console.ReadLine());
if(temp == 0)
{
break;
}
numbers[i] = temp;
You'll still get 0 as the lowest value, because the remaining indexes in the array has not been assigned to (int initializes to 0), so you might want to take that into account by either filtering the array before ordering:
int lowest = numbers.Where(num => num > 0).OrderBy(num => num).First();
Or by using a dynamically sized data structure, such as a list:
List<int> numbers = new List<int>();
for(int i = 0; i < 100; i++)
{
Console.WriteLine("Input any number. Once you enter 0, the application will end");
var temp = int.Parse(Console.ReadLine());
if(temp == 0)
{
break;
}
numbers.Add(temp);
}
int lowest = numbers.OrderBy(num => num).First();
This of course assumes you want to store all the input values, otherwise just keep track of the lowest value in a single int
if you don't need to keep all the input values, you can use an int variable to keep the lowest value between this one and the new input value.
So at the end of the loop you have to print this variable which contains the lowest value.
int lowest = Int32.MaxValue;
for(int i = 0; i < numbers.Length; i++)
{
Console.WriteLine("Input any number. Once you enter 0, the application will end");
lowest = Math.Min(int.Parse(Console.ReadLine()), lowest);
if(lowest == 0)
{
break;
}
}
Console.WriteLine($"The lowest number was: {lowest}");
Console.ReadLine();
Put a value to the array after checking:
var number = int.Parse(Console.ReadLine());
if (number == 0) break;
numbers[i] = number;
try this too
int[] numbers = new int[100];
int x = 0;
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine("Input any number. Once you enter 0, the application will end");
switch (x = int.Parse(Console.ReadLine()))
{
case 0:
break;
default:
numbers[i] = x;
break;
}
if (x == 0)
break;
}
int lowest = numbers.OrderBy(num => num).First();
Console.WriteLine($"The lowest number was: {lowest}");
Console.ReadLine();
The issue is that you are declaring int[] numbers = new int[100]; the default value of an int array is 0 therefore if for example you only enter 5 values you have the other 95 values still initialised to 0. when you sort the array you have all the zeros at the beginning.
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
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 have an assingment and I'm a bit lost. In an array of 10 (or less) numbers which the user enters (I have this part done), I need to find the second smallest number. My friend sent me this code, but I'm having a hard time understanding it and writing it in c#:
Solved it!!! :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int vnesena;
int? min1 = null;
int? min2 = null;
for(int i=1; i<11; i=i+1)
{
Console.WriteLine("Vpiši " + i +"." + " število: ");
vnesena = Convert.ToInt32(Console.ReadLine());
if (vnesena == 0)
{
break;
}
if (min1 == null || vnesena < min1)
{
min2 = min1;
min1 = vnesena;
}
else if (vnesena != min1 && (min2==null || vnesena<min2))
{
min2 = vnesena;
}
}
if (min1 == null || min2 == null)
{
Console.WriteLine("Opozorilo o napaki");
}
else
{
Console.WriteLine("Izhod: " + min2);
}
Console.ReadKey();
}
}
}
That code is too complicated, so try something like this.
int[] numbers = new int[10];
for (int i = 0; i < 10; i++)
{
numbers[i] = int.Parse(Console.ReadLine());
}
Array.Sort(numbers);
Console.WriteLine("Second smallest number: " + numbers[1]);
If the code isn't too obvious, let me explain:
Declare an array of 10 integers
Loop 10 ten times and each time, ask for user input & place input as an integer to the array
Sort the array so each number is in the number order (smallest first, biggest last).
The first integer is smallest (input at index 0, so numbers[0]) and the second smallest is obviously numbers[1].
Of course, for this piece of code to work, you have to use this code in console program.
As you didn't mention if you are allowed to use built in sorting functions etc, I assume that Array.Sort() is valid.
EDIT: You updated your topic so I'll change my code to match criterias.
int[] numbers = new int[10];
bool tooShortInput = false;
for (int i = 0; i < 10; i++)
{
int input = int.Parse(Console.ReadLine());
if (input != 0)
{
numbers[i] = input;
}
else
{
if (i == 2)
{
Console.WriteLine("You only entered two numbers!");
tooShortInput = true;
break;
}
else
{
for (int j = 0; j < 10; j++)
{
if (numbers[j] == 0)
{
numbers[j] = 2147483647;
}
}
break;
}
}
}
// Sort the array
int temp = 0;
for (int write = 0; write < numbers.Length; write++) {
for (int sort = 0; sort < numbers.Length - 1; sort++) {
if (numbers[sort] > numbers[sort + 1]) {
temp = numbers[sort + 1];
numbers[sort + 1] = numbers[sort];
numbers[sort] = temp;
}
}
}
if (!tooShortInput)
{
Console.WriteLine("Second smallest number: " + numbers[1]);
}
If you don't understand the updated code, let me know, I will explain.
NOTE: This is fastly coded and tested with android phone so obviously this code isn't 5 star quality, not even close, but it qualifies :-).
Regards, TuukkaX.
To paraphrase the code given:
Set 2 variables to nothing. (This is so that there can be checks done later. int? could be used if you want to use null for one idea here.
Start loop through values.
Get next value.
If the minimum isn't set or the new value is lower than the minimum, replace the second lowest with the former lowest and lowest with the new value that was entered.
Otherwise, check if the new value isn't the same as the minimum and if the minimum isn't set or the entered value is lower than the second lowest then replace the second lowest with this new value.
Once the loop is done, if either minimum value isn't filled in then output there isn't such a value otherwise output the second lowest value.
Imagine if you had to do this manually. You'd likely keep track of the lowest value and second lowest value as you went through the array and the program is merely automating this process. What is the problem?
This is a rough translation of what your friend gave you that isn't that hard to translate to my mind.
int enteredValue;
int? smallest = null, secondSmallest = null;
for (int i = 0; i < 10; i = i + 1)
{
Console.WriteLine("Vpiši " + i+1 + " število: ");
enteredValue = Convert.ToInt32(Console.ReadLine());
if (smallest==null || enteredValue<smallest) {
secondSmallest=smallest;
smallest = enteredValue;
} else if (enteredValue!=smallest && enteredValue<secondSmallest) {
secondSmallest= enteredValue;
}
}
Why use a loop and not take advantage of the Array.Sort method?
int[] numbers = new int[4] { 4, 2, 6, 8 };
Array.Sort(numbers);
int secondSmallestNumber = numbers[1];
I have an assignment where I need to find the product of all of the numbers in an array, I'm not sure how to do this.
int[] numbers = new int[SIZE];
Console.WriteLine("Type in 10 numbers");
Console.WriteLine("To stop, type in 0");
for (int input = 0; input < SIZE; input++)
{
userInput = Console.ReadLine();
numberInputed = int.Parse(userInput);
if (numberInputed == ZERO)
{
numberInputed = ONE;
break;
}
else
{
numbers[input] = numberInputed;
}
}
This is where I'm trying to find the product of all of the numbers in the array.
foreach (int value in numbers)
{
prod *= value;
}
Console.WriteLine("The product of the values you entered is {0}", prod);
What am I doing wrong in the foreach statement? Thanks in advance
Edit, left out my declared values
const int SIZE = 10;
const int ZERO = 0;
string userInput;
int numberInputed;
int prod = 1;
It now works when I type in all ten values but if I put a 0 in order to break the loop then everything equals 0. How do I prevent a 0 from being entered into the array?
It's possible you initialize prod to 0, which means no matter what numbers are in your array, prod will remain 0. Make sure you initialize it to 1 to get the correct result:
int prod = 1;
foreach (int value in numbers)
{
prod *= value;
}
You could also use Linq's Aggregate extension method to do the same thing:
using System.Linq; // put with other using directives
int prod = numbers.Aggregate(1, (a, b) => a * b);
Update
The real problem (which I failed to notice before) is that your array isn't being fully populated if you break out of your loop early. So any array entries you didn't set are still initialized to 0. To fix this, use a List<int> instead of an int[]:
using System.Collections.Generic; // put with other using directives
List<int> numbers = new List<int>(SIZE); // Capacity == SIZE
...
for (int input = 0; input < SIZE; input++)
{
...
if (numberInputed == ZERO)
{
break;
}
else
{
numbers.Add(numberInputed);
}
}
The problem is that you don't keep track of how many items there are in the array that actually are assigned a value. If you exit from the loop using a zero input, then the rest of the items are unchanged. As they are zero by default, you will be using those zeroes in your second loop, and when you have a zero somewhere in the array, the total product becomes zero.
Keep track of how many items there are by keeping the loop variable outside the loop:
int input = 0;
while (input < SIZE)
{
userInput = Console.ReadLine();
numberInputed = int.Parse(userInput);
if (numberInputed == ZERO) {
break;
}
numbers[input] = numberInputed;
input++;
}
Now you can use only the items that are actually assigned:
for (int i = 0; i < input; i++) {
prod *= numbers[i];
}
Multiply all numbers inside an Array
int[] array = { 1, 2, 3, 4, 5 };
int sum = array[0];
for (int i = 1; i != array.Length; i++)
{
sum *= array[i];
}
If your array is somehow populated with zeroes (0), then use List instead of an array.
I have this code I'm using to create a program that takes a a range and outputs to the Console the prime numbers. I have one problem, I'm trying to iterate through the array I built so the loop should only write to the console the values that are prime using my method's return value. The problem I'm having is that I have the second condition set to numArray.Length but it seems to give me the Index out of Range Exception. I just want the loop to iterate through all values in the numArray and stop when it's done figuring out whether the last value is prime or not.
public struct Prime
{
public int x;
// constructor for Prime
public Prime(int x1)
{
x = x1;
}
public int IsPrime(int number)
{
int i;
for (i = 2; i * i <= number; i++)
{
if (number % i == 0) return 0;
}
return 1;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter an Integer");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter a Second Integer of Greater Value");
// int num2 = 0;
int num2 = Convert.ToInt32(Console.ReadLine());
/* if (num2temp > num1)
{
num2temp = num2;
}
else
{
Console.WriteLine("You Did Not Enter An Integer Greater Than the First Integer, Please Enter Your Integers Again.");
Environment.Exit(0);
}
*/ int index = 1;
int[] numArray = new int[num2];
for (int i = num1; i <= num2; i++)
{
numArray[index] = i;
Console.WriteLine(" index: {0} assignment: {1}", index, i);
index++;
Console.WriteLine("index: {0}",index);
}
Console.WriteLine("value: {0}", numArray[40]);
/* Prime myprime = new Prime();
if (myprime.IsPrime(numArray[12]) == 1)
{
Console.WriteLine("true");
}
else
{
Console.WriteLine("False");
} */
Prime myprime = new Prime();
int value = 0;
for (int y = 1; y <= num2; y++)
{
if (myprime.IsPrime(numArray[y]) == 1)
{
value = numArray[y];
Console.Write("{0} \t", value);
}
}
You're currently trying to iterate up to and including the size of the array. Arrays are 0-indexed in C#. So this:
int[] numArray = new int[num2];
for (int i = num1; i <= num2; i++)
should be:
for (int i = num1; i < num2; i++)
And note that to get at the first element array, num1 would have to be 0, not 1.
Likewise, your initial assignment of index as 1 should be 0 instead. Basically you need to go through all your code (it's confusing at the moment with lots of bits commented out) and check everywhere that you're assuming arrays are 1-based, and instead change your code as they're 0-based.
(In some cases you may just want to make the array one bigger, of course. If you want an array which logically contains the values 1 to x inclusive, you can either create an array of size x and subtract one from each index all the time, or create an array of size x + 1.)
Your index starts from 1 but should start from 0:
int index = 0; //CHANGE HERE
int[] numArray = new int[num2];
for (int i = num1; i <= num2; i++)
{
numArray[index] = i;
Console.WriteLine(" index: {0} assignment: {1}", index, i);
index++;
Console.WriteLine("index: {0}",index);
}
and then here y should also be 0 and check should if it is less than num2:
for (int y = 0; y < num2; y++)
{
if (myprime.IsPrime(numArray[y]) == 1)
{
value = numArray[y];
Console.Write("{0} \t", value);
}
}
because array indexing in C# start from 0.