infinite loop in C# - c#

This simple program take an input of integers and print them , but stop printing if it sees 60
string input = string.Empty;
int intValue = 0;
int[] numbers = new int[5];
for (int i = 0; i < 4; i++)
{
input = Console.ReadLine();
if (int.TryParse(input, out intValue))
numbers[i] = intValue;
}
for (int i = 0; i < numbers.Length; i++)
{
while (numbers[i] != 60)
{
Console.WriteLine(intValue);
}
}
the program go on an infinite loop after the 4th input
like that
Input:
1
2
3
4
4
4
4
4
4 ........ and so on
and i don't know the reason .... ^_^

while (numbers[i] != 60)
{
Console.WriteLine(intValue);
}
should be:
if (numbers[i] != 60)
{
Console.WriteLine(intValue);
}

string input = string.Empty;
int intValue = 0;
int[] numbers = new int[5];
for (int i = 0; i < 4; i++)
{
input = Console.ReadLine();
if (int.TryParse(input, out intValue))
numbers[i] = intValue;
}
for (int i = 0; i < numbers.Length; i++)
{
/*while (numbers[i] != 60)*/
if (numbers[i] != 60) // it should be if condition, while statement made it infinite
{
Console.WriteLine(intValue);
}
}

Related

calculator computing multiple numbers

