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();
Related
I'm trying to get a list with random numbers with my decision
when I start the application I get to decide which number I want it to insert/count but insert doesn't do anything, I know that am missing something coding with the number generator but I just can't find out what it is.
So basically i want it to show this if i typed 5
Random Number
Random Number
Random Number
Random Number
Random Number
then if i typed 3 i want it to show me how many three's are there.
for now I made this code:
Console.Write("insert number to decide: ");
int numbers = Convert.ToInt32(Console.ReadLine());
Console.Write("Number to count: ");
int yoy = Convert.ToInt32(Console.ReadLine());
Random random = new Random();
numbers = random.Next(0, 10);
var number = numbers;
var count = 0;
var digit = yoy;
var n = number;
while (n > 0)
{
if (n % 10 == digit)
count++;
n = n / 10;
}
Console.WriteLine($"Number: {number}");
Console.WriteLine(
$"Digit {digit} appears {count} times.");
Console.ReadKey();
Let me try to explain your code
Console.Write("insert number to decide: ");
int numbers = Convert.ToInt32(Console.ReadLine());
Console.Write("Number to count: ");
int yoy = Convert.ToInt32(Console.ReadLine());
Random random = new Random();
numbers = random.Next(0, 10); // You are overwriting user input here from line 2.
var number = numbers; // Redundant duplicate variable.
var count = 0;
var digit = yoy;
var n = number;
while (n > 0)
{
if (n % 10 == digit)
count++;
n = n / 10;
}
Console.WriteLine($"Number: {number}");
Console.WriteLine(
$"Digit {digit} appears {count} times.");
Console.ReadKey();
What are you trying to achieve?
If you want to count the occurrence of a digit in a random number between 0 and the users input, then I would write this on line 6:
numbers = random.Next(0, numbers + 1);
Remove '+ 1' if users input should not be included.
UPDATE:
for your updated explanation i would write:
Console.Write("insert number to decide: ");
string userNumber = Console.ReadLine();
Console.Write("Number to count: ");
string userYoy = Console.ReadLine();
int number = 0;
int yoy = 0;
int count = 0;
bool numbersSuccess = int.TryParse(userNumber, out number);
bool yoySuccess = int.TryParse(userYoy, out yoy);
if(numberSuccess && yoySuccess)
{
Random random = new Random();
List<int> numbers = new List<int>();
for(int i = 0; 0 < number; i++)
{
int randomNumber = random.Next(0,10);
if(randomNumber == yoy)
{
count++;
}
Console.WriteLine($"Number: {randomNumber}");
}
Console.WriteLine(
$"Digit {yoy} appears {count} times.");
}
else
{
Console.WriteLine("Something went wrong, only type hole numbers!");
}
Console.ReadKey();
UPDATE #2
For an N digit long random number, you could write something like this:
Console.Write("insert number to decide: ");
string userNumber = Console.ReadLine();
Console.Write("Number to count: ");
string userYoy = Console.ReadLine();
int numberOfDigits = 0;
int yoy = 0;
int count = 0;
bool numbersSuccess = int.TryParse(userNumber, out numberOfDigits );
bool yoySuccess = int.TryParse(userYoy, out yoy);
if(numberSuccess && yoySuccess)
{
int randomMax = (int)Math.Pow(10,numberOfDigits);
Random random = new Random();
int number = random.Next(0,randomMax);
var n = number;
while (n > 0)
{
if (n % 10 == digit)
count++;
n = n / 10;
}
Console.WriteLine($"Number: {number}");
Console.WriteLine($"Digit {digit} appears {count} times.");
}
else
{
Console.WriteLine("Something went wrong, only type hole numbers!");
}
Console.ReadKey();
I want to input 10 numbers and get the total sum of them if you take out the highest and lowest number that was input. So basically it'll be 8 numbers that i get the sum of when i take out the highest and lowest number that was input out of the 10. So far i can only count the total sum out of the 10 numbers, but not sure how to take out the highest and lowest. What approach could i take?
static void Main(string[] args)
{
int number, sum = 0, n;
for (number = 1; number < 11; number++)
{
Console.WriteLine("Enter a number");
n = Convert.ToInt32(Console.ReadLine());
sum += n;
}
Points(sum);
Console.ReadLine();
}
static void Points(int sum)
{
Console.WriteLine("Totalpoint is " + sum);
}
Addition is additive, so you can simply remove them on the end:
int sum = 0;
int min = int.MaxValue;
int max = int.MinValue;
for (int i = 0; i < 10; ++i)
{
Console.WriteLine("Enter a number");
int n = Convert.ToInt32(Console.ReadLine());
sum += n;
min = Math.Min(min, n);
max = Math.Max(max, n);
}
sum -= min;
sum -= max;
Points(sum);
Console.ReadLine();
An easy implementation to explain my thought process, could be the following:
static void Main(string[] args)
{
int number, sum = 0, n;
List<int> inputNumbers = new List<int>();
for(number = 0; number < 10; number++)
{
inputNumbers.Add(Convert.ToInt32(Console.ReadLine()));
}
// Obtain maximum and minimum values
var maximum = inputNumbers.Max();
var mimimum = inputNumbers.Min();
foreach (var item in inputNumbers)
{
if(item == maximum)
{
inputNumbers.Remove(item);
break;
}
}
foreach(var item in inputNumbers)
{
if(item == mimimum)
{
inputNumbers.Remove(item);
break;
}
}
Console.WriteLine("Sum: "+inputNumbers.Sum());
Console.ReadKey();
}
The solution is rather simple, since after populating the List with the specified 10 values, you query it to obtain the minimum and maximum values.
When you know them, you can simply loop through the list and remove both the maximum and minimum (break is completely necessary after those operations).
Downside? In this simple implementation, you would be iterating through the List two times, which should definitely be optimized, even if for clean code sake.
But it might the best first step to you!
Just have two more variables to track max and min values as you read them:
min = Math.Min(min, n);
max = Math.Max(max, n);
Then, as you exit the loop, you can simply subtract those from the total sum before printing.
sum -= min + max;
You can try this:
List<int> testNum = new List<int>();
int num = 0;
int sum = 0;
try
{
// This will loop until you have 10 inputs
while(testNum.Count < 10)
{
Console.WriteLine("Enter a number:");
num = Convert.ToInt32(Console.ReadLine()); // Need to have the Try/Catch in case user doesn't input a number
testNum.Add(num);
}
// Get the min and max values (you will need System.Linq for this)
int minVal = testNum.Min();
int maxVal = testNum.Max();
// Remove the min and max values from the List
testNum.Remove(testNum.IndexOf(minVal));
testNum.Remove(testNum.IndexOf(maxVal));
// Sum the remaining values up
foreach(int n in testNum)
{
sum = sum + n;
}
return sum;
}
catch
{
throw;
}
Add the input numbers in the List and sum their values excluding min and max values
public static void Main(string[] args)
{
var list = new List<int>();
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Enter number " + i);
int num = Convert.ToInt32(Console.ReadLine());
list.Add(num); //adding the input number in list
}
Sum(list);
}
private static void Sum(List<int> list)
{
int max = list.Max();
int min = list.Min();
int sum = list.Where(x => x != max && x != min).Sum(); //taking the sum of all values exlcuding min and max
Console.WriteLine("Sum is " + sum);
}
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.
This Console Application is Supposed to Display Prices and then set it in a average format and in a Less than NUM and Higher then NUM which I am entirely confused. The total and the Average come Out to the right amount just not the lessthanfive and the higherthanaverage.
CODE:
double[] prices = new double[5];
int count = 0;
double TotalValues = 0;
double Average = 0;
string inputString;
double lessthanfive = 0;
double higherthanaverage = 0;
int x;
for (x = 0; x < prices.Length; x++)
{
count += 1;
Console.Write("Enter the price for {0}: ", count);
inputString = Console.ReadLine();
prices[x] = Convert.ToDouble(inputString);
TotalValues += prices[x];
Average = TotalValues / prices.Length;
if (prices[x] < 5)
lessthanfive++;
if (prices[x] > Average)
higherthanaverage++;
}
Console.WriteLine();
Console.WriteLine("The Sum of The Values Are: {0}", TotalValues.ToString("C2"));
Console.WriteLine("Numbers Less Than $5.00 Are: {0}", lessthanfive.ToString("C2"));
Console.WriteLine("The Average of The 20 Prices Are: {0}", Average.ToString("C2"));
Console.WriteLine("Numbers Higher then Average Are: {0}", higherthanaverage.ToString("C2"));
Console.ReadLine();
You can't know the average until after the last value has been entered, so you need another loop to count the number of items above the average:
for (x = 0; x < prices.Length; x++)
{
count += 1;
Console.Write("Enter the price for {0}: ", count);
inputString = Console.ReadLine();
prices[x] = Convert.ToDouble(inputString);
TotalValues += prices[x];
if (prices[x] < 5) {
lessthanfive++;
}
}
Average = TotalValues / prices.Length;
for (x = 0; x < prices.Length; x++)
{
if (prices[x] > Average) {
higherthanaverage++;
}
}
Your average is going to be wrong, and your counts are going to be off because of it. Calculating everything outside of that loop will keep things easy to debug, as well. Now, this isn't the most elegant solution out there, but it uses a List to leverage the built-in Sum and Average functions, as well as allowing your list to be re-sizable, in case you don't want to add 20 numbers each time.
List<decimal> prices = new List<decimal>();
int numPrices;
decimal totalPrice;
decimal averagePrice;
string inputString;
int lessThanFive = 0;
int higherThanAverage = 0;
Console.Write("Enter the number of prices that you will be entering: ");
numPrices = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < numPrices; i++)
{
Console.Write("Enter the price for item #{0}: $", i+1);
inputString = Console.ReadLine();
prices.Add(Convert.ToDecimal(inputString));
}
totalPrice = prices.Sum();
averagePrice = prices.Average();
foreach (decimal item in prices)
{
if (5 > item)
{
lessThanFive++;
}
if (averagePrice > item)
{
higherThanAverage++;
}
}
Console.WriteLine();
Console.WriteLine("The sum of the values are: {0:C}", totalPrice);
Console.WriteLine("The number of prices less than $5.00 are: {0}", lessThanFive);
Console.WriteLine("The average of the prices entered is: {0:C}", averagePrice);
Console.WriteLine("The number of prices that are higher than average are: {0}", higherThanAverage);
Console.ReadLine();
Now, I used decimal instead of double for these because, well, in this example it certainly wouldn't need a double for anything, but it could be converted back without any problems. Also added some minor string formatting, etc. The main thing is, I checked the math and it works.
The average is calculated in the wrong scope (inside the loop) and so is the higherthanaverage. To fix it:
class Program
{
static void Main(string[] args)
{
double[] prices = new double[5];
int count = 0;
double TotalValues = 0;
double Average = 0;
string inputString;
double lessthanfive = 0;
double higherthanaverage = 0;
int x;
for (x = 0; x < prices.Length; x++)
{
count += 1;
Console.Write("Enter the price for {0}: ", count);
inputString = Console.ReadLine();
prices[x] = Convert.ToDouble(inputString);
TotalValues += prices[x];
if (prices[x] < 5)
lessthanfive++;
}
Average = prices.Average();
higherthanaverage = prices.Where(price => price > Average).Count();
Console.WriteLine();
Console.WriteLine("The Sum of The Values Are: {0:C2}", TotalValues);
Console.WriteLine("Numbers Less Than $5.00 Are: {0:C2}", lessthanfive);
Console.WriteLine("The Average of The 20 Prices Are: {0:C2}", Average);
Console.WriteLine("Numbers Higher then Average Are: {0:C2}", higherthanaverage);
Console.ReadLine();
}
}
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();