In computer graphics, z-buffering is the management of image depth coordinates in three-dimensional (3-D) graphics, usually done in hardware, sometimes in software. It is one solution to the visibility problem, which is the problem of deciding which elements of a rendered scene are visible, and which are hidden. The painter's algorithm is another common solution which, though less efficient, can also handle non-opaque scene elements.

When an object is rendered by a 3D graphics card, the depth of a generated pixel (z coordinate) is stored in a buffer (the z-buffer). This buffer is usually arranged as a two-dimensional array (x-y) with one element for each screen pixel. If another object of the scene must be rendered in the same pixel, the graphics card compares the two depths and chooses the one closer to the observer. The chosen depth is then saved to the z-buffer, replacing the old one. In the end, the z-buffer will allow the graphics card to correctly reproduce the usual depth perception: a close object hides a farther one.

The granularity of a z-buffer has a great influence on the scene quality: a 16-bit z-buffer can result in artifacts (called "z-buffer fighting") when two objects are very close to each other. A 24-bit or 32-bit z-buffer behaves much better. An 8-bit z-buffer is almost never used since it has too little precision.

Additionally, precision in the z-buffer distance values is not spread evenly over distance. Nearer values are much more precise (and hence can display closer objects more properly) than values which are farther away. Generally, this is desirable, but sometimes it will cause artifacts to appear as objects become more distant. A variation on z-buffering which results in more evenly distributed precision is called w-buffering.

At the start of a new scene, the z-buffer must be cleared to a defined value, usually 1.0, because this value is the upper limit (on a scale of 0 to 1) of depth, meaning that no object is present at this point through the viewing frustum.

The invention of the z-buffer concept is most often attributed to Edwin Catmull.

#include <iostream.h>
#include <graphics.h>
#include <conio.h>

void main()
{
	int gdriver = DETECT, gmode, errorcode;
	initgraph(&gdriver, &gmode, "");
	int zbuf[100][100], color[100][100];
	for (int i=0;i<100;i++)
		for (int j=0;j<100;j++)
			zbuf[i][j]=0,color[i][j]=0;
	char cho='y';
	int xn,xx,yn,yx,z,c,j;
	while (cho=='y')
	{
		cout<<"Enter z ";
		cin>>z;
		cout<<"Enter co-ordinates of rectangle ";
		cin>>xn>>yn>>xx>>yx;
		cout<<"Enter color ";
		cin>>c;
		for (i=xn;i<=xx;i++)
			for (j=yn;j<=yx;j++)
				if (zbuf[i][j]<z)
				{
					zbuf[i][j]=z;
					color[i][j]=c;
				}
		for (i=0;i<100;i++)
			for (j=0;j<100;j++)
				putpixel(i+getmaxx()/2,getmaxy()/2-j,color[i][j]);
		cout<<"More ?";
		cin>>cho;
	}
}