//Ask user how many woodchucks to simulate
while(!validNumber)
{
Write("How many woodchucks would you like to simulate? (1 - 100) ");
int.TryParse(ReadLine(), out woodchuckSim);
if((woodchuckSim <= 0) || (woodchuckSim > 100))
{
WriteLine("\nPlease enter a correct amount of woodchucks to simulate: ");
}
if((woodchuckSim >= 1) && (woodchuckSim <= 100))
{
validNumber = true;
}
}
//Ask user how many days to simulate
while(!validDays)
{
Write("\nHow many days would you like to simulate? (1 - 10) ");
int.TryParse(ReadLine(), out numOfDays);
if((numOfDays <= 0) || (numOfDays > 10))
{
WriteLine("Please enter a positive whole number between 1 and 10: ");
}
if((numOfDays >= 1) && (numOfDays <= 10))
{
validDays = true;
}
}
//Using random class populate each cell between 1 and 50 that represents # of pieces of wood chucked by specific woodchuck on that specific day
int[,] sim = new int[woodchuckSim, numOfDays];
WriteLine($"{woodchuckSim} {numOfDays}");
for (int i = 0; i < sim.Length; i++)
{
for (int j = 0; j < sim.Length; j++)
{
sim[i, j] = ran1.Next(1, 50);
WriteLine(sim[i, j]);
}
}
WriteLine("Press any key to continue...");
ReadLine();
So this is my code so far, and I keep getting a "Index was outside the bounds of the array" error and I'm basically trying to ask the user to input the numbers of woodchucks and the number of days then populate the 2d array with random numbers. Any help will be really appreciated, and btw I am a beginner in programming. Thanks!
As Quercus already said, Length property refers to overall size of the array and array.GetLength(index) should be used instead.
Moreover, since you are a beginner in programming as you mentioned, I would like to tell you as an advice that it would be better to use if-else statement in this case:
if((woodchuckSim <= 0) || (woodchuckSim > 100)) {
WriteLine("\nPlease enter a correct amount of woodchucks to simulate: ");
} else {
validNumber = true;
}
If-else statement is pretty basic but important concept in programming and since your if hypotheses are mutual exclusive you can use it here for a nicer code.
You have incorrect cycle bounds. sim.Length is an overall size of array, which is woodchuckSim * numOfDays.
To get size of each dimension use sim.GetLength(0) and sim.GetLength(1) respectively.
Length is the size of the first dimension of the array - the number of Woodchucks in your case. For the size of the other dimensions, you could use GetLength(index):
for (int i = 0; i < sim.GetLength(0); i++)
{
for (int j = 0; j < sim.GetLength(1); j++)
{
sim[i, j] = ran1.Next(1, 50);
WriteLine(sim[i, j]);
}
}
Related
Good day
I have have this assignment at school about a factious company that measures covid-19 temperatures. We are asked to design a c# program that will perform tasks with the stats.
The array of collected temperatures from 50 people:
double[] temperatures = new double[50] {36.7, 36.5, 36.6, 36.9, 37.0, 36.2, 36.4, 36.8, 37.2, 37.4,
36.2, 36.6, 36.7, 36.9, 36.8, 36.7, 36.5, 37.0, 36.3, 36.7,
37.6, 37.1, 37.8, 38.2, 36.7, 36.8, 36.5, 36.8, 37.1, 37.9,
36.0, 35.5, 36.8, 36.9, 37.0, 37.8, 36.4, 36.8, 36.7, 36.1,
37.2, 37.1, 38.5, 37.4, 37.9, 38.0, 35.9, 37.0, 36.7, 36.5};
Body Temperature Categories and Body Temperature Ranges (in Celsius)
Cold: Lower than 36.5 - Normal: From 36.5 to 37.4 - Hot: Higher than 37.4
Problem: find out how many element in the Array fall under 'normal' body temperature.
The required method to solve the problem is 'counter controlled for loop'.
Thanks in advance!
double normalTemp = temperatures[0];
double hotTemp = temperatures[0];
double coldTemp = temperatures[0];
for (double index = 0; index < temperatures.Length; index++)
{
if (index >= 36.5 && normalTemp <= 37.4)
{
normalTemp = index;
}
}
Console.WriteLine("Number of Normal Temperatures: {0}", normalTemp);
This is what I've tried, cant seem to find a way
You are not checking the temperature itself, but checking on the index of the array instead and in your declaration of the double normalTemp = temperatures[0]; you are assigning the first value in the array which is incorrect.
int normalTemp = 0;
for (int index = 0; index < temperatures.Length; index++)
{
if (temperatures[index] >= 36.5 && temperatures[index] <= 37.4)
{
++normalTemp;
}
}
Console.WriteLine("Number of Normal Temperatures: {0}", normalTemp);
Your code has an obvious bug! You are iterating through indices of your array and then trying to use the index instead of the underlying array element which would be temperatures[index]. Also array index is an int so it's pointless to declare it as a double! So your criteria (the if block) should look like this after the fix:
if (temperatures[index] >= 36.5 && temperatures[index] <= 37.4)
{
normalTemp++;
}
int normalTemp = 0;
for (int index = 0; index < temperatures.Length; index++)
{
if (tempretures[index] >= 36.5 && tempretures[index] <= 37.4)
{
normalTemp ++;
}
}
Console.WriteLine("Number of Normal Temperatures: {0}", normalTemp);
I'm currently trying to learn C# for my university degree and I can't work out how to get my code to print out only the even numbers from 0-100 starting at the largest number i.e 100 down too 0. I have the code printing the output from smallest to largest but cannot get it to go the other way around.
Can anyone give me a hand?
This is my code:
Console.WriteLine("Print first 100 even No in reverse");
for (int i = 1; i < 100; i++)
{
if (i % 2 == 0)
{
Console.Write(i + " ");
}
}
You need to replace your code with this code:
Console.WriteLine("Print first 100 even No in reverse");
for (int i = 100; i >= 0 ; i--)
{
if (i % 2 == 0)
{
Console.Write(i + " ");
}
}
you just need to start your loop from 100 and decrease from there:
for (int i = 100; i >= 0; i--)
use ">" instead of ">=" operator, if you don't want the zero included
This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 years ago.
I'm a newbie to C# Programming and we're still starting on the loops. For our exercise today, we were tasked to create program using (while loop).
the question is :
Read 5 marks from the user, print the sum and "Passed" if the marks greater or equal to 50 or if among the marks there is only one mark less than 50.
if the user enters 2 marks less than 50 then the program should print STOP and end the program.
this is my try
unfortunately not complete and I can't do it
May you help me, please ?
int sum=0 , counter = 0, number=0 ;
while (counter < 5 || number < 50)
{
number = Convert.ToInt16(Console.ReadLine());
sum = sum + number;
counter++;
}
Console.WriteLine(sum + "\nPassed");
In the while loop you need && (and) instead of || (or).
After reading a number you can check if it's less than 50 or not and you can also count these.
So after the loop you need to check the lessCounter to decide to print Passed or STOP.
int sum = 0, counter = 0, number = 0, lessCounter = 0;
while (counter < 5 && lessCounter <= 1)
{
number = Convert.ToInt16(Console.ReadLine());
sum += number;
if (number < 50)
lessCounter++;
counter++;
}
if (lessCounter <= 1)
Console.WriteLine(sum + "\nPassed");
else
Console.WriteLine(sum + "\nSTOP");
Thank you all for all your effort and a time, special thanks to Mr.Szkup.
I was able to do it this way:
int number = 0, sum = 0, count = 0;
while (number < 5)
{
Console.Write("Input Number {0} : " , (number + 1));
int mark = Convert.ToInt16(Console.ReadLine());
if (mark < 50)
{
count++;
}
if (count == 2)
{
Console.WriteLine("\nStop\n");
break;
}
sum += mark;
number++;
}
if (count <= 1)
{
Console.WriteLine("\nsum = {0}\nPassed\n",sum);
}
This thing that I'm writing should do the following: get as an input a number, then, that many kids' names, and that many grades. Then, assign each kid a number of coins, so that if their grade is bigger, than their neighbor's, they get more coins and vice versa. What I wrote is this:
string input = Console.ReadLine();
int n = Convert.ToInt32(input);
int i = 0;
string[] names = new string[n];
for (i = 0; i < n; i++)
{
names[i] = Console.ReadLine();
}
string[] gradeText = new string[n];
int[] grades = new int[n];
for (i = 0; i < n; i++)
{
gradeText[i] = Console.ReadLine();
grades[i] = Convert.ToInt32(gradeText[i]);
}
int[] minCoins = { 1, 2, 3 };
int[] coinArray = new int[n];
for (i = 1; i < n - 2; i++)
{
if (grades[0] > grades[1])
{
coinArray[0] = 3;
}
else
{
coinArray[0] = 1;
}
if (grades[i] > grades[i + 1] && grades[i] > grades[i - 1])
{
coinArray[i] = 3;
}
if (grades[i] > grades[i + 1] || grades[i] > grades[i - 1])
{
coinArray[i] = 2;
}
if (grades[i] < grades[i + 1] && grades[i] < grades[i - 1])
{
coinArray[i] = 1;
}
if (grades[n - 1] > grades[n - 2])
{
coinArray[n - 1] = 3;
}
else
{ coinArray[n - 1] = 1; }
}
for (i = 0; i < n; i++)
{
Console.WriteLine(names[i] + " " + coinArray[i]);
}
I know my loop is hella messed up, but any tips on how to fix it would be kindly appreciated!
Others here have already suggested how to deal with index out of bounds issues. So this is slight different approach to solving your problem.
It is very easy to see this as one problem and then try to resolve it all in one place but that isn't always the best solution.
Your for loop is trying to do quite a lot. Each iteration could have many checks to make. In addition you are making checks you have previously made.
Do I have a neighbour to the left.
Do I have a neighbour to the right.
Did I get a better grade than both neighbours.
Did I get a better grade than one neighbour.
Did I lose to both neighbours.
My advice would be to break this down into two separate tasks.
1, To calculate how many neighbours each person got a higher grade than.
string[] names = new string[]{"John", "Paul", "Ringo", "George"};
int[] grades = new[] {3, 4, 3,2};
int[] winnersandloser = new int[4];
for (int i = 1; i < grades.Length; i++) //note starting at position 1 so I dont need to handle index out of bounds inside the for loop
{
if (grades[i] > grades[i - 1])
{
winnersandloser[i]++;
}
else
{
winnersandloser[i - 1]++;
}
}
In the above code you should have an array with these values: {0,2,1,0}
0 = you lost to both neighbours
1 = you beat one neighbour
2 = well done you beat both neighbours
Then using this winnersandlosers array you can calculate how many coins to give each person. I'll leave that for you to do.
Update
If you require different behaviour for the first and last in the list of people you need to add the logic to your code for allocating coins.
An array gives each value and index value, starting from 0. So 0 points to the first value in you array. George is the 4th entry in the array but as the array index starts with 0 the index value is 3, you also get this from arrayname.Length - 1
So now when looping through the array to allocate coins we can add a check for the first and last positions in the array.
//allocating coins
for (int i = 0; i < winnersandloser.Length; i++)
{
if (i == 0 || i == winnersandloser.Length - 1)
{
//allocating rules for first and last
}
else
{
//allocating rules for everyone else
}
}
One common way to approach this kind of issue is to oversize your array by as many elements as you need to look ahead/look behind. Place you real elements in the "middle"1 of this array and suitable dummy values into the elements at the start/end that don't correspond to real entries. You pick the dummy values such that the comparisons work out how you need them to (e.g. often you'll put int.MinValue in the dummy elements at the start and int.MaxValue in the dummy elements at the end).
You then just enumerate the real elements in the array, but all of your computed look aheads/look behinds still correspond to valid indexes in the array.
1Sometimes you'll have uneven look ahead/look behind requirements so it may not be the true middle. E.g. say you need to be able to look behind one element and ahead 3 elements, and you want to process 20 elements. You then create an array containing 24 entries, put dummy values at index 0, 21, 22 and 23, and populate your real elements into indexes 1 - 20.
I just barely understood how to use if statement and "for loop." In addition right now I have to do this
Sort the integer elements within the array from lowest (element 0) to highest (element 4). Do not use the preexisting Array.Sort method; code your own.
This is a homework problem and I don't even know where to start. Can somebody walk me through this?
class Program
{
static void Main(string[] args)
{
int i;
double power = 0, sum = 0;
int[] mArray = new int[5];
Console.WriteLine("Please Enter Number Between 10 and 50 \nMake sure all of your Number entered correctly \notherwise you will need to enter everything again ");
for (i = 0; i < mArray.Length; i++)
{
Console.WriteLine("Please enter your Number.");
mArray[i] = Convert.ToInt32(Console.ReadLine());
if (mArray[i] >= 50 || mArray[i] <= 10)
{
i--;
Console.WriteLine("Please enter numbers only between 10 and 50.");
}
}
for (i = 0; i < mArray.Length; i++)
{
sum = sum + (mArray[i]);
}
double mean = sum / mArray.Length;
for (i = 0; i < mArray.Length; i++)
{
power += Math.Pow((mArray[i] - mean), 2);
}
double rMean = power / (mArray.Length - 1);
Console.WriteLine("Mean {0}", mean);
Console.WriteLine("Variance {0}", rMean);
Console.WriteLine("Here is sorted numbers");
Console.ReadKey();
}
}
There are many sorting algorithms you can try like Insertion Sort
Selection Sort,
Bubble Sort,
Shell Sort,
Merge Sort,
Heap Sort,
Quick Sort,
And many Others.