Is it ever stated why Gandalf entered Fangorn? Or was it just a coincidence?
What I mean by that is how does he just manage to stumble upon Merry and Pippin, or did he know it was going to happen?
Technically, he didn't meet Merry and Pippin in Fangorn. He was there recovering from his "struggle with the Eye of Mordor", and happened to see Treebeard walking by. Neither of them spoke to the other, and the encounter occurred two days prior to Treebeard meeting Merry and Pippin.
"For [Treebeard] came here two days ago and bore [Merry and Pippin] away to his dwelling far off by the roots of the mountains. He often comes here, especially when his mind is uneasy, and rumours of the world outside trouble him. I saw him four days ago striding among the trees, and I think he saw me, for he paused; but I did not speak, for I was heavy with thought and weary after my struggle with the Eye of Mordor, and he did not speak either, nor call my name."
-Gandalf, The Two Towers, "The White Rider"
As far as I can recall, Gandalf never explains why he was in Fangorn at the time he and Treebeard spotted each other, and they didn't speak to one another until some later date. Only then did he realize that Treebeard had found the hobbits and taken them under his wing (err - I mean, under his branch).
The meeting in Fangorn between Gandalf, Treebeard, and the two hobbits only occurs in the movie. As far as the book is concerned, Gandalf found out where the hobbits were when Gwaihir the Windlord told him:
“Will you not first give us news of the hobbits,” [asked Aragorn] “Did you find them, and are they safe?”
“No, I did not find them,” said Gandalf. “There was a darkness over the valleys of the Emyn Muil, and I did not know of their captivity, until the eagle told me.”
“The eagle!” said Legolas. "I have seen an eagle high and far off : the last time was three days ago, above the Emyn Muil,”
“Yes,” said Gandalf, “that was Gwaihir the Windlord, who rescued me from Orthanc. I sent him before me to watch the River and gather tidings. ..”