Validation using loop when entering numbers in array - c#

Okay so basically i have this code where i need to enter 7 numbers from 0-37 and i dont want any other numbers to be entered, ive tried doing it with if/else statement and do/while but i cant exactly get it right, i want it to go on until u enter 7 numbers from 0-37. How can i do this?
static void Main(string[] args) {
int[] numbers = new int[7];
Console.WriteLine("Enter a number between 0-37");
for (int i = 0; i < numbers.Length; i++) {
Console.WriteLine($"Enter {i + 1} number");
numbers[i] = Convert.ToInt32(Console.ReadLine());
}
}

Just try this:
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine($"Enter {i + 1} number");
while (!int.TryParse(Console.ReadLine(), out var number) || number < 0 || number > 37)
{
Console.WriteLine($"invalid number ");
}
numbers[i] = number;
}

Try this:
static void Main(string[] args)
{
int[] numbers = new int[7];
Console.WriteLine("Enter a number between 0-37");
bool IsGoodNumber(int n) => n >= 0 && n <= 37;
for (int i = 0; i < numbers.Length; i++)
{
do
{
Console.WriteLine($"Enter {i + 1} number");
numbers[i] = Convert.ToInt32(Console.ReadLine());
} while (!IsGoodNumber(numbers[i]));
}
}
Another way would be:
static void Main(string[] args)
{
int[] numbers = new int[7];
Console.WriteLine("Enter a number between 0-37");
bool IsGoodNumber(int n) => n >= 0 && n <= 37;
for (int i = 0; i < numbers.Length; i++)
{
while(true)
{
Console.WriteLine($"Enter {i + 1} number");
numbers[i] = Convert.ToInt32(Console.ReadLine());
if (IsGoodNumber(numbers[i]))
break;
Console.WriteLine("Invalid number");
}
}
}

Related

Comparison of grades of students and Coins distributions

I'm stuck at this. I`m beginner into software development. You get a list of N students and then a list of ratings for each student. A student which has bigger rating than his neighbour from list gets more coins than both of them. For example:
Data input:
3
John
Dan
Sam
9
10
8
Data output:
John 1
Dan 3
Sam 1
My output is just the names of the students.
I wrote this code:
using System;
class Program
{
private static void Main(string[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
var numberCoins = new int[n];
string[] studentNames = new string[n];
numberCoins[0] = 1;
for (int i = 0; i < n; i++)
{
studentNames[i] = Console.ReadLine();
}
int[] grades = new int[n];
for (int i = 0; i < n; i++)
{
grades[i] = Convert.ToInt32(Console.ReadLine());
}
for (int i = 1; i < n; i++)
{
if (grades[i] > grades[i - 1])
{
numberCoins[i] = numberCoins[i - 1] + 1;
}
}
for (int i = n - 2; i >= 0; i--)
{
if (grades[i] > grades[i + 1])
{
numberCoins[i] = numberCoins[i + 1] + 1;
}
}
for (int i = 0; i < n; i++)
{
Console.WriteLine(studentNames[i], " ", numberCoins[i]);
}
Console.ReadLine();
}
}
You didn't mention if there is any pattern to give coins to the students. And if we have specific number of coins or not.
If we consider at first no one has any coins the result must be something like the following:
Please specify the number of the students:
3
Please write students' name (after each name hit the ENTER):
John
Dan
Sam
Please write students' ratings (after each rating hit the ENTER):
9
10
8
The result:
John: 0
Dan: 2
Sam: 0
I wrote a piece of code which might help you approach the functionality you want.
using System;
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Please specify the number of the students:");
int n = int.Parse(Console.ReadLine());
string[] studentNames = new string[n];
int[] studentRatings = new int[n];
int[] studentCoins = new int[n];
Console.WriteLine();
Console.WriteLine("Please write students' name (after each name hit the ENTER):");
for (int i = 0; i < n; i++)
{
studentNames[i] = Console.ReadLine() ?? string.Empty;
}
Console.WriteLine();
Console.WriteLine("Please write students' ratings (after each rating hit the ENTER):");
for (int i = 0; i < n; i++)
{
studentRatings[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine();
Console.WriteLine("The result:");
for (int i = 0; i < n; i++)
{
int coins = 1;
studentCoins[i] = 0;
if (i != 0)
if (studentRatings[i] > studentRatings[i - 1])
coins++;
if (i != n - 1)
if (studentRatings[i] > studentRatings[i + 1])
coins++;
studentCoins[i] = coins;
}
for (int i = 0; i < n; i++)
{
Console.WriteLine($"{studentNames[i]}: {studentCoins[i]}");
}
}
}

Is there a way to throw an exception when string is typed in an arrayc#?

I am new in this fascinating world of programming. I have done this array, but when I type a non integer it crashes. I have tried many ways like int.Parse(console.readLine)), tryparse(text, out int) and ConvertTo32 ,However it continues saying that "Input string was not in correct format." Thanks
using System;
namespace BubbleSort
{
class Program
{
public static void HelpME(int[] a, int t)
{
for (int j = 0; j <= a.Length - 2; j++)
{
for (int i = 0; i <= a.Length - 2; i++)
{
if (a[i] > a[i + 1])
{
t = a[i + 1];
a[i + 1] = a[i];
a[i] = t;
}
}
}
}
static void Main(string[] args)
{
int[] num = { 1, 2, 3, 4, 5 };
int[] a = new int[5];
for (int x = 0; x < 5; x++)
{
Console.WriteLine($"Input enter {num[0 + x]} of five");
a[0 + x] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The Array is : ");
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine(a[i]);
}
{
HelpME(num, 5);
}
Console.WriteLine("The Sorted Array :");
foreach (int aray in a)
{
Console.Write(aray + " ");
}
Console.ReadLine();
}
}
}
you should validate the user unput by using int.TryParse method. If the entered string can be converted to int then only it should be inserted into the array, otherwise the program should ignore that value.
static void Main(string[] args)
{
int[] num = { 1, 2, 3, 4, 5 };
int[] a = new int[5];
for (int x = 0; x < 5; x++)
{
Console.WriteLine($"Input enter {num[0 + x]} of five");
int temp = 0;
string input = Console.ReadLine();
if(int.TryParse(input, out temp))
{
a[0 + x] = Convert.ToInt32(input);
}
}
Console.WriteLine("The Array is : ");
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine(a[i]);
}
{
HelpME(num, 5);
}
Console.WriteLine("The Sorted Array :");
foreach (int aray in a)
{
Console.Write(aray + " ");
}
Console.ReadLine();
}

Storing values in an array and outputting the highest,lowest,average. Output flaw

This was a small problem the teacher gave us at school. We were asked to make a program which keeps asking the user to input test scores until he inputs -99 to stop the program. The values are stored in an array and the highest, lowest and average scores are displayed.
The problem I have with my code is that whenever I run it it always gives me a value of 0 for lowest scores even though there are no zeros in the input. Can anyone please point out the mistake in my code?
Code:
static void Main(string[] args)
{
int[] za = new int[100];
scores(za, 0);
}
public static void scores(int[] ar, int x)
{
Console.Write("Please enter homework score [0 to 100] (-99 to exit): ");
int a = Convert.ToInt16(Console.ReadLine());
if (a != -99)
{
ar[x] = a;
x++;
scores(ar, x);
}
else
{
Console.Clear();
Console.WriteLine("Homework App");
int[] arr = new int[x];
foreach (int l in arr)
{
arr[l] = ar[l];
}
int lowest = arr[0];
for (int i = 1; i < arr.Length; i++)
{
if (lowest > arr[i]) { lowest = arr[i]; }
}
int highest = arr[0];
for (int j = 1; j < arr.Length; j++)
{
if (highest < arr[j]) { highest = arr[j]; }
}
double sum = 0;
double nums = 0;
for (int k = 0; k < arr.Length; k++)
{
sum = sum + arr[k];
nums++;
}
double average = sum / nums;
Console.WriteLine("Highest Score: {0}", highest);
Console.WriteLine("Lowest Score: {0}", lowest);
Console.WriteLine("Average Score: {0}", average);
Console.ReadLine();
}
}
When you're copying items, don't use a foreach loop and then the element stored in the array as the index that you're inserting to. Instead, use a for loop with a counter variable.
You should change this:
int[] arr = new int[x];
foreach (int l in arr)
{
// You're using the wrong value for the index here.
// l represents the value of the item stored in `arr`, which is `0`
arr[l] = ar[l];
}
To this:
int[] arr = new int[x];
for (var counter = 0; counter < x; counter++)
{
arr[counter] = ar[counter];
}

do/while and if/else problems

I have to put in an extra "test score" to get an answer.
(i.e i have to enter six 5' to get 25)
I can't get the do/while & if statements to loop if there is more than one number outside the "while" range. I haven't been coding for very long, a couple weeks so try and break down the answers. Thanks for the help!
Here is my code
Console.Write("Enter the number of tests: ");
int n = int.Parse(Console.ReadLine());
int[] scores = new int[n];
Console.WriteLine("----------------------------------------");
Console.WriteLine("Please enter the test scores");
int i;
do
{
i = Convert.ToInt32(Console.ReadLine());
if (i < 0)
{
Console.WriteLine("Please enter a value greater than 0");
}
if (i > 100)
{
Console.WriteLine("Please enter a value less than 100");
}
} while (i < 0 || i > 100);
for (i = 0; i < n; i++)
{
scores[i] = int.Parse(Console.ReadLine());
}
int sum = 0;
foreach (int d in scores)
{
sum += d;
}
Console.WriteLine("The sum of all the scores is {0}",sum);
Console.ReadLine();
Put the do block that does the input validation inside the for loop:
Console.Write("Enter the number of tests: ");
int n = int.Parse(Console.ReadLine());
int[] scores = new int[n];
Console.WriteLine("----------------------------------------");
Console.WriteLine("Please enter the test scores");
for (int i = 0; i < n; i++)
{
int input = -1;
do
{
input = Convert.ToInt32(Console.ReadLine());
if (input < 0)
{
Console.WriteLine("Please enter a value greater than 0");
}
else if (input > 100)
{
Console.WriteLine("Please enter a value less than 100");
}
} while (input < 0 || input > 100);
scores[i] = input;
}
int sum = 0;
foreach (int d in scores)
{
sum += d;
}
Console.WriteLine("The sum of all the scores is {0}", sum);
Console.ReadLine();
n is the number of tests, meaning the amount of scores counter i should be the same as the amount of tests. Also prefer Convert.ToInt32 to int.Parse since it throws exceptions in case it isn't able to make the conversion.
Console.Write("Enter the number of tests: ");
int n = Convert.ToInt32(Console.ReadLine());
int sum = 0, i = 0, score = 0;
int[] scores = new int[n];
Console.WriteLine("----------------------------------------");
do {
Console.WriteLine("Please enter the test score #" + (i + 1));
score = Convert.ToInt32(Console.ReadLine());
if (score < 0) {
Console.WriteLine("Please enter a value greater or equal to 0");
}
else if (score > 100)
{
Console.WriteLine("Please enter a value less or equal to 100");
}
else {
scores[i] = score;
i++;
}
} while (i < n);
foreach (int d in scores) {
sum += d;
}
Console.WriteLine("The sum of all the scores is {0}", sum);
Console.ReadLine();
Just for the potential learning opportunity, and and not as a direct answer to your question, here is the way I would do this exercise:
Console.Write("Enter the number of tests: ");
int n = int.Parse(Console.ReadLine());
Console.WriteLine("----------------------------------------");
Console.WriteLine("Please enter the test scores");
int AskForInteger()
{
while (true)
{
if (int.TryParse(Console.ReadLine(), out int i) && i >= 0 && i <= 100)
{
return i;
}
Console.WriteLine("Please enter a value between 0 and 100 inclusive");
}
}
int[] scores =
Enumerable
.Range(0, n)
.Select(x => AskForInteger())
.ToArray();
Console.WriteLine("The sum of all the scores is {0}", scores.Sum());
Console.ReadLine();
There are two options:
a. Start at 1 rather than 0 --> for (i = 1; i < n; i++)
b. Lower the value of n by 1 --> for (i = 1; i < n-1; i++)
Good luck

Getting an error about variable not existing in current context

I have written out a program that declares an array of 10 integers, takes input from the user and puts them in the array and then accepts out parameters for the highest value, lowest value, sum of all values, and the average.
The main method displays all the stats. I don't know why, but I get the error
k does not exist in the current context - line 51 column 5
when I have previously declared it before that given line. Any help would be appreciated.
using System;
namespace IntegerStatistics
{
class Program
{
static void Main()
{
Console.Clear();
// Declaring variables
int[] userArray = FillArray();
int ArrayHighest = 0;
int ArrayLowest = 0;
int ArraySum = 0;
int ArrayAverage = 0;
Calculations(userArray, out ArrayHighest, out ArrayLowest, out ArraySum, out ArrayAverage);
Console.WriteLine("The lowest value in the array is {0}, while the highest is {1}.", ArrayLowest, ArrayHighest);
Console.WriteLine("The array has a sum of {0} and averages out to {1}.", ArraySum, ArrayAverage);
Console.ReadLine();
}
private static int[] FillArray()
{
int[] intArray = new int[10];
int numbersEntered = 0;
int intTemp = 0;
string strTemp = "";
for(int k = 0; k < 10; ++k)
{
Console.WriteLine("Enter a whole number or 999 to quit: ");
strTemp = Console.ReadLine();
while(!int.TryParse(strTemp, out intTemp))
{
Console.WriteLine("Input was not in the correct format");
Console.Write("Please enter a valid number: ");
strTemp = Console.ReadLine();
}
}
if(intTemp != 999)
{
intArray[k] = intTemp;
++numbersEntered;
}
else
{
k = 10;
}
Array.Resize(ref intArray, numbersEntered);
return intArray;
}
private static void Calculations(int[] intArray, out int Highest, out int Lowest, out int intSum, out int average)
{
intSum = 0;
Array.Sort(intArray);
Lowest = intArray[0];
Array.Reverse(intArray);
Highest = intArray[0];
Array.Reverse(intArray);
for(int k = 0; k < intArray.Length; ++k)
{
intSum += intArray[k];
}
average = intSum / intArray.Length;
}
}
}
The line I'm specifically having issues with is:
if (intTemp != 999)
{
intArray[k] = intTemp;
++numbersEntered;
}
else
{
k = 10;
}
I think you meant to place the if-else block inside the for-loop.
Since you want to check if the input number is 999 for each iteration, you could write your for-loop like this:
for(int k = 0; k < 10; ++k)
{
Console.WriteLine("Enter a whole number or 999 to quit: ");
strTemp = Console.ReadLine();
while(!int.TryParse(strTemp, out intTemp))
{
Console.WriteLine("Input was not in the correct format");
Console.Write("Please enter a valid number: ");
strTemp = Console.ReadLine();
}
if(intTemp != 999)
{
intArray[k] = intTemp;
++numbersEntered;
}
else
{
k = 10;
}
}
The loop variable k goes out of scope when the code leaves the for loop. So, you can use variable k only within the loop.
So, you need to move your if-else inside your for loop. Change your FillArray() method to
private static int[] FillArray()
{
int[] intArray = new int[10];
int numbersEntered = 0;
int intTemp = 0;
string strTemp = "";
for (int k = 0; k < 10; ++k)
{
Console.WriteLine("Enter a whole number or 999 to quit: ");
strTemp = Console.ReadLine();
while (!int.TryParse(strTemp, out intTemp))
{
Console.WriteLine("Input was not in the correct format");
Console.Write("Please enter a valid number: ");
strTemp = Console.ReadLine();
}
if (intTemp != 999)
{
intArray[k] = intTemp;
++numbersEntered;
}
else
break;
}
Array.Resize(ref intArray, numbersEntered);
return intArray;
}
Also, I'd suggest changing ArrayAverage to double type. e.g. 2, 3 => average 2.5
double ArrayAverage = 0; //average need not be whole number
Additionally, with Linq you can shorten your Calculations method as
//using System.Linq;
private static void Calculations(int[] intArray, out int Highest, out int Lowest, out int intSum, out double average)
{
Lowest = intArray.Min();
Highest = intArray.Max();
intSum = intArray.Sum();
average = intArray.Average();
}

Categories

Resources