Dear student
The valency of carbon is always 4 in all the compounds. The difference lies just in the bonding.
In graphite, carbon undergoes sp2 hybridisation. Carbon atom in graphite form three sigma bonds with another three carbons and these sigma bonds are formed by the overlap of three sp 2 hybridised orbitals of carbon (one s orbital mixes with the two p orbitals of carbon to form sp 2 hybridised orbitals). The remaining perpendicular p orbitals of carbon are used for the delocalisation of Π electrons.
In CO2 also, the valency of carbon is 4
Let x be the valency of C
then x+2(-2) =0
x-4=0
x=4
Regards