I'm new to C# and programming as a whole and i have a quick question to ask you guys, I've searched a bit but only found far too complicated examples for me to implement in my work so here goes:
int[] newArray = new int[7];
Console.WriteLine("Hello! Please enter 7 numbers between 1-25, press ENTER after each number. ");
for (int i = 0; i < newArray.Length; i++)
bool loop = true;
do
{
try
{
newArray[i] = Convert.ToInt32(Console.ReadLine());
loop = false;
}
catch
{
Console.WriteLine("You may only enter numbers!");
}
} while (loop);
Console.Write("You entered the following numbers: ");
for (int i = 0; i < newArray.Length; i++)
{
Console.WriteLine(newArray[i]);
}
}
This is the first part of a bingogame im trying to write, but i can't understand why the names loop and i don't exist, should i make something static? Move some brackets around? Please help.
You need to wrap the entire for statement in braces, otherwise it will only execute the next line of code, which is just bool loop = true;.
for (int i = 0; i < newArray.Length; i++)
{ // <-- Add this
bool loop = true;
do
{
try
{
newArray[i] = Convert.ToInt32(Console.ReadLine());
loop = false;
}
catch
{
Console.WriteLine("You may only enter numbers!");
}
} while (loop);
Console.Write("You entered the following numbers: ");
}
It's worth to mention about string.Join method to print all elements of the list.
Console.WriteLine("You entered the following numbers: ");
Console.WriteLine(string.Join(", ", newArray));
After using Parse/TryParse method, you don't need to use Convert.ToInt32 any more.
To validate number and be able to reenter it, it is much better to do 2 IF statements instead of using Constains method of Enumerable class.
while (!int.TryParse(Console.ReadLine(), out number) || number < 1 || number > 25)
{
Console.WriteLine("You may only enter numbers from range 1-25!");
}
Make one single bracket right after your for cycle.
You're missing an open brace. This looks like homework so I'm not going to rewrite it for you. Take a closer look and work on the formatting and indentations. That will give you a clue as to were that missing brace should be.
Here is a nicer way to test for number input without the try/catch
var newArray = new int[7];
Console.WriteLine("Hello! Please enter 7 numbers between 1-25, press ENTER after each number. ");
for (var i = 0; i <= newArray.Length - 1; i++)
{
int number;
while (!int.TryParse(Console.ReadLine(), out number))
{
Console.WriteLine("You may only enter numbers!");
}
newArray[i] = Convert.ToInt32(number);
}
Console.WriteLine("You entered the following numbers: ");
foreach (var t in newArray)
{
Console.WriteLine(t);
}
Related
I created an array that lets a business input zip codes that they serve, and give them the ability to search. I want to give the ability for a user to enter 0 to exit the program. How can I do this in the "while" section of the do while loop? (I am aware that entering zip codes as strings is better).
I've tried putting while(lookup != 0) and I get an error telling me that the name lookup does not exist.
int[] zipCodes = new int[5];
for (int i = 0; i < zipCodes.Length; i = i + 1)
{
Console.WriteLine("Enter a 5 digit zip code that is supported in your area");
zipCodes[i] = Convert.ToInt32(Console.ReadLine());
}
Array.Sort(zipCodes);
for (int i = 0; i < zipCodes.Length; i = i + 1)
{
Console.WriteLine("zip codes {0}: {1}", i, zipCodes[i]);
}
do
{
Console.Write("Enter a zip code to look for: ");
Console.WriteLine();
Console.WriteLine("You may also enter 0 at any time to exit the program ");
Int64 lookup = Convert.ToInt64(Console.ReadLine());
int success = -1;
for (int j = 0; j < zipCodes.Length; j++)
{
if (lookup == zipCodes[j])
{
success = j;
}
}
if (success == -1) // our loop changes the -1 if found in the directory
{
Console.WriteLine("No, that number is not in the directory.");
}
else
{
Console.WriteLine("Yes, that number is at location {0}.", success);
}
} while (lookup != 0);
Console.ReadLine();
Input zip codes that they serve, and give them the ability to search.
Display the zip codes entered into the array, then give the option to search or exit the program.
Like I said in the comment above: you need to define the lookup variable outside of your do while loop, it only currently exists within, hence when the condition is ran it causes an error :)
Int64 lookup = 1; //or something other than 0
do
{
...
your code
...
} while (lookup != 0);
Generally whenever you declare a variable in a block of code that is bounded by {} (such as if or while), the variable will only exist inside that block. To answer your question, your lookup variable exists only inside the while loop and therefore cannot be used in the condition. To prevent this, define it outside your loop.
Int64 lookup = 1;
do
{
Console.Write("Enter a zip code to look for: ");
Console.WriteLine();
Console.WriteLine("You may also enter 0 at any time to exit the program ");
lookup = Convert.ToInt64(Console.ReadLine());
int success = -1;
for (int j = 0; j < zipCodes.Length; j++)
{
if (lookup == zipCodes[j])
{
success = j;
}
}
if (success == -1) // our loop changes the -1 if found in the directory
{
Console.WriteLine("No, that number is not in the directory.");
}
else
{
Console.WriteLine("Yes, that number is at location {0}.", success);
}
}
while (lookup != 0);
I need to create a program that adding the user input to reach a target, as a result, is just like below.
I have to use 'While Loop' for this,
but it is difficult for me to use while loop...
Here is my code
Console.WriteLine("Enter Target Value: 6");
int total = 0;
int target = 6;
int i;
for (i = 1; i <= 4; i++)
{
Console.Write("Enter #{0}:\t", i);
total += Convert.ToInt32(Console.ReadLine());
}
while (total == target);
Console.WriteLine("It took {0} inputs to take the sum to\t{1}",i, total);
Console.ReadLine();
Could you please help me to find the problems?
Do you know what number the user will enter? No, you do not know. So you do not know how many numbers will it take to reach the sum as well.
Pick the right tool for the job.
For Loop
A "For" Loop is used to repeat a specific block of code a known number of times.
While Loop
A "While" Loop is used to repeat a specific block of code an unknown number of times,
Given the above 2 options, your pick should be a while loop since you do NOT know how many times you will need to ask the user to enter a number to reach the sum. It may be 1 or many, many times.
In C#, there is also the do while loop, which is to be used if you know you must do something at least once and possibly more, Therefore, for your case the best option would be to use do while.
You may read more on while loop, for loop, and do while.
Here is the complete example.
static void Main(string[] args)
{
try
{
int i = 0;
int number;
int input=0;
Console.WriteLine("Enter target number ");
number = int.Parse(Console.ReadLine());
while (input != number && input < number)
{
Console.WriteLine($"Enter number {i+1}");
input += int.Parse(Console.ReadLine());
i++;
}
Console.WriteLine($"It took {i} number to make the sum {number}");
}
catch (Exception e)
{
}
Console.ReadLine();
}
Your code is perfectly operational. I hope this helps:
Console.WriteLine("Enter Target Value: 6");
int total = 0;
int target = 6;
int i = 1;
while (i <= 4)
{
Console.Write("Enter #{0}:\t", i);
total += Convert.ToInt32(Console.ReadLine());
i++;
}
while (total == target);
Console.WriteLine("It took {0} inputs to take the sum to\t{1}",i, total);
Console.ReadLine();
I need some help with a C# program that i am creating. So in this scenario i am inputting duplicate values into the program. For Example, a,b,b,c,c.
The exercise is that if there are any duplicated letters inputted (no numbers) i should get an error stating "Duplicate Value. Please Try Again!" and will not accept the duplicate value, and should show the values as a,b,c,d,e.
class Program
{
static void Main(string[] args)
{
char[] arr = new char[5];
//User input
Console.WriteLine("Please Enter 5 Letters only: ");
for (int i = 0; i < arr.Length; i++)
{
arr[i] = Convert.ToChar(Console.ReadLine());
}
//display
for(int i = 0; i<arr.Length; i++)
{
Console.WriteLine("You have entered the following inputs: ");
Console.WriteLine(arrArray[i]);
}
}
}
Choose right data structure at beginning, use HashSet instead of array since the operations are mainly looking up & inserting.
Using a hashtable (Generic Dictionary) is an efficient way to determine if an entered character has already been encountered.
Also, the Char.IsLetter method in the .NET framework is a great way to check for bad data.
static void Main(string[] args) {
Dictionary<char, bool> charsEntered = new Dictionary<char, bool>();
Console.WriteLine("Please enter 5 characters, each on a separate line.");
while (charsEntered.Count() < 5) {
Console.WriteLine("Enter a character:");
char[] resultChars = Console.ReadLine().ToCharArray();
if(resultChars.Length != 1 || !Char.IsLetter(resultChars[0])) {
Console.WriteLine("Bad Entry. Try again.");
} else {
char charEntered = resultChars[0];
if (charsEntered.ContainsKey(charEntered))
Console.WriteLine("Character already encountered. Try again.");
else
charsEntered[charEntered] = true;
}
}
Console.WriteLine("The following inputs were entered:");
Console.WriteLine(String.Join(", ", charsEntered.Keys));
Console.ReadLine();
}
Use Any linq expression to validate duplicates. char.TryParse will validates input and returns true when succeeded.
public static void Main()
{
char[] arr = new char[5];
//User input
Console.WriteLine("Please Enter 5 Letters only: ");
for (int i = 0; i < arr.Length; i++)
{
char input;
if(char.TryParse(Console.ReadLine(), out input) && !arr.Any(c=>c == input))
{
arr[i] = input;
}
else
{
Console.WriteLine( "Error : Either invalid input or a duplicate entry.");
i--;
}
}
Console.WriteLine("You have entered the following inputs: ");
//display
for(int i = 0; i<arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
}
Working Code
Elaborating on Shelvin's answer of using HashSet
HashSet<char> chars = new HashSet<char>();
//User input
Console.WriteLine("Please Enter 5 Letters only: ");
for (int i = 0; i < 5; )
{
char c = Convert.ToChar(Console.ReadLine());
if(!("abcdefghijklmnopqrstuvwxyz".Contains(c.ToString().ToLower())))
{
Console.WriteLine("Please enter an alphabet");
continue;
}
else if (!chars.Contains(c))
{
chars.Add(c);
i++;
}
else
{
Console.WriteLine("Duplicate value please try again");
continue;
}
}
//display
Console.WriteLine("You have entered the following inputs: ");
foreach(char c in chars)
Console.WriteLine(c.ToString());
Console.Read();
Keep it simple, and although a HashSet is nice semantically, it's not needed for 5 elements (it's actually slower than a List in that case). Worse, it requires a parallel structure to track the characters (assuming you care about order).
Clearly none of these considerations matter for such a small example but it's good to learn them up front and don't always jump to big-O notation when actually measured performance and memory consumption should be your guide for most practical applications.
Instead you can simply do:-
List<char> chars = new List<char>(5);
while (chars.Count < 5)
{
char c = Console.ReadKey().KeyChar;
if (!char.IsLetter(c)) continue;
if (chars.Contains(char)) continue;
chars.Add(char);
}
Plus whatever error messages you want to add.
I am new to C# and was doing this program as an exercise. I have managed to get my program to print the reversed number of the input given by the user, but when I move onto checking whether it is a palindrome or not, it does not calculate the answer correctly. It always prints 'not a palindrome'.
After some error checking, I realized that the reason why it was doing this is because the last number that gets stored in newnum is just the last digit after being reversed and not the entire number. How can I rectify this??
My Code
int i, remainder = 0, newnum = 0;
Console.WriteLine("Enter a Number: ");
int uinput = Convert.ToInt32((Console.ReadLine()));
for (i = uinput; i > 0; i = (i / 10))
{
remainder = i % 10;
Console.Write(remainder);
newnum = remainder;
}
if (newnum == uinput)
{
Console.WriteLine("The Number {0} is a palindrome", uinput);
}
else
{
Console.WriteLine("Number is not a palidrome");
}
Console.WriteLine(uinput);
Console.WriteLine(newnum);
Console.ReadKey();
}
I also looked online at another code example, but the thing I don't understand in that is why num is being converted to boolean type in the while loop? Is that just to keep the loop running?
The Code reffered to above
int num, rem, sum = 0, temp;
//clrscr();
Console.WriteLine("\n >>>> To Find a Number is Palindrome or not <<<< ");
Console.Write("\n Enter a number: ");
num = Convert.ToInt32(Console.ReadLine());
temp = num;
while (Convert.ToBoolean(num))
{
rem = num % 10; //for getting remainder by dividing with 10
num = num / 10; //for getting quotient by dividing with 10
sum = sum * 10 + rem; /*multiplying the sum with 10 and adding
remainder*/
}
Console.WriteLine("\n The Reversed Number is: {0} \n", sum);
if (temp == sum) //checking whether the reversed number is equal to entered number
{
Console.WriteLine("\n Number is Palindrome \n\n");
}
else
{
Console.WriteLine("\n Number is not a palindrome \n\n");
}
Console.ReadLine();
Any sort of help is much appreciated!! Thank You :)
I'm not sure what you're asking, since the second snippet of code you found online should fix your issue.
Your code works, if you just change the line
newnum = remainder;
to
newnum = (newnum*10) + remainder;
The issue in your case is not the condition you used in the for loop, it's just that you're overwriting newnum with the remainder every time, so newnum is only storing the last reminder that was calculated in the loop, "forgetting" all the others it had calculated before.
To reverse the number, every time you enter the loop, you should add the last remainder you've found to the right of newnum, which is effectively equivalent to multiplying everything by 10 and adding remainder.
Try to follow it step by step with pen and paper (or with a debugger).
public bool isPalindome(int num)
{
string sNum = num.ToString();
for (int i = 0; i<sNum.Length; i++)
if (sNum[i] != sNum[sNum.Length-1-i]) return false;
return true;
}
I think that will do it... Untested!!
As dognose (and Eren) correctly assert you only need to go halfway through
public bool isPalindome(int num)
{
string sNum = num.ToString();
for (int i = 0; i < sNum.Length/2; i++)
if (sNum[i] != sNum[sNum.Length-1-i]) return false;
return true;
}
You will also need to decide what happend to negative numbers.. ie is -121 a plaindome? This method will say that it isn't...
Easiest way:
public static Boolean isPalindrom(Int32 number){
char[] n1 = number.ToString().ToCharArray();
char[] n2 = number.ToString().ToCharArray();
Array.Reverse(n2);
String s1 = new String(n1);
String s2 = new String(n2);
return (s1 == s2);
}
https://dotnetfiddle.net/HQduT5
you could also use Integers for s1 and s2 and return (s1-s2 == 0)
You have many ways of accomplish this exercise.
A. You can leave the input as string and loop it over, every iteration to check if the value of index 'i' and value of index 'len-i-1' are equals, if not false, otherwise return at the end of the loop true. (the loop should run till i < len/2)
B. You can create a new string and insert the text from end to start and then compare if the original string and result string are equals.
C. there are much more ways without using the string solutions, just with calculation..
int x;
cin<<x; //input the number
int ar[];
int i=0;
temp2=0;
while(x/10 != 0)
{
int temp=x%10;
ar[i]=temp;
x=x/10;
i++;
}
for(int j=0, j<i,j++)
{
temp2=temp2*10+ar[j];
}
if(temp2==x){cout<<"palindrome"}
else {"not palindrome"}
ok here is the logic:
we first input the number x(it can be of any length)..Next we split the number into array..the condition to do this is tha we check for the qoutient to decide whether the number is fully split..next we take the array and rejoin it and check with the input number..
Use the following code:
public boolean isPalindrom(Integer number)
{
return number.Equals(int.Parse(String.Join("", String.Join("", number.ToString().ToCharArray().Reverse().ToArray()))));
}
I want to add multiple values into an array, but I want to stop when I feel like it.
Here is the condition I added
while (numbers[i] != 10)
{
i++;
numbers[i] = int.Parse(Console.ReadLine());
Console.WriteLine(numbers[i]);
}
It will stop when the value entered is 10. But I want it to stop when I just press ENTER.
How do I do this?
If you are asking about how to detect the "just press ENTER" condition:
var input = Console.ReadLine();
if (input == "") {
break;
}
numbers[i] = int.Parse(input);
// etc
var numbers = new List<int>();
string s;
while(!string.IsNullOrEmpty(s = Console.ReadLine())) {
numbers.Add(int.Parse(s));
}
I guess you are looking for some way to re-size the array, you can use Array.Resize
Declare numbers like this.
List<int> numbers = new List<int>();
Then modify the loop as such.
while (numbers[i] != 10)
{
i++;
string input = Console.ReadLine();
if (string.IsNullOrEmpty(input)) { break; }
numbers.Add(int.Parse(input));
Console.WriteLine(numbers[i]);
}