I am trying to make a factorial calculator in C#, but I am having difficulties taking the product of all the numbers after I have collected them into a list.
List<int> myList = new List<int>();
Console.WriteLine("My Job is to take the factorial of the number you give");
Console.WriteLine("What is the number?");
string A = Console.ReadLine();
int C = Convert.ToInt32(A);
T:
myList.Add(C);
C--;
if (C == 0) goto End;
goto T;
End:
// This is where the problem is,
// i don't know of a way to take to product of the list "myList"
//Any Ideas?
int total = myList.product();
Console.WriteLine(" = {0}", total);
Console.ReadLine();
You don't need a list to do a factorial:
Console.WriteLine("My Job is to take the factorial of the number you give");
Console.WriteLine("What is the number?");
int c = Convert.ToInt32(Console.ReadLine());
int total = 1;
for (int i = 2; i < c; i++)
{
total *= i;
}
Console.WriteLine(total.ToString());
Console.ReadLine();
There doesn't seem to be much benefit in adding all the numbers to a list unless you need that for something.
As an alternative, something like this should work:
// set product to the number, then multiply it by every number down to 1.
private int GetFactorial(int number)
{
int product = number;
for (var num = number - 1; num > 0; num--)
{
product *= num;
}
return product;
}
Related
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.
I am trying to create a bowling program that when you enter in your name followed by your score, it will take the average, lowest, and highest scores of the players and print them. However for some reason I cannot get the lowest score to print, as when I hit enter twice, it will use the blank value instead of the lowest entered value and name. How can I fix this so that it will display the lowest score?
{
class Program
{
static void Main(string[] args)
{
const int SIZE = 10;
int i;
// create an array with 10 elements
string[] scoreInfo = new string[SIZE];
string[] names = new string[SIZE];
int[] scores = new int[SIZE];
for (i = 0; i < SIZE; i++)
{
// Prompt the user
Console.Write("Enter your first name and score on one line");
Console.WriteLine(" separated by a space.");
// Read one line of data from the file and save it in inputStr
string inputStr = Console.ReadLine( );
// if statement to break when the user enters a zero
if (inputStr == String.Empty)
{
break;
}
// The Split method creates an array of two strings
scoreInfo = inputStr.Split();
// Parse each element of the array into the correct data type
names[i] = scoreInfo[0];
scores[i] = int.Parse(scoreInfo[1]);
}
Console.WriteLine("The avarage score is {0}", AverageScore(scores, i));
Console.WriteLine("{0} scored the lowest at {1}", names[LowScore(scores, i--)], scores[LowScore(scores, i--)]);
Console.WriteLine("{0} scored the highest at {1}", names[HighScore(scores)], scores[HighScore(scores)]);
Console.ReadLine();
Console.ReadLine();
}
static int LowScore(int[] scores, int j)
{
int min = scores.Min();
return Array.IndexOf(scores, min);
}
static int HighScore(int[] scores)
{
int max = scores.Max();
return Array.IndexOf(scores, max);
}
static double AverageScore(int[] numbers, int j)
{
double average = 0;
for (int i = 0; i < j--; i++)
{
int product = 1;
product = numbers[i] * product;
average = product / j;
}
return average;
}
}
}
Use a different data structure and make less work for yourself.
Start with a dictionary that maps names to scores so that you don't have to mess around with indexes.
Then, LINQ is your friend, as you've already noticed. You don't need to create functions for things that already exist (like min/max/average).
eg.
Dictionary<string, int> ranking = new Dictionary<string, int>();
ranking.Add("adam", 20);
ranking.Add("bill", 10);
ranking.Add("carl", 30);
double avg = ranking.Average(kvp => (double)kvp.Value);
var sorted = ranking.OrderBy(kvp => kvp.Value);
var min = sorted.First();
var max = sorted.Last();
Console.WriteLine("Average: {0}", avg);
Console.WriteLine("Lowest: {0} with {1}", min.Key, min.Value);
Console.WriteLine("Highest: {0} with {1}", max.Key, max.Value);
Modify your Average function like this:-
static double AverageScore(int[] numbers, int j)
{
double sum = 0;
for (int i = 0; i < j; i++)
{
sum += numbers[i];
}
return (double)sum / j;
}
I am not sure why you were taking product of items for finding average of scores.
And Your Min function like this:-
static int LowScore(int[] scores, int j)
{
int min = scores.Where((v, i) => i < j).Min();
return Array.IndexOf(scores, min);
}
Here, you are passing the complete array of integer, so if only 3 players entered values, rest of the values will be initialized to default, i.e. 0 for int, Thus you were getting 0 as Min value.
Also, You need to change the method invocation like this:-
Console.WriteLine("{0} scored the lowest at {1}", names[LowScore(scores, i)], scores[LowScore(scores, i)]);
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.
I'm new to C#, well, coding in general.
I have done fairly well by myself to date, in this introduction course I am taking, but I ran into a road bump.
I am trying to figure out how to code a if statement that will run inside a loop to analyze 5 different ints as they are entered and to put the max int and min int seperatly so that I can ue the remaining three ints to make a calculation.
To be exact, validate user input and remove the min/max user input to average the remaining three.
PS, I tried an array but for some reason it wasn't working well. I don't have the code as I'm at work right now though. I was told in a lecture that an if statement should be used but arrays are possible too.
Thank you for your time and any possible answers.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string userIsFinished = "";
string name, city, value;
double rating, avg = 0;
double[] array1 = new double[5];
double max = 0;
double min = double.MaxValue;
double score, totalScore = 0;
//get basic information
do
{
Console.WriteLine("Please enter divers name.");
name = Console.ReadLine();
Console.WriteLine("Please enter the divers city.");
city = Console.ReadLine();
//get and validate user input for 1 dive rating
Console.WriteLine("Please enter a dive rating between 1.00 and 1.67.");
rating = Double.Parse(Console.ReadLine());
while (rating < 1 || rating > 1.69)
{
Console.WriteLine("Oops, you entered an invalid number. Please, enter a dive rating between 1.00 and 1.67.");
rating = Double.Parse(Console.ReadLine());
}
Console.ReadLine();
// get and validate user input for 5 judge scores
for (int s = 1; s <= 5; s++)
{
Console.WriteLine("Please enter the score for judge {0}.", s);
value = Console.ReadLine();
score = Convert.ToDouble(value);
while (score < 0 || score > 10)
{
Console.WriteLine("Invalid entry, please enter a number in between 0 - 10.");
score = Convert.ToDouble(Console.ReadLine());
}
array1[s] = Convert.ToDouble(score); //----this line keeps throwing an exception
}
Console.ReadLine();
//calculate totalScore by dropping min/max scores and averaging them times dive rating
foreach (int i in array1)
{
if (i > max)
max = i;
if (i < min)
min = i;
avg += i;
}
totalScore = avg * rating;
//Print gathered and calculated information
Console.WriteLine("Divers name: {0}", name);
Console.WriteLine("Divers city: {0}", city);
Console.WriteLine("Dive degree of difficulty: {0}", rating);
Console.WriteLine("Total dive score is: {0}", totalScore);
// Ask if user wants to process another diver and continue or exit program
Console.WriteLine("Would you like to enter another divers information? [Y]es [N]o: ");
userIsFinished = Console.ReadLine();
}
while
(userIsFinished.ToLower() != "n");
Console.ReadLine();
}
}
}
or you can go list route and
List<int> apples = new List<int>();
apples.Add(31);
apples.Add(34);
apples.Add(100);
apples.Add(57);
apples.Add(1);
int min = apples.Min();
int max = apples.Max();
apples.Remove(min);
apples.Remove(max);
decimal average = (decimal)(apples.Sum()) / apples.Count;
Not sure about your question... You want to know, the max and min about 5 values, and the avarage about the three others...
int[] n = { 4, 7, 29, 3, 87 };
int max = 0;
int min = int.MaxValue;
double avg = 0;
foreach (int i in n)
{
if (i > max)
max = i;
if (i < min)
min = i;
avg += i;
}
avg = avg / n.Count - 2;
try this code:
int[] a = new int[5];
int minpos;
int maxpos;
int min = Int32.MaxValue;
int max = a[0];
int temp = 0;
for (int i = 0; i < 5; i++)
{
Console.WriteLine(" Enter number " + (i + 1));
Int32.TryParse(Console.ReadLine(), out temp);
a[i] = temp;
//Decision Making Logic
if (min > temp)
{
min = temp;
minpos = i;
}
if (max < temp)
{
max = temp;
maxpos = i;
}
}
//At the end of this loop you will see that minpos contains the index of minimum element
//and maxpos contains index of maximum element,values in remaining indeces contain elements that are neither max or min in that //collection
Thanks guys, it appears I needed a good night of sleep. Thanks a ton for all these helpful answers as I'm sure I will be delving into those methods soon and it will be good to be able to get a head start on them. Here is my code,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string userIsFinished = "";
string name, city;
double rating, avg = 0;
double max = 0;
double min = 10;
double score, value = 0, totalScore = 0, finalScore = 0;
//get basic information
do
{
Console.WriteLine("\n");
Console.WriteLine("Please enter divers name.");
name = Console.ReadLine();
Console.WriteLine("Please enter the divers city.");
city = Console.ReadLine();
//get and validate user input for 1 dive rating
Console.WriteLine("Please enter a dive rating between 1.00 and 1.67.");
rating = Double.Parse(Console.ReadLine());
while (rating < 1 || rating > 1.69)
{
Console.WriteLine("Oops, you entered an invalid number. Please, enter a dive rating between 1.00 and 1.67.");
rating = Double.Parse(Console.ReadLine());
}
Console.ReadLine();
// get and validate user input for 5 judge scores
for (int s = 1; s <= 5; s++)
{
Console.WriteLine("Please enter the score for judge {0}.", s);
score = Convert.ToDouble(Console.ReadLine());
while (score < 0 || score > 10)
{
Console.WriteLine("Invalid entry, please enter a number in between 0 - 10.");
score = Convert.ToDouble(Console.ReadLine());
}
if (score > max)
max = score;
if (score < min)
min = score;
totalScore = score + totalScore;
}
Console.ReadLine();
\\Calculate values
value = totalScore - max - min;
avg = value / 3;
finalScore = avg * rating;
//Print gathered and calculated information
Console.WriteLine("Divers name: {0}", name);
Console.WriteLine("Divers city: {0}", city);
Console.WriteLine("Dive degree of difficulty: {0}", rating);
Console.WriteLine("Total dive score is: {0}", finalScore);
Console.WriteLine("\n");
// Ask if user wants to process another diver and continue or exit program
Console.WriteLine("Would you like to enter another divers information? [Y]es [N]o: ");
userIsFinished = Console.ReadLine();
}
while
(userIsFinished.ToLower() != "n");
Console.ReadLine();
Console.WriteLine("\n");
}
}
}