How can I do user input times word.Add - c#

I want to create a List with words and later compare them. First I need is to add strings to List for wordsnumber times. If user inputs wordsnumber = 5, how can I write that ?
while (wordsnumber < 1 || wordsnumber > 20)
{
Console.WriteLine("*Leader Instructor: You must follow my instructions !");
Console.Write("Your number: ");
wordsnumber = Convert.ToInt32(Console.ReadLine());
}
if(wordsnumber >= 1 || wordsnumber < 20)
{
Console.WriteLine("*Leader Instructor: Awesome.");
}
List<string> words = new List<string>();

You can use a normal for loop to ask the user to enter wordsNumber amount of words. Normally the structure of the for loop would look something like:
List<string> words = new List<string>();
for (int i = 0; i < wordsnumber; i++)
{
Console.Write($"Enter word #{i + 1}: ");
words.Add(Console.ReadLine());
}
A couple other things: you should use int.TryParse to try to get the number so the program doesn't crash if they enter some non-numeric text, and you don't need the if condition since the while loop is already enforcing a valid range of numbers. Just for fun, I also showed how to color the leader instructor text in red, so it stands out more:
int wordsnumber;
Console.WriteLine("Enter the number of words (1 - 20): ");
while (!int.TryParse(Console.ReadLine(), out wordsnumber) ||
wordsnumber < 0 || wordsnumber > 20)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("*Leader Instructor: You must follow my instructions !");
Console.ResetColor();
Console.Write("Enter the number of words (1 - 20): ");
}

You can simply add a word into a list with words.Add(wordsnumber);. After adding a word into a list you can iterate through the list with a for loop and then ad if statement for comparing your words like:
for (int i = 0; i < words.length; i++){
for (int j = 0; j < words.length; j++) {
//so you don't compare the word with itself
if (i != j) {
if (words[i] == words[j]) {
...words are the same do something
}
}
}
}
And also as #Rufus said try using int.TryParse instead of Convert.ToInt32

Related

Create Pyramid with decremental value

I'm trying to create a pyramid in c# using a number input.
I know how to create a normal pyramid that counts from 1-20 but I can't seem to find what to change on my code to make it.
Instead of:
1
2 2
3 3 3
4 4 4 4
I need it to be:
4
3 3
2 2 2
1 1 1 1
Here's my current code:
using System;
public class Exercise17
{
public static void Main()
{
int i,j,spc,rows,k;
Console.Write("\n\n");
Console.Write("Display the pattern like pyramid with repeating a number in same row:\n");
Console.Write("-----------------------------------------------------------------------");
Console.Write("\n\n");
Console.Write("Input number of rows : ");
rows= Convert.ToInt32(Console.ReadLine());
spc=rows+4-1;
for(i=1;i<=rows;i++)
{
for(j=spc;j>=1;j--)
{
Console.Write(" ");
}
for(k=1;k<=i;k++)
Console.Write("{0} ",i);
Console.Write("\n");
spc--;
}
}
}
First, you need to reverse the for loop. So that it starts with rows, loops while greater than zero, and decrements and each iteration
for (i = rows; i > 0; i--)
This is the main part. But you also need to take care of the spaces. So to do this we now need to keep track of how many iterations we have already performed. So we need a new variable initiated before the loop.
int iteration = 1;
for (i = rows; i > 0; i--)
.....
Then we need to use this, in the loop to output the number. And then increment it afterwards.
for (k = 1; k <= iteration; k++)
Console.Write("{0} ", i);
iteration++;
So the whole loop now looks like;
int iteration = 1;
for (i = rows; i > 0; i--)
{
for (j = spc; j >= 1; j--)
{
Console.Write(" ");
}
for (k = 1; k <= iteration; k++)
Console.Write("{0} ", i);
Console.Write("\n");
spc--;
iteration++;
}
Now the challenge is, can you try to optimise this further?
Instead of the following:
Console.Write("{0} ",i);
You can write:
Console.Write("{0} ", (rows - i) + 1);

Making a program that sums up only even numbers entered from console

