Alright so my problem here is I'm trying to create a user input array, and notify console if a specific data point is in the user input array. I realize you can see that the data point is there on the console, but I've been asked to do this and I don't ask why :'D.
public static void Main()
{
double [] array= new double [10]
double temp;
Console.WriteLine("Insert 10 numbers");
for (int i = 0; i < array.Length; i++)
{
array[i] = Convert.ToDouble(Console.ReadLine());
}
Console.WriteLine("What number do you wish to find?");
temp = Convert.ToDouble(Console.ReadLine());
foreach (int i in array)
{
if (temp == i)
{
Console.WriteLine("The number is in the array.")
break;
}
else if (temp != i)
{
Console.WriteLine("The number is not part of the array.");
break;
}
}
}
The output is: if you put the number that was in the first slot, it would come out as "The number is in the array", any other number that is part of the array will out put "The number is not part of the array" . If you remove the breaks in the If and Else if codes, the list will tell you one by one if the number is or is not part of the array.
How do I make it that it reads the entire array, and tells me that whatever number is part of the array?
Note I've been asked not to use LINQ nor the Array. objects
You should not check for temp != i, but == only within the loop:
// array is double[] - item is double
foreach (double item in array) {
// item found, we shall report and exit the method
if (item == temp) { // <- dubious: we should check doubles with tolerance
Console.WriteLine("The number is in the array.");
return; // <- not break
}
}
// entire array has been scanned, no item found
Console.WriteLine("The number is not part of the array.");
If you don't want to return, but insist on break:
bool inTheArray = false;
foreach (double item in array)
if (item == test) {
inTheArray = true;
break;
}
Console.WriteLine(inTheArray
? "The number is in the array."
: "The number is not part of the array.");
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 do not understand why this code prints the contents of the array twice.
static void Main(string[] args)
{
Int64 userlength;
Int64 userlengthcounter;
String unencrypted;
char current;
start:
Console.WriteLine("Please enter how many characters the string you want encrypyted to be:");
userlength = Convert.ToInt64(Console.ReadLine());
Console.WriteLine("Please enter the string you want to be encrypted:");
unencrypted = Console.ReadLine();
int[] first = new int[userlength];
int[] second = new int[userlength];
if (userlength != unencrypted.Length)
{
Console.WriteLine("The string you entered was not the same length as the number of characters you specified");
goto start;
}
for (int i = 0; i < userlength; i++)
{
Console.WriteLine(unencrypted[i]);
current = unencrypted[i];
first[i] = current;
}
foreach (char item in first)
{
Console.WriteLine(item.ToString());
}
Console.ReadLine();
}
For example entering abcd would return abcdabcd and i don't understand why. Any help would be appreciated thanks.
It's because you have two loops, first you print each character in unencrypted in the for loop and store the chars in first array.
Then you loop over the array and print the chars again with foreach.
Additional Note: Using goto is almost always a bad idea because it makes your code hard to follow and unreadable. Because you have to manually track where the code jumps.
You can do the same thing with a do-while loop instead.
do {
Console.WriteLine("Please enter how many characters the string you want encrypyted to be:");
userlength = Convert.ToInt64(Console.ReadLine());
Console.WriteLine("Please enter the string you want to be encrypted:");
unencrypted = Console.ReadLine();
int[] first = new int[userlength];
int[] second = new int[userlength];
if (userlength != unencrypted.Length)
{
Console.WriteLine("The string you entered was not the same length as the number of characters you specified");
}
} while(userlength != unencrypted.Length);
you specifically build "first" then you print it in foreach, basically displaying the same content twice:
for (int i = 0; i < userlength; i++)
{
Console.WriteLine(unencrypted[i]);
current = unencrypted[i];
first[i] = current;
}
foreach (char item in first)
{
Console.WriteLine(item.ToString());
}
I'm working on an application that has the user choose how many integers to enter into an array, and then has them input the numbers to be added to the array. After each number is inputted, it shows all non-duplicate integers entered by the user up to that point in a vertical list. If it isn't unique, it informs the user that it has already been inputted.
I'm not sure how to make the application list every integer entered, rather than just the most recent one.
Here's my code:
static void Main(string[] args)
{
//checks how many numbers will be entered
int manyNumbers;
Console.WriteLine("How many numbers will you enter?");
manyNumbers = Convert.ToInt32(Console.ReadLine());
int[] array = new int[manyNumbers];
//starts asking for numbers
for (int i = 0; i < manyNumbers;)
{
Console.Write("\nEnter number: ");
string entered = Console.ReadLine();
int val;
//checks to see if valid number
if (!Int32.TryParse(entered, out val))
{
Console.Write("Invalid number '{0}'", entered);
array[i++] = val;
}
//checks to see if already entered
else if (i > 0 && array.Take(i).Contains(val))
{
Console.Write("{0} has already been entered", val);
array[i++] = val;
}
//prints inputted integer
else {
array[i++] = val;
Console.WriteLine("{0}", val);
}
}
}
Just loop over the array so far printing each.
Forgive my mobile crafted code, but more or less this:
//prints inputted integer
else {
array[i++] = val;
for(int j=0 ; j<i;j++) {
Console.WriteLine("{0}", array[j]);
}
}
You may use foreach loop
foreach(int num in array)
{
Console.WriteLine("{0}", num);
}
Very Basic approach, try one of the following:
for(var x=0;x<array.length;x++)
or
foreach(var i in array)
But your use case, use HashSet data structure
Mathematically, Set is unique list of things.
try this code, it uses a Dictionary to keep the list in memory and to search to see if the an integer has been added,
using System.Collections.Generic;
static void Main(string[] args)
{
//checks how many numbers will be entered
int manyNumbers;
Console.WriteLine("How many numbers will you enter?");
manyNumbers = Convert.ToInt32(Console.ReadLine());
Dictionary<int, int> array = new Dictionary<int, int>();
//starts asking for numbers
for (int i = 0; i < manyNumbers; )
{
Console.Write("\nEnter number: ");
string entered = Console.ReadLine();
int val;
//checks to see if valid number
if (!Int32.TryParse(entered, out val))
{
Console.Write("Invalid number '{0}'", entered);
}
//checks to see if already entered
else
if (i > 0 && array.ContainsKey(val))
{
Console.Write("{0} has already been entered", val);
//array[i++] = val;
}
else
{
//* add the new integer to list
array.Add(val, 0);
//prints the complete list
List<int> keys = new List<int>(array.Keys);
Console.WriteLine();
for(int j=0; j<keys.Count; j++) Console.WriteLine(keys[j]);
}
}
}
Not Homework..So I've got a simple console program to read exam scores and prints out the average and grade. So far it's the following:
public static void Main ()
{
int sum = 0;
int count = 0;
double average = 0;
Console.WriteLine ("Enter all your exam scores one by one. When finished, enter -99");
string scores = Console.ReadLine ();
while (scores != "-99") {
sum += int.Parse (scores);
count++;
scores = Console.ReadLine ();
}
if (scores == "-99") {
average = sum / count;
if (average >= 90)
Console.WriteLine ("Your average score is {0}. This is good for a letter grade of A", average);
Console.WriteLine(....more scores etc...);
Now I want to check for invalid entries with TryParse. I thought I'd stick in another while loop before the other and change the original one like this:
Console.WriteLine ("Enter all your exam scores one by one. When finished, enter -99");
string scores = Console.ReadLine ();
while (int.TryParse(scores, out numbers) == false){
Console.WriteLine("Please enter a valid integer")
scores = Console.ReadLine();
sum += int.Parse(scores);
count++;
}
while (scores != "-99" && int.TryParse(scores, out numbers) == true) {
sum += int.Parse (scores);
count++;
scores = Console.ReadLine ();
}
if (scores == "-99") {
average = sum / count;
if (average >= 90)
Console.WriteLine ("Your average score is {0}. This is good for a letter grade of A", average); ...etc...
The problem here is that if the user enters valid entries at first and then enters an invalid one, the compiler can't get back to the first while loop to check for the invalid entry. So I tried to swap the positions of the while loops. But this has the same effect; it can't get back to the first while loop to check for valid entries after an invalid one is entered. The answer is most likely simple, but I'm stuck.
The issue you are having is that you break from the first loop when the TryParse returns true, but have no recourse to re-enter the loop. Instead you should nest your loops. The loop with the sentinel should be the outer loop, and the loop that validates and re-prompts the user should be the inner loop. Here is an example:
while(scores != "-99")
{
scores = Console.ReadLine();
while((int.TryParse(scores, out numbers) == false)
{
//validation failed, re-prompt user for better number
Console.WriteLine("Bad value, try again")
scores = Console.ReadLine()
}
//do stuff here with the valid score value
}
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()))));
}