Issues with looping code and do-while loops (c#) - c#

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

Related

Calculation Not Updating

I have been running this syntax with one variable successfully, but now I am trying to change it to a foeach() loop and take a range of values and show the results as a message box. My issue with the syntax is that ecll always retains the value of the first number passed, and the calculation is never updated for each subsequent number in the array.
Where did I err that is preventing this from being updated for each subsequent number in the array?
private void btnGetData_Click(object sender, EventArgs e)
{
int start = 2;
int end = 10;
int[] nums = Enumerable.Range(start, end - start).ToArray();
foreach (int n in nums)
{
float tp_x = 0, tp_y = 0;
SAP = new List<PointF>();
float fbw = m_pd.bl[m_pd.bl.Count - 1].m_Width;
float Location1_X = tp_x + fbw;
float Location1_Y = tp_y;
SAP.Add(new PointF(Location1_X, Location1_Y));
float iBH = gbh(m_pd.bl.Count - 1);
float lbw = m_pd.bl[0].m_Width;
float Location2_X = tp_x + lbw;
float Location2_Y = tp_y + (iBH) + 1.5f;
PointF rip = new PointF();
if (!Getrip(ftp, rhep, ref rip))
{
SAP = null;
return;
}
for (int iRowIndex = saii; iRowIndex < m_pd.pp.Count; iRowIndex++)
{
float Xvalue = m_pd.pp[iRowIndex].X;
float Yvalue = m_pd.pp[iRowIndex].Y;
SAP.Add(new PointF(Xvalue, Yvalue));
if (Yvalue == LeftIntersectionPoint.Y)
{
pp.X = Xvalue;
pp.Y = Yvalue;
continue;
}
if (Xvalue >= rip.X)
{
Xvalue = rip.X;
SAP[SAP.Count - 1] = new PointF(rip.X, rip.Y);
}
if (Xvalue == rip.X)
{
break;
}
pp.X = Xvalue;
pp.Y = Yvalue;
}
double ecll = Getll(Location1_X, Location1_Y, rip.X, rip.Y);
Messagebox.Show(Convert.ToString(ec11));
txtLength.Text = ll.ToString("0.00");
}
}
I feel like this is more of a comment based on what's going on here, but I kind of need the code section to explain this better I believe.
Let's simplify away from your points, widths, etc. I think we can all agree that n is never used within your function, so let's do a similar example:
So I have a function I wrote that adds 1 to 1
var newNum = 1 + 1;
It does what is expected, sets newNum to 2, but let's say I wanted to enhance it so that it adds 1 to the numbers in nums (from your original function):
int start = 2;
int end = 10;
int[] nums = Enumerable.Range(start, end - start).ToArray();
but if I try to reuse my function outright:
foreach (int n in nums)
{
var newNum = 1 + 1;
}
Every single pass, I'm always going to have newNum set at 2 because I'm not using the variable.
what I should do is write this:
foreach (int n in nums)
{
var newNum = 1 + n;
}
so based on your 2 through 10, I should see newNum set to 3 through 11 at various iterations.
Each iteration in the 'Foreach' loop assigns a new value to 'n'.
However in the loop body, that value (n) is not used anywhere in the calculations (unless I am missing something). So, of course the result of these calculations will always be the same.
As soon as you include 'n' in some of the calclations, the result will change...

Trouble suming totals [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Have trouble adding a summary for columns number, square and cube for totals. Any pointers where I should be looking at? Below is copy of my code.
static void Main(string[] args)
{
int number;
int total = 0;
Console.WriteLine("number\t" + "square\t" + "cube");
Console.WriteLine("-----------------------------");
for (int i = 0; i <= 20; i += 2)
{
number = i;
int k = 0;
do
{
Console.Write(number + "\t");
number *= i;
total += number;
k++;
} while (k < 3);
Console.WriteLine("Total is",total);
Console.WriteLine();
}
Console.WriteLine("---------------------------------------");
If I understand what you want correctly, one way to do this is to keep track of the running totals for each power (1, 2, and 3) in an array, and then display those values at the end.
The array would have 3 indexes, and each time we increase the 'power' that we're raising our number to, we add that value to the corresponding index in the array.
For example:
static void Main(string[] args)
{
// This array will hold three items:
// - totals[0] = numberTotal
// - totals[1] = squareTotal
// - totals[2] = cubeTotal
var totals = new int[3];
Console.WriteLine("number\t" + "square\t" + "cube");
Console.WriteLine("-----------------------------");
for (int number = 0; number <= 20; number += 2)
{
// Grab a copy of 'number' so we don't modify the loop variable
var thisNumber = number;
for(int powerIndex = 0; powerIndex < 3; powerIndex++)
{
// Write this number to screen
Console.Write($"{0:n0}\t", thisNumber);
// Add this number to the current number in 'power' index
totals[powerIndex] += thisNumber;
// Power up
thisNumber *= number;
}
Console.WriteLine();
}
Console.WriteLine("-----------------------------");
Console.WriteLine("{0:n0}\t{1:n0}\t{2:n0}\t", totals[0], totals[1], totals[2]);
// Alternatively, if you're using C#6.0, you could write:
Console.WriteLine($"{totals[0]:n0}\t{totals[1]:n0}\t{totals[2]:n0}\t");
Console.Write("\nDone!\nPress any key to exit...");
Console.ReadKey();
}
Output:
There are two errors in your code:
First one is about Console.WriteLine. To get it working you should pass parameters as for example shown here (it's not the only way to do it but it's the simplest)
Console.WriteLine("Total is" + total);
Secon one is more about algorithm. Let's check when you are adding number to total. If you look closer you can see that you are not adding same number, which you displayed, but your adding number * i ! Thats big mistake but to fix it just swap that two lines like that:
Console.Write(number + "\t");
total += number;
number *= i;
k++;
I belive that fixes every issue, hope it helps :-)
Full code:
using System;
namespace Sum
{
public class Program
{
public static void Main(string[] args)
{
int number;
Console.WriteLine("number\t" + "square\t" + "cube");
Console.WriteLine("-----------------------------");
for (int i = 0; i <= 20; i += 2)
{
number = i;
int total = 0;
int k = 0;
do
{
Console.Write(number + "\t");
total += number;
number *= i;
k++;
} while (k < 3);
Console.WriteLine("Total is "+total);
Console.WriteLine();
}
Console.WriteLine("---------------------------------------");
}
}
}

Infinite Series: While loop ends in infinity

I want to compute a series, but i don't get my do..while loop correct.
The user makes in input x, which then is summed up as following:
sum = sum + x / 2 ^ n, where n is the running variable.
This has to be looped, until the sum <= 0.00001.
Then the program will notify the user about the value of the sum and how big the running variable is.
My code so far:
public static int n = 0;
static void Main(string[] args)
{
double x, sum = 0, e = 0.00001;
Console.Write("input x: ");
x = Convert.ToDouble(Console.ReadLine());
do
{
sum = sum + x / Math.Pow(2,n);
n++;
} while (sum >= e);
Console.WriteLine ("Sum = " + sum + ", " + n + " count");
}
But my code results in an infinite loop. Do you have any ideas, how i could achieve it?
You're looping until the sum is very small; you should loop until the increment is very small:
var delta = e;
do
{
delta = x / Math.Pow(2,n);
sum = sum + delta;
n++;
} while (delta >= e);

Adding up total through a for loop - total always 0

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.

Why is this Fibonacci code not correct? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Project Euler Question 2.
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
My solution :
int firstNum = 1;
int secondNum = 2;
int resultNum = firstNum + secondNum;
int sum = 0;
for (int i = 0; i < 4000000; i++)
{
firstNum = i;
secondNum = i;
if(resultNum == firstNum + secondNum)
{
sum += resultNum;
Console.WriteLine(sum);
}
}
Why is this not correct and can you guide me into the right way of thinking?
Try this:
int n1, n2, fib;
//n1 = 0;
//n2 = 1;
n1 = 1;
n2 = 1;
fib = n1 + n2;
while (fib < 4000000)
{
n2 = n1;
n1 = fib;
fib = n1 + n2;
}
Then find the even fib numbers and sum it
For a more modular approach (mixed with LINQ):
IEnumerable<Int32> Fibonacci(Int32 limit = 4000000)
{
for (Int32 previous = 0, current = 1, next = 0;
current <= limit; current = next)
{
next = previous + current;
previous = current;
yield return next;
}
}
Then:
var allNumbers = Fibonacci(4000000); // 1,2,3,5,8,13,21
var evenNumbers = allNumbers.Where(x => x % 2 == 0); // 2,8,34,144,610,2584
var sum = evenNumbers.Sum(); // 4613732
The fibonacci series is defined as
A0 = 1,
A1 = 1
An = An-1 + An-2
You are aiming at producing the pattern
1 2 3 5 8 13 etc
While iterating, you are going to want to adjust the input similar to a sliding window and then check to see if you have come across a valid insertion (i.e. < 4M and even)
int sum = 0;
int max = 4000000;
for( int n = 0; n < max ; n++ )
{
//only sum the even numbers
if( second % 2 == 0 ) sum += second;
//adjust
int result = first + second;
first = second;
second = result;
//test for numbers greater than max
if( result > max ) break;
}
//output
Console.WriteLine(sum); //An for all even An values
After looking at this hopefully you can see some of the issues you came across.
You are setting your variables to the iterator i which is not going to produce An as defined but instead something entirely different.
firstNum = i;
secondNum = i;
Further, you only calculate the result once. This needs to be done in the loop. Only calculating once will basically use a static value the entire time.
int resultNum = firstNum + secondNum;
The conditional statement should be testing for an even number in order to properly add to the sum, but this code will only test the static value of resultNum
if(resultNum == firstNum + secondNum)
Also, there needs to be some check on the sum in order to break out when the max is exceeded. 4M iterations will be too many.
There is even more optimization that can occur here though. Looking at the for loop, it is clear that while not used yet, the iterator can be a powerful tool.
The reason being that the fibonacci conforms to the "Golden ratio".
By making the simple observation that the fibonacci series hits an even number ever 3 iterations, the iterator can be used to skip through the series.
double p = (1 + Math.Pow(5,.5)) / 2;
for( int n = 3, sum = 0;;n+=3)
{
double f = ( Math.Pow(p,n) - Math.Pow( 1 - p , n ) ) / Math.Pow(5,.5);
if( f > 4000000 ){
Console.WriteLine(sum);
break;
}
sum += (int)Math.Round(f);
}
Your code does not produce a Fibonacci sequence and does no check for even-valued terms
Try this instead
int firstNum = 1;
int secondNum = 2;
int sum = 0;
while (secondNum <= 4000000)
{
if (secondNum % 2 == 0)
sum += secondNum;
int resultNum = firstNum + secondNum;
firstNum = secondNum;
secondNum = resultNum;
}
Console.WriteLine(sum);

Categories

Resources