I mean how to count and sum input numbers until receive "end".
thanks !
And also how to find out input is number or letter in c#?
class Program
{
static void Main(string[] args)
{
int n = 0;
int sum = 0;
string inp;
do
{
Console.Write("Numbers ");
inp = Console.ReadLine();
int num= Convert.ToInt16(inp);
sum = sum + num;
n++;
} while (too == "end");
int average = sum / n;
Console.WriteLine(" " + average);
Console.ReadLine();
}
}
I would suggest you use a normal while loop and also add validation to check to integer input.
For the while loop you want to loop until the input is not equal to "end":
while(inp != "end")
For the validation, you can use int.TryParse method:
int num = 0;
if (int.TryParse(inp, out num)) { }
Here is a modified example of your code:
int n = 0;
int sum = 0;
string inp = null;
while(inp != "end")
{
Console.Write("Numbers ");
inp = Console.ReadLine();
int num = 0;
if (int.TryParse(inp, out num))
{
sum = sum + num;
n++;
}
}
int average = sum / n;
Console.WriteLine(" " + average);
Console.ReadLine();
// A list to hold all of the numbers entered
List<int> numbers = new List<int>();
// Will hold the inputted string
string input;
// This needs to be outside the loop so it's written once
Console.Write("Numbers: " + Environment.NewLine);
// Keep going until we say otherwise
while (true)
{
// Get the input
input = Console.ReadLine();
// Will hold the outcome of parsing the input
int number = -1;
// Check to see if input was a valid number
bool success = int.TryParse(input, out number);
// If it was a valid number then remember it
// If ANY invalid or textual input is detected then stop
if (success)
numbers.Add(number);
else
break;
}
// Write the count and average
Console.WriteLine("Count:" + numbers.Count);
Console.WriteLine("Average:" + numbers.Average());
Console.ReadLine();
Input:
Numbers:
1
2
3
4
5
Output:
Count: 5
Average: 3
The only thing here a little different to what you specified is ANY invalid or textual entry causes it to finish, not just typing the word "end", although that obviously works too.
Related
I am currently working on a program that is a loop with a sentinel value that asks the user to enter a number or enter -99 to end the program and it runs perfectly. If I were to change that -99 to just the word "Quit" is there a certain parameter that I would have to put? For example, if I want to use a letter, I know that I could use:
char (undefined parameter) = 'A'
But how would I do this with a word? When I simply try to change the value of -99 to Quit, I receive an error as expected.
using System;
class Program {
public static void Main (string[] args) {
int sum = 0;
int counter = 0;
int max = Int32.MinValue;
int min = Int32.MaxValue;
bool keepGoing = true;
while(keepGoing) {
Console.WriteLine("Please enter a number or enter -99 to stop the program:");
int number = Convert.ToInt32(Console.ReadLine());
if (number == -99){
keepGoing = false;
} else {
counter++;
sum += number;
if (number >= max) {
max = number;
}
if (number <= min) {
min = number;
}
}
}
double average = (double) sum / counter;
Console.WriteLine($"{counter} numbers were entered.");
Console.WriteLine("The average is:" + average);
Console.WriteLine("The sum is:" + sum);
Console.WriteLine("The maximum value is:" + max);
Console.WriteLine("The minimum value is:" + min);
}
}
It's difficult to store "Quit" in an int, so the root of your problem is that you have no separation between pulling the string from the console and converting it to an int:
int number = Convert.ToInt32(Console.ReadLine());
if (number == -99){
keepGoing = false;
} else {
counter++;
If you did have a separation, it becomes possible:
string input = Console.ReadLine();
if (input == "Quit"){
keepGoing = false;
} else {
int number = Convert.ToInt32(input);
counter++;
I have been trying to make a program that you input a number and i keeps asking for numbers untill their sum has reached the number and displays how many numbers it took. the problem i'm facing is that if the last number makes it over the input number it still counts it while it should stop.
static void Main(string[] args)
{
int sumLimit = Convert.ToInt32(Console.ReadLine());
int sum = 0;
int count = 0;`
while (sum < sumLimit)
{
int number = Convert.ToInt32(Console.ReadLine());
sum += number;
count++;
}
Console.WriteLine(sum + " " + count);
Console.ReadLine();
}
Here's one option to fix it, depending on your expected result you can let the count start at -1 or 0:
int sumLimit = Convert.ToInt32(Console.ReadLine());
int sum = 0;
int count = -1;
int number = 0;
while (sum + number < sumLimit)
{
sum += number;
count++;
number = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine(sum + " " + count);
Console.ReadLine();
"Exercise Guidelines:
First read the count of numbers, for example in a variable n. Then consequently enter n numbers with one for loop. While entering each new number, save in two variables the smallest and the largest number until this moment.(...)"
I do an exercise from C# tutorial and I have problem with extracting numbers from one line string consisting of unknown number of numbers.
I have such code so far:
Console.WriteLine("Type in several Integers:");
string input = System.Console.ReadLine();
string[] splittedLine = input.Split(' ');
foreach(string number in splittedLine)
{
Console.Write(" " + number);
}
Console.Read();
I am supposed to print smallest and biggest number from input using for loop.
As far as I understand I need to parse numbers from splitedLine array so they are integers, then compare them and use Int32.MaxValue and Int32.MinValue.
I'm stuck on "Parsing" part of the code.
---------- update -----------
When I add
int[] parsedNumbers = int.Parse(splittedLine[])
I get error that splittedLine[] needs a value. Is it possible to bulk-parse all elements from array?
The most basic solution (no linq or anything) based on your code:
Console.WriteLine("Type in several Integers:");
string input = System.Console.ReadLine();
string[] splittedLine = input.Split(' ');
int max = Int32.MinValue; // initialize the maximum number to the minimum possible values
int min = Int32.MaxValue; // initialize the minimum number to the maximum possible value
foreach(string number in splittedLine)
{
int currentNumber = int.Parse(number); // convert the current string element
// to an integer so we can do comparisons
if(currentNumber > max) // Check if it's greater than the last max number
max = currentNumber; // if so, the maximum is the current number
if(currentNumber < min) // Check if it's lower than the last min number
min = currentNumber; // if so, the minium is the current number
}
Console.WriteLine(string.Format("Minimum: {0} Maximum: {1}", min, max));
No error checking done here, so the input must be correct
To get min and max values of user input you can use LINQ.
Sample code:
Console.WriteLine("Type in several Integers:");
string input = System.Console.ReadLine();
List<int> numbers = null;
if(!string.IsNullOrWhiteSpace(input)) // Check if any character has been entered by user
{
string[] splittedLine = input.Split(' '); // Split entered string
if(splittedLine != null && splittedLine.Length != 0) // Check if array is not null and has at least one element
{
foreach (var item in splittedLine)
{
int tmpNumber;
if(int.TryParse(item, out tmpNumber)) // Parse string to integer with check
{
if (numbers == null) numbers = new List<int>(); // If is at least one integer - create list with numbers
numbers.Add(tmpNumber); // Add number to list of int
}
}
}
}
else
{
// TODO: info for user
}
if(numbers != null) // Check if list of int is not null
{
Console.WriteLine("Min: {0}", numbers.Min()); // Get min value from numbers using LINQ
Console.WriteLine("Max: {0}", numbers.Max()); // Get max value from numbers using LINQ
}
else
{
// TODO: info for user
}
Console.Read();
Min and Max value without using LINQ:
...
if(numbers != null)
{
var min = numbers[0];
var max = numbers[0];
foreach (var item in numbers)
{
if (item < min) min = item;
if (item > max) max = item;
}
Console.WriteLine("Min: {0}", min);
Console.WriteLine("Max: {0}", max);
}
...
Try
int test;
var numbers =
from n in input.Split(' ')
where int.TryParse(n, out test) // Only to test if n is an integer
select int.Parse(n)
;
int maxValue = numbers.Max();
int minValue = numbers.Min();
Without Linq
int maxValue = int.MinValue;
int minValue = int.MaxValue;
foreach(var s in input.Split(' '))
{
int number;
if(int.TryParse(s, out number))
{
maxValue = Math.Max(maxValue, number);
minValue = Math.Min(minValue, number);
}
}
class Program
{
static public void Main(string[] args)
{
// Get input
Console.WriteLine("Please enter numbers seperated by spaces");
string input = Console.ReadLine();
string[] splittedInput = input.Split(' ');
// Insure numbers are actually inserted
while (splittedInput.Length <= 0)
{
Console.WriteLine("No numbers inserted. Please enter numbers seperated by spaces");
splittedInput = input.Split(' ');
}
// Try and parse the strings to integers
// Possible exceptions : ArgumentNullException, FormatException, OverflowException
// ArgumentNullException shouldn't happen because we ensured we have input and the strings can not be empty
// FormatException can happen if someone inserts a string that is not in the right format for an integer,
// Which is : {0,1}[+\-]{1,}[0-9]
// OverflowException happens if the integer inserted is either smaller than the lowest possible int
// or bigger than the largest possible int
// We keep the 'i' variable outside for nice error messages, so we can easily understand
// What number failed to parse
int[] numbers = new int[splittedInput.Length];
int i = 0;
try
{
for (; i < numbers.Length; ++i)
{
numbers[i] = int.Parse(splittedInput[i]);
}
}
catch (FormatException)
{
Console.WriteLine("Failed to parse " + splittedInput[i] + " to an integer");
return;
}
catch (OverflowException)
{
Console.WriteLine(splittedInput[i] + " is either bigger the the biggest integer possible (" +
int.MaxValue + ") or smaller then the lowest integer possible (" + int.MinValue);
return;
}
// Save min and max values as first number
int minValue = numbers[0], maxValue = numbers[0];
// Simple logic from here - number lower than min? min becomes numbers, and likewise for max
for (int index = 1; index < numbers.Length; ++i)
{
int currentNumber = numbers[index];
minValue = minValue > currentNumber ? currentNumber : minValue;
maxValue = maxValue < currentNumber ? currentNumber : maxValue;
}
// Show output
Console.WriteLine("Max value is : " + maxValue);
Console.WriteLine("Min value is : " + minValue);
}
}
This is the most accurate, non-linq and extensive answer I could write on Notepad++
I am new to programming and I think I have confused myself I'm trying to make a loop that asks users for integers when the user inputs a integer greater than 100 then the console displays the amount of integers the user has input and the sum of these integers. I know it's basic but I can't figure where I went wrong.
namespace Wip
{
class Program
{
static void Main(string[] args)
{
string strNum1, strNum2;
int num1, num2;
int i = 0;
int sum =0 ;
Console.WriteLine("Please enter a integer between 1 and 100"); // asks for user input
strNum1 = Console.ReadLine();
num1 = int.Parse(strNum1);
do //repeat asking for user input
{
Console.WriteLine("Please enter another integer between 1 and 100"); // asks for user input
strNum2 = Console.ReadLine();
num2 = int.Parse(strNum2); //input is stored as num2
sum = num2; //store num2 in sum
i++;
if (num2 >= 100) // if num2 int is greater than 100
{
sum = (num1 +num2 +sum); // do calculation
Console.WriteLine("No of integers entered is {0} {1}", i, sum); //output calculation
}
}
while (i < 100);
}
}
}
any help would be appreciated thanks everyone!
You're on the right track... a couple of things:
Do... While is used when you always want to run through the block at least once, so your first 'get' from the user can be inside the block. You can code whatever you want to happen after the condition fails right after the block, instead of checking the same condition inside it.
Make sure if you're simply using Parse that you wrap it in a try...catch, because your user could type in anything (not just numbers). Personally I usually use TryParse instead.
Finally, make sure you're comparing to the correct variable. Checking that i < 100 will keep looping until 100 numbers have been entered; you want to compare the user's input instead.
namespace Wip
{
class Program
{
static void Main(string[] args)
{
string prompt = "Please enter {0} integer between 1 and 100";
string strNum;
int num = 0;
int i = 0;
int sum =0 ;
do //ask once and repeat while 'while' condition is true
{
string pluralPrompt = i > 0 ? "another" : "an";
prompt = string.Format(prompt,pluralPrompt);
Console.WriteLine(prompt); // asks for user input
strNum = Console.ReadLine();
if (!Int32.TryParse(strNum, out num)) //input is stored as num
{
// warn the user, throw an exception, etc.
}
sum += num; //add num to sum
i++;
}
while (num < 100);
Console.WriteLine("No of integers entered is {0} {1}", i, sum); //output calculation
}
}
}
namespace Wip
{
class Program
{
static void Main(string[] args)
{
string strNum;
int num;
int i = 0;
int sum = 0;
do //repeat asking for user input
{
Console.WriteLine("Please enter another integer between 1 and 100"); // asks for user input
strNum = Console.ReadLine();
if (int.TryParse(strNum, out num)) //input is stored as num2
{
if (num < 101)
{
i++;
sum += num;
continue;
}
else
{
Console.WriteLine("No of integers entered is {0} {1}", i, sum); //output calculation
break;
}
}
}
while (i < 100);
}
}
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();