Print random numbers in a range - c#

I have got this homework assignment and I have come with a solution which works, but I do not understand why when entering range from [0 to 1] the Random() function prints only zeroes. When I ad 1 to the max argument it works //rnd.Next(min, max + 1);, but why only zeroes when it is left like this: rnd.Next(min, max);
static void Main()
{
Console.Write("Please enter integer n: ");
int n = int.Parse(Console.ReadLine());
Console.Write("Please enter min integer: ");
int min = int.Parse(Console.ReadLine());
Console.Write("Please enter max integer: ");
int max = int.Parse(Console.ReadLine());
Random rnd = new Random();
for (int i = 0; i <= n; i++)
{
Console.WriteLine(rnd.Next(min, max+1));
}
}

Random.Next produces a number in the range [min, max) -- that means min is a possible result, but max is not. The only integer in the range [0, 1) is 0.

It is part of the language definition.
The maximum value is exclusive, not inclusive, so if you want max to be included, you must add 1 to it.

Related

Error while finding the largest number from a list

I'm trying to solve a problem where you add random number from the keyboard and when you type "0" it stops and shows the largest number.
This is what I did:
int max = 0;
Console.WriteLine();
String input = Console.ReadLine();
do
{
Console.WriteLine();
int n = Convert.ToInt32(Console.ReadLine());
if (n > max)
max = n;
}
while (!input.ToLower().Equals("0"));
Console.WriteLine(max);
Console.ReadLine();
I keep getting ": 'Input string was not in a correct format.'" and I don't know why. I'm not expecting any other result than an int.

How do I sum up every 5th number instead of all numbers?

