Violations?

I wrote this code, but, after I enter any number in LabeledEdit1 and press the button, it gives an access violation dialog. Codes:0x00401bc0,0x11aec8b4.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
  //---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop
#include <math.h>
#include "Unitheyes.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
}
//---------------------------------------------------------------------------

int isEven(int x)
{
        float y=x/2;
        if(y==floor(y))
        {
                return 1;
        }
        else return 0;
}

//---------------------------------------------------------------------------

void __fastcall TForm1::Button1Click(TObject *Sender)
{
long n, t, h[1000000000], max=1, u=0;
        n=StrToInt(LabeledEdit1->Text);
        while(n!=1)
        {
                if(isEven(n)==1)
                {
                        n=n/2;
                }
                else
                {
                        n=n*3;
                        n++;
                }
                h[t]=n;
                if(n>max)
                {
                        max=n;
                }
                t++;
        }
        for(u=0;u>=t;u++)
        {
                LabeledEdit2->Text=IntToStr(h[u]+',');
        }
        LabeledEdit3->Text=IntToStr(t);
        LabeledEdit4->Text=IntToStr(max);
}
//---------------------------------------------------------------------------
Last edited on
I completely have no idea how to use vectors.
The code can be rewritten to avoid h:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
long n, t, max=1, u=0;
n=StrToInt(LabeledEdit1->Text);

// Note: You forgot to initialize t.
t = 0;

while(n!=1)
{
    if(isEven(n)==1)
    {
            n=n/2;
    }
    else
    {
            n=n*3;
            n++;
    }
    LabeledEdit2->Text=IntToStr(n+',');
    if(n>max)
    {
            max=n;
    }
    t++;
}
LabeledEdit3->Text=IntToStr(t);
LabeledEdit4->Text=IntToStr(max);
Last edited on
I tried this and the second labeled edit is ALWAYS 45. 3 and 4 are incorrect.
My expected output is that 2 is this:https://en.wikipedia.org/wiki/Collatz_conjecture . 3 is the number of steps that it took to reach 1. 4 is the top number of this sequence.
Last edited on
Topic archived. No new replies allowed.