Valentin
Valentin

Reputation: 1

How to multiply odd numbers from an array?

I have a program that reads a N number of integers and push them into an array, then I need to multiply the odd numbers from the array.

Program p2;
type 
    tab = array[1..10] of integer;
var 
    a, c : tab;
    n, i, prod : integer;
begin
    writeln('n=');
    readln(n);
    prod := 1;
    writeln('Enter array numbers:');

    for i := 1 to n do
        read(a[i]);

    if (a[i] mod 2 = 1) then
        prod := a[i] * prod;

    writeln('The produs of the odd numbers is: ',prod);
end.

For example when you enter the n as 5, and the numbers: 1, 2, 3, 4, 5; The result of multiplication of odd numbers should be 15. Can someone help me to fix it working properly.

Upvotes: 0

Views: 478

Answers (1)

Chris
Chris

Reputation: 36596

First off, whitespace and indentation are not terribly significant in Pascal, but they can be your ally in understanding what your program is doing, so let's make your code easier to read.

Program p2;
type 
    tab = array[1..10] of integer;
var 
    a, c : tab;
    n, i, prod : integer;
begin
    writeln('n=');
    readln(n);
    prod := 1;
    writeln('Enter array numbers:');

    for i := 1 to n do
        read(a[i]);

    if a[i] mod 2 = 1 then
        prod := a[i] * prod;
  
    writeln('The produs of the odd numbers is: ', prod);
end.

With indentation, it should be apparent what's happening. Your conditional only runs once, rather than each time through your loop. As suggested in the comments, begin and end neatly solve this problem by creating a block where the conditional is checked each time the loop runs.

program p2;
type
    tab = array[1 .. 10] of integer;
var
    a, c : tab;
    n, i, prod : integer;
begin
    writeln('n=');
    readln(n);
    prod := 1;
    writeln('Enter array numbers:');

    for i := 1 to n do
    begin
        read(a[i]);

        if a[i] mod 2 = 1 then
            prod := a[i] * prod;
    end;

    writeln('The produs of the odd numbers is: ', prod);
end.

Upvotes: 1

Related Questions