I am learning C# and I came to this "for" function and something really bothers me about it:
int[] arrayNumbers = new int[numberAmmount];
// take "numberAmmount" as 5 so numberAmmount = 5;
for (int i = 0; i < numberAmmount; i++)
{
Console.Write("{0} Number: ", i + 1);
numberAmmount[i] = int.Parse(Console.ReadLine());
}
Isn't "i++" in for function the same i as in the Console.Write "i + 1"
Shouldn't i after the first cycle be 2?
and after the second cycle be 4 because of the i + 1 in console.write???
Basically I am trying to get in a number from the user which will be the amount of numberAmmount and by this for function i give every numberAmmount[x] a value and then have my program decide the highest and the lowest number but I don't understand why the i + 1 doesn't add an extra 1
edit: got it thanks
The syntax i + 1 does not have an assignment operator. That code is printing the value of i plus a constant. So when your loop is looping from 0...n Console.write is printing the counting value of each loop 1...n+1.
Related
I am having a bit issue with how I have to logically think for my code.
What I want to do is have the user type in how many numbers they want and then ask them where they want that sequence of numbers to start. Then I would print out the numbers. So if the user typed in 7 and then 4 the result would be 4 5 6 7 8 9 10.
Here is my code so far
int userInInt, userIntStart;
Console.Write("How many integers do you want to print? ");
userInInt = Int32.Parse(Console.ReadLine());
Console.Write("What is the first integer you want printed? ");
userIntStart = Int32.Parse(Console.ReadLine());
for(int counts = userIntStart; userIntStart <= userInInt; userIntStart++)
{
Console.WriteLine(userIntStart);
}
I realized after doing this for loop that it would just be incrementing the starting number up until the userInInt which is not what I want. I've been spending a while trying figure out what else I need.
Thank you
The name you give to variables is important for the understanding of the code and makes it easier to think about it. userInInt does not reflect the purpose of the variable.
Console.Write("How many integers do you want to print? ");
int count = Int32.Parse(Console.ReadLine());
Console.Write("What is the first integer you want printed? ");
int start = Int32.Parse(Console.ReadLine());
Often i is used as loop variable, because in math it is used as index. You have different choices as how you can formulate the loop. The most typical is
for (int i = 0; i < count; i++)
{
Console.WriteLine(start + i);
}
But you can also add start to the loop variable start value and to the count.
for (int i = start; i < count + start; i++)
{
Console.WriteLine(i);
}
You can even increment more than one variable:
for (int i = 0; i < count; i++, start++)
{
Console.WriteLine(start);
}
Change your for loop as below
int userInInt, userIntStart;
Console.Write("How many integers do you want to print? ");
userInInt = Int32.Parse(Console.ReadLine());
Console.Write("What is the first integer you want printed? ");
userIntStart = Int32.Parse(Console.ReadLine());
for(int counts = userIntStart; counts < userIntStart + userInInt; counts++)
{
Console.WriteLine(counts);
}
The problem to your initial code is that your for loop is wrong, first you should assign to counts the initial value, then you should provide correct exit condition in the second arg and third arg is increment step which is 1, have a look at for loop syntax here.
In your code first you need to use the correct variable name in increment step(++). Secondly please note, you need to use a separate variable to keep track of number of integers. In my case, I am using variable 'i' for that. Hopefully it will help.
int userInInt, userIntStart;
Console.Write("How many integers do you want to print? ");
userInInt = Int32.Parse(Console.ReadLine());
Console.Write("What is the first integer you want printed? ");
userIntStart = Int32.Parse(Console.ReadLine());
int i = 0;
for (int counts = userIntStart; i<userInInt; counts++,i++)
{
Console.WriteLine(counts);
}
Console.ReadLine();
I am trying to generate a probability of getting a specific number from n dice, with no guarantee of them having the same number of sides. (eg, 1d6 + 2d10)
I know there is a really expensive way of doing it (With recursion), but if there is a mathematical way of determining the chance of an event happening, that would be way better.
One way to do this:
Create an output array count with length sum(sides all dice)+1, i.e. so that the max that can possibly be rolled works as an index.
This represents the number of ways that the index can be rolled. Initialise this with [0] = 1.
For each dice of N sides, enumerate the results of each possible rolled value.
Copy the existing count array into prev, say, and create a new empty count array
for roll = 1 to N, for total = 0 to count.length-1-roll, count[total+roll]+=prev[total]
Now the probability of rolling value = count[value] / sum(count)
Notes:
This isn't, as you feared, either really expensive or needs recursion. This will be O(N^2) where N as the total faces on all dice.
This will compute the probability of all outputs not just the one output that you're interested in, which may be an issue if the total faces is extremely large and the value you're interested in small. You could cap the count array at length (value you're interested in) + 1, if necessary, and compute the total number of rolls as the product of each die face as you process it rather than from sum(count) as I've suggested above.
#Rup already gave one standard solution, the bottom up dynamic programming method.
The top down approach is to write your recursive function..and then memoize it. That is when your function is called you first check whether you have seen this before (ie you look into a dictionary to see if you have a "memo" to yourself about the answer), and if you haven't you calculate the answer and save it. Then you return the memoized answer.
The usual tradeoffs apply:
Top down is easier to figure out and write.
Bottom up lets you see that you don't need to store 2 dice answers when you have the 3 dice ones, and therefore reduces working memory requirements.
Therefore it is good to know both approaches, but I always reach for a top down approach first.
Here I generated from 2 dice rolling
1 Randon() will be generated from n faces
2 here n times is rolled on
3 sum is displayed for n rolled
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dicerolling
{
class Program
{
static void Main(string[] args)
{
Random x = new Random();
int throw_times = 1;
int sum = 0;
int[] dice = new int[2];
dice[0] = x.Next(1, 7);
dice[1] = x.Next(1, 7);
Console.WriteLine("enter the no of rollings :");
var n = int.Parse(Console.ReadLine());
for (int i = 1; i <= n; i++)
{
dice[0] = x.Next(1, 7);
dice[1] = x.Next(1, 7);
int total_var = dice[0] + dice[1];
sum += dice[0] + dice[1] ;//total in array
Console.Write("Throw " + throw_times + ": " + dice[0] + " d " + dice[1] + " = ");
Console.WriteLine(total_var);
throw_times++;
Array.Sort(dice);
for (int a = dice.Length - 1; a >= 0; a--)
{
int s = dice[a];
Console.WriteLine("#" + s);
}
}
Console.WriteLine("Total sum: " + sum);//only returns sum of last 2 rolls
Console.ReadLine();
}
}
}
I'm writing code in C# and trying to add all of the numbers between the number 1 and N, N being the number that is inputted in a textbox. I'm doing this, at least trying to do this, by putting it into a while loop.
I have added all the numbers between 2 textboxes before but for some reason I'm driving myself crazy and can't figure this out. I'm a beginning programmer so please be gentle.
Any help would be greatly appreciated.
Edit:
One of the six thousand things I've tried. I think this has me in an infinite loop?
private void btnAddAll_Click(object sender, EventArgs e)
{
int n;
int count = 0;
int answer = 0;
n = int.Parse(txtNum.Text);
count = n;
while (count >= 1)
{
answer = answer + count;
count++;
}
lstShow.Items.Add("Sum = " + answer);
lstShow.Text = answer.ToString();
}
Why not use Gauss formula. (N*(N+1))/2
private void btnAddAll_Click(object sender, EventArgs e)
{
int n, answer;
n = int.Parse(txtNum.Text);
answer = (n*(n+1))/2;
lstShow.Items.Add("Sum = " + answer);
lstShow.Text = answer.ToString();
}
If you change the ++ to a -- it should work as you want it to.
int n;
int count = 0;
int answer = 0;
n = 3;
count = n;
while (count >= 1)
{
answer = answer + count;
count--; // here was the error
}
Console.WriteLine (answer);
Output: 6
Also, just for a point of additional interest you can use That uses Enumerable.Range and Enumerable.Sum instead of the while loop (probably goes beyond what is expected for a homework but it's useful to know what's out there).
answer = Enumerable.Range(1, n).Sum();
Your edit: you should decrement count..
Another edit, it appears I need to explain more:
By decrement I mean --. The post or pre decrement operator decreases the value by 1.
If count keeps increasing by 1, count >=1 will never be met. You need to reduce count to 1.. hence count--;
Also I suggest you use TryParse(string,out int) ; or at least wrap the Parse call in a try catch block.
Here is a pointer in pseudocode:
GetInput From User
TryParse Input
If Between 1 and N
Declare sum = 1;
for i to N-1
sum+=i;
/* if you don't want to use the for loop
while i < N
sum+=i;
inc i; */
Print sum
Debugging is an important skill for any programmer. There are some good tools in Visual Studio to help with debugging.
A good way to debug your code when you are stuck is to use 'breakpoints' and step through the code.
Select the line you want your code to stop at (e.g. n = int.Parse(txtNum.Text);) and press F9 - this will add a breakpoint at this line.
Now, when you run your programme, it will stop at the breakpoint. If you press F11, you can 'step' through the code one line at a time. You can hold your mouse over a variable to see its value while you are doing this.
You will quickly find the problem in your code if you do this.
This question asks to write a program that accepts input for five 'stores'. The input should ideally be a range from 100 to 2000. Each input should be divided by 100, and have that amount displayed in asterisks (i.e. 500 is *, etc.). I believe I have the first part, but I've got no idea how to go about doing the rest. I cannot use arrays, as I have not learned them yet, and I want to be learn this myself instead of just copy-pasting from another student. So far, I only have
int loop;
loop = 1;
while (loop <= 5)
{
string input1;
int iinput1, asteriskcount1;
Console.WriteLine("Input number of sales please!");
input1 = Console.ReadLine();
//store value?
loop = loop + 1;
input1 = Convert.ToInt32(input1);
asteriskcount1 = iinput1 / 10;
}
Not sure if I understand what you're trying to do. But maybe this will help. This is untested, but it should do what I THINK you are asking, but I am unsure what you wanted done with the asterisks. Please explain more if this isn't what you were getting at.
string Stored = "";
for (int i=0; i < 5; i++;)
{
string input1;
int iinput1, asteriskcount1;
Console.WriteLine("Input number of sales please!");
input1 = Console.ReadLine();
//Adds to existing Stored value
Stored += input1 + " is ";
//Adds asterisk
iinput1 = Convert.ToInt32(input1);
asteriskcount1 = iinput1 / 100;
for(int j = 0; j < asteriskcount1; j++)
{
Stored += "*";
}
//Adds Comma
if(i != 4)
Stored += ",";
}
Console.WriteLine(Stored); //Print Result
Don't want to write it out for you but here's some thoughts ...
first, you can do a for loop for the 5 stores:
for (int loop = 0; loop < 5; loop++)
You'll probably want asterickCount (not asterickCount1) since you're in a loop. You'll also want to divide by 100 since you're range is up to 2000 and you have 80 chars on a console. That means it will print up to 20 astericks.
You'll want a PrintAstericks(int count); function that you call right after calculating the asterickCount that you call. That function simply loos and calls Console.Write (not WriteLine) to write an asterick n times (new string has overload to take char and count).
But, that pattern will print the astericks after you take each input. If you want the pattern to be (1) accept the counts for the five stores and then (2) print the asterick rows for all five, you'll need an array with 5 slots to store the inputs then loop through the array and print the asterick rows.
Finally, you'll want to put some validation on the inputs. Look at Int32.TryParse:
http://msdn.microsoft.com/en-us/library/bb397679.aspx
Super easy
int asteriskCount = int.Parse(input1)/ 100;
string output = new string('*', asteriskCount );
I am working on a text-based game, and I want to print the results in the end.
However, at the moment it only prints the latest input data and not the 5 loops in the array.
This is my array
int[] turnarr = new int[5];
turnarr[x] = turn;
for (int i = 0; i < turnarr.Length; i++)
Console.WriteLine(turnarr[i] + "\t" );
It's hard to be certain, as I only see part of the code, but I suspect that you are recreating the turnarr array in each turn, which would make every entry except the last one zero.
If the value of x never changes then you're only writing to a single item in the array, and thus overwriting it every time with the latest value of turn.
If turn is your last turn value, and x is 4, you will see four zeroes on their own lines and then the value of turn because you are only assigning to the xth index of turnarr
I took a look at your pastebin and tracked the issue down I believe:
The following line:
Console.WriteLine(turnarr[i] + "\t" + windarr[i] + " ms \t" + apmeterarr[x] + "m\t\t" + lenghtarr[x] + " meter\t\t");
you are using i for 2 spots, and x for the other 2 for your index variable...
Change
apmeterarr[x] and
lenghtarr[x]
To
apmeterarr[i] and
lenghtarr[i]