1

I have a problem in PAscal. I want to count prime numbers but no result : My code is:

Program arrayToFunction;
const
 size = 5;
type
  a = array [1..size] of integer;
var
 aNumbers:  a = (1, 7, 3, 4, 5);
 iCountNumbers: integer;
function countPrimeNumbers( var arr: a) : integer;
  var
   i :0..size;
   sum,j,count: integer;
  begin
  sum := 0;count:=0;
  for i := 0 to size do
  begin
      for j := 2 to arr[i] do
          begin
               if(arr[i] mod j = 0) then sum:=1;
          end;
      if(sum=0) then count:=count+1;

  end;
 countPrimeNumbers := count;
end;
begin
 iCountNumbers := countPrimeNumbers( aNumbers ) ;*)
  writeln( 'Numbers: ', iCountNumbers);
  readln;
end.  

For this array I want to get 3 but I get 2...I don't understand where is my problem. Help me please

Harea Costea
  • 275
  • 5
  • 19
  • Main problem as i can see is that you does not reinitialize `sum` variable, so after `sum` value becomes to 1, it always will be 1. Add `sum := 0;` after `if(sum=0) then count:=count+1;`. But there are also some errors in your code. For example your array index starts from 1 but loop `for i := 0 to size do` starts from 0 so you will have error in `arr[i]` at the first iteration. – Abelisto Dec 10 '14 at 20:23
  • It's been a while since I did any pascal ( 34 years ) but either the index starts from zero or one. And you use both. So I'd guess that's what the problem is – Vorsprung Dec 10 '14 at 20:24
  • 1
    This would be a great time to learn to use the debugger. It's highly unlikely, BTW, that you're using Free Pascal, Pascal Script, and Turbo Pascal all at the same time, since they're nowhere near compatible with the code you've written. Only add tags that *actually apply* to your question - don't just randomly add those that seem to be similar. In this case, those would appear tobe only `pascal` and `freepascal` or `pascal` and `turbo-pascal` (but not all of them). – Ken White Dec 10 '14 at 23:05

1 Answers1

5

You have type a = array [1..size] of integer;, but then you iterate over the array using for i := 0 to size. The subscript needs to match the declared range.

You set sum := 0; before entering that loop, but never set it back to zero again. Once you find a non-prime, you'll set sum := 1;, and there it will stay. You never detect a prime once you've detected a non-prime.

The two primes you found were whatever garbage is at arr[0], and the 1 at arr[1]. Notice that 1 is not a prime, but your code will conclude it is. 7 is a prime, but your code will think it is not, because it will eventually notice that it's divisible by itself.

Rohit Gupta
  • 4,022
  • 20
  • 31
  • 41
ganbustein
  • 1,593
  • 11
  • 10