Congratulations, Karin, I bet you are very excited!
I checked this out recently for a friend who doesn't speak much Spanish and is arriving three days before you, and the train fare is not much more than bus and much shorter. Bus is at least 5 and up to 7 hours and about 29 euros. Train is a little more than 3 hours and 35 euros. But maybe you like buses, I'm not trying to dissuade you, just tell you the options in case you didn't know.
I have taken the bus from Madrid to Pamplona, and the bus leaves from the Avda. Americas bus station, which is very convenient from the airport. There's a city bus that goes straight there, with no or just a few stops. I don't know if you're planning to spend time in Madrid or just get going right away as soon as you land at Barajas, but there might also be an option of getting a bus right at the airport, but I haven't checked into that.
And to answer your question about buying tickets -- there are frequent buses between Madrid and Pamplona, at least every couple of hours, and I have bought my ticket as late as 15 minutes before departure without a problem. So I'd say if it's a weekday, non-holiday, you shouldn't have a problem.
Buen camino, Laurie