Are you familiar with linear interpolation?
Consider the function X1 = X1 + F(X2-X1)
Where X1 is the start value, X2 is the end value, and F is the fraction between 0 and 1.
This fraction represents how far along in between X1 and X2 you want to go. For example,
if F = 0 you’ll get X1, if F = 1, you’ll get X2, and if F = 0.5, you’ll get a value half way in between X1 and X2.
You use linear interpolation to find values along the triangle’s edges, and across the triangle’s surface. So for your Z problem, you interpolate between the Z values of vertex 1 (X1) and vertex 2 (X2). An F value of 0 will give you the Z value of vertex 1 and an F value of 1 will give you the Z value of vertex 2.
In order to find the F value, you need to find the change of Z over the change in Y. This dz/dy is the F value and is constant for the entire edge of the triangle.
Loop over each of the Y values between vertex 1 and vertex 2, incrementing a counter by F.
float F = (vertex2.z - vertex1.z) / (vertex2.y - vertex1.y);
float interpZ = vertex1.z;
while (vertex1.y < vertex2.y) {
// interpolate across X using a similar method
// interpZ is the Z value in between the edges.
interpZ += F;
}