Reputation: 302
I'm new to c# development. I have a label on the form that shows the following sequence 1,1,1,3,5,9 and a button. When the button is clicked I want it to add the sequence of numbers to the label. For example : I know how the the above sequence works 1+1+1=3,3+1+1=5,5+3+1=9 ,so it calculates the previous 3 numbers to add to the sequence. What I'm trying to achieve is when the button is clicked each time it must show the next numbers that come in ex: after 9, will be 17 because 3+5+9=17 And so on... It must go up every time it's clicked .your help will be highly appreciated.
Upvotes: 0
Views: 419
Reputation: 1402
I believe the algorithm you are looking to do is create a List<int>
to contain the int
s that are going to be used on the label.
List<int> numbers = new List<int>();
Then you are trying to .Add
the first 6 starting numbers into the list like so:
numbers.Add(1);
numbers.Add(1);
numbers.Add(1);
numbers.Add(3);
numbers.Add(5);
numbers.Add(9);
Once the user clicks the button, change the original label's text information to also have the result of adding the last three elements of int
within the List<int>
.
This can be done by using .Count
to get the length/size of the List<int>
in the following fashion:
int x = numbers[numbers.Count - 1]; //Last number/element in List
int y = numbers[numbers.Count - 2]; //Second to last
int z = numbers[numbers.Count - 3]; //Third to last
int result = x + y + z; //sum of last number plus second to last number plus third to last number
Don't forget to .Add
the result of adding the last three elements to the end of the List<int>
.
numbers.Add(result);
Once you have the result added, you can set the label's .Text
value to the joining of a string in the following way:
numbersLabel.Text = string.Join(", ", numbers);
A sample demonstration of a class that contains a button, and a label that accomplishes this algorithm is below.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class LabelAlgorithm : Form
{
public List<int> numbers = new List<int>();
public LabelAlgorithm()
{
numbers.Add(1);
numbers.Add(1);
numbers.Add(1);
numbers.Add(3);
numbers.Add(5);
numbers.Add(9);
InitializeComponent();
numbersLabel.Text = string.Join(", ", numbers);
}
private void SubmissionButton_Click(object sender, EventArgs e)
{
int x = numbers[numbers.Count - 1];
int y = numbers[numbers.Count - 2];
int z = numbers[numbers.Count - 3];
int result = x + y + z;
numbers.Add(result);
numbersLabel.Text = string.Join(", ", numbers);
}
}
}
Output to Label:
1, 3, 5, 9, 17, 31, 57, 105, 193, 355, 653, 1201, 2209, 4063...
Upvotes: 2