C# Displaying every other number from a user in a console app - c#

I need to write a console app that asks the user how many number (double) to enter. After accepting that many numbers, display every other number entered. There always seems to be an error when I try to use a double. I also get this error "System.IndexOutOfRangeException was unhandled
HResult=-2146233080
Message=Index was outside the bounds of the array."
after the the for loop has gone through the last loop for this line
myArrai1[i] = int.Parse(Console.ReadLine());
in the first for loop
this all the code I have been able to try to brainstorm with.
class Program
{
static void Main(string[] args)
{
Console.Write("Enter Item Count: ");
int number = int.Parse(Console.ReadLine());
int[] myArrai1 = new int[number];
int i = 0;
for (i = 1; i <= number; i++)
{
Console.WriteLine("Enter Number " + i.ToString() + ": ");
myArrai1[i] = int.Parse(Console.ReadLine());
}
for (i = 0; i < number; i++)
{
Console.WriteLine("Every other number entered: ");
Console.WriteLine(myArrai1[i += 2]);
}
Console.ReadLine();
}
}
}

Not too far off, main changes to fix fix this was loop#1 was set to 0 index to prevent out of range and loop#2 was simplified by intervaling at 2 of ++.
The rest of the changes were aesthetic; I changed the input Console.WriteLine to just Console.Write to keep the input on the same line, and moved the Every Other Line statement to precede the output display loop instead of being written on every iteration.
Console.Write("Enter Item Count: ");
int number = int.Parse(Console.ReadLine());
int[] myArrai1 = new int[number];
for (int i = 0; i < number; i++) {
Console.Write("Enter Number " + (i + 1) + ": ");
myArrai1[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("Every other number entered: ");
for (int j = 0; j < number; j = j + 2) {
Console.WriteLine(myArrai1[j]);
}

Related

I am have two errors with double score

static void Main(string[] args)
{
SortedList<string, double> num2 = new SortedList<string, double>();
string Name;
double Score;
for (int i = 0; i < 1; i++)
{
Console.WriteLine("Name Score:");
Name = Console.ReadLine();
double.TryParse(Console.ReadLine(), out Score);
num2.Add(Name, Score);
}
for (int i = 0; i < 1; i++)
{
Console.WriteLine("Name Score:");
Name = Console.ReadLine();
double.TryParse(Console.ReadLine(), out Score);
num2.Add(Name, Score);
}
for (int i = 0; i < 1; i++)
{
Console.WriteLine("Name Score:");
Name = Console.ReadLine();
double.TryParse(Console.ReadLine(), out Score);
num2.Add(Name, Score);
}
for (int i = 0; i < 1; i++)
{
Console.WriteLine("Name Score:");
Name = Console.ReadLine();
double.TryParse(Console.ReadLine(), out Score);
num2.Add(Name, Score);
}
for (int i = 0; i < 1; i++)
{
Console.WriteLine("Name Score:");
Name = Console.ReadLine();
double.TryParse(Console.ReadLine(), out Score);
num2.Add(Name, Score);
}
Name = "";
foreach (var Score in num2) // error with Score
{
Name += Name + "\t"
+ Score + "\n";
Console.WriteLine(Score);
}
for (int j = 0; j < 1; j++)
{
Console.WriteLine("Name:");
Double Average;
Double Curve;
Average = Score / 5; // wont average.
Curve = 75 - Average;
Console.WriteLine();
}
Console.ReadLine();
}
I am tried to declare the Score and Name for the reader to use at the top before the sort list function.
And I got an error on the line of the comments. Basically, what im trying to do is set the sort list to read 5 scores and Names. Then I use the 5 scores and Names to find the average and Curve. So when I try to do this I get an error. Im also having trouble with the for each loop. How can I fix this program?
Your foreach isn't working because Score is defined as a double already further up in the scope of your Main method (resulting in a syntax error). I'm not sure what you are trying to achieve with that loop - looks like your maybe trying to output each name and the corresponding score for that name in your SortedList:
foreach (var listItem in num2)
{
Console.WriteLine($"Name: {listItem.Key} Score: {listItem.Value}");
}
As for your other problems, you definitely do not need 6 separate for loops. Just make one to read in all of your input:
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Enter a Name");
string name = Console.ReadLine();
Console.WriteLine("Enter a Score");
double score = double.Parse(Console.ReadLine());
num2.Add(name, score);
}
This will ask the user to supply 5 names and 5 scores. Then to get your average and curve, you can do something like:
double average = num2.Sum(item => item.Value) / 5;
double curve = 75 - average;
Console.WriteLine($"Average: {average} Curve: {curve}");
Console.ReadLine();
This uses the Enumerable.Sum
to add together all of your Value's in your Sorted List (you may need to add using System.Linq; to your file. No need to wrap this in another for loop as far as I can tell.
With your code, despite all of your for loops, it should still have captured 5 names and scores. However, when it comes to actually doing something with the values you captured from input, you weren't using them in any way. Ignoring the foreach loop, Score would have been set to whatever the last value entered in your 5th for loop, explaining why your Average wasn't working as expected.
Some other things to note:
If two identical names are supplied, this will error, since you can't have two items with the same Key in a SortedList. You'll want to handle that.
double.TryParse will result in the out parameter being set to 0 if the value attempting to be parsed cannot be. This could cause unexpected results with your average and curve later on. I switched it to use just double.Parse instead, which will throw an error if it cannot parse the value. You could account for this by doing something like this:
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Enter a Name");
string name = Console.ReadLine();
Console.WriteLine("Enter a Score");
double score;
bool isScoreValid = double.TryParse(Console.ReadLine(), out score);
while (!isScoreValid)
{
Console.WriteLine("Invalid score. Please enter a new one");
isScoreValid = double.TryParse(Console.ReadLine(), out score);
}
num2.Add(name, score);
}