static void Main(string[] args)
{
string again;
do
{
Console.Write("Enter size to compute: ");
int size = Convert.ToInt32(Console.ReadLine());
int[] numbers = new int[size];
float[] numberS = new float[size];
Console.Write("Pick one of the operation \"(+) (-) (*) (/)\": ");
string operation = Console.ReadLine();
if (operation == "+")
{
for (int i = 0; i < size; i++)
{
Console.Write("Enter numbers: ");
numbers[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The sum is:" + add(numbers));
}
else if (operation == "-")
{
for (int i = 0; i < size; i++)
{
Console.Write("Enter numbers: ");
numbers[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The subtraction is:" + subtract(numbers));
}
else if (operation == "*")
{
for (int i = 0; i < size; i++)
{
Console.Write("Enter numbers: ");
numbers[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The mulplication is:" + multiply(numbers));
}
else if (operation == "/")
{
for (int i = 0; i < size; i++)
{
Console.Write("Enter numbers: ");
numberS[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The division is:" + division(numberS));
}
else Console.WriteLine("Invalid Input");
Console.Write("Do you want to compute again Y/N: ");
again = Console.ReadLine().ToUpper();
Console.Clear();
} while (again == "Y");
}
static int add(int[] numbers)
{
int total = 0;
for (int i = 0; i < numbers.Length; i++)
{
total += numbers[i];
}
return total;
}
static int subtract(int[] numbers)
{
int total = 0;
for (int i = 0; i < numbers.Length; i++)
{
total += numbers[i] - numbers[i];
}
return total;
}
static int multiply(int[] numbers)
{
int total = 0;
for (int i = 0; i < numbers.Length; i++)
{
total += numbers[i] * numbers[i];
}
return total;
}
static float division(float[] numbers)
{
float total = 0;
for (int i = 0; i < numbers.Length; i++)
{
total += numbers[i] / numbers[i];
}
return total;
}
I was expecting the same results in my phones calculator but no
Your code itself is fine. However your subtract, multiply and division methods are wrong. They are calculating something totally different than intended.
The multiply-method sums the squares of the entered numbers.
The subtract-method always subtracts the current number of itself which equals 0 and always results with a total of 0.
The division method always divides the current number by itself which is 1 and results with a total which equals the number of numbers entered.
Try these methods instead:
static int subtract(int[] numbers)
{
if (numbers.Length == 0)
return 0;
int total = numbers[0];
for (int i = 1; i < numbers.Length; i++)
{
total -= numbers[i];
}
return total;
}
static int multiply(int[] numbers)
{
if (numbers.Length == 0)
return 0;
int total = numbers[0];
for (int i = 1; i < numbers.Length; i++)
{
total *= numbers[i];
}
return total;
}
static float division(float[] numbers)
{
if (numbers.Length == 0)
return 0;
float total = numbers[0];
for (int i = 1; i < numbers.Length; i++)
{
total /= numbers[i];
}
return total;
}
In all of these methods the program first checks if there are any numbers passed. Otherwise it just returns 0.
If there are any numbers you set the first entered number to the total variable because it will be used anyway. The temporary result is always stored in the total variable.
Because the first element is already used the for-loop starts from index 1 instead of 0.
Then the operations are applied to the variable with all remaining numbers.

Number Pattern Programs in C#

I want to print something like this
54321
5432
543
54
5
4
3
2
1
int n = 5;
Console.WriteLine();
for (int i = n; i >= 0; i--)
{
for (int j = 1; j <= i; j++)
Console.Write(i.ToString());
Console.WriteLine();
}
Console.WriteLine();
Console.ReadLine();
I would solve this with while-loops
int i = 5, input = 0;
while (i > 0)
{
input *= 10;
input += i--;
}
while (input > 10)
{
Console.WriteLine(input);
input /= 10;
}
while (input > 0)
{
Console.WriteLine(input--);
}
https://dotnetfiddle.net/1L6j6A

Nested For Loop To Print Below Mentioned Pattern

I wanting to print
1
23
456
78910
in C# Console application, Can any one help in doing it for me
I am using this code which works fine for me but I want not to use if statement just want to show my result in nested loop
for (int i = 1; i <= 10; i++)
{
Console.Write(i.ToString());
if (i==1 || i == 3 || i == 6)
{
Console.WriteLine();
}
}
Try this This should print nummber in format as you mentioned
int len = 0;
int count = 1;
for (int i = 1; i < 11; i++)
{
count++;
if (count >= len)
{
len++;
count = 0;
Console.WriteLine("");
}
Console.Write(i);
}
int len = 1;
int count = 0;
for(int i = 0; i < 11 ; i++)
{
count++;
if(count > len)
{
len++;
count = 0;
Console.WriteLine("");
}
Console.Write(i);
}

What to use instead of null

static int min(int[] arr, int a)
{
int min = arr[0];
for (int i = 1; i < a; i++)
if (arr[i] < min)
min = arr[i];
return min;
}
static void Main(string[] args)
{
int[] arr = new int[10];
int i;
Console.WriteLine("Vnesi števila: ");
for (i = 0; i < 10; i++)
{
int stevilo = int.Parse(Console.ReadLine());
if (stevilo == 0)
break;
arr[i] = stevilo;
}
if (i < 2)
{
Console.WriteLine("Napaka - premalo števil!");
Console.ReadKey();
return;
}
int min1 = min(arr, i);
int? min2 = null;
for (int j = 0; j < i; j++)
{
int stevilo = arr[j];
if(stevilo != min1 && (min2 == null || stevilo < min2))
min2 = stevilo;
}
if(min2 == null)
Console.WriteLine("Napaka - vsa števila enaka!");
else
Console.WriteLine("Drugo najmanjše: " + min2.ToString());
Console.ReadKey();
}
}
}
So this code reads from 2 to 10 numbers and writes out the second smallest out of one of them. You can cancel entering the numbers with the key 0. In a case where the second smallest number can't be written out(all entered are for instance 5 5 5 5), then no number is written out).
BUT I found out that we can't use null values, so what can I replace it with? Thanks!
Initialize the min2 variable to 0 then test it when you need to search for the min value and do not use a nullable integer
int min2 = 0;
for (int j = 0; j < i; j++)
{
int stevilo = arr[j];
if(stevilo != 0 && stevilo != min1 && stevilo < min2))
min2 = stevilo;
}
if(min2 == 0)
Console.WriteLine("Napaka - vsa števila enaka!");
else
Console.WriteLine("Drugo najmanjše: " + min2.ToString());
You should also change the input loop to avoid problems with the user input
int stevilo;
string userInput = Console.ReadLine();
if(!Int32.TryParse(userInput, out stevilo) || stevilo == 0)
break;
arr[i] = stevilo;
The use of Int32.TryParse avoids an exception if your user types something that cannot be converted to an integer number
Well, a strange constraint, but once you have it, then just use a bool flag or the fact that the min2 must be different from min1 like this
// ...
int min1 = min(arr, i);
int min2 = min1;
for (int j = 0; j < i; j++)
{
int stevilo = arr[j];
if(stevilo != min1 && (min2 == min1 || stevilo < min2))
min2 = stevilo;
}
if(min2 != min1)
Console.WriteLine("Napaka - vsa števila enaka!");
else
Console.WriteLine("Drugo najmanjše: " + min2.ToString());

C# Recursion Logic

I am attempting to write a function in which the number of nested loops is dependent upon an integer (numStroke) passed into it. For example, when numStrokes is 1, the code executed should be:
double checkProfitability(GameState state, int numStrokes)
{
double[] possiblePayoffs = new double[50000];
int pPIndex = 0;
double sumOfPayoffs = 0;
double averagePayoff = 0;
for (int i = 0; i <= 5; i++)
{
// Populate possiblePayoffs[]
}
for (int ii = 0; ii < pPIndex; ii++)
{
sumOfPayoffs += possiblePayoffs[i];
}
averagePayoff = sumOfPayoffs / pPIndex;
return averagePayoff;
}
When numStrokes is 3, it should be:
double checkProfitability(GameState state, int numStrokes)
{
double[] possiblePayoffs = new double[50000];
int pPIndex = 0;
double sumOfPayoffs = 0;
double averagePayoff = 0;
for (int i = 0; i <= 5; i++)
{
state.colors[i]++;
for (int j = 0; j <= 5; j++)
{
state.colors[j]++;
for (int k = 0; k <= 5; k++)
{
// Populate possiblePayoffs[]
}
state.colors[j]--;
}
state.colors[i]--;
}
for (int ii = 0; ii < pPIndex; ii++)
{
sumOfPayoffs += possiblePayoffs[i];
}
averagePayoff = sumOfPayoffs / pPIndex;
return averagePayoff;
}
Linked is the extra example of when numStrokes is 6, just in case what I'm trying to do isn't already clear:
http://hastebin.com/hemolikodo.avrasm
So far, I have come up with the following attempt to implement numStrokes amount of nested loops, but it does not work (if for no other reason, because the function tries to create another copy of int i when it calls itself recursively). I'm not sure if this code is even the right approach. I'm not even certain that I should be trying to do this recursively. I considered just using a giant if statement that executes code based on the value of numStrokes, but a more general implementation seemed preferable.
double checkProfitability(GameState state, int numStrokes, int i)
{
double[] possiblePayoffs = new double[50000];
int pPIndex = 0;
double sumOfPayoffs = 0;
double averagePayoff = 0;
if (numStrokes == 0)
{
// Populate possiblePayoffs[]
}
else
{
for (int i = 0; i <= 5 && numStrokes >= 1; i++)
{
checkProfitability(state, --numStrokes, i);
}
}
for (int ii = 0; ii < pPIndex; ii++)
{
sumOfPayoffs += possiblePayoffs[ii];
}
averagePayoff = sumOfPayoffs / pPIndex;
richTextBox1.Text = averagePayoff.ToString();
return averagePayoff;
}
Can anyone explain how to implement this properly?
Edit: The problem is that I don't know how many nested loops I need until run time.
for (int i = 0; i < Math.Pow(6, numStrokes); i++)
{
int innerForIndex = i;
for (int j = 0; j < numStrokes; j++)
{
colors[innerForIndex % 6]++;
innerForIndex /= 6;
}
//populate your possiblePayoffs[]
innerForIndex = i;
for (int j = 0; j < numStrokes; j++)
{
colors[innerForIndex % 6]--;
innerForIndex /= 6;
}
}
numStrokes for loops from 0 to 5 inclusive means you have total Math.Pow(6, numStrokes) elements. You use your inner loops indexes to increment/decrement some cololrs array. Those indexes can be easily calculated from element number. For numStroke == 3 example k can be calculated as innerForIndex % 6, j as (innerForIndex / 6) % 6, i as ((innerForIndex / 6) / 6) % 6.
This is the closest I think I can get you to a solution for this.
First up this is the checkProfitability method:
double checkProfitability(GameState state, int numStrokes)
{
var possiblePayoffs = new double[50000];
computePayoffs(state, possiblePayoffs, Enumerable.Empty<int>(), numStrokes);
var averagePayoff = possiblePayoffs.Select(x => (double)x).Average();
richTextBox1.Text = averagePayoff.ToString();
return averagePayoff;
}
The recursion is now in the computePayoffs method:
void computePayoffs(GameState state, int[] possiblePayoffs,
IEnumerable<int> values, int numStrokes)
{
if (numStrokes == 0)
{
// Populate possiblePayoffs[]
}
else
{
for (int i = 0; i <= 5; i++)
{
state.colors[i]++;
computePayoffs(
state,
possiblePayoffs,
values.Concat(new [] { i }),
numStrokes - 1);
state.colors[i]--;
}
}
}
for (int i = 0; i <= 5 * numstrokes; i++)
{
// Populate possiblePayoffs[]
if(i % 5 == 0)
{
//start of next loop
}
}
Why not do this?
The question is not clear. But I think recursion will help you to solve these type of cases. What i could understand is you need to do some looping numstocks*6(The below code will loop this much time. If this is the case The code will be structured as(Didn't test it. May need some minor modifications)
double checkProfitability(GameState state, int numStrokes)
{
if(numStrokes!=0)
{
for (int i = 0; i <= 5; i++)
{
checkProfitability(state,numStrokes-1);
}
}
//your code //calls this code numStrokes*6 times
}
More over beware of stackoverflow Exception also

Categories