I want to print array of n prime number, like if the input is 5 so it'll print [2,3,5,7,11].
This is my code
program prime;
type
prime_number = array [1..10] of Integer;
var
dataset:prime_number;
n,i,j,count,angka:Integer;
function isPrime(a:Integer): Boolean;
var
i: Integer;
begin
for i := 2 to round(sqrt(a)) do
begin
if(a mod i = 0) then isPrime:=false
else isPrime:=true;
end;
end;
procedure printPrime(a:Integer;var df:prime_number);
var
number,primeCount,i: Integer;
begin
number:=2;
primeCount:=0;
while (primeCount < a) do
begin
if(isPrime(number)) then
begin
for i := 1 to a do
begin
df[i]:=number;
primeCount:=primeCount+1;
end;
end;
number:=number+1;
end;
end;
begin
write('Enter n: ');read(n);
printPrime(n,dataset);
end.
When I run the program it's totally fine, but it prints nothing instead of the array :( What's wrong with my code, anyone?
I see at least a couple of issues.
First, isPrime: You'll want to break out of the loop as soon as you see something that divides the test value, a, so it should be more like
function isPrime(a:Integer): Boolean;
var
i: Integer;
begin
for i := 2 to round(sqrt(a)) do
begin
if(a mod i = 0) then begin
isPrime:=false;
exit;
end;
end;
isPrime:=true;
end;
Then, in printPrime you have some, frankly, odd logic.
First of all, you're not printing anything anywhere within that procedure.
Then, when you do find a prime, you initialize all values in df up to the size with that value, why not just set the value at primeCount? You know, as in
procedure printPrime(a:Integer;var df:prime_number);
var
number,primeCount,i: Integer;
begin
number:=2;
primeCount:=0;
while (primeCount < a) do
begin
if(isPrime(number)) then
begin
primeCount:=primeCount+1;
df[primeCount]:=number;
end;
number:=number+1;
end;
end;
Related
This program is supposed to sort an array and fill it with random integers from 1 to 1000. It needs to find the maximum value and print the array. It should print the array in two ways: ARRAY OF INTEGER and ArrayType. I need help to print this array in ArrayType. I am not super familiar with Pascal and my assignment is to print this array with ArrayType as a parameter. This is my code I have so far:
PROGRAM SortingAlgorithm;
Var intArray : array[1..20] OF INTEGER;
Var i, j, index : INTEGER;
PROCEDURE Sort(intArray : ARRAY OF INTEGER; size : INTEGER);
BEGIN
FOR i := 2 to 20 do
BEGIN
index := intArray[i];
j := i;
WHILE ((j > 1) AND (intArray[j-1] > index)) do
BEGIN
intArray[j] :=intArray[j-1];
j := j - 1;
END;
intArray[j] := index;
END;
END;
PROCEDURE fillArray(var a,b : integer);
VAR temp : INTEGER;
BEGIN
temp := a;
a := b;
b := temp;
END;
BEGIN
FOR i := 1 to 20 do
intArray[i] := i;
FOR i := 1 to 20 do
fillArray(intArray[i],intArray[random(20)+1]);
END.
PROCEDURE findMax(intArray : ARRAY OF INTEGER; size : INTEGER);
VAR max : INTEGER;
begin
max := 1;
FOR i := 2 to size do
BEGIN
IF intArray[i] > intArray[max] THEN
max:=i;
END;
END;
PROCEDURE printArray(intArray : ARRAY OF INTEGER; size : INTEGER);
BEGIN
FOR i := 1 to 20 do
Writeln(intArray[i]);
END;
PROCEDURE printArray2();
BEGIN
END;
BEGIN
fillArray (intArray);
printArray (intArray);
printArray2 (intArray);
largestValue := findMax (intArray);
WriteLn (‘The largest value is ‘, largestValue);
sort (intArray);
printArray (intArray);
END.
printArray2 is for the ArrayType parameter. This is all the information I was given for this program, I'm not sure what printing with a parameter of ArrayType means. Any help is appreciated. Thanks.
As you know in Excel column names are letters. When it reaches Z it continues with AA-AB-AC. Is it possible to make a similar function in Delphi XE7 + for loop?
I've tried:
var
i:integer;
str:string;
begin
str:='a';
for i := 0 to 26-1 do
begin
inc (str,1);
memo1.Lines.Add(str);
end;
but it returned:
[dcc32 Error] FBarkodsuzIndesignVerisiOlustur.pas(249): E2064 Left side cannot be assigned to
I assume that's because str is not an integer.
I can convert numbers to letters with this function:
function numberToString(number: Integer): String;
begin
Result := '';
if (number < 1) or (number > 26) then
Exit;
Result := 'abcdefghijklmnopqrstuvwxyz'[number];
end;
But I have no idea how we can create letters like AA when it exceeds 26.
Also with below approach, it creates 26 letters just fine but when it exceeds 26 it starts to use characters like brackets:
for i := 0 to 27-1 do
begin
memo1.Lines.Add(Char(Ord('a') + i));
end;
Output of it:
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z
{
when it reach to Z it'll continue as "AA" "BB" "CC" and so on like Excel creates column names.
This is the function that I use for the task.
function SpreadSheetColName(const Col: Integer): string;
var
c: Char;
begin
Assert(Col >= 0);
if Col<26 then begin
c := 'A';
Inc(c, Col);
Result := c;
end else begin
Result := SpreadSheetColName(Col div 26 - 1) + SpreadSheetColName(Col mod 26);
end;
end;
Note that it uses zero based indices. I would suggest that you also use zero based indices as a general rule throughout your programming.
If you can't bring yourself to do that, then a one based version would look like this:
function SpreadSheetColName(const Col: Integer): string;
function SpreadSheetColNameZeroBased(const Col: Integer): string;
var
c: Char;
begin
Assert(Col >= 0);
if Col<26 then begin
c := 'A';
Inc(c, Col);
Result := c;
end else begin
Result := SpreadSheetColNameZeroBased(Col div 26 - 1) + SpreadSheetColNameZeroBased(Col mod 26);
end;
end;
begin
Result := SpreadSheetColNameZeroBased(Col - 1);
end;
procedure TfrmMain.createpnl(i: integer);
var
j,c: integer;
begin
c:=5;
top := pnlResult1.top;
for j := 1 TO i do
if (arrFound[j] <> -1) or (arrFound[j] <> 0) then
begin
with dmAll do
begin
tblHouses.First;
while not tblHouses.Eof do
begin
if tblHouses['ID'] = arrFound[j] then
begin
if j > 1 then
itop := j * pnlResult1.top + (j - 1) * pnlResult1.Height;
SetLength(arrpnl, c);
SetLength(arrimg, c);
SetLength(arrlbl[1], c);
SetLength(arrlbl[2], c);
SetLength(arrlbl[3], c);
SetLength(arrlbl[4], c);
SetLength(arrlbl[5], c);
SetLength(arrlbl[6], c);
{ the violation usually happes at arrlbl[6] but it has been in the neighboring area before }
/// ///////////dupe panels
arrpnl[c] := TPanel.Create(frmMain);
with arrpnl[c] do
begin
Parent := scbMain;
Width := pnlResult1.Width;
Height := pnlResult1.Height;
left := pnlResult1.left;
top := itop;
Visible := true;
Color := pnlResult1.Color;
end;
frmMain.Position:=poScreenCenter;
/// //////////dupe photos
arrimg[c] := TImage.Create(frmMain);
with arrimg[c] do
begin
Parent := arrpnl[c];
Width := Image1.Width;
Height := Image1.Height;
left := Image1.left;
top := Image1.top;
end;
{ i cut some spaghetti code to shorten question }
tblPhotos.First;
while NOT tblPhotos.Eof do
begin
if tblPhotos['HouseID'] = tblHouses['ID'] then
if fileexists(tblPhotos['photo']) then
begin
arrimg[c].Picture.LoadFromFile(tblPhotos['photo']);
arrimg[c].Stretch := true;
end
else
begin
if fileexists('H:\v0.1\not-found-image-15383864787lu.jpg') then
begin
arrimg[c].Picture.LoadFromFile
('H:\v0.1\not-found-image-15383864787lu.jpg');
arrimg[c].Stretch := true;
end;
end;
tblPhotos.Next
end;
tblOwners.First;
while NOT tblOwners.Eof do
begin
if tblOwners['ID'] = tblHouses['hOwner'] then
begin
arrlbl[4][c].caption := 'Email: ' + tblOwners['oEmail'] + #10 +
'Cell number: ' + tblOwners['oCell'];
end;
tblOwners.Next;
end;
inc(c);
bFound := true;
end;
tblHouses.Next;
end;
end;
end;
end;
I search through a database to find guesthouses that match the search criteria in an above procedure.
The search returns an array (arrFound) filled with ID's of houses that match search criteria.
I then make all duplicate results -1 and create TPanels dynamically to return the guesthouses as browseable results in a TScrollBox.
The dynamic array in question (arrlbl) is a 2D array of TLabels with a predetermined first value and a dynamic second value (depending on the amount of results).
I used 1D arrays but that gave the same error and I have a similar procedure on another form that doesn't give any errors.
It seems like you got the indices wrong.
In general, a dynamic array with n elements has indices 0..n - 1.
For example, if a is a dynamic array with 5 elements, the elements are a[0], a[1], a[2], a[3], and a[4]. There is no a[5].
I'm making a small Delphi program using Delphi XE5. In my code there is a dynamic boolean array and I'm no able to change the value of some of the arrays elements. I tried to initialize the array after setting it's length but it didn't help. Here is part of the code:
procedure DoSomething(names: array of string);
var startWithA: array of Boolean;
i: integer;
begin
SetLength(startWithA, Length(names)); // each element is false by default
for i := 0 to Length(names) - 1 do begin
if (names[i].indexOf('A') = 0) then begin
startWithA[i] := true; // the value is not changed after executing this line
end;
end;
end;
Your code works absolutely fine. Here is the proof:
{$APPTYPE CONSOLE}
uses
System.SysUtils;
function StartsWithAIndices(const Names: array of string): TArray<Boolean>;
var
i: Integer;
begin
SetLength(Result, Length(Names));
for i := 0 to high(Result) do begin
if (Names[i].IndexOf('A') = 0) then begin
Result[i] := true;
end;
end;
end;
var
Indices: TArray<Boolean>;
b: Boolean;
begin
Indices := StartsWithAIndices(['Bob', 'Aaron', 'Aardvark', 'Jim']);
for b in Indices do begin
Writeln(BoolToStr(b, True));
end;
Readln;
end.
Output
False
True
True
False
Perhaps your confusion stems from the fact that you assign to an array that is a local variable and whose values are never read. How can you say that the array values are not modified if you never read from them? Or perhaps you have optimizations enabled and the compiler decided to optimize away the local variable whose values are written to but never read.
As an aside, your function could be written more simply like this:
function StartsWithAIndices(const Names: array of string): TArray<Boolean>;
var
i: Integer;
begin
SetLength(Result, Length(Names));
for i := 0 to high(Result) do begin
Result[i] := Names[i].StartsWith('A');
end;
end;
This question already has answers here:
How do I declare an array when I don't know the length until run time?
(2 answers)
Closed 9 years ago.
This post was edited and submitted for review 4 months ago and failed to reopen the post:
Original close reason(s) were not resolved
I have a procedure in Delphi which currently looks like this:
Procedure Time.TimeDB(algorithm: string; Encode, Decode: InputFunction; N, R: Int);
VAR
i : LongInt;
Errors : Array[N] of LongInt;
BEGIN
for i := 0 to N-1 do
Errors[i] := 0;
END;
I'm given the error that N, as passed to the definition of Errors, is an undeclared identifier, despite declaring it in the procedure definition. N is recognized in the BEGIN-END section, though. Any ideas what's causing this and how I can otherwise declare a variable-length array in the VAR section?
You write array of Int to declare a dynamic array of Ints:
procedure Time.TimeDB(algorithm: string; Encode, Decode: InputFunction; N, R: Int);
var
i: int;
errors: array of Int;
begin
SetLength(errors, N);
for i := 0 to N - 1 do
Errors[i] := 0;
end;
Also notice that if an array has N elements, then they are indexed 0, 1, ..., N - 1. There is no element indexed N.
(Also, are you sure you don't mean integer when you write Int?)
The construct array[M..N] of Int is called a static array. In this case, M and N must be constants, like array[0..15] of TColor. You also got the static array declaration array[TMyType] of TMySecondType where the index will be of type TMyType, as in array[byte] of TColor or array[TFontStyle] of cardinal.
In your code your initializing your Errors Array to zero...Note with SetLength you don't need to do this...just set the Array to 0 and then set it to the length you want, and then just assign the values you need.
procedure WorkArrays(var aWorking: array of integer);
begin
if High(aWorking) >= 0 then
aWorking[0] := 1;
if High(aWorking) >= 3 then
aWorking[3] := 5;
end;
procedure WorkArrays2(var aWorking: array of integer);
begin
if High(aWorking) >= 1 then
aWorking[1] := 4;
if High(aWorking) >= 9 then
aWorking[9] := 7;
end;
procedure WorkArrays3(var aWorking: TIntArray);
begin
SetLength(aWorking, 4);
aWorking[0] := 1;
aWorking[3] := 5;
end;
procedure WorkArrays4(var aWorking: TIntArray);
begin
SetLength(aWorking, 10);
aWorking[1] := 4;
aWorking[9] := 7;
end;
procedure TForm58.ShowArrays(aWorking: array of integer);
var
a_Index: integer;
begin
for a_Index := Low(aWorking) to High(aWorking) do
Memo1.Lines.Add(IntToStr(aWorking[a_Index]));
end;
procedure TForm58.ShowArrays2(aWorking: TIntArray);
var
a_Index: integer;
begin
for a_Index := Low(aWorking) to High(aWorking) do
Memo1.Lines.Add(IntToStr(aWorking[a_Index]));
end;
procedure TForm58.Button1Click(Sender: TObject);
var
a_MyArray: array of integer;
a_MyArray1: TIntArray;
begin
SetLength(a_MyArray, 3);//note this is a Zero based Array...0 to 2
WorkArrays(a_MyArray);//note aWorking[3] will not show...because High is 2...
ShowArrays(a_MyArray);
SetLength(a_MyArray, 0);
SetLength(a_MyArray, 10);//note this is a Zero based Array...0 to 9
WorkArrays2(a_MyArray);
ShowArrays(a_MyArray);
WorkArrays3(a_MyArray1);
ShowArrays2(a_MyArray1);
WorkArrays4(a_MyArray1);
ShowArrays2(a_MyArray1);
end;
end.