I'm curious to know how you would convert the following into a while loop. I know it doesn't make the most sense in this situation but I am working out of a student workbook and would like to see another example. Thanks in advance, any help is much appreciated.
int sides = 0;
int number = 0;
int total = 0;
Random random = new Random();
Console.WriteLine("Choose the number of sides.");
sides = int.Parse(Console.ReadLine());
Console.WriteLine("Choose number of dice.");
number = int.Parse(Console.ReadLine());
for (int i = 0; i < number; i++)
{
int die = random.Next(1, sides);
Console.WriteLine("You Rolled {0}", die.ToString());d
total += die;
}
Console.WriteLine("Your total is {0}", total);
Console.ReadLine();
int i = 0;
while(i < number)
{
int die = random.Next(1, sides);
Console.WriteLine("You Rolled {0}", die.ToString());
total += die;
i++
}
You want to convert a for-loop to a while-loop if I understand correctly.
int currentNum = 0;
while (currentNum < number)
{
int die = random.Next(1, sides);
Console.WriteLine("You Rolled {0}", die.ToString());
total += die;
currentNum++;
}
Related
static void Main(string[] args)
{
string again;
do
{
Console.Write("Enter size to compute: ");
int size = Convert.ToInt32(Console.ReadLine());
int[] numbers = new int[size];
float[] numberS = new float[size];
Console.Write("Pick one of the operation \"(+) (-) (*) (/)\": ");
string operation = Console.ReadLine();
if (operation == "+")
{
for (int i = 0; i < size; i++)
{
Console.Write("Enter numbers: ");
numbers[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The sum is:" + add(numbers));
}
else if (operation == "-")
{
for (int i = 0; i < size; i++)
{
Console.Write("Enter numbers: ");
numbers[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The subtraction is:" + subtract(numbers));
}
else if (operation == "*")
{
for (int i = 0; i < size; i++)
{
Console.Write("Enter numbers: ");
numbers[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The mulplication is:" + multiply(numbers));
}
else if (operation == "/")
{
for (int i = 0; i < size; i++)
{
Console.Write("Enter numbers: ");
numberS[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The division is:" + division(numberS));
}
else Console.WriteLine("Invalid Input");
Console.Write("Do you want to compute again Y/N: ");
again = Console.ReadLine().ToUpper();
Console.Clear();
} while (again == "Y");
}
static int add(int[] numbers)
{
int total = 0;
for (int i = 0; i < numbers.Length; i++)
{
total += numbers[i];
}
return total;
}
static int subtract(int[] numbers)
{
int total = 0;
for (int i = 0; i < numbers.Length; i++)
{
total += numbers[i] - numbers[i];
}
return total;
}
static int multiply(int[] numbers)
{
int total = 0;
for (int i = 0; i < numbers.Length; i++)
{
total += numbers[i] * numbers[i];
}
return total;
}
static float division(float[] numbers)
{
float total = 0;
for (int i = 0; i < numbers.Length; i++)
{
total += numbers[i] / numbers[i];
}
return total;
}
I was expecting the same results in my phones calculator but no
Your code itself is fine. However your subtract, multiply and division methods are wrong. They are calculating something totally different than intended.
The multiply-method sums the squares of the entered numbers.
The subtract-method always subtracts the current number of itself which equals 0 and always results with a total of 0.
The division method always divides the current number by itself which is 1 and results with a total which equals the number of numbers entered.
Try these methods instead:
static int subtract(int[] numbers)
{
if (numbers.Length == 0)
return 0;
int total = numbers[0];
for (int i = 1; i < numbers.Length; i++)
{
total -= numbers[i];
}
return total;
}
static int multiply(int[] numbers)
{
if (numbers.Length == 0)
return 0;
int total = numbers[0];
for (int i = 1; i < numbers.Length; i++)
{
total *= numbers[i];
}
return total;
}
static float division(float[] numbers)
{
if (numbers.Length == 0)
return 0;
float total = numbers[0];
for (int i = 1; i < numbers.Length; i++)
{
total /= numbers[i];
}
return total;
}
In all of these methods the program first checks if there are any numbers passed. Otherwise it just returns 0.
If there are any numbers you set the first entered number to the total variable because it will be used anyway. The temporary result is always stored in the total variable.
Because the first element is already used the for-loop starts from index 1 instead of 0.
Then the operations are applied to the variable with all remaining numbers.
I am beginner in C# coding, and I am trying to write some code for the program where my program will show the average of numbers given by users. I have written below code, but I am thinking this would be more better and efficient. Can anyone please help me. Thanks in advance.
static void Main(string[] args)
{
int a=0;
double total = 0;
double result;
Console.Write("For how many numbers you want to do the average calculation: ");
a = int.Parse(Console.ReadLine());
double[] array = new double[a];
for (int j = 0; j < a; j++)
{
Console.Write("Please enter value for {0}: ", j+1);
array[j]= double.Parse(Console.ReadLine());
}
foreach (var item in array)
{
total += item;
}
result = total / a;
Console.WriteLine($"Your Calculated average value is {result}");
Console.ReadKey();
}
You dont need to take extra array for your purpose, you can do this just by adding each input value and then divide that total with total number of input items.
double total = 0;
double result;
Console.Write("For how many numbers you want to do the average calculation: ");
int a = int.Parse(Console.ReadLine());
for (int j = 0; j < a; j++)
{
Console.Write("Please enter value for {0}: ", j + 1);
total += double.Parse(Console.ReadLine());
}
result = total / a;
Console.WriteLine($"Your Calculated average value is {result}");
Console.ReadKey();
Basically I'm writing a method where I want to find the summation of whole numbers with a for loop.
The output should be something like this:
Enter value of number 1: 23
Enter value of number 2: 23
Enter value of number 3: 23
The sum is: 69
The user will be able choose of many numbers to be added.
My code currently looks like this:
private void ReadInput()
{
Console.Write("Number of values to sum?");
numOfInput = int.Parse(Console.ReadLine());
Console.WriteLine();
}
private void ReadInput()
{
Console.Write("Number of values to sum?");
numOfInput = int.Parse(Console.ReadLine());
Console.WriteLine();
}
private void SumNumbers()
{
int index;
int num = 0;
for (index = 0; index < numOfInput; index++)
{
Console.WriteLine("Please give the value of no " + index);
num = int.Parse(Console.ReadLine());
}
}
how should I fix it
private void SumNumbers()
{
int index;
int num = 0;
for (index = 0; index < numOfInput; index++)
{
Console.WriteLine("Please give the value of no <whole numbers> " + index);
num += int.Parse(Console.ReadLine());
num = sum;
}
}
private void ShowResults()
{
Console.WriteLine("----------------------------------------------\n");
Console.WriteLine("The sum is \t{0}", sum);
Seems to be the solution + the classes above it are still used but yes.
Thank y'all very much
Try this,
private static void SumNumbers()
{
int numOfInput = 3;
int index;
int num = 0;
for (index = 1; index <= numOfInput; index++)
{
Console.WriteLine("Please give the value of no " + index);
num += int.Parse(Console.ReadLine());
}
Console.WriteLine("The sum is:" + num.ToString());
Console.ReadLine(); // to keep console alive
}
Hope helps,
private void SumNumbers()
{
int index;
int num = 0;
for (index = 0; index < numOfInput; index++)
{
Console.WriteLine("Please give the value of no " + index);
num += int.Parse(Console.ReadLine());
Console.WriteLine("The sum so far is : "+num.ToString("N0")+". Enter another number to continue summation.");
}
Console.WriteLine("Maximum input received. Total is: "+num.ToString("N0")+".");
Console.ReadLine();
}
This will work as per your need:
int index;
int num = 0;
Console.WriteLine("Number of values to sum: ");
int numOfInput = int.Parse(Console.ReadLine());
for (index = 1; index <= numOfInput; index++)
{
Console.WriteLine("Please give the value of no " + index);
num += int.Parse(Console.ReadLine());
}
Console.WriteLine("The sum is: " + num);
The following output will be generated:
Number of values to sum: 3
Please give the value of no 1
23
Please give the value of no 2
23
Please give the value of no 3
23
The sum is: 69
What calculations do I need to find the total?
else if (a =2) {
TotalCredit = new int[15];
Console.WriteLine("please enter the credits");
int i = 0;
for (i = 0; i < 15; i++) {
int Credit = Convert.ToInt32(Console.ReadLine());
Total + Credit;
}
Console.WriteLine(Total);
}
You need to declare the variable Total ahead it use and it should be before loop to keep its scope available after loop. More than that your sum operation should be corrected using += operator
Correct it as follows:
int Total=0;
for (i = 0; i < 15; i++)
{
int Credit = Convert.ToInt32(Console.ReadLine());
Total += Credit;
}
Console.WriteLine(Total);
Try this.
else if (a ==2)
{
int[] TotalCredit = new int[15];
Console.WriteLine("please enter the credits");
int i = 0;
int Total = 0;
for (i = 0; i < 15; i++)
{
int Credit = Convert.ToInt32(Console.ReadLine());
Total += Credit;
}
Console.WriteLine(Total);
}
I've added this line int Total = 0; to declare a variable Total with the value 0, to store the total there.
Then I've changed a line in the for to be Total += Credit; which is the same as Total = Total + Credit; so every new value will be added and store into the variable Total.
This is a C# I guess, as convention https://msdn.microsoft.com/en-us/library/ff926074.aspx you'd better declare the variables to be lowercase.
As you have declared an array of ints I'm going to assume you want to keep the actual values the user has entered and not just the total. Make sure you add System.Linq in your using clauses.
else if (a==2)
{
var totalCredit = new int[15];
Console.WriteLine("please enter the credits");
for (int i = 0; i < 15; i++)
totalCredit[i] = Convert.ToInt32(Console.ReadLine());
var total = totalCredit.Sum();
Console.WriteLine (total);
}
A good idea would be to validate input gracefully, and minimize duplication of the magic constant 15—even better would be to assign it a meaningful name (the same goes for the a variable). Also, if you intend to store each input into the array for later usage outside of the else if block, you'll need to declare it outside of said block. However, if you do not need the individual credit values, the array is unnecessary.
const int numberOfCredits = 15;
int[] credits = new int[numberOfCredits];
...
else if (a == 2)
{
int total = 0;
int count = 0;
while (count < numberOfCredits)
{
Console.WriteLine("Enter credit #" + (count + 1).ToString() + ":");
int input;
if (int.TryParse(Console.ReadLine(), out input))
{
credits[count] = input;
total += input;
count += 1;
}
}
Console.WriteLine(total);
}
Hi guys so i'm starting to learn C# and I came up with this problem when I was trying to mix things up
It says "Input string was not in correct format" at the
n = Convert.ToInt32(Console.ReadLine());
Here's the whole code
namespace Exercise13
{
class Program
{
static void Main(string[] args)
{
char choice;
Console.Write("What operation would you like to use?");
Console.WriteLine("\na. Addition \tb. Subtraction \tc.Multiplication \td.Division");
choice = (char)Console.Read();
if (choice == 'a')
{
sumValues();
}
else if (choice == 'b')
{
minusValues();
}
else if (choice == 'c')
{
timesValues();
}
Console.ReadLine();
}
static void sumValues()
{
int n = 0;
int sum = 0;
int i = 0,val = 0;
Console.Write("How many numbers do you want calculate: ");
n = Convert.ToInt32(Console.ReadLine());
for (i = 0; i < n; i++)
{
Console.Write("\nInput number: ");
val = Convert.ToInt32(Console.ReadLine());
sum += val;
}
Console.Write("\nThe Answer is: "+sum);
}
static void minusValues()
{
int diff = 0, m, z, value;
Console.Write("How many numbers do you want calculate: ");
m = int.Parse(Console.ReadLine());
for (z = 0; z < m; z++)
{
Console.Write("\nInput number: ");
value = int.Parse(Console.ReadLine());
diff -= value;
}
Console.Write("\nThe Answer is: " + diff);
}
static void timesValues()
{
int prod = 0, e, i, val;
Console.Write("How many numbers do you want to calculate: ");
e = Convert.ToInt32(Console.ReadLine());
for (i = 0; i < e; i++)
{
Console.Write("\nInput number: ");
val = int.Parse(Console.ReadLine());
prod *= val;
}
Console.Write("\nThe answer is: " + prod);
}
}
}
Use Integer.TryParse to handle the strings potentially not being numbers. Then prompt the user if the input is not parsable to enter valid input.
Convert and Parse both will throw exceptions if the string is not an exact number.
https://msdn.microsoft.com/en-us/library/f02979c7%28v=vs.110%29.aspx
int n = 0;
int sum = 0;
int i = 0,val = 0;
Console.Write("How many numbers do you want calculate: ");
var isValidNumber = Int32.TryParse(Console.ReadLine(), out n);
if(!isValidNumber) {
Console.WriteLine("Invalid number entered!");
}
else {
//Use the number
}