function x = gaussloops(A, b)
%GAUSSLOOPS - solve the system of linear equations A*x = b
%             using gaussian elimination with pivoting

% This version of the code uses loops 

    [n, ~] = size(A);

    % Forward elimination
    for k = 1:n-1

        [~, m] = max(abs(A(k:n,k)));
        m = m + k - 1;

        if [m ~= k]
            A([k,m],:) = A([m,k], :);
        end

        for i = k+1:n
            mult = A(i,k)/A(k,k);
            for j = k+1:n
                A(i,j) = A(i,j) - mult*A(k,j);
            end
            % Update the right hand side vector:
            b(i) = b(i) - mult*b(k);
        end
    end

    % preallocate the solution vector
    x = zeros(n, 1);

    % Back substitution
    for k = n:-1:1
        x(k) = b(k)/A(k,k);
        for i = 1:k-1
            b(i) = b(i) - A(i,k)*x(k);
        end
    end

end