Find the sum of user input (only the positive integers) C#

Find the sum of user input (only the positive integers). The code I wrote calculates them in weird way and i got confused. Thanks in advance.
Console.WriteLine("Enter numbers lenght: ");
int lenght = Convert.ToInt32(Console.ReadLine());
int sum = 0;
int input = 0;
for(int i = 0; i < lenght; ++i)
{
Console.WriteLine("Enter a number: ");
input = Convert.ToInt32(Console.ReadLine());
if(input >= 0)
{
sum = input + input;
}
}
Console.WriteLine("The sum of the positive numbers is: " + sum);
sum = input + input; is wrong,
change it to :
sum = sum + input;
or
sum += input;

How to set a range for elements within an array in C#

I´m still very new to C#, we are supposed to use for-loops not methods. My question is how to limit values (1 to 25) that users puts in.
"The game" is supposed to ask a user to put in his values then it throw´s a random number and checks if it´s among numbers kept in myArray.
{
int[] myArray = new int[10];
Console.WriteLine("Write down your numbers");
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Type in values for index nr {0}: ", i);
//user is asked to put in 10 values, what I need to do is to limit and
save as elements values in range between 1 and 25, so the loop continues (i++), if user types in a number that is outside that range my loop supposed to go a step back as if (i--)
myArray[i] = int.Parse(Console.ReadLine());
}
var rand = new Random(); //a random number is thrown
int rand1 = Convert.ToInt32(rand.Next(0, 25)); //random number ranges between 0 and 25
Console.WriteLine("{0}", rand1);
for (int i = 0; i < tal.Length; i++) //checking if random number is among users inputs
{
if (tal[i] == rand1)
{
Console.WriteLine("The random number {0} is among
your values", rand1);
}
else
{
Console.WriteLine("Random number isn´t among your
numbers");
break;
}
}
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Type in values for index nr {0}: ", i);
if (int.TryParse(Console.ReadLine(), out int result) && result >= 0 && result <= 25)
{
myArray[i] = result;
}
else
{
i--;
Console.WriteLine("Wrong number!");
}
}
Your issue is that you try to maintain an index i that indicate your current position in the array.
One of the solution will be to simply drop it and add item to a collection till you have 10 items.
Here I took a HashSet<int> because we can't have duplicate in HashSet.
Any time you try to add one, it will simply drop it. But If you want to allow duplicate you can use a simple List<int>.
int collectionSize = 10;
int lowerBound = 1, upperBound = 25;
var userSelectedNumbers = new HashSet<int>();
while (userSelectedNumbers.Count() < collectionSize)
{
Console.WriteLine($"Enter an int between {lowerBound} and {upperBound} : ");
var input = Console.ReadLine();
if (int.TryParse(input, out int value)
&& lowerBound <= value
&& value < upperBound
)
{
userSelectedNumbers.Add(value);
}
else {
Console.WriteLine("Not a valid input!");
}
}
Console.Clear();
Console.WriteLine(
$"userSelectedNumbers contains {userSelectedNumbers.Count()} elements : {"
+ string.Join(", ", userSelectedNumbers) + "}"
);
You can then validate if the random numer is within the range using Contains :
var random = new Random();
int computerPick = random.Next(0, 25);
Console.WriteLine("Computer picked : " + computerPick);
if (userSelectedNumbers.Contains(computerPick))
{
Console.WriteLine("You win!");
}
else {
Console.WriteLine("You loose!");
}
Don't forget the using :
using System.Collections.Generic;
using System.Linq;
nb: The range is define using 1 ≤ x < 25, using W. Dijkstra convention http://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF

Counting times values occured in Array

I am having a hard time with a program I need to write. The requirements are that the user enters in the size of the Array. Then they enter the elements of the array after this the program needs to display the values entered then how many times each value occurs. While everything seems to work except its not display the "occurs" part properly. Lets say "1 1 2 3 4" is entered (Array size being 5) It prints
1 occurs 1 time.
1 occurs 1 time.
2 occurs 1 time.
3 occurs 1 time.
4 occurs 2 times.
this isn't right because 1 occured 2 times and 4 is only 1 time. Please Help...
static void Main(string[] args)
{
int[] arr = new int[30];
int size,
count=0,
count1=0,
count2=0;
Console.Write("Enter Size of the Array: ");
size = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the elements of an Array: ");
for (int i=0; i < size; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}
Console.Write("Values Entered: \n");
for (int i = 0; i < size; i++)
{
Console.WriteLine(arr[i]);
if (arr[i] <= 10)
count++;
else
count1++;
}
for(int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if (arr[i] == arr[j])
count2++;
else
count2 = 1;
}
Console.WriteLine(arr[i] + " Occurs " + count2 + " Times.");
}
Console.WriteLine("The number of valid entries are: " + count + "\nThe number of invalid entries are: " + count1);
Console.ReadKey();
}
if you can use Linq, this is easy job:
After
Console.Write("Values Entered: \n");
add
var grouped = arr.GroupBy(x => x);
foreach (var group in grouped)
{
Console.WriteLine("number {0} occurs {1} times", group.Key, group.Count());
}
EDIT
Since OP isn't allowed to use Linq, here's array-only solution. Much more code than that dictionary approach, but with arrays only.
Console.Write("Values Entered: \n");
//an array to hold numbers that are already processed/counted. Inital length is as same as original array's
int[] doneNumbers = new int[arr.Length];
//counter for processed numbers
int doneCount = 0;
//first loop
foreach (var element in arr)
{
//flag to skip already processed number
bool skip = false;
//check if current number is already in "done" array
foreach (int i in doneNumbers)
{
//it is!
if (i == element)
{
//set skip flag
skip = true;
break;
}
}
//this number is already processed, exit loop to go to next one
if (skip)
continue;
//it hasn't been processed yes, so go through another loop to count occurrences
int occursCounter = 0;
foreach (var element2 in arr)
{
if (element2 == element)
occursCounter++;
}
//number is processed, add it to "done" list and increase "done" counter
doneNumbers[doneCount] = element;
doneCount++;
Console.WriteLine("number {0} occurs {1} times", element, occursCounter);
}
You can simply use dictionary:
static void Main(string[] args)
{
var dic = new Dictionary<int, int>();
Console.Write("Enter Size of the Array: ");
int size = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the elements of an Array: ");
for (int i = 0; i < size; i++)
{
int val = Convert.ToInt32(Console.ReadLine());
int current;
if (dic.TryGetValue(i, out current))
{
dic[val] = current + 1;
}
else
{
dic.Add(val, 1);
}
}
foreach (int key in dic.Keys)
{
Console.WriteLine(key + " Occurs " + dic[key] + " Times.");
}
Console.Read();
}
The problem is that you're resetting count2 to 1 any time you find a mismatch.
What you should do instead is set count2 to 0 in the outer loop (so it basically resets once for each item), and then let the inner loop count all the instances of that number:
// For each item 'i' in the array, count how many other items 'j' are the same
for (int i = 0; i < size; i++)
{
count2 = 0; // processing a new item, so reset count2 to 0
for (int j = 0; j < size; j++)
{
if (arr[i] == arr[j]) count2++;
}
Console.WriteLine(arr[i] + " occurs " + count2 + " times.");
}