I need some help with the for-loop. I'm trying to sum up every fifth number that I type in, instead it sums them all up. What do I have to change?
int count = 0;
double total = 0;
Console.Write("Enter your number: ");
int input = int.Parse(Console.ReadLine());
while (input != 0)
{
count++;
for (count = 0; count <= 0; count += 5)
{
total = total + input;
}
Console.Write("Enter your number: ");
input = int.Parse(Console.ReadLine());
}
Console.WriteLine("The sum of every +5 numbers is: {0}", total);
Console.ReadKey();
Assuming that you enter a list of numbers, and the 1st number and every five afterwards is added (so 1st, 6th, 11th, etc.):
int count = 0;
double total = 0;
Console.Write("Enter your number: ");
int input = int.Parse(Console.ReadLine());
while (input != 0)
{
count++;
if (count % 5 == 1)
total = total + input;
Console.Write("Enter your number: ");
input = int.Parse(Console.ReadLine());
}
Console.WriteLine("The sum of every +5 numbers is: {0}", total);
Console.ReadKey();
This works by using the modulo operator (%). The modulo operator returns the remainder of a division operation involving the number you specify.
In the code if (count % 5 == 1), the question is:
Is the remainder of count divided by 5 equal to 1?
If so, it adds the number. If not, it is skipped
The reason the remainder is one is because we want results 1, 6, 11, etc:
1 / 5 = remainder 1
6 / 5 = remainder 1
11 / 5 = remainder 1
If you change the modulo value to 0 it will return the results at position 5, 10, 15, etc.
You could just store the numbers in a list and calculate it at the end:
var numbers = new List<int>();
Console.Write("Enter your number: ");
var input = int.Parse(Console.ReadLine());
while (input != 0)
{
numbers.Add(input);
input = int.Parse(Console.ReadLine());
}
var total = numbers.Where((x, i) => (i + 1) % 5 == 0).Sum(); // i + 1 since indexes are 0-based.
Console.WriteLine("The sum of every +5 numbers is: {0}", total);
You can try this:
double total = 0;
int passover = 4;
int input = 0;
do
{
passover++;
Console.Write("Enter your number: ");
int.TryParse(Console.ReadLine(), out input);
if ( passover != 5 ) continue;
passover = 1;
total = total + input;
}
while ( input != 0 );
Console.WriteLine("The sum of every fifth numbers is: {0}", total);
Console.ReadKey();
I think the best way is to recover all the values ​​before making the sum, this code works:
double total = 0;
int input = -1;
List<int> allInput = new List<int>();
while (input != 0)
{
Console.Write("Enter your number: ");
input = int.Parse(Console.ReadLine());
allInput.Add(input);
}
for (int i = 0; i < allInput.Count()-1; i += 5)
{
total = total + allInput[i];
}
Console.WriteLine("The sum of every +5 numbers is: {0}", total);
Console.ReadKey();
Your sample would go forever, because there is no break point in your loop. You should always put a break point in your loop, otherwise it'll loop indefinitely.
Here is what you need :
int total = 0;
int count = 0;
Console.Write("Enter your number: ");
while (true)
{
int input = 0;
bool isNumber = int.TryParse(Console.ReadLine(), out input);
if (isNumber)
{
count++;
if (count % 5 == 0)
total += input;
}
else
{
break;
}
Console.Write("Add another number or press enter to get the sum : ");
}
Console.WriteLine("The sum of every +5 numbers is: {0}", total);
Console.ReadKey();
So, you'll need first to put the user input inside a loop, and keep asking the user for adding another number until hits the condition where you close this loop. In the example, I decided to break the loop if the user typed anything not a number. but I told the user to press enter to get the some, to end the loop. For you, you'll need to translate that to your application breakpoint, how would you want the user to get the sum ?. Then, change the condition to your logic, so it breaks the loop and gets the sum.
another point is that int.TryParse. When you want to convert strings to numbers (int, long, decimal ..etc). You should always use `TryParse, this will verify the number, if the conversion failed, it'll return false. This way you can maintain the conversion and do something about it.

How to populate a 2d array via user input?

I'm trying to create a 5,4 array in C# where each cell is made up of user data. The code I have below works sometimes, but not consistently. I can input data into cell [4,5] or [3,4] for example. However, sometimes when I run the code It does not accept the data and displays an empty cell. and Any tips?
decimal[,] departments = new decimal[4, 5];
//int count = 0;
Console.WriteLine("If you would like to run the program, type enter");
string exit = Console.ReadLine();
while (exit != "yes")
{
Console.WriteLine("What is the department number that you would like to enter sales for? Enter 9 to exit");
int departmentNo = int.Parse(Console.ReadLine());
Console.WriteLine("What day would you like to enter sales for?");
int input = int.Parse(Console.ReadLine());
Console.WriteLine("Enter sales");
departments[departmentNo, input] = decimal.Parse(Console.ReadLine());
Console.WriteLine("If you are finished, enter yes");
exit = Console.ReadLine();
}
Example output
0 0 0 0
0 0 0 0
0 0 500 0
500 0 0 0
You can use .GetUpperBound(dimension) to obtain the maximum bound (in the example below, it will return 1 for each dimension) for a specific dimension. Once you've got that, you just need to go through each position (I'm assuming you just need to fill data at each position).
Here's a sample:
int[,] items = new int[2, 2];
int width = items.GetUpperBound(0) + 1;
int height = items.GetUpperBound(1) + 1;
for (int x = 0; x < width; ++x)
{
for (int y = 0; y < height; ++y)
{
string input;
int inputValue;
do
{
Console.WriteLine($"Please input value for ({x},{y}): ");
}
while (!int.TryParse(input = Console.ReadLine(), out inputValue));
items[x, y] = inputValue;
}
}
Or if you do need the user to be able to specify where the sales value goes, you can update your code to add some validation checks:
while (exit != "yes")
{
Console.WriteLine("What is the department number that you would like to enter sales for? Enter 9 to exit");
int departmentNo = int.Parse(Console.ReadLine());
if (departmentNo > departments.GetUpperBound(0) || departmentNo < 0)
{
Console.WriteLine("Please enter a valid department number.");
continue;
}
Console.WriteLine("What day would you like to enter sales for?");
int input = int.Parse(Console.ReadLine());
if (input > departments.GetUpperBound(1) || input < 0)
{
Console.WriteLine("Please enter a valid input.");
continue;
}
Console.WriteLine("Enter sales");
if (!decimal.TryParse(Console.ReadLine(), out decimal value))
{
Console.WriteLine("Please enter a valid sales figure.");
continue;
}
departments[departmentNo, input] = value;
Console.WriteLine("If you are finished, enter yes");
exit = Console.ReadLine();
}
You probably want to change it to be similar to my example above so that you don't have to restart the entire loop again if the input is bad.
Because the departments has a fixed length of [4,5], it means the departmentNo can only be in range 0-3 and the input can only be in range 0-4. In addition, decimal keyword indicates a 128-bit data type, it's mean the value for a cell is in range ±1.0 x 10^28 to ±7.9228 x 10^28, which means 28-29 significant digits approximately. You should make some if conditions to make sure input values are in available range.

C# programming-code for sum of digits and reverse number

I wrote a code to find the sum of the digits and the reverse of a number-
static void Main(string[] args)
{
int number, sum = 0;
Console.WriteLine("Enter a number:");
number = int.Parse(Console.ReadLine());
while (number!= 0)
{
int m = number % 10;
number = number / 10;
sum = sum + m;
}
Console.WriteLine("Sum of digits of the number:" + sum);
Console.ReadLine();
int reverse = 0;
while (number!= 0)
{
reverse = reverse * 10;
reverse = reverse + number % 10;
number = number / 10;
}
Console.WriteLine("Reversed Number is:" + reverse);
Console.ReadLine();
}
but, the output for reversed number comes as 0. I checked my code, and I am not sure what is wrong with it.
You modify number as you sum the digits so when you try to go through the second loop, number is already at 0. Save off the input and reset number before the second loop:
Console.WriteLine("Enter a number:");
int input = int.Parse(Console.ReadLine());
number = input;
while (number!= 0)
{
// ...
}
Console.WriteLine("Sum of digits of the number:" + sum);
number = input; // reset number back to original input
// ...
There's also a possible solution to the problem using LINQ:
int number = 1234567890;
int sumOfDigits = number.ToString().Select(c => int.Parse(c.ToString())).Sum();
int reversedNumber = int.Parse(new string(number.ToString().Reverse().ToArray()));
Console.WriteLine($"sum of digits: {sumOfDigits}");
Console.WriteLine($"reversed number: {reversedNumber}");

C# - displaying the max, min, and average

I am new to C#. I have been working on this program and researching but am not getting anywhere. The goal is to have the user enter numbers (how many is up to the user). when they enter a 0, it will stop the program and display the minimum number entered, the maximum number entered, and the average of all numbers entered. I am not getting any errors and I am getting. If someone can please point me in the right direction.
The WriteLines are returning:
Lowest number is 0
Highest number is 0
Average is: 0
Count: 5
Here is my code:
int LOWEST =0;
int HIGHEST=0;
const int STOP = 0;
double average = 0;
int input;
int count = 0;
Console.WriteLine("Enter a number. You can end the program at anytime by entering 0");
input = Convert.ToInt32(Console.ReadLine());
while (input != STOP)
{
for (int i=0; input != STOP; i++)
{
Console.WriteLine("Enter a number. You can end the program at anytime by entering 0");
input = Convert.ToInt32(Console.ReadLine());
count++;
var Out = new int[] { input };
LOWEST = Out.Min();
HIGHEST = Out.Max();
average = Out.Average();
if ((input > LOWEST) || (input < HIGHEST))
{
LOWEST = Out.Min();
}
if (input > HIGHEST)
{
HIGHEST = Out.Max();
}
}
}
Console.WriteLine("Lowest number is {0}", LOWEST);
Console.WriteLine("Highest number is {0}", HIGHEST);
Console.WriteLine("Average is {0}", average);
Console.WriteLine("Count: {0}", count);
Console.ReadLine();
On each run you are constructing a new array of integers:
var Out = new int[] { input };
After this line, Out contains one item: the last input. Calling Min, Max and Average on it will return the last value. Which is zero if you ended the program.
instead of creating a new array each time, you want to create a List<int> at the beginning of your program and then add each input to it. You can then use the whole list of values to calculate Min, Max and Average.
Eventually you can change your code into something like this:
const int STOP = 0;
int input = -1;
List<int> Out = new List<int>();
while (input != STOP)
{
Console.WriteLine("Enter a number. You can end the program at anytime by entering 0");
input = Convert.ToInt32(Console.ReadLine());
if (input == STOP) break;
Out.Add(input);
}
Console.WriteLine("Lowest number is {0}", Out.Min());
Console.WriteLine("Highest number is {0}", Out.Max());
Console.WriteLine("Average is {0}", Out.Average());
Console.WriteLine("Count: {0}", Out.Count);
Console.ReadLine();
List<int> numbers = new List<int>();
numbers.Add(10);
numbers.Add(30);
numbers.Add(20);
numbers.Add(0);
numbers.Max();
numbers.Min();
numbers.Average();
returns 30, 0 and 15.
Before your loop, you should probably make Out an extensible data structure analogous to an array, the List.
List<int> Out = new List<int>();
then each loop, you can
Out.Add(input);
Since this sounds like an exercise for the reader, you can then traverse your list and compute the average from all data values.
Alternately, before the loop, you could declare
int n = 0;
int total = 0;
and each loop, do
n += 1;
total += input;
From these, you should be easily able to compute the average.

Categories