I have an assignment where I need to find the product of all of the numbers in an array, I'm not sure how to do this.
int[] numbers = new int[SIZE];
Console.WriteLine("Type in 10 numbers");
Console.WriteLine("To stop, type in 0");
for (int input = 0; input < SIZE; input++)
{
userInput = Console.ReadLine();
numberInputed = int.Parse(userInput);
if (numberInputed == ZERO)
{
numberInputed = ONE;
break;
}
else
{
numbers[input] = numberInputed;
}
}
This is where I'm trying to find the product of all of the numbers in the array.
foreach (int value in numbers)
{
prod *= value;
}
Console.WriteLine("The product of the values you entered is {0}", prod);
What am I doing wrong in the foreach statement? Thanks in advance
Edit, left out my declared values
const int SIZE = 10;
const int ZERO = 0;
string userInput;
int numberInputed;
int prod = 1;
It now works when I type in all ten values but if I put a 0 in order to break the loop then everything equals 0. How do I prevent a 0 from being entered into the array?
It's possible you initialize prod to 0, which means no matter what numbers are in your array, prod will remain 0. Make sure you initialize it to 1 to get the correct result:
int prod = 1;
foreach (int value in numbers)
{
prod *= value;
}
You could also use Linq's Aggregate extension method to do the same thing:
using System.Linq; // put with other using directives
int prod = numbers.Aggregate(1, (a, b) => a * b);
Update
The real problem (which I failed to notice before) is that your array isn't being fully populated if you break out of your loop early. So any array entries you didn't set are still initialized to 0. To fix this, use a List<int> instead of an int[]:
using System.Collections.Generic; // put with other using directives
List<int> numbers = new List<int>(SIZE); // Capacity == SIZE
...
for (int input = 0; input < SIZE; input++)
{
...
if (numberInputed == ZERO)
{
break;
}
else
{
numbers.Add(numberInputed);
}
}
The problem is that you don't keep track of how many items there are in the array that actually are assigned a value. If you exit from the loop using a zero input, then the rest of the items are unchanged. As they are zero by default, you will be using those zeroes in your second loop, and when you have a zero somewhere in the array, the total product becomes zero.
Keep track of how many items there are by keeping the loop variable outside the loop:
int input = 0;
while (input < SIZE)
{
userInput = Console.ReadLine();
numberInputed = int.Parse(userInput);
if (numberInputed == ZERO) {
break;
}
numbers[input] = numberInputed;
input++;
}
Now you can use only the items that are actually assigned:
for (int i = 0; i < input; i++) {
prod *= numbers[i];
}
Multiply all numbers inside an Array
int[] array = { 1, 2, 3, 4, 5 };
int sum = array[0];
for (int i = 1; i != array.Length; i++)
{
sum *= array[i];
}
If your array is somehow populated with zeroes (0), then use List instead of an array.
Related
In my class i have to create a method that will find multiple maximum numbers within an array. the user will input how many maximum numbers they are wanting and then the code should display all those numbers. if i select 2 this code will show me the 2 maximum numbers but if im wanting more it just doesnt work. i was trying to search the array for the maximum number and then have it display the outcome and then change that element to 0 and than repeat the loop until it hits that number (userinput). im soo frustrated can someone help me please
public static int FindingMaxNum(int[] arr, int max)
{
int userinput;
Console.Write("Enter the number of maximum values: ");
userinput = Convert.ToInt32(Console.Read());
int i = 0;
int c = 0;
for (i = 0; i < arr.Length; i++)
{
if (arr[i] >= max)
{
max = arr[i];
c++;
while (c <= userinput)
{
Console.WriteLine(max);
arr[i] = 0;
break;
}
}
}
return -1;
}
If I understand correctly, you want to get some number of items from an array whose values are greater than all the others in the array.
If so, something like this modified version of your method may do the trick:
public static void WriteMaxNum(int[] arr)
{
if (arr == null)
{
Console.WriteLine("The array is null");
return;
}
if (arr.Length == 0)
{
Console.WriteLine("The array is empty");
return;
}
int count = arr.Length;
int numMaxValues;
// Get number of max values to return from user
do
{
Console.Write("Enter the number of maximum values (1 - {0}): ", count);
} while (!int.TryParse(Console.ReadLine(), out numMaxValues) ||
numMaxValues < 1 ||
numMaxValues > count);
// Output the max values
Console.Write("The {0} max values are: ", numMaxValues);
Console.WriteLine(string.Join(", ", arr.OrderByDescending(i => i).Take(numMaxValues)));
}
Usage
static void Main(string[] args)
{
var myArray = new[] { 1, 9, 4, 8, 2, 5, 0, 7, 6, 3 };
WriteMaxNum(myArray);
Console.Write("\nDone!\nPress any key to exit...");
Console.ReadKey();
}
Output
Simple solution with average complexity O(nlogn):
Sort the array first then print the last N nos.
int[] arr = new int[]{-5,-69,1250,24,-96,32578,11,124};
Array.Sort(arr);
int n=3;
for(int i=arr.Length-1;i>=0 && n>0 ;--i){
n--;
Console.WriteLine(arr[i]);
}
Now coming to your code, there are multiple problems. First there is no need to take 'max' as parameter in your function. Second you are looping only arr.Length times once. There should be nested loop, outer one of which has to run userInput times and inner on has to iterate over all the values. Third you should initialize to extracted value position to minimum value so that the method works for negative numbers too.
Refined code:
for(int i=0;i<userinput;++i){
int max = int.MinValue,pos=-1;
for(int j=0;j<arr.Length;++j){
if(max<arr[j]){
pos = j;
max = arr[j];
}
}
arr[pos] = int.MinValue;
Console.Write(max+",");
}
I have implemented binary search algorithm in a console window application in C#. I am generating random values to the array and sorting them using Random() and Array.Sort() functions respectively.
The Problem - No matter what Key(item to be searched in the array) I give, the program is returning Key not found when the array items are generated using Random function
This does not happen if I enter the array elements manually using Console.ReadLine().
TLDR: Binary Search algorithm works fine when array items are entered manually, but does not work when array items are generated using Random function.
Can anyone point out what is the mistake I am doing?
My code - Random Generated array items.
namespace BSA
{
class Program
{
static void Main(string[] args)
{
var arr = new int[10];
Random rnd = new Random();
for (int i = 0; i < arr.Length; i++)
{
arr[i] = rnd.Next(1, 1000);
}
Array.Sort(arr);
for (int i = 0; i < arr.Length; i++)
{
Console.Write("{0}\n", i);
}
while (true)
{
Console.WriteLine("Enter the number to be searched in the array.");
var searchItem = Convert.ToInt32(Console.ReadLine());
var foundPos = Search(arr, searchItem);
if (foundPos > 0)
{
Console.WriteLine("Key {0} found at position {1}", searchItem, foundPos);
}
else
{
Console.WriteLine("Key {0} not found", searchItem);
}
}
}
public static int Search(int[] arr, int item)
{
var min = 0;
var N = arr.Length;
var max = N - 1;
int basicOperations = 0;
basicOperations++;
do
{
var mid = (min + max)/2;
if (arr[mid] == item)
return mid;
if (item < arr[mid])
max = mid - 1;
else
min = mid + 1;
basicOperations++;
} while (min <= max);
return basicOperations;
}
}
}
Please let me know if I am doing any silly mistake or I am committing a blunder in the above code. Any help would be really helpful.
Your search code works fine as far as I can see. However when you list the contents of the random array, you should write arr[i] rather than i to see what's in the array so you can pick a search value in it. Alternatively, pass arr[x] as the search item. It should return x.
Your code works correctly. You're just not looking for the right keys. The function that prints the values generated into the array prints the loop counter instead:
for (int i = 0; i < arr.Length; i++)
{
Console.Write("{0}\n", i);
}
You need to change it to:
for (int i = 0; i < arr.Length; i++)
{
Console.Write("{0}\n", arr[i]);
}
This will show you the values actually generated.
Comment too short for this so added answer to show how to set basicOperations and still return search position. You declare basicOperations as an out parameter which means the method can change it so the caller can see it when method returns.
public static void Main(string[] args)
{
... ... ...
int basicOperations;
int searchPos = IntArrayBinarySearch(arr, arr[5], out basicOperations);
Console.WriteLine("Found at {0} basic ops={1}", searchPos, basicOperations);
}
public static int IntArrayBinarySearch(int[] data, int item, out int basicOperations)
{
var min = 0;
var N = data.Length;
var max = N - 1;
basicOperations = 0;
basicOperations++;
and at bottom, you don't need to return out parameters, just return -1 to indicate failure as you did before
return -1;
I have an assingment and I'm a bit lost. In an array of 10 (or less) numbers which the user enters (I have this part done), I need to find the second smallest number. My friend sent me this code, but I'm having a hard time understanding it and writing it in c#:
Solved it!!! :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int vnesena;
int? min1 = null;
int? min2 = null;
for(int i=1; i<11; i=i+1)
{
Console.WriteLine("Vpiši " + i +"." + " število: ");
vnesena = Convert.ToInt32(Console.ReadLine());
if (vnesena == 0)
{
break;
}
if (min1 == null || vnesena < min1)
{
min2 = min1;
min1 = vnesena;
}
else if (vnesena != min1 && (min2==null || vnesena<min2))
{
min2 = vnesena;
}
}
if (min1 == null || min2 == null)
{
Console.WriteLine("Opozorilo o napaki");
}
else
{
Console.WriteLine("Izhod: " + min2);
}
Console.ReadKey();
}
}
}
That code is too complicated, so try something like this.
int[] numbers = new int[10];
for (int i = 0; i < 10; i++)
{
numbers[i] = int.Parse(Console.ReadLine());
}
Array.Sort(numbers);
Console.WriteLine("Second smallest number: " + numbers[1]);
If the code isn't too obvious, let me explain:
Declare an array of 10 integers
Loop 10 ten times and each time, ask for user input & place input as an integer to the array
Sort the array so each number is in the number order (smallest first, biggest last).
The first integer is smallest (input at index 0, so numbers[0]) and the second smallest is obviously numbers[1].
Of course, for this piece of code to work, you have to use this code in console program.
As you didn't mention if you are allowed to use built in sorting functions etc, I assume that Array.Sort() is valid.
EDIT: You updated your topic so I'll change my code to match criterias.
int[] numbers = new int[10];
bool tooShortInput = false;
for (int i = 0; i < 10; i++)
{
int input = int.Parse(Console.ReadLine());
if (input != 0)
{
numbers[i] = input;
}
else
{
if (i == 2)
{
Console.WriteLine("You only entered two numbers!");
tooShortInput = true;
break;
}
else
{
for (int j = 0; j < 10; j++)
{
if (numbers[j] == 0)
{
numbers[j] = 2147483647;
}
}
break;
}
}
}
// Sort the array
int temp = 0;
for (int write = 0; write < numbers.Length; write++) {
for (int sort = 0; sort < numbers.Length - 1; sort++) {
if (numbers[sort] > numbers[sort + 1]) {
temp = numbers[sort + 1];
numbers[sort + 1] = numbers[sort];
numbers[sort] = temp;
}
}
}
if (!tooShortInput)
{
Console.WriteLine("Second smallest number: " + numbers[1]);
}
If you don't understand the updated code, let me know, I will explain.
NOTE: This is fastly coded and tested with android phone so obviously this code isn't 5 star quality, not even close, but it qualifies :-).
Regards, TuukkaX.
To paraphrase the code given:
Set 2 variables to nothing. (This is so that there can be checks done later. int? could be used if you want to use null for one idea here.
Start loop through values.
Get next value.
If the minimum isn't set or the new value is lower than the minimum, replace the second lowest with the former lowest and lowest with the new value that was entered.
Otherwise, check if the new value isn't the same as the minimum and if the minimum isn't set or the entered value is lower than the second lowest then replace the second lowest with this new value.
Once the loop is done, if either minimum value isn't filled in then output there isn't such a value otherwise output the second lowest value.
Imagine if you had to do this manually. You'd likely keep track of the lowest value and second lowest value as you went through the array and the program is merely automating this process. What is the problem?
This is a rough translation of what your friend gave you that isn't that hard to translate to my mind.
int enteredValue;
int? smallest = null, secondSmallest = null;
for (int i = 0; i < 10; i = i + 1)
{
Console.WriteLine("Vpiši " + i+1 + " število: ");
enteredValue = Convert.ToInt32(Console.ReadLine());
if (smallest==null || enteredValue<smallest) {
secondSmallest=smallest;
smallest = enteredValue;
} else if (enteredValue!=smallest && enteredValue<secondSmallest) {
secondSmallest= enteredValue;
}
}
Why use a loop and not take advantage of the Array.Sort method?
int[] numbers = new int[4] { 4, 2, 6, 8 };
Array.Sort(numbers);
int secondSmallestNumber = numbers[1];
I am trying to create a bowling program that when you enter in your name followed by your score, it will take the average, lowest, and highest scores of the players and print them. However for some reason I cannot get the lowest score to print, as when I hit enter twice, it will use the blank value instead of the lowest entered value and name. How can I fix this so that it will display the lowest score?
{
class Program
{
static void Main(string[] args)
{
const int SIZE = 10;
int i;
// create an array with 10 elements
string[] scoreInfo = new string[SIZE];
string[] names = new string[SIZE];
int[] scores = new int[SIZE];
for (i = 0; i < SIZE; i++)
{
// Prompt the user
Console.Write("Enter your first name and score on one line");
Console.WriteLine(" separated by a space.");
// Read one line of data from the file and save it in inputStr
string inputStr = Console.ReadLine( );
// if statement to break when the user enters a zero
if (inputStr == String.Empty)
{
break;
}
// The Split method creates an array of two strings
scoreInfo = inputStr.Split();
// Parse each element of the array into the correct data type
names[i] = scoreInfo[0];
scores[i] = int.Parse(scoreInfo[1]);
}
Console.WriteLine("The avarage score is {0}", AverageScore(scores, i));
Console.WriteLine("{0} scored the lowest at {1}", names[LowScore(scores, i--)], scores[LowScore(scores, i--)]);
Console.WriteLine("{0} scored the highest at {1}", names[HighScore(scores)], scores[HighScore(scores)]);
Console.ReadLine();
Console.ReadLine();
}
static int LowScore(int[] scores, int j)
{
int min = scores.Min();
return Array.IndexOf(scores, min);
}
static int HighScore(int[] scores)
{
int max = scores.Max();
return Array.IndexOf(scores, max);
}
static double AverageScore(int[] numbers, int j)
{
double average = 0;
for (int i = 0; i < j--; i++)
{
int product = 1;
product = numbers[i] * product;
average = product / j;
}
return average;
}
}
}
Use a different data structure and make less work for yourself.
Start with a dictionary that maps names to scores so that you don't have to mess around with indexes.
Then, LINQ is your friend, as you've already noticed. You don't need to create functions for things that already exist (like min/max/average).
eg.
Dictionary<string, int> ranking = new Dictionary<string, int>();
ranking.Add("adam", 20);
ranking.Add("bill", 10);
ranking.Add("carl", 30);
double avg = ranking.Average(kvp => (double)kvp.Value);
var sorted = ranking.OrderBy(kvp => kvp.Value);
var min = sorted.First();
var max = sorted.Last();
Console.WriteLine("Average: {0}", avg);
Console.WriteLine("Lowest: {0} with {1}", min.Key, min.Value);
Console.WriteLine("Highest: {0} with {1}", max.Key, max.Value);
Modify your Average function like this:-
static double AverageScore(int[] numbers, int j)
{
double sum = 0;
for (int i = 0; i < j; i++)
{
sum += numbers[i];
}
return (double)sum / j;
}
I am not sure why you were taking product of items for finding average of scores.
And Your Min function like this:-
static int LowScore(int[] scores, int j)
{
int min = scores.Where((v, i) => i < j).Min();
return Array.IndexOf(scores, min);
}
Here, you are passing the complete array of integer, so if only 3 players entered values, rest of the values will be initialized to default, i.e. 0 for int, Thus you were getting 0 as Min value.
Also, You need to change the method invocation like this:-
Console.WriteLine("{0} scored the lowest at {1}", names[LowScore(scores, i)], scores[LowScore(scores, i)]);
I have a 1-dimensional array that fills up a table of 40 random elements (all the values are either 0 or 1). I want to find the longest consecutive span of values.
For example:
In 111100101 the longest row would be 1111 because it has four consecutive values of 1.
In 011100 the result is 111.
I have no idea how to check upon the "next element" and check if it's a 0 or 1.
Like the first would be 1111 (count 4) but the next would be a 0 value, meaning I have to stop counting.
My idea was placing this value (4) in a other array (example: 111100101), and place the value of the 1's back on zero. And start the process all over again.
To find the largest value I have made another method that checks up the biggest value in the array that keeps track of the count of 0's 1's, this is not the problem.
But I cannot find a way to fill the array tabelLdr up, having all the values of the group of elements of the same kind (being 0 or 1).
In the code below I have 2 if's and of course it will never go into the second if (to check if the next value in the array is != to its current state (being 0 or 1).
public void BerekenDeelrij(byte[] tabel, byte[] tabelLdr)
{
byte LdrNul = 0, Ldréén = 0;
//byte teller = 0;
for (byte i = 0; i < tabel.Length; i++)
{
if (tabel[i] == 0)
{
LdrNul++;
//this 2nd if cleary does not work, but i have no idea how to implend this sort of idea in my program.
if (tabel[i] == 1) //if value != 0 then the total value gets put in the second array tabelLdr,
{
tabelLdr[i] = LdrNul;
LdrNul = 0
}
}
if (tabel[i] == 1)
{
Ldréén++;
if (tabel[i] == 0)
{
tabelLdr[i] = Ldréén;
Ldréén = 0;
}
}
}/*for*/
}
This method should do what you need:
public int LargestSequence(byte[] array) {
byte? last = null;
int count = 0;
int largest = 0;
foreach (byte b in array) {
if (last == b)
++count;
else {
largest = Math.Max(largest, count);
last = b;
count = 1;
}
}
return Math.Max(largest, count);
}
Even while i is the loop counter, it is still just a variable. A valid for statement is for (;;), which is an infinite loop. Notice the for statement increments i, as in i++. The expression i = i + 1 works just as well.
Im unsure if you need the longest "row" of ones or longest row of either 0 or 1. This will work for the latter
var max = 0;
var start = 0;
var current = -1;
var count = 0;
for(int i = 0;i<table.Length;i++)
{
if(current = table[i])
{
count++;
}
else
{
current = table[i];
if(max < count)
{
max = count;
start = i-count;
}
count = 1;
}
}
if(max < count)
{
max = count;
start = i-count;
}
//max is the length of the row starting at start;