The crowd cheered even louder when he said that he did not understand why leaders do not step down “especially when they’ve got a lot of money,” again going beyond his prepared text in a knowing reference to African officials who have accumulated great fortunes while in office, often through corruption.

Joseph Atta-Mensah, a Ghanaian who is a policy adviser at the United Nations Economic Commission for Africa, said Mr. Obama’s message was critically important. “One of the most important things was, in terms of good governance and institutions, the need for people to leave when their term is up,” he said. “They should leave and allow for new blood. I think that was good.”

Still, some analysts were skeptical about the potential impact of Mr. Obama’s remarks.

“I think it has little direct impact on leaders, who can play up sovereignty,” said Pierre Englebert, an African politics expert at Pomona College. Beyond that, he cited American support for, or silence on, some autocratic African governments. “The U.S. is not consistent in delivering this message, so that weakens it,” he said.

Mr. Obama’s tone on Tuesday was more forceful than when he visited Kenya and Ethiopia earlier on the trip. In Kenya, where the deputy president faces charges of crimes against humanity in the International Criminal Court and the country’s president faced them until December, Mr. Obama preferred to focus on what he saw as movement in the right direction, particularly a five-year-old Constitution meant to resolve disputes that arose out of contested 2007 elections.

As for Ethiopia, where the ruling party and its allies just won 100 percent of the seats in Parliament and where journalists have repeatedly been imprisoned for criticizing the government, Mr. Obama gently urged greater progress while expressing understanding of the country’s difficult history. Aides said that in private, Ethiopia’s leaders were unusually candid in acknowledging flaws in their system and seemed committed to change.

Finding the right balance between advocating democracy and human rights on the one hand, and cultivating cooperation on other issues like economics and security on the other, has been a challenge for Mr. Obama no matter where he travels. He came away with a sour aftertaste following the so-called Arab Spring, when countries in the Middle East and North Africa cast off autocrats only to fail to install successful democracies.