Computer Science Canada

Help with Array program

Author:  Sporg [ Wed May 25, 2005 7:51 am ]
Post subject:  Help with Array program

Hello, I recently was assigned an array program for my class. I am not a very good turing programmer. In my program im suppose to find the highest and lowest numbers in a predefined array. I think there is something wroung with my functions and with my array. Hopefully someone here will be able to help me.

code:
function smallest (list : array 1 .. 5 of int) : int
    var smalln : int
    for i : 1 .. upper(list)
        if (i) < smalln then
            smalln := i
        end if
    end for
    result smalln
end smallest

function largest (list : array 1 .. 5 of int) : int
    var largen : int
    for i: 1 .. upper(list)
        if (i) > largen then
            largen := list(i)
        end if
    end for
    result largen
end largest

var numbers : array 1 .. 5 of int :=init(62, 38, 75, 92, 83)

put "The smallest number is :", smallest (numbers)
put "The largest number is :", largest (numbers)

Author:  jamonathin [ Wed May 25, 2005 8:01 am ]
Post subject: 

When you first run it, an error pops up saying one of the variables has no value. That would be the variable smalln. You're going to want to make it equal to one of the numbers in list, and do the same thing for largen.

Now you're checking if (i) is greater, don't you mean list (i)?.

Also, in your function, make list : array 1 .. * of int, because we never know exactly how many are going in.

So this is what your program should look like.

Turing:

function smallest (list : array 1 .. * of int) : int
    var smalln : int := list (1)
    for i : 1 .. upper (list)
        if list (i) < smalln then
            smalln := list (i)
        end if
    end for
    result smalln
end smallest

function largest (list : array 1 .. * of int) : int
    var largen : int := list (1)
    for i : 1 .. upper (list)
        if list (i) > largen then
            largen := list (i)
        end if
    end for
    result largen
end largest

var numbers : array 1 .. 5 of int := init (62, 38, 75, 92, 83)

put "The smallest number is :", smallest (numbers)
put "The largest number is :", largest (numbers)

Author:  Sporg [ Wed May 25, 2005 8:11 am ]
Post subject:  Thanks!

works great, and from this code im able to figure out my other programs im assigned, so far anyway. Thanks

Author:  MysticVegeta [ Wed May 25, 2005 3:17 pm ]
Post subject: 

code:
var temp : int
var numbers : array 1 .. 6 of int
for a : 1 .. 6
    get numbers (a)
end for
put ""

for i : 1 .. 6
    for j : i .. 6
        if (numbers (i) > numbers (j)) then
            temp := numbers (i)
            numbers (i) := numbers (j)
            numbers (j) := temp
        end if
    end for
    put numbers (i)
end for


Shorter method i guess


: