wrote a program to calculate and display the first 20 fibonacci numbers, the sequence goes as follows:
1, 1, 2, 3, 5, 8, 13... (each number is the sum of the previous two numbers)
The problem is that the numbers that get displayed are from 2 onwards , the first and second numbers of the sequence do not get displayed , could someone tell me what needs to be done to correct this?
Code:
private void button1_Click(object sender, EventArgs e)
{
int previousNumber = 1;
int currentNumber = 1;
int nextNumber = 1;
while (currentNumber <= 11000)
{
nextNumber = previousNumber + currentNumber;
previousNumber = currentNumber;
currentNumber = nextNumber;
textBox1.AppendText(Convert.ToString(nextNumber) + " ");
nextNumber++;
}
}
I suggest carefully tracing through the logic and predicting what the computer will do at each step. Since the bug affects the very first output, you won't have to look at very many statements to encounter the problem. This is a basic skill for a programmer, so it will be well worth the time, especially since this sounds like homework.
Initially you need to display the current number twice before next number calculation. Also you need to move the number display before the next number calculation. Also next number should be previous number + currentNumber. I have made the changes to your code below which should work.
private void button1_Click(object sender, EventArgs e)
{
int previousNumber = 1;
int currentNumber = 1;
int nextNumber = 1;
textBox1.AppendText(Convert.ToString(currentNumber) + " ");
while (currentNumber <= 11000)
{
textBox1.AppendText(Convert.ToString(currentNumber) + " ");
nextNumber = previousNumber + currentNumber;
previousNumber = currentNumber;
currentNumber = nextNumber;
nextNumber = previousnNumber + currentNumber;
}
}
Since the first two digits in a Fibonacci are the seed values (1 and 1 or 0 and 1) you should print those first and then calculate the next values.
I would simplify the code. You can test it out at https://dotnetfiddle.net/3cV96L
int initialSeed = 1;
int currentNumber = 1;
//Write seed values
Console.Write("{0} {1} ", initialSeed, currentNumber);
while (currentNumber <= 11000)
{
currentNumber += currentNumber;
Console.Write(currentNumber + " ");
}
Just change int currentNumber = 0;
Related
I have been trying to make a program that you input a number and i keeps asking for numbers untill their sum has reached the number and displays how many numbers it took. the problem i'm facing is that if the last number makes it over the input number it still counts it while it should stop.
static void Main(string[] args)
{
int sumLimit = Convert.ToInt32(Console.ReadLine());
int sum = 0;
int count = 0;`
while (sum < sumLimit)
{
int number = Convert.ToInt32(Console.ReadLine());
sum += number;
count++;
}
Console.WriteLine(sum + " " + count);
Console.ReadLine();
}
Here's one option to fix it, depending on your expected result you can let the count start at -1 or 0:
int sumLimit = Convert.ToInt32(Console.ReadLine());
int sum = 0;
int count = -1;
int number = 0;
while (sum + number < sumLimit)
{
sum += number;
count++;
number = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine(sum + " " + count);
Console.ReadLine();
static double calculateTotals(double a)
{
double transfee = a * .01;
double total = a + transfee;
return total;
}
static void Main(string[] args)
{
Console.WriteLine("How many dontations to process?");
int donations = Convert.ToInt16(Console.ReadLine());
int[] count = new int[] { donations + 1 };
int ct = 1;
int i = -1;
do
{
Console.WriteLine("Enter name: ");
string name = Console.ReadLine();
Console.WriteLine("Enter donation amount: ");
double amount = Convert.ToDouble(Console.ReadLine());
double transfee = amount * .01;
i++;
ct = count[i += 1];
Console.WriteLine(name + "\t" + amount + "\t" + transfee);
} while (i < donations);
Console.WriteLine("TOTALS:" + "\t" + calculateTotals(amount) + "\t" + transfee);
Console.ReadLine();
}
}
Hello. I am a beginner at coding, so I apologize if this is a poor attempt.
I am trying to make an app that records the amount donated by an individual, calculates a transaction fee, and outputs the results for each person. At the end, I am creating a final row of output that will state the total donations and the total transaction fees.
I am currently unsure how to properly implement the array into my loop, and am unsure if the loop is optimized in general.
Again, I am a beginner. I apologize for such code, but I'd love some clarification on these things.
Thank you!
First, your array declaration syntax is wrong. See this link.
So it should be int[] count = new int[donations+1];
Second, you need to declare and instantiate your amount and transfee variables outside of your loop.
double transfee = 0.0F;
double amount = 0.0F;
do
{
...
amount = Convert.ToDouble(Console.ReadLine());
transfee = amount * .01;
...
} while (i < donations);
This should be enough information to get you going again. Since you're learning, I don't think anyone would really unfold an answer for you that does the job you're trying to figure out :)
Your code :
int i = -1;
do
{
...
i++;
ct = count[i += 1];
...
} while (i < donations);
You are actually increase i two times, then get values from count[i] assign to ct variable
See this sample :
int[] count = new int[3];
count[0] = 0;
count[1] = 1;
count[2] = 2;
int i = -1;
do
{
i++;
int x = count[i += 1];
Console.WriteLine(x);
} while (i < 3);
It will cause IndexOutOfRangeException
Explain :
First Loop :
i++; // i increased 1, so i = 0
int x = count[i += 1]; // i increased 1, so i = 1, then get count[1] assign to x, x is 1
Second loop:
i++; // i increased 1, so i = 2
int x = count[i += 1]; // i increased 1, so i = 3, then get count[3] assign to x
count[3] cause IndexOutOfRangeException
Something like count[i += 1] will make your code more difficult to maintain, in my opinion, you should avoid it if possible, try to write it explicity as you can
I have a method to work out intervals from a file containing training data. It detects spikes and drops in power to figure out intervals and I'm developing a method to work out averages for each interval. Here is the method:
public void getIntervalData()
{
//Remove first drop anomaly
drops.Remove(0);
int intervalAltitude;
int intervalPower;
int intervalSpeed;
int altitudeAddUp = 0;
int powerAddUp = 0;
int speedAddUp = 0;
int counter = 0;
//Loop through to get all spikes and drops
for (int j = 0; j < spikes.Count(); j++)
{
int firstNumber = Convert.ToInt32(spikes[j]);
int secondNumber = Convert.ToInt32(drops[j]);
MessageBox.Show(firstNumber.ToString());
counter++;
//Difference to work out averages
int difference = secondNumber - firstNumber;
//Get seperate interval data (first number = spike, second number = drop)
for (int i = firstNumber; i < secondNumber; i++)
{
int altitudeNumber = altitudeList[i];
int powerNumber = powerList[i];
int speedNumber = Convert.ToInt32(speedList[i]);
//Add up data
altitudeAddUp += altitudeNumber;
powerAddUp += powerNumber;
speedAddUp += speedNumber;
}
MessageBox.Show("Alt add up:" + altitudeAddUp.ToString());
intervalAltitude = altitudeAddUp / difference;
intervalPower = powerAddUp / difference;
intervalSpeed = speedAddUp / difference;
intervalAverages.Add(new Tuple<int, int, int>(intervalAltitude, intervalPower, intervalSpeed));
MessageBox.Show("Interval: " + counter.ToString() + ": Avgs: " + intervalAverages[0]);
}
MessageBox.Show("Interval averages added. There were: " + counter + " intervals");
}
altitudeAddUp, powerAddUp and speedAddUp are always 0, but I can't figure out why it's not adding up. Probably a rookie error I just can't see it.
I've used a message box previously to test if altitudeNumber, powerNumber and speedNumber contain data and they do, but it won't add up.
I think the problem is that all your variables are integers. And integers don't have any decimal precision, that means that if an interval is 0.999, the actual integer value is 0 (0.999 doesn't exist as integer, to the value is truncated when you call ToInt32).
Use float, double or decimal, depending on the need of precision and range.
I am trying to write a C# program that takes an input value from user and then puts that value inside a sequence, then prints the result of every calculated number of the sequence inside a listBox. the sequence is like this:
S = 1 - X + X^2 / 2! - X^3 / 3! + X^4 / 4! - ...
First number that will be shown inside the listBox every time the program starts is 1. i am stuck at the part where i should subtract 1 from the user input (X) and then add the result to the third calculated number of the sequence. For example if user enters 2 as input, first output is 1, second output is -1 and then the program should add the result (-1) to the third calculated number of the sequence which is 2 and output should be 1. again subtract the result (1) from the fourth calculated number and again add the result to the fifth calculated number of the sequence and ...
so far i wrote this:
private void button1_Click(object sender, EventArgs e)
{
int x = Convert.ToInt32(textBox1.Text);
listBox1.Items.Clear();
listBox1.Items.Add("1".ToString());
double numerator = 1, Fact = 1, firstNum = 1, result;
for (int i = 1; i <= 20; i++)
{
numerator = x * numerator;
Fact = Fact * i;
result = numerator / Fact;
firstNum = firstNum - result;
listBox1.Items.Add(firstNum.ToString());
}
But i can't figure out how to write the code for the parts of sequence that should add the result to the next calculated number. Above codes will only subtract the result from next number and prints the result, but now how to add the result of subtraction to the next number and prints it again to the listbox?
First number of sequence - Second number of sequence = Result (show in listbox)
Result + Third number of sequence = Result (show in listbox)
Result - Fourth number of sequence = Result (show in listbox)
Result + Fifth number of sequence = Result (show in listbox)
I am very sorry if i explained the problem bad, i tried to be as specific as possible. I know i'm missing a very tiny piece, but i can't figure out what is it, and sorry for the writing, english is not my native language.
Thanks in advance
You are almost on the right track. Just missing few things.
Here is the corrected version of your program --->
private void button1_Click(object sender, EventArgs e)
{
int x = Convert.ToInt32(textBox1.Text);
listBox1.Items.Clear();
listBox1.Items.Add("1".ToString());
double numerator = 1, Fact = 1, firstNum = 1, result=0;
for (int i = 1; i <= 20; i++)
{
Fact = 1; // Reinitialising every time for new denomerator.
numerator = Math.Pow(x, i); // This is how power is calculated.
for (int j = 1; j<=i; j++) // One more inner loop is needed for Factorial.
Fact = Fact * j;
result = numerator / Fact;
firstNum = firstNum + (Math.Pow(-1, i) * result); // This is the main logic for alternate plus minus.
listBox1.Items.Add(firstNum.ToString());
}
}
I hope it solves your problem. :)
Maybe try to store the result of the subtraction(firstNum - result) to a variable and then add it to the next number?
Looks like the sequence formula is
f(i) = (-x)^i / i! for i in 0..N, 0! = 1
which can be produced as follows
private void button1_Click(object sender, EventArgs e)
{
int x = Convert.ToInt32(textBox1.Text);
listBox1.Items.Clear();
double numerator = 1, denominator = 1;
int i = 0;
while(true)
{
var result = numerator / denominator;
listBox1.Items.Add(result.ToString());;
if (++i > 20) break;
numerator *= -x;
denominator *= i;
}
}
var seqLimit = Convert.ToInt32(Textbox1.Text);
var numberX = Convert.ToInt32(XTextBox.Text);
ListBox1.Items.Clear();
var result = 1.0;
for (var i = 1; i <= seqLimit; i++)
{
ListBox1.Items.Add(result);
if (i%2 == 0) result = result + (Math.Pow(numberX, i)/Factorial(i));
else result = result - (Math.Pow(numberX, i)/Factorial(i));
}
static int Factorial(int n)
{
if (n <= 1)
return 1;
int result = 1;
for (int i = 2; i <= n; i++)
{
result = result * i;
}
return result;
}
Try this, it would work.
In C# how do i ask user for starting and stopping point within the array?
Below is my code so far:
class Program
{
static void Main(string[] args)
{
double[] num = { 10, 20, 30, 40, 50 };
double n = num.Length;
Console.Write("Elements of, arrary are:" + Environment.NewLine);
for (int i = 0; i < n; i++)
{
Console.WriteLine(num[i]);
}
double sum = 0;
for (int i = 0; i < n; i++)
{
sum = sum + num[i];
}
Console.WriteLine("The sum of elements:" + sum);
Console.ReadKey();
}
}
You'll take the sum of the elements between starting and stopping point, as I guess. Take two inputs from the user and assign them to starting and ending points to the for-loop. Such as:
int startingPoint = Convert.ToInt32(Console.ReadLine());
int endingPoint = Convert.ToInt32(Console.ReadLine());
for(int i = startingPoint; i <= endingPoint; i++)
{
//take sum etc.
}
Don't forget to inform the user about the element values in the array and what input value they are entering at that moment.
Another important thing here is to control the inputs. They should be numeric and between 0-n, starting point should be smaller than ending point.
For numeric control you can write like follows:
if (int.TryParse(n, out startingPoint))
{
// operate here
}
else
{
Console.WriteLine("That's why I don't trust you, enter a numeric value please.");
}
startingPoint should be between 0-n and cannot be n. To control it:
if (startingPoint >= 0 && startingPoint < n)
{
// operate here
}
else
{
Console.WriteLine("Please enter a number between 0 and " + n + ".");
}
After taking startingPoint successfully, you should control if endingPoint. It should be between startingPoint-n. After controlling for being numeric you can write as follows:
if (endingPoint >= startingPoint && endingPoint < n)
{
// operate here
}
else
{
Console.WriteLine("Please enter a number between " + startingPoint + " and " + n + ".");
}
I don't know what can I explain more for this question. Please let me know for further problems.
If you want to prompt the user for the start and end indexes:
Console.WriteLine("Please enter start index");
string startIndexAsString = Console.ReadLine();
int startIndex = int.Parse(startIndexAsString);
Console.WriteLine("Please enter end index");
string endIndexAsString = Console.ReadLine();
int endIndex = int.Parse(endIndexAsString);
var sum = num.Skip(startIndex).Take(endIndex - startIndex + 1).Sum();