In my code I have to run through some files with a load of numbers in and at some point need the user to input a number to see if it is in the file or not , if it is in the file then the returning output should be the positioning of where in the file. If it is not in the list then I need to return the closest value to their input. Eg 669 is in the list however 668 is not. My code is as follows for a function to find the nearest value:
static int nearest(int close_num, int[] a)
{
int result = -1;
long smallestDelta = long.MaxValue;
foreach (int bob in a)
{
long delta = (bob > close_num) ? (bob - close_num) : (close_num - bob);
if (delta < smallestDelta)
{
smallestDelta = delta;
result = bob;
}
}
return result;
Then the linear search and the rest is as follows :
Console.WriteLine("Enter a number to find out if is in the selected Net File: ");
int i3 = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < a.Length; i++)//looping through array
{
if (a[i] == i3)//checking to see the value is found in the array
{
Console.WriteLine("Value found and the position of it in the selected Net File is: " + i, a[i]);
break;
}
else
{
int found = nearest(i3, a);
Console.WriteLine("Cannot find this number in the Net File however here the closest number to that: " + found);
However these are my outputs:[Output 1 : Entering a value that is the file , for some reason prints the else call 3x before , if I remove the break in the code it just breaks. 1
Output 2: Prints whilst running through the whole list of values
how can I fix these formatting issues bc the code is doing what I need it to , just not in a way it should.
Thanks
Related
i want to make user input random number example : 5-3-10-50
, system will split " - " and then the result 5 3 10 50
, how to make subtraction from first number minus second number and so on,
like this 5 - 3 = 2 , 2 - 10 = -8 , -8 - 50 = -58
and then system will print the final answer -58
my code :
bool Subtraction = true;
int AskSubtraction = 0;
while (Subtraction)
{
Console.Write("\n" + "input number ( example : 1 - 2 - 3 - 4 ) : ");
var InputNumber = Console.ReadLine();
double Answer = 0;
foreach (var result in InputNumber.Split('-'))
{
if (double.TryParse(result, out _))
{
double NumberResult = Convert.ToDouble(result);
Answer -= NumberResult;
}
else
{
Console.WriteLine("\n" + "Wrong input !");
AskSubtraction++;
}
}
Console.WriteLine("\n" + "subtraction result : " + Answer);
}
i know my code is wrong, im beginner i already try to fix this but i cant fix it until now, i hope someone tell me what's wrong with my code and fix it too, thank you.
The reason yours doesn't work is because you set Answer = 0.
And you used foreach. On the first iteration of the loop, the first number is subtracted from Answer which results in -5.
Use for (int i=1; i<arr.Length; i++)
instead of foreach
Start from index 1, and then subtract the values.
Example:
var arr = InputNumber.Split('-');
double Answer = 0;
if (double.TryParse(arr[0], out _))
{
// We set Answer to the first number, since nothing is subtracted yet
Answer = Convert.ToDouble(arr[0]);
}
// We start index from 1, since subtraction starts from 2nd number on the String array
for (int i=1; i<arr.Length; i++)
{
if (double.TryParse(arr[i], out _))
{
double NumberResult = Convert.ToDouble(arr[i]);
Answer -= NumberResult;
}
}
Tested on Online C# Compiler
You would need a condition inside the foreach loop to check for the first parsed double before you begin subtraction. Also there is no need to call Convert.ToDouble() since the double.TryParse() function already returns the parsed double value, All you would need is a variable to contain the out value of the double.TryParse() function, See example below
bool Subtraction = true;
int AskSubtraction = 0;
while (Subtraction)
{
Console.Write("\n" + "input number ( example : 1 - 2 - 3 - 4 ) : ");
var InputNumber = Console.ReadLine();
double Answer = 0;
double numResult;
foreach (var result in InputNumber.Split('-'))
{
if (double.TryParse(result, out numResult))
{
if(Math.Abs(Answer)>0){
Answer -= numResult;
}
else{
Answer=numResult;
}
}
else
{
Console.WriteLine("\n" + "Wrong input !");
AskSubtraction++;
}
}
Console.WriteLine("\n" + "subtraction result : " + Answer);
}
This code shows result like:
distance from target : 10
distance from target : 9
distance from target : 8
(line by line)
I want to show the result like- distance from target : 10, then 9,8,7 replacing the place of 10, (only the place of 10 will update)
public void Attack()
{
for (int i = 1; i < 3; i++)
{
if (i == 1)
{
Console.WriteLine("Target Locked (+)");
Thread.Sleep(2000);
}
if (i == 2)
{
Console.WriteLine("Fired!");
Thread.Sleep(1000);
}
}
Random random = new Random();
int distance = random.Next(100, 3000);
for (int i = distance; i > 0; i = i - 3)
{
Console.WriteLine("distance from target : " + i);
Thread.Sleep(30);
//Console.Clear();
}
Console.WriteLine("BloooW!");
}
You could use CursorTop, CursorLeft and SetCursorPosition to fine control the point where you write your output. But the real trick is to delete what you have previously written in that place. Here you could use the format string capabilities of Console.Write/WriteLine
// This needs to be written just one time
Console.Write("distance from target : ");
// Now get the current cursor position after the write above
int posX = Console.CursorLeft;
int posY = Console.CursorTop;
for (int i = distance; i > 0; i = i - 3)
{
// Position the cursor where needed
Console.SetCursorPosition(posX, posY);
// Replace the previous write with a number aligned on the left on 4 spaces
Console.Write($"{i,-4:D}");
// As an alternative to SetCursorPosition you could have
// Console.CursorLeft -= 4;
// but, to me this is less clear....
Thread.Sleep(30);
}
// Do not forget to jump to the next line
Console.WriteLine("\r\nBloooW!");
You can change from Console.WriteLine to Console.Write add a \r to the front of your string:
for (int i = distance; i > 0; i = i - 3)
{
Console.Write("\rdistance from target : " + i);
Thread.Sleep(30);
//Console.Clear();
}
Console.WriteLine("");
This will cause the console to return to the beginning of the line and write the string again covering the string that was there from the last write. Also be sure to add a Console.WriteLine(""); after the for loop to move to the next line, so your next write doesn't end up starting on that line.
This solution works best if your string will only get longer.
If your string is is going to get shorter you can add some white space to end of the string like this:
Console.Write("\rdistance from target : {0} ", i);
This is the case for you when you go form 10 to 9
then you should first delete the distance written to console, it can be done with one or more backspaces \b
change
for (int i = distance; i > 0; i = i - 3)
{
Console.WriteLine("distance from target : " + i);
Thread.Sleep(30);
//Console.Clear();
}
to
int lastDistanceLength = 0; // save the last number of distance chars written
for (int i = distance; i > 0; i = i - 3)
{
if(lastDistanceLength == 0) { // no distance chars written yet.
Console.Write("distance from target : " + i);
}
else {
for(int j=0;jā¹lastDistanceLength;j++)
Console.Write("\b"); // delete old distance
Console.Write(""+i);
}
lastDistanceLength = i==10 ? 2 : 1;
Thread.Sleep(30);
//Console.Clear();
}
Console.WriteLine("\r\nBloooW!");
you will most likely need a more advanced algorithm for calculating lastDistanceLength, maybe just convert i to a string and take the length e.g. lastDistanceLength = (""+i).Length
there is a quite comprehensive explanation here : Is there a way to delete a character that has just been written using Console.WriteLine?
You can use Console.CursorTop like this :
for (int i = distance; i > 0; i = i - 3)
{
Console.WriteLine("distance from target : " + i + " "); // dirty trick to erase longer previous numbers
Thread.Sleep(30);
Console.CursorTop--;
}
Console.CursorTop++; // so that we advance to the next line after the loop.
It moves cursor one line up, so subsequent calls overwrite what was previously in line above.
This approach is not the most efficient one as it will rewrite whole line, but it is simple and from user's point of view only numeric value will be updated.
If so small performance differences matter, you can try to set cursor position more precisely to the place where numeric value starts. I am not sure it is possible but worth trying if it matters.
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);
My question is how to output things in the array in reverse order
grouped by two things with resorting only to the while-loop
(i.e., without for-loop and Reverse method, etc.)
I know that the second while-loop is not correct but I do not know how to modify it.
Thank you in advance for your suggestions.
Console.WriteLine("Please type four things.");
const int MAX_SIZE = 4;
string[] things = new string[MAX_SIZE];
int i = 0;
while (i < MAX_SIZE)
{
Console.WriteLine("Please type the things.");
things[i] = Console.ReadLine();
i++;
}
i = 0;
while (i < MAX_SIZE)
{
Console.Write(things[i] + ", ");
i--;
}
Try
i = MAX_SIZE - 1
while (i >= 0)
{
Console.Write(things[i] + ", ");
i--;
}
The reason I am using MAX_SIZE-1 is because arrays in C# are 0-based. The first element will always be in position 0. If the array has 4 elements, the final element will be in position 3.
If you want to print things in twos, you can just do the following:
i = MAX_SIZE - 1
while (i >= 0)
{
Console.Write(things[i-1] + ", " things[i]);
i -= 2;
}
Is there any reason you want to use a while loop instead of a for loop?
for(var i=0;i<MAX_SIZE;i++) {
Console.WriteLine("Please type the things.");
things[i] = Console.ReadLine();
i++;
}
for(var i=MAX_SIZE-1;i>=0;i--){
Console.Write(things[i] + ", ");
}
If I understand the task correctly, next code should work for you:
int i = things.Length - 1;
while(i > 0)
{
Console.Write("({0}, {1}) ", things[i], things[i - 1]);
i -= 2;
}
//in case the the list lenght is odd, output the last element without pair
if(i == 0)
{
Console.Write("({0})", things[i]);
}
if statement can be omitted if things list length is always even because it is required only if you need to pring the last (the first in things list) element, which has no pair.
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()))));
}