# Assembling sparse matrix in PETSC for Poisson equation

I am a novice at PETSC, and I have been trying to write an FVM code for steady heat conduction in 2D using PETSC (square, regular grid, Dirichlet boundaries)

Since the large matrix , say A, will be sparse I declare 5 non-zeros per row and use MatCreateSeqAIJ()

My question is about assembling the entries of the matrix. In each CV, I call MatSetValues()

and add the 5 coefficients into A using local arrays II, JJ and Values_IJ

1) Is this the "right" or "usual" way to do this? I ask because, it seems to me, am assembling by implicitly using a COO type representation of sparsity in my loop while the matrix representation in PETSC is CSR.

2) If not, is there a way to create the local arrays II, JJ and Values_IJ to fit the CSR format of the matrix and then call MatSetValues()?

PETSc does not immediately create your sparse matrix representation. So, when you call MatSetValues(), you, usually, place the values in the intermediate cache which will occasionally get "dumped" into the real sparse matrix storage. So, the impact of the order in which you insert matrix elements is limited.
The fact that the cache is used, allows multiple optimizations during the actual creation of the matrix and more flexibility in the assembly process (which you take advantage of). That's why you would call MatAssemblyBegin() and MatAssemblyEnd() before you are able to use your matrix.
You also have an option to create three-array CSR yourself and use MatCreateSeqAIJWithArrays().