In one of my classes I was given an assignment to write a simple program that combines multiple numbers entered from the console, but only adding up the even ones. I was able to do the summing up part pretty easily but I can't figure out how to check for even numbers! If anyone can figure out how or explain for a beginner how to do it would be greatly appreciated.
Here's the full code so far:
using System;
namespace Test_3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Amount of numbers n = ");
var n = int.Parse(Console.ReadLine());
Console.WriteLine("Enter numbers:");
var sum = 0;
for (int i = 0; i < n; i++)
{
if (sum%2 == 0)
{
}
else
{
}
var num = int.Parse(Console.ReadLine());
sum = sum + num;
}
Console.WriteLine("The sum of the numbers is " + sum);
}
}
}
You seem to already know how to get the even numbers but here is how to apply it!
Console.WriteLine("Amount of numbers n = ");
var n = int.Parse(Console.ReadLine());
Console.WriteLine("Enter numbers:");
var sum = 0;
for (int i = 0; i < n; i++)
{
var num = int.Parse(Console.ReadLine()); //first read a number from the console
if (num % 2 == 0) //then check if it is even
{
sum = sum + num; //if it is, then add it to sum
}
}
Console.WriteLine("The sum of the numbers is " + sum);
You seem not to get the idea of an if-clause, let me explain this, using the following pieces of code:
Your code:
for (int i = 0; i < n; i++)
{
if (sum%2 == 0)
{
}
else
{
}
var num = int.Parse(Console.ReadLine());
sum = sum + num;
}
This calculates the sum of all numbers (you check whether a number is even or not, but you don't use that information).
My proposal: (you check if a number is even, and you use that information)
for (int i = 0; i < n; i++)
{
if (sum%2 == 0)
{
var num = int.Parse(Console.ReadLine());
sum = sum + num;
}
else
{
}
}
Another one, how to calculate the sum of the odd numbers? (Here you check if a number is even, but you use the case where it is not)
for (int i = 0; i < n; i++)
{
if (sum%2 == 0)
{
}
else
{
var num = int.Parse(Console.ReadLine());
sum = sum + num;
}
}
So, you see? You can use if-clauses to filter out what you want to do when a condition is met or when a condition is not met, that's the whole idea behind it.
You need to check whether the variable num is divisible by two instead of the sum. The code you have checks if the sum is even and if so does nothing since you didn't add anything to the if statement. Instead, you should be doing if ( num % 2 == 0) .
You also need to move where num is declared to the top of the for loop and move the part where you add to the sum to the inside of the conditional (The if statement).

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

How do I create an infinite loop with a question that when answered, categorizes the answer into 1 of 3 different arrays?

I have 3 different categories.
1. Todlers (Age 1-4)
2. Children (Age 5-17)
3. Grownups (Age 18 and above)
I'd like to infinitely loop "Give a number", so that even when all 3 arrays are filled, it still continues. I want the loop to end only when a 0 is typed. (This I seemed to manage)
Only the ten first values have to be stored, any values after the arrays have been filled can be disregarded. (10 values per 3 arrays is 30 values total)
Then I'd like to categorize the ages as explained above. My current age output ('input') remains 0 for every element in each of the 3 arrays. I realise my if-statements aren't being triggered because of "...Length", but how would you recommend replacing that?
I tried "i < 10" but that lead to Array Out of Bounds Exception, as well as putting todlers[i]/children[i]/grownups[i] < 10
Sorry if I am not being concise enough, but I'm still a beginner and English isn't my mothertongue.
Thanks in advance.
class Program
{
static void Main(string[] args)
{
int[] todlers = new int[10];
int[] children = new int[10];
int[] grownups = new int[10];
for (int i = 0; ; i++)
{
Console.Write("Give a number (0 = stop) : ");
int input = int.Parse(Console.ReadLine());
if (todlers.Length < 10 && input < 5 && input > 0)
{
todlers[i] = input;
}
else if (children.Length < 10 && input > 4 && input < 18)
{
children[i] = input;
}
else if (grownups.Length < 10 && input > 17)
{
grownups[i] = input;
}
else if (input == 0)
{
break;
}
else
{
continue;
}
}
Console.Write("\n");
Console.WriteLine("TODLERS");
for (int i = 1; i < 11; i++)
{
Console.WriteLine("Todler {0} is {1} years old", i, todlers[i]);
}
Console.Write("\n");
Console.WriteLine("CHILDREN");
for (int i = 1; i < 11; i++)
{
Console.WriteLine("Child {0} is {1} years old", i, children[i]);
}
Console.Write("\n");
Console.WriteLine("GROWNUPS");
for (int i = 1; i < 11; i++)
{
Console.WriteLine("Man/Woman {0} is {1} years old", i, grownups[i]);
}
Console.ReadKey();
}
}
The Length of your arrays doesn't change, it stays the same as at initialization (10) throughout your program. As a result todlers.Length < 10 is always false.
Given that you never put 0 inside your arrays you can replace todlers.Length < 10 with todlers[9] == 0 that will effectively check that you haven't yet changed the last element in the array.
for (int i = 1; i < 11; i++)
you should change to
for (int i = 0; i < 10; i++)
it because you had initialize array with 10 elements and the first one will be 0
todlers[0],todlers[1] ... todlers[9]
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/
Use a List to store a collection of things when you don't know how many items you will have. Use a do - while loop to run a block of code at least once and at most infinitely.
Try something like this (untested code):
using System;
using System.Collections.Generic;
public class Program
{
public static void Main(string[] args)
{
List<int> todlers = new List<int>();
List<int> children = new List<int>();
List<int> grownups = new List<int>();
int input = 0;
do
{
Console.Write("Give a number (0 = stop) : ");
input = int.Parse(Console.ReadLine());
if (todlers.Count < 10 && input < 5 && input > 0)
{
todlers.Add(input);
}
else if (children.Count < 10 && input > 4 && input < 18)
{
children.Add(input);
}
else if (grownups.Count < 10 && input > 17)
{
grownups.Add(input);
}
}while(input>0);
Console.Write("\n");
Console.WriteLine("TODLERS");
for (int i = 0; i < todlers.Count; i++)
{
Console.WriteLine("Todler {0} is {1} years old", i+1, todlers[i]);
}
Console.Write("\n");
Console.WriteLine("CHILDREN");
for (int i = 0; i < children.Count; i++)
{
Console.WriteLine("Child {0} is {1} years old", i+1, children[i]);
}
Console.Write("\n");
Console.WriteLine("GROWNUPS");
for (int i = 0; i < grownups.Count; i++)
{
Console.WriteLine("Man/Woman {0} is {1} years old", i+1, grownups[i]);
}
Console.ReadKey();
}
}
This will stop adding to the lists when there are 10 entries, but the user will have no warning their input is being discarded. It will also only output the number of entries that have been added, instead of zeroes if the user inputs fewer than ten in a category.

C# Patterns;for loops

Develop a C# console application that displays the following pattern. Use for loops (hint: nested) to generate the patterns. All asterisks should be displayed by a single statement of the form Console.Write("*"); which displays the asterisks leading up to the number value shown in the example. Note the sequence of each number in turn. You will need to deduce how the numbers are computed (they are the result of a computation) and where that computation will be placed in the loop structures. You may not hardcode the displayed numbers into your loops.
I already have the "*" but can't figure out the numbers.
The two patterns should look similar to the following:
*2
**4
***6
****8
*****10
******12
*******14
********16
*********18
**********20
{
for (int row = 0; row < 10; row++)
{
Console.Write(" ");
for (int col = 0; col <= row; col++)
{
Console.Write("*");
Console.Write(" ");
}
Console.WriteLine(" ");
}
Console.WriteLine(" ");
for (int row = 0; row < 10; row++)
{
Console.Write(" ");
for (int col = 10; col > row; col--)
{
Console.Write("*");
Console.Write(" ");
}
Console.WriteLine(" ");
}
}
}
}
I already have the "*" but can't figure out the numbers.
You have the hardest part then: getting the numbers to print is much easier. Note that the number that you print is equal to two times the number of asterisks in front of it. Therefore, what you need to write is 2*n, where n is the limit in the loop that wrote the asterisks (i.e. the row plus one in your code).
You can combine the printing with writing the end-of-line mark: replace
Console.WriteLine(" ");
with
Console.WriteLine(2*(row+1));
to get the desired result.
I decided to make my comment to dasblinkenlight's answer into an answer on its own:
for(int row = 0; row < 10; row++) {
for(int col = 0; col <= row; col++) {
Console.Write("*");
}
Console.Write("{0}{1}", (row+1)*2, Environment.NewLine);
}
Notice, that the rownumer displayed at the end of the line is calculated as (row+1)*2, because your loop starts at index 0. The output would be faulty otherwise. This is followed by a new line.

Categories