The first part of my code is where the input numbers are put into an array, this part works fine. In the second part you need to read in a searchterm and search for the searchterm in the array. After searching for it I need to show how many times the searchterm is found in the array. The second part is what i have tried but it doesn't work.
int[] number = new int[20];
int i = 0;
int notnull = 1;
while ( ( i < 20 ) && ( notnull != 0 ) )
{
Console.Write("Give a number <0 = stop> : ");
number[i] = int.Parse(Console.ReadLine());
notnull = number[i];
i++;
}
Console.WriteLine("Give searchterm (number): ");
int searchterm = int.Parse(Console.ReadLine());
int count = 1;
if ( searchterm == number[i] )
count++;
Console.WriteLine("The number {0} shows up {1} times", searchterm, count);
You can easily count items in an Array or an IEnumerable<T> in general, that have to fulfill a certain condition, with LINQ's Count():
Console.WriteLine("Give searchterm (number): ");
int searchterm = int.Parse(Console.ReadLine());
int count = number.Count(i => i == searchterm);
Console.WriteLine("The number {0} shows up {1} times", searchterm, count);
First, let's get rid of magic numbers - 20 in your case; let's change collecrtion's type: array doesn't have Add which List<T> provides:
List<int> number = new List<int>();
Then let's be cafeful with user input: what if user put bla-bla-bla? In order to avoid crash we can use TryParse instead of Parse:
while (true) {
// 0 is not a good choice; let it be Q (Quit) instead
Console.WriteLine("Give a number or Q to stop : ");
// Trim: let's be nice and tolerate trailing/leading spaces
string input = Console.ReadLine().Trim();
// Let's accept Q, q, quit, etc.
if (input.StartsWith("Q", StringComparison.OrdinalIgnoreCase))
break;
if (int.TryParse(input, out int value))
number.Add(value);
else
Console.WriteLine("Sorry, invalid input");
}
Now we have number to work with. Let's obtain searchterm with the technique (TryParse)
int searchterm = -1; // initialization, let compiler be happy
while (true) {
Console.WriteLine("Give searchterm (number): ");
if (int.TryParse( Console.ReadLine(), out searchterm))
break;
Console.WriteLine("Sorry, invalid input");
}
Finally, let's compute count; usually we put Linq for this:
int count = number.Count(searchterm);
However, if you want good old loops
int count = 0;
foreach (var item in number)
if (item == searchterm)
count += 1;
Final suggestion is to use string interpolation as more readable then formatting:
Console.WriteLine($"The number {searchterm} shows up {count} times");
You can try this:
using System.Linq;
using System.Collections.Generic;
static void Test()
{
int capacity = 20;
List<int> numbers = new List<int>(capacity);
Console.WriteLine($"Enter up to {capacity} numbers (0 or not an integer to stop): ");
int value = 0;
do
{
int.TryParse(Console.ReadLine(), out value);
if ( value != 0 )
numbers.Add(value);
}
while ( numbers.Count < capacity && value != 0 );
if ( numbers.Count > 0 )
{
Console.WriteLine();
Console.WriteLine("Enter a number to search occurences: ");
int.TryParse(Console.ReadLine(), out value);
if ( value > 0 )
{
Console.WriteLine();
Console.WriteLine("The number {0} shows up {1} times",
value,
numbers.Count(n => n == value));
}
}
}
Sample:
Enter up to a number (0 or not an integer to stop):
1
2
3
1
5
6
7
3
2
0
Enter un number to search occurences:
3
The number 3 shows up 2 times
Related
I am learning C# and having an issue understanding why my highNumber value is being displayed as 56 when running my code snippet.
//Write a program and ask the user to enter a series of numbers separated by comma. Find the maximum of the numbers
//and display it on the console. For example, if the user enters “5, 3, 8, 1, 4", the program should display 8
int highNumber = 0;
Console.Write("Enter a series of numbers separated by comma: ");
var userInput = Console.ReadLine();
for (var i = 0; i < userInput.Length; i++)
{
if (char.IsNumber(userInput[i]) == true)
{
if (userInput[i] > highNumber)
{
highNumber = Convert.ToInt32(userInput[i]);
}
}
}
Console.WriteLine("The largest number is {0}", Convert.ToInt32(highNumber));
You've entered the ASCII character '8', which has the numeric value 56.
If it's a single digit character then convert it with this
int val = (int)Char.GetNumericValue(userInput[i]);
If it's a numeric string then convert it in one call with this
int val;
bool success = Int32.TryParse(userInput, out val);
or
int val = System.Convert.ToInt32(userInput);
The LordWilmore`s answer is somehow correct if you dont use numbers greater than 10 but you can simplify and make it more accurate as below:
int highNumber = 0;
int valueTemp;
Console.Write("Enter a series of numbers separated by comma: ");
var userInput = Console.ReadLine();
string[] array = userInput.Split(',');
for (var i = 0; i < array.Length; i++)
{
if (int.TryParse(array[i], out valueTemp))
{
if (valueTemp > highNumber)
{
highNumber = valueTemp;
}
}
}
Console.WriteLine("The largest number is {0}", highNumber);
or using Max() function if you have knowledge about the List<> in c#:
int valueTemp;
Console.Write("Enter a series of numbers separated by comma: ");
var userInput = Console.ReadLine();
string[] array = userInput.Split(',');
List<int> intList = new List<int>();
for (var i = 0; i < array.Length; i++)
{
if (int.TryParse(array[i], out valueTemp))
{
intList.Add(valueTemp);
}
}
Console.WriteLine("The largest number is {0}", intList.Max());
This is a more accurate example because if put 3,33,4 in your example it will fail since you get each character and not values separated by comma. In my case I split them into pieces accordingly and then continue to test them appropriately.
Console.ReadLine(); returns a string. When you use the indexer ([i]) on the string you get individual characters, not strings or numbers. What you want is to Split the string by the commas, then use TryParse to ensure that each string is a number:
string userInput = Console.ReadLine();
string[] parts = userInput.Split(',');
for (var i = 0; i < parts.Length; i++)
{
int number;
if (int.TryParse(parts[i], out number))
{
if (number > highNumber)
{
highNumber = number;
}
}
}
I am trying to continuously ask user for a number between 300-850. When the user enters a valid number, add it to the total and ask again. If the number is invalid, display an error. Before program ends, display the average of total number by amount of times of input. End program if user enters a sentinel value. I don't know how to check if user enters a sentinel value.
using System;
class CreditScores
{
static void Main()
{
var iterations = 0;
double total = 0;
int sum = 0;
double average = 0;
int count = 0;
Console.WriteLine("Enter value between 300 to 850.");
int first = int.Parse(Console.ReadLine());
//trying to get it to stop when sentinel value reached.
while (iterations < 1000)
{
iterations++;
Console.WriteLine("Enter value between 300 to 850.");
int input = int.Parse(Console.ReadLine());
//not sure how to check if input is a number or not
if(input == integer)
{
if( input < 850 && input > 300 )
{
total +=input;
}
}
else
{
break;
}
}
total = sum + total;
Console.WriteLine("Total is {0}", total);
average = total / count;
Console.WriteLine("The average is {0}", average);
}
}
Modification/fix of Your Method
Also, I would read all the way to the end for the more robust method you could use.
First thing I would change:
while (iterations < 1000)
{
...
}
To this (which we are not done yet, read to the end):
while (input != "calculate") // or some other string
{
...
}
Then, before the while starts, make input a string.
string input = "";
while (input != "calculate") // or some other string
{
...
}
Now, we declared an input variable that is already an int later on. Let's fix that.
Console.WriteLine("Enter value between 300 to 850.");
input = Console.ReadLine();
int value = 0;
if (int.TryParse(input, out value))
{
// Clearly it's a valid integer at this point
if (value < 850 && value > 300)
{
total += value;
}
}
else
{
// Wasn't a number, might be our sentinel.
if (input == "calculate")
break;
else
{
// Throw an error or something.
}
}
Now, we need to put it together and do some cleaning.
int total = 0;
int numbersEntered = 0;
string input = "";
while (input != "calculate")
{
Console.WriteLine("Enter value between 300 to 850.");
input = Console.ReadLine();
int value = 0;
if (int.TryParse(input, out value))
{
// Clearly it's a valid integer at this point
if (value < 850 && value > 300)
{
total += value;
numbersEntered++;
}
}
else
{
// Wasn't a number, might be our sentinel.
if (input == "calculate")
break;
else
{
// Throw an error or something.
}
}
}
Console.WriteLine("Total is {0}", total);
double average = (double)total / numbersEntered;
Console.WriteLine("The average is {0}", average);
(I know, long answer. But it should help you step through the problem in the future. Also, I wrote this all by memory, I can't guarantee it will compile.)
Update: just tested it, works as expected.
A more Robust Method
Lastly, and this is really the coolest method in my opinion, use a List<int> and some extension methods.
List<int> values = new List<int>();
string input = "";
while (input != "calculate")
{
Console.WriteLine("Enter value between 300 to 850.");
input = Console.ReadLine();
int value = 0;
if (int.TryParse(input, out value))
// Clearly it's a valid integer at this point
if (value < 850 && value > 300)
values.Add(value);
else
{
// Was outside our range
}
else
// Wasn't a number, might be our sentinel.
if (input == "calculate")
break;
else
{
// Throw an error or something.
}
}
Console.WriteLine("Total is {0}", values.Sum());
Console.WriteLine("The average is {0}", values.Average());
Advantages to this method? It saves a list of the values entered, allowing you to do more with them that you cannot do with the method you currently have. It also uses the int.Sum() and int.Average() extension methods rather than your own math.
What is this int.TryParse(string, out int) sorcery?
The int.TryParse(string, out int) method (as defined by MSDN) will take an input string, and return a boolean value that indicates if it would make a valid int structure or not.
In the case that the string is a valid int, then the int parameter is filled with the integer representation of the string.
I.e.:
string myString = "100";
int value = 0;
if (int.TryParse(myString, out value))
Console.WriteLine("myString was a valid int: {0}", value);
else
Console.WriteLine("myString was not a valid int.");
This version will return true and print: myString was a valid int: 100.
Example 2:
string myString = "blah";
int value = 0;
if (int.TryParse(myString, out value))
Console.WriteLine("myString was a valid int: {0}", value);
else
Console.WriteLine("myString was not a valid int.");
This version will return false, and print myString was not a valid int.. The value variable would also be 0.
Warning:
When using int.TryParse(string input, out int value), do not rely on the value parameter as 0 to indicate failure. If the input is "0", then the value will also be 0, and the method will return true.
You want to set the condition of your while loop to something that a user can trigger as false (the sentinel).
Then put a for loop inside that if you want to do a set number of iterations, for loops are better for situations where you know how many iterations you're doing.
BUT if you want to stick to while loops only, here's a quick code snippet you could use:
while (input != 0 && iterations < 1000) //or some sentinel value you choose
{
//Your logic here, now the loop will quit if if the user enters 0
//OR you run out of iterations
}
using System;
class CreditScores
{
static void Main()
{
double total = 0;
int sum = 0;
int count = 0;
Console.WriteLine("Enter value between 300 to 850.");
int first = int.Parse(Console.ReadLine());
//trying to get it to stop when sentihel value reached.
for (iterations = 0; iterations < 1000; iterations++)
{
Console.WriteLine("Enter value between 300 to 850.");
int input;
// Check number is integer
if (int.TryParse(Console.ReadLine(), out input)
{
if(input > 300 && input < 850)
{
total +=input;
}
}
else
{
break;
}
count++;
}
total = sum + total;
Console.WriteLine("Total is {0}", total);
double average = total/count;
Console.WriteLine("The average is {0}", average);
Console.ReadLine(); // Either this or run with Ctrl-F5
}
}
The behaviour would be to add the totals until the user entered something that couldn't be parsed, and then exit.
Does this work?
string sentinalValue = "done";
string input = "";
while (iterations < 1000 && input != sentinalValue)
{
iterations++;
Console.WriteLine("Enter value between 300 to 850.");
input = Console.ReadLine();
int value;
if (int.TryParse(input, out value))
{
if( value < 850 && value > 300 )
{
total +=input;
}
}
else
{
Console.WriteLine("That is not a number!");
}
}
i am working on a very specific problem. this program prompts the user for a number between 1-10000000 and then another number 1-10000. the first number is how many random numbers and the second is what the max those numbers can be is. im trying to print the result on user prompt and print if user wants to print results and the result are number of primes. first problem is i cannot get the program to respond to the user pushing 1 or 0 to print results. second is i cannot get the number of primes that were created to print as a resut
namespace PRIMECON
{
class PRIMECON
{
static void Main(string[] args)
{
//creates stopwatch
Stopwatch watch = new Stopwatch();
//creates randoms
Random rnd = new Random();
//starts the stopwatch
watch.Start();
//gets number from 1 to 10 million
Console.WriteLine("\nPlease enter a number between 1 and 10,000,000");
bool checkn;
int number; //input
checkn = int.TryParse(Console.ReadLine(), out number);
//gets number from 1 to 10 thousand
Console.WriteLine("\nPlease enter a number between 1 and 10,000");
bool checkr;
int range; //range of values from 0 to r
checkr = int.TryParse(Console.ReadLine(), out range);
if (checkn == true && checkr == true && number > 0 && number <= 10000000 && range > 0 && range <= 10000)
{
//array
int arraySize = 0;
//int[] array = new int[range];
for (int i = 0; i < number; i++)
{
int randomNumber = rnd.Next(1, range);
bool primeNumber = PRIMELIB.PRIMELIB.IsItPrime(randomNumber); //calls library method
if (primeNumber == true)
arraySize++; //adds to the array for each prime number
//array[i] = randomNumber;
//prints numbers
Console.WriteLine(i.ToString() + " " + randomNumber.ToString() + " " + primeNumber.ToString()); // prints index, number, true/false
}
//int[] array = new int[arraysize];
watch.Stop();
Console.WriteLine("\nElapsed Time = " + watch.Elapsed.ToString());
int exit = 1;
do
{
Console.WriteLine("would you like to print results? 0-no 1-yes");
Console.ReadLine();
int rangeHigh;
int rangeLow;
bool high = int.TryParse(Console.ReadLine(), out rangeHigh);
bool low = int.TryParse(Console.ReadLine(), out rangeLow);
if (high == true && low == true)
{
for (int i = rangeLow; i < rangeHigh; i++)
{
//Console.WriteLine( i + ". " + array[i]);
}
}
}
while (exit != 0);
}
else if (checkn == false || number > 10000000 || number < 0)
Console.WriteLine("First number was not valid");
else if (checkr == false || range > 10000000 || range < 0)
Console.WriteLine("Range was not valid");
else
Console.WriteLine("entry not valid");
Console.ReadKey();
}
}
}
At the moment I can post an answer about your "cannot get the program to respond to the user pushing 1 or 0 to print results" issue. Since your are reading the console line within the do/while loop you can use the int.Parse function then put the inner part of the while loop in an if statement so it will only execute if the user picked yes. The loop will now become this:
int exit = 1;
do
{
Console.WriteLine("would you like to print results? 0-no 1-yes");
exit = int.Parse(Console.ReadLine());
if (1 == exit)
{
int rangeHigh;
int rangeLow;
bool high = int.TryParse(Console.ReadLine(), out rangeHigh);
bool low = int.TryParse(Console.ReadLine(), out rangeLow);
if (high == true && low == true)
{
for (int i = rangeLow; i < rangeHigh; i++)
{
//Console.WriteLine( i + ". " + array[i]);
}
}
}
}
while (exit != 0);
For your library issue with not being able to get the number of primes that were created my only suggestion is to check your references to see if you include it, and if you added the using for it at the top of your code. I have not used custom libraries in c#, but searching around in google on how to use libraries in c# will be your best bet.
I am brand new to programming and was interested in C#. I am studying arrays and have to compare my variable (checkNum) to my array(myNums[10]). I read posts here and several other sites and saw how to compare but getting stuck on how to properly display the comparison as shown in my attempt with the if/else statement below:(I will continue to research, but would appreciate and nudges in the right direction. Not necessarily the answer as I am wanting to learn) :)
Here is my code:
int[] myNums = new int[10];
int checkNum;
Console.WriteLine("Enter 10 numbers:");
for (int i = 0; i < 10; i++)
{
Console.Write("Number {0}: ", i + 1);
myNums[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("You entered:");
foreach (int x in myNums)
{
Console.Write("{0} ", x);
}
Console.ReadLine();
Console.WriteLine("Enter another number:");
checkNum = int.Parse(Console.ReadLine());
bool exists = myNums.Contains(checkNum);
if (checkNum == myNums[10])
{
Console.WriteLine("Your number {0} is in the Array.", checkNum);
}
else
{
Console.WriteLine(
"Your number {0} does not match any number in the Array.",
checkNum);
}
Console.ReadLine();
bool exists = myNums.Contains( checkNum );
if( checkNum == myNums[10] )
{
Console.WriteLine( "Your number {0} is in the Array.", checkNum );
}
else
{
Console.WriteLine( "Your number {0} does not match any number in the Array.", checkNum );
}
Should be
bool exists = myNums.Contains( checkNum );
// or simply if(myNums.Contains(checkNum)) as you don't use the variable again
if( exists )
{
Console.WriteLine( "Your number {0} is in the Array.", checkNum );
}
else
{
Console.WriteLine( "Your number {0} does not match any number in the Array.", checkNum );
}
You perform the check correctly, but you don't use the result (exists) and simply (attempt to) compare the new number to the last element in the array. Of course, at this point your program just crashes because you have overrun the bounds of your array.
Arrays are 0 indexed, i.e., nums[10] contains indices 0-9.
You need to iterate through the array to see if the value is in it:
bool exists = false;
for (int i=0; i<myNums.Length; i++)
{
if (checkNum == myNums[i])
{
exists = true;
break;
}
}
if (exists)
{
Console.WriteLine("Your number {0} is in the Array.", checkNum);
}
else
{
Console.WriteLine(
"Your number {0} does not match any number in the Array.",
checkNum);
}
Why do you have the last if statement checking for: checkNum == myNums[10]? It should use the exists variable.
i know how to make a console read two integers but each integer by it self like this
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
if i entered two numbers, i.e (1 2), the value (1 2), cant be parse to integers
what i want is if i entered 1 2 then it will take it as two integers
One option would be to accept a single line of input as a string and then process it.
For example:
//Read line, and split it by whitespace into an array of strings
string[] tokens = Console.ReadLine().Split();
//Parse element 0
int a = int.Parse(tokens[0]);
//Parse element 1
int b = int.Parse(tokens[1]);
One issue with this approach is that it will fail (by throwing an IndexOutOfRangeException/ FormatException) if the user does not enter the text in the expected format. If this is possible, you will have to validate the input.
For example, with regular expressions:
string line = Console.ReadLine();
// If the line consists of a sequence of digits, followed by whitespaces,
// followed by another sequence of digits (doesn't handle overflows)
if(new Regex(#"^\d+\s+\d+$").IsMatch(line))
{
... // Valid: process input
}
else
{
... // Invalid input
}
Alternatively:
Verify that the input splits into exactly 2 strings.
Use int.TryParse to attempt to parse the strings into numbers.
You need something like (no error-checking code)
var ints = Console
.ReadLine()
.Split()
.Select(int.Parse);
This reads a line, splits on whitespace and parses the split strings as integers. Of course in reality you would want to check if the entered strings are in fact valid integers (int.TryParse).
Then you should first store it in a string and then split it using the space as token.
Read the line into a string, split the string, and then parse the elements. A simple version (which needs to have error checking added to it) would be:
string s = Console.ReadLine();
string[] values = s.Split(' ');
int a = int.Parse(values[0]);
int b = int.Parse(values[1]);
string[] values = Console.ReadLine().Split(' ');
int x = int.Parse(values[0]);
int y = int.Parse(values[1]);
in 1 line, thanks to LinQ and regular expression (no type-checking neeeded)
var numbers = from Match number in new Regex(#"\d+").Matches(Console.ReadLine())
select int.Parse(number.Value);
string x;
int m;
int n;
Console.WriteLine("Enter two no's seperated by space: ");
x = Console.ReadLine();
m = Convert.ToInt32(x.Split(' ')[0]);
n = Convert.ToInt32(x.Split(' ')[1]);
Console.WriteLine("" + m + " " + n);
This Should work as per your need!
public static class ConsoleInput
{
public static IEnumerable<int> ReadInts()
{
return SplitInput(Console.ReadLine()).Select(int.Parse);
}
private static IEnumerable<string> SplitInput(string input)
{
return Regex.Split(input, #"\s+")
.Where(x => !string.IsNullOrWhiteSpace(x));
}
}
int a, b;
string line = Console.ReadLine();
string[] numbers= line.Split(' ');
a = int.Parse(numbers[0]);
b = int.Parse(numbers[1]);
Try this:
string numbers= Console.ReadLine();
string[] myNumbers = numbers.Split(' ');
int[] myInts = new int[myNumbers.Length];
for (int i = 0; i<myInts.Length; i++)
{
string myString=myNumbers[i].Trim();
myInts[i] = int.Parse(myString);
}
Hope it helps:)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SortInSubSet
{
class Program
{
static int N, K;
static Dictionary<int, int> dicElements = new Dictionary<int, int>();
static void Main(string[] args)
{
while (!ReadNK())
{
Console.WriteLine("***************** PLEASE RETRY*********************");
}
var sortedDict = from entry in dicElements orderby entry.Key/3 , entry.Value ascending select entry.Value;
foreach (int ele in sortedDict)
{
Console.Write(ele.ToString() + " ");
}
Console.ReadKey();
}
static bool ReadNK()
{
dicElements = new Dictionary<int, int>();
Console.WriteLine("Please entere the No. of element 'N' ( Between 2 and 9999) and Subset Size 'K' Separated by space.");
string[] NK = Console.ReadLine().Split();
if (NK.Length != 2)
{
Console.WriteLine("Please enter N and K values correctly.");
return false;
}
if (int.TryParse(NK[0], out N))
{
if (N < 2 || N > 9999)
{
Console.WriteLine("Value of 'N' Should be Between 2 and 9999.");
return false;
}
}
else
{
Console.WriteLine("Invalid number: Value of 'N' Should be greater than 1 and lessthan 10000.");
return false;
}
if (int.TryParse(NK[1], out K))
{
Console.WriteLine("Enter all elements Separated by space.");
string[] kElements = Console.ReadLine().Split();
for (int i = 0; i < kElements.Length; i++)
{
int ele;
if (int.TryParse(kElements[i], out ele))
{
if (ele < -99999 || ele > 99999)
{
Console.WriteLine("Invalid Range( " + kElements[i] + "): Element value should be Between -99999 and 99999.");
return false;
}
dicElements.Add(i, ele);
}
else
{
Console.WriteLine("Invalid number( " + kElements[i] + "): Element value should be Between -99999 and 99999.");
return false;
}
}
}
else
{
Console.WriteLine(" Invalid number ,Value of 'K'.");
return false;
}
return true;
}
}
}
I have a much simpler solution, use a switch statement and write a message for the user in each case, using the Console.write() starting with a ("\n").
Here's an example of filling out an array with a for loop while taking user input. * Note: that you don't need to write a for loop for this to work*
Try this example with an integer array called arrayOfNumbers[] and a temp integer variable. Run this code in a separate console application and Watch how you can take user input on the same line!
int temp=0;
int[] arrayOfNumbers = new int[5];
for (int i = 0; i < arrayOfNumbers.Length; i++)
{
switch (i + 1)
{
case 1:
Console.Write("\nEnter First number: ");
//notice the "\n" at the start of the string
break;
case 2:
Console.Write("\nEnter Second number: ");
break;
case 3:
Console.Write("\nEnter Third number: ");
break;
case 4:
Console.Write("\nEnter Fourth number: ");
break;
case 5:
Console.Write("\nEnter Fifth number: ");
break;
} // end of switch
temp = Int32.Parse(Console.ReadLine()); // convert
arrayOfNumbers[i] = temp; // filling the array
}// end of for loop
The magic trick here is that you're fooling the console application, the secret is that you're taking user input on the same line you're writing your prompt message on. (message=>"Enter First Number: ")
This makes user input look like is being inserted on the same line. I admit it's a bit primitive but it does what you need without having to waste your time with complicated code for a such a simple task.