I'm trying to make a binary search for a random array which has 10 numbers. When I run my code, and the number I input is a number within the random array, instead of just outputting "Found it" once, it will continuously output "Found it" until I close the program, but I can't understand what I've done to make it keep outputting "Found it".
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Binary_Search
{
class Program
{
static void Main(string[] args)
{
int n = 10; //10 values in array
Random r = new Random();
int b; //value to search
int i; //loop control value
int[] a = new int[n + 1];
a[0] = 0; //starts at 0
for (i = 1; i <= n; i++) // set the array up
a[i] = a[i - 1] + r.Next(1, 10); // + random numbers from 1 to 10
for (i = 1; i <= n; i++)
Console.WriteLine(" a[" + i + "] + " + a[i] + ": "); // outputs the numbers for each value of array
Console.WriteLine();
Console.ReadLine();
Console.WriteLine("What number are you looking for?");
b = int.Parse(Console.ReadLine()); // enter value that you want to find
i = 1;
Console.ReadLine();
int min = 1;
int max = n - 1;
do
{
int mid = (min + max) / 2;
if (a[mid] == b)
{
Console.WriteLine("Found it");
}
else if (a[mid] > b)
max = mid;
else if (a[mid] < b)
min = mid;
} while (min <= max);
Console.ReadLine();
}
}
}
You need to break/stop the loop once you've found it.
if (a[mid] == b)
{
Console.WriteLine("Found it");
break; // add this
}
The "Found it" message keeps getting printed because of your do-while condition. You get into an infinite loop because after several iterations, min equals to max.
Set the condition to while (min < max); instead of while (min <= max); and have the if condition after the loop.
This should do the trick:
do
{
int mid = (min + max) / 2;
if (a[mid] > b)
max = mid;
else if (a[mid] < b)
min = mid;
} while (min < max);
if (a[mid] == b)
{
Console.WriteLine("Found it");
}
Related
I am a Beginner in C# and I was wondering what I got wrong with this code.
I want the user to input the amount of numbers
Then an array with that amount gets created
Then finally I want to display all the numbers in the array.
The Code:
using System;
using System.Threading;
using System.Collections.Generic;
namespace Console_Project_alpha
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter the amount of numbers: ");
int amount = Convert.ToInt32(Console.ReadLine());
int[] numbers = new int[amount];
string nth = "";
for( int i = 1; i <= amount ; i++)
{
if(i == 1)
{
nth = i + "st";
}
else if( i == 2)
{
nth = i + "nd";
}
else if( i == 3)
{
nth = i + "rd";
}else{
nth = i + "th";
}
Console.Write("\nEnter " + nth + " Number:");
int num = Convert.ToInt32(Console.ReadLine());
for(int j = 0; j <= numbers.Length; j++)
{
numbers[j] = num;
}
}
System.Console.WriteLine(numbers);
}
}
}
Any help is highly appreciated. Thanks in advance
In your code you all time overwriting the same value to all index in
array.
If you want to display values from array in console just iterate after array
Properly worked example based on your code:
class Program
{
static void Main(string[] args)
{
Console.Write("Enter the amount of numbers: ");
int amount = Convert.ToInt32(Console.ReadLine());
int[] numbers = new int[amount];
string nth = "";
int index = 0;
for (int i = 1; i <= amount; i++)
{
if (i == 1)
{
nth = i + "st";
}
else if (i == 2)
{
nth = i + "nd";
}
else if (i == 3)
{
nth = i + "rd";
}
else
{
nth = i + "th";
}
Console.Write("\nEnter " + nth + " Number:");
int num = Convert.ToInt32(Console.ReadLine());
numbers[index] = num;
index++;
}
for (int i = 0; i <= numbers.Length - 1; i++)
{
Console.WriteLine(numbers[i]);
}
Console.ReadLine();
}
}
I am trying to solve an exercise in C# as follows:
Write a program that generates 20 random integers between 0 and 9 and displays the count for each number.
Use an array of ten integers, say counts, to store the counts for the number of 0s, 1s, ..., 9s.)
This is what i come up with which kind of work but i have a problem with the 0's counting 1 extra all the time.
using System.Collections.Generic;
using System.Text;
namespace ArrayExercises
{
class TaskFive
{
public static void FindNumberCount()
{
int c0=0,c1=02,c2=0,c3=0,c4=0,c5=0,c6=0,c7=0,c8=0,c9=0;
int[] arr = new int[20];
Random rand = new Random();
Console.WriteLine("Numbers generated ");
for (int i = 0; i < 19; i++)
{
arr[i] = rand.Next(0, 10);
Console.WriteLine(arr[i]);
}
foreach(int number in arr)
{
if (number == 0) { c0++; }
else if (number == 1) { c1++; }
else if (number == 2) { c2++; }
else if (number == 3) { c3++; }
else if (number == 4) { c4++; }
else if (number == 5) { c5++; }
else if (number == 6) { c6++; }
else if (number == 7) { c7++; }
else if (number == 8) { c8++; }
else if (number == 9) { c9++; }
}
Console.WriteLine
(
$"Number of 0's: {c0} \n" +
$"Number of 1's: {c1} \n" +
$"Number of 2's: {c2} \n" +
$"Number of 3's: {c3} \n" +
$"Number of 4's: {c4} \n" +
$"Number of 5's: {c5} \n" +
$"Number of 6's: {c6} \n" +
$"Number of 7's: {c7} \n" +
$"Number of 8's: {c8} \n" +
$"Number of 9's: {c9}"
);
}
}
}
Thanks in advance :)
You could shorten it like this
public static void FindNumberCount()
{
int[] count = new int[10];
Random rand = new Random();
int[] arr = new int[20];
for (int i = 0; i < arr.Length; i++)
{
arr[i] = rand.Next(0, 10);
Console.WriteLine(arr[i]);
count[arr[i]]++;
}
for (int i = 0; i < count.Length; i++)
{
Console.WriteLine($"Number of {i}'s: {count[i]}");
}
}
If you want draw 20 numbers you should for (int i = 0; i < 20; i++) not 19.
int[] counts = new int[10];
int[] numbers = new int[20];
var random = new Random();
for (int i = 0; i < numbers.Length; i++)
{
// Generate random numbers
numbers[i] = random.Next(0, 9);
// Increment the count of the generated number
counts[numbers[i]]++;
}
the for loop you use loops only 19 times.
You must change the "i < 19" to "i < 20".
In your program, the for loop leaves the last int in the array at it's default value (0),
this also explains, why you always have one more zero.
Hope this helped.
The issues is in this line
for (int i = 0; i < 19; i++)
You initialized an array with 20 int and set only value to 19 of them.
If you don't set the value int defaults to Zero and hence you always get one extra zero
Change your code as below
for (int i = 0; i <= 19; i++)
The halting condition of the first for loop should be i<20. Then your program should work.
This is how I would solve it:
static void Main(string[] args)
{
Random random = new Random();
//Fill array with random numbers
int[] array = new int[20];
for (int i = 0; i < array.Length; i++)
array[i] = random.Next(0, 10);
//Count how many times a number occurs
int[] numberCounts = new int[10];
for (int i = 0; i < array.Length; i++)
numberCounts[array[i]]++;
//Print the count of the numbers
for(int i = 0; i < numberCounts.Length; i++)
Console.WriteLine("Number of " + i + "'s: " + numberCounts[i]);
//Keep the console open
Console.ReadLine();
}
I have to create a program to print pyramid pattern (1 2 33 44 555 666...) and sum the numbers.
Here is my solution:
static void Main(string[] args)
{
int i, j;
i = 1;
int sum = 0;
while (i < 9)
{
for (j = 1; j <= i; j+=2)
{
Console.Write(i);
}
Console.Write("\n");
sum += i;
i++;
}
Console.WriteLine("Summary: " + sum);
Console.ReadLine();
}
And my output:
What am I doing wrong here (wrong summary)?
Here is an optimized and working version of your code:
int sum = 0;
for (int i = 1; i < 9; i++)
{
int current = 0;
for (int j = 1; j <= i; j += 2)
{
Console.Write(i);
current = 10 * current + i;
}
Console.WriteLine();
sum += current;
}
Console.WriteLine("Summary: " + sum);
The main issue is that you were only capturing the value of i (integer being printed) and using that to calculate the summary. As seen here, the current value is captured (for the entire line) within the nested loop and then added to the summary to give you the result you expect.
HTH
Only made small adjustments to your code.
static void Main(string[] args)
{
int i, j;
i = 1;
int sum = 0;
while (i <= 9)
{
for (j = 0; j <= i - 1; j++)
{
Console.Write(i);
sum += i * (int)Math.Pow(10, j);
}
Console.WriteLine();
i++;
}
Console.WriteLine("Sum: " + sum);
Console.ReadLine();
}
If you like to extend your code to let the user pick a number you can do this:
Instead of this line:
while (i <= 9)
You can do this:
Console.WriteLine("Please enter a number between 1 and 9:");
int maxValue = 1;
while (true)
{
if (!int.TryParse(Console.ReadLine(), out maxValue) || maxValue < 1 || maxValue > 9)
{
Console.WriteLine("Wrong input! Try again:");
continue;
}
break;
}
while (i <= maxValue)
Please find not optimized but quick solution
int i, j;
i = 1;
int sum = 0;
while (i < 9)
{
int current = 0;
for (j = 1; j <= i; j += 2)
{
current = 10 * current + i;
Console.Write(i);
}
Console.Write("\n");
sum += current;
i++;
}
Console.WriteLine("Summary: " + sum);
Console.ReadLine();
I need to find the difference of each number value in an array from an average value. I need to loop through each value and subtract each value FROM the average and display the difference. I have tried several different ways but the difference always comes out as 0 at the end. What am i doing wrong here?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
namespace AvgNDiff
{
class Program
{
static void Main(string[] args)
{
int[] numbers = new int[10];
int x = 0;
int i;
string entryString = "";
int counter = 0;
int countdown = 10;
int sum = 0;
int average = 0;
while (counter < numbers.Length && numbers[x] != 10 && entryString != "0")
{
if (x == 0)
Write("Enter up to 10 numbers or type 0 to stop > ");
else if (x == 9)
Write("Enter {0} more number or type 0 to stop > ", countdown);
else
Write("Enter up to {0} more numbers or type 0 to stop > ", countdown);
entryString = ReadLine();
numbers[x] = Convert.ToInt32(entryString);
if (entryString != "0")
{
sum += numbers[x];
counter++;
x++;
}
countdown--;
}
average = sum / x;
WriteLine("\n\nYou entered {0} numbers with a sum of {1}", x, sum);
WriteLine("The average of your numbers is " + average);
WriteLine("\n\nNumber Difference");
WriteLine("-------------------------------");
for (i=0; i < x; i++)
{
int value = numbers[i];
int diff = average-value;
WriteLine(String.Format("{0,-10} {1,-10}", (numbers[i]), diff));
}
ReadKey();
}
}
}
Take a look here
int value = numbers[i];
int diff = value - average;
WriteLine(String.Format("{0,-10} {1,-10}", (numbers[i]), value));
the key issue here is the writeline statement.
Youve told it to display numbers[i], and oh wait.. numbers[i] (as thats what value is)
yet diff contains the variance from the average...
static void Main(string[] args)
{
List<int> numberList = new List<int>();
Console.WriteLine("Enter up to 10 numbers or type 0 to stop:");
for (int i = 0; i < 10; i++)
{
int userInput = 0;
while (!int.TryParse(Console.ReadLine(), out userInput))
{
Console.WriteLine("Only integer numbers accepted, let's try again...:");
}
if (userInput == 0)
{
break;
}
else
{
numberList.Add(userInput);
if (i < 9)
{
Console.WriteLine("Yeah, {0} more number{1} to go!", (9 - i), (i == 8 ? "" : "s"));
}
}
}
double average = numberList.Average();
for (int i = 0; i < numberList.Count; i++)
{
Console.WriteLine("#{0}: {1} - {2} = {3}", (i+1), numberList[i], average, (numberList[i] - average));
}
Console.ReadLine();
}
Do not cram the entire soultion into the single Main, extract (and debug) a method:
// Subtract each item from the average
private static double[] MyNormalize(int[] source) {
double sum = 0.0;
foreach (var item in source)
sum += item;
double[] result = new double[source.Length];
for (int i = 0; i < source.Length; ++i)
result[i] = sum / source.Length - source[i];
return result;
}
...
static void Main(string[] args) {
int[] numbers = new int[10];
...
// Input
while (counter < numbers.Length && numbers[x] != 10 && entryString != "0") {
...
entryString = ReadLine();
numbers[x] = Convert.ToInt32(entryString);
}
// Business logic
double[] norm = MyNormalize(numbers);
// Output
for (int i = 0; i < numbers.Length; ++i)
WriteLine(String.Format("{0,-10} {1,-10}", numbers[i], norm[i]));
}
I'm trying to get this program to let me enter a desired number(entries), then enter a desired value to this entries. It should write out the biggest value(green), smallest(red) then the rest of the sequence. And in the next row, biggest and smallest should change places(didn't even type code for this). What am I doing wrong(especially in the last 'for loop' )
int max = int.MinValue;
int min = int.MaxValue;
Console.WriteLine("How many numbers do you want to enter ? ");
int kolicinaBrojeva = int.Parse(Console.ReadLine());
int[] niz = new int[kolicinaBrojeva];
for (int i = 0; i < kolicinaBrojeva; i++)
{
Console.WriteLine("Enter {0}. a number:", i + 1);
niz[i] = int.Parse(Console.ReadLine());
if (niz[i] > max)
{
max = niz[i];
}
if (niz[i] < min)
{
min = niz[i];
}
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(max + ", ");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(min + ", ");
Console.ResetColor();
for (int i = 1; i >= 0; i--)
{
if (niz[i] < max && niz[i] > min)
{
Console.Write(niz[i] + ", ");
}
}
The last for loop should be like below:
for (int i = kolicinaBrojeva - 1; i >= 0; i--)
{
if (niz[i] < max && niz[i] > min)
{
Console.Write(niz[i] + ", ");
}
}
Your current code will read in kolicinaBrojeva numbers correctly, but min and max will not be set correctly. No other int is greater than int.MaxValue and similarly, no other int is less than int.MinValue. You could do the following instead:
int max = int.MinValue;
int min = int.MaxValue;
With this, you'll get the correct min and max, however, I'm not sure of what you're trying to do in the last loop.
Try this.
using System;
class Test
{
static void Main()
{
string[] temp = Console.ReadLine().Split();
int[] numbers = new int[temp.Length];
for (var i = 0; i < numbers.Length; i++)
numbers[i] = int.Parse(temp[i]);
int minIndex = 0;
int maxIndex = 0;
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] < numbers[minIndex])
minIndex = i;
if (numbers[i] > numbers[maxIndex])
maxIndex = i;
}
Swap(ref numbers[maxIndex], ref numbers[0]);
Swap(ref numbers[minIndex], ref numbers[numbers.Length - 1]);
Print(numbers, ConsoleColor.Green, ConsoleColor.Red);
Swap(ref numbers[0], ref numbers[numbers.Length - 1]);
Print(numbers, ConsoleColor.Red, ConsoleColor.Green);
}
static void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
static void Print(int[] array, ConsoleColor a, ConsoleColor b)
{
Console.ForegroundColor = a;
Console.Write(array[0] + " ");
Console.ResetColor();
for (int i = 1; i < array.Length - 1; i++)
Console.Write(array[i] + " ");
Console.ForegroundColor = b;
Console.WriteLine(array[array.Length - 1]);
Console.ResetColor();
}
}