How to call function to enter multiple integers into an array?

So the code for the function (Named InsertMark) is below. How would you call this function to enter the marks for say 10 people into an array called iMarks?
static void InsertMark(int [] piMarkArray, int piStuNum)
{
int iMark;
Console.Write("Enter mark for student " + piStuNum + ": ");
iMark = Convert.ToInt32(Console.ReadLine());
while (iMark < 0 || iMark > 100)
{
Console.Write("Not a percentage. Enter again: ");
iMark = Convert.ToInt32(Console.ReadLine());
}
//update array element with this mark
piMarkArray[piStuNum] = iMark;
}
Thanks.
Just move the line piMarkArray[piStuNum] = iMark; inside while loop, use index, and exit the loop if index is not less than array length.
int index=0;
while ((iMark < 0 || iMark > 100) && index < piMarkArray.Length) // exit the loop array is full
{
Console.Write("Not a percentage. Enter again: ");
iMark = Convert.ToInt32(Console.ReadLine());
piMarkArray[index++] = iMark; // Here marks are set
}
//update array element with this mark
Here you create array which will hold 10 marks and fill it with your method in a loop:
int[] marks = new int[10];
for(int i = 0; i < marks.Length; i++)
InsertMark(marks, i);
In main function you could have a code:
int iMarks[10];
for(int i = 0; i <10; i++ )
InsertMark(iMarks, i)
are you looking for something like this?
for(int i=0; i<10; i++)
{
InsertMark(iMarks, i);
}
You need to declare an array of size 10: int[] iMarks = new int[10], then in a for loop pass the array and the counter value through to the function.
int[] iMarks = new int[10];
for(int x = 0; x < 10; x++)
InsertMark(iMarks, x);
Here is the full class/ working example:
static void Main(string[] args)
{
int[] iMarks = new int[10];
for(int x = 0; x < 10; x++)
InsertMark(iMarks, x);
Console.Read();
}
static void InsertMark(int[] piMarkArray, int piStuNum)
{
int iMark;
Console.Write("Enter mark for student " + piStuNum + ": ");
iMark = Convert.ToInt32(Console.ReadLine());
while(iMark < 0 || iMark > 100)
{
Console.Write("Not a percentage. Enter again: ");
iMark = Convert.ToInt32(Console.ReadLine());
}
//update array element with this mark
piMarkArray[piStuNum] = iMark;
}
}
There are always multiple ways to code anything, and this is no exception. What I'm putting here is one example of idiomatic C# to do this. There are at least two variants I can think of which would be better, but this keeps the closest to the original idea.
First, a basic Student class:
class Student
{
public int ID;
public int Mark;
}
Then, a function to prompt for the mark
int GetMark(int studentID)
{
Console.Write("Enter mark for student " + studentID + ": ");
int mark = Convert.ToInt32(Console.ReadLine());
while (iMark < 0 || iMark > 100)
{
Console.Write("Not a percentage. Enter again: ");
iMark = Convert.ToInt32(Console.ReadLine());
}
return mark;
}
Finally, from your main program, you have a list or array of Student objects called AllStudents and you do:
foreach (Student student in AllStudents)
{
student.Mark = GetMark(student.ID);
}
Alternatively, if you aren't using classes, your loop could be:
int[] marks = new int[10]; // Or whatever size it needs to be.
for (int i = 0; i < marks.Length; i++)
{
marks[i] = GetMark(i);
}

Categories