Somalia's interim parliament has chosen Abdullahi Yusuf as the new president in the latest bid to bring political stability to the lawless African state.
The new president's first task is to appoint a prime minister
The election was held in a sports stadium in the Kenyan capital, Nairobi, because Somalia's capital is still considered too dangerous.
The country has seen numerous attempts to restore order since 1991 when warlords ousted the military ruler.
Chaos followed, as rival militias fought and two million Somalis fled.
Sunday's election was the culmination of two years of often difficult negotiations in Nairobi.
The election followed two years of peace talks
After two rounds of voting and three voluntary withdrawals, the field was narrowed down from 28 to just two candidates.
Abdullahi Yusuf, a military strongman and president of the Somali semi-autonomous region of Puntland, was going head-to-head with Abdullahi Adow, a financier and former ambassador to Washington.
After the final third round, Abdullahi Yusuf emerged the winner by securing 189 votes against 79 for his run-off rival.
His election was greeted by loud cheers in the hall, the BBC's Adam Mynott in Nairobi reports.
The 275 MPs, most of them clan leaders and warlords, had earlier queued to go through metal detectors and enter Nairobi's Kasarani Sports Centre Gymnasium, which is serving as the election venue.
As the voting began the MPs - who were nominated in August - were called one by one to cast their votes in transparent ballot boxes.
In his first speech Abdullahi Yusuf pledge to reconcile Somalis and bring peace to the country.
His first job will be to choose a prime minister, our correspondent says.
In faction and clan-ridden Somalia, this decision will be made after considerable horse-trading, much of which has been going on in the corridors and backrooms of the sports hall.
Abdullahi Yusuf Ahmed is not expected to return to Somalia for at least two months, our correspondent says.
Before voting began, parliamentary speaker Sharif Hassan Sheikh Aden urged the international community to recognise the outcome and Somalis to support whoever was elected.
One of the candidates who pulled out, outgoing transitional President Abdulkassim Salat Hassan, said he was ready to do that.
"That is democracy," he said.
Decade of chaos
The stadium was packed while thousands more Somalis gathered outside where heavily armed Kenyan police were patrolling the venue.
Somalis are hoping that a new administration under a new president and prime minister will set them on the road to peace and stability.
But optimism is tempered by the knowledge that there have been numerous failed attempts to restore stability, correspondents say.
Somalia descended into chaos as rival militias tore the country apart after the military ruler Mohammed Siad Barre was overthrown.
Many of the two million Somalis who fled became refugees in neighbouring countries.