In the end, President Obama may have gotten closer to the bones of ancient mankind than to ordinary Africans on what was probably his last trip to Africa as president. But no one can say he did not try.

In a region that is home to some of the world’s newest tech start-ups and oldest wars, Obama tried to reconcile his abundant hope for Africa’s future with a determination to tell the truth about its challenges, past and present.

In a major speech to Kenyan students and in more intimate gatherings with members of civil society, he sometimes seemed torn between heaping praise on the economic progress that has lifted living standards for millions and acknowledging the corruption, violence and security issues that continue to afflict the continent.

He celebrated the ingenuity of African business leaders and then promptly confronted South Sudan’s deepening civil war. His plane took off for Ethiopia, one of Africa’s fastest-growing economies, just as a prominent hotel was attacked in neighboring Somalia.

[Obama: ‘Africa is on the move’]

What some had expected to be a sentimental journey for Obama was punctuated with reminders of a region wrestling with crisis. But that didn’t dim the enthusiasm of the Kenyans and Ethiopians who greeted him, the first sitting U.S. president to visit either country.

In a speech at the African Union headquarters here Tuesday, he warned that Africa’s “democratic progress is . . . at risk” when leaders refuse to give up power, holding up the U.S. Constitution’s term limits as an example. But he added that if he were able to run again, he could win.

“I love my work. But under our Constitution, I cannot run again. I can’t run again. I actually think I’m a pretty good president. I think if I ran I could win. But I can’t,” he said.

In Nairobi, he spoke Sunday in an arena to a crowd of 4,500, a scene reminiscent of the kind of adulation he got during the heady days of his first campaign. The city was peppered with U.S. flags for his visit, which Kenyans described proudly as a homecoming. Even though onlookers were kept hundreds of yards away by grim-faced men with automatic weapons, they were giddy with excitement.

For his part, Obama embraced Kenya, his father’s homeland, as a place with a special connection for him. But much of the policy he articulated referred to the country’s battle against al-Qaeda-linked terrorists, a war that Kenyan President Uhuru Kenyatta last week called “an existential fight.”

On Monday, Obama huddled with several African heads of state, discussing what to do when the latest rounds of peace talks in South Sudan fail; on Tuesday, he spoke to the African Union about the need to beat back the threat of Islamist terrorists.

The trip underscored that Obama’s work in Africa remains unfinished.

[Obama visits a rising Africa but one still plagued by economic problems]

Still, he pointed to some of his administration’s signature programs, which have had a measurable impact in Africa. Feed the Future, an initiative that pairs federal funding with money from other nations and the private sector, works to boost the productivity of small farmers in developing nations. The administration released a report Tuesday saying the program was responsible for a 25 percent reduction in stunting, a form of childhood malnutrition, in two provinces in Kenya between 2009 and 2014, and a 16 percent decline in rural poverty across Uganda in recent years.

Also Tuesday, Obama visited the floor of the Faffa Food factory in Addis Ababa, which makes fortified baby food, flours, barley mixes and other products. A local farmer and one of the factory workers explained how they’ve been able to boost agricultural yields and overall production with the help of Feed the Future.

Standing near silos and sorting belts, the president told reporters: “There have been questions before about what are some signature initiatives that really make a difference. This is making a difference in very concrete ways.”

The Power Africa initiative, another public-private partnership that aims to add 30,000 megawatts of power to serve 60 million households and business, has attracted $26 billion in pledges from donors and private firms in the United States and abroad.

‘A fragile foundation’

Those initiatives were part of a narrative Obama returned to throughout his visit: Africa is a continent where problems are being solved, where the middle class is growing, where countries are modernizing.

But for all the successes, some of the administration’s major hopes for Africa have been dashed by conflict. In South Sudan, where the United States in 2011 championed the birth of the world’s newest nation, civil war has claimed tens of thousands of lives since breaking out in 2013. In recent weeks, the United Nations reported that children have been brutally slaughtered.

[ Obama to meet with African leaders on South Sudan]

This week, Obama described “continued roadblocks” to peace there, and administration officials expressed pessimism that the conflict would end anytime soon.

In Somalia, the al-Qaeda-linked terrorist group al-Shabab continues to wage brutal assaults on civilians and the country’s nascent government. The group also has the ability to stage attacks across the border in Kenya.

“When they’re willing to target soft targets and civilians, and are prepared to die, they can still do a lot of damage,” Obama said in Nairobi on Saturday.

The next day, as the president left for Ethiopia, al-Shabab fighters drove a truck packed with explosives into the Jazeera Hotel, frequented by foreign diplomats and journalists in Somalia’s capital, Mogadishu, killing 15.

The specter of terrorism had made preparing for this trip particularly complicated for the White House. A law enforcement official familiar with Secret Service security and logistics planning said the visit had been the most challenging since George W. Bush went to Islamabad in 2006, based on the level of terrorist activity and lack of infrastructure in the region.

Aside from terrorism, there were less-violent but still insidious issues that cast shadows — the Ethio­pian government’s jailing of journalists, for example, and Kenyan security forces’ targeting of Muslims.

Those problems, among others, forced Obama to qualify his praise for the continent’s progress.

“We must acknowledge that many of these gains rest on a fragile foundation,” he said at the African Union on Tuesday. The president said more should be done to promote democracy. “When journalists are put behind bars for doing their jobs or activists are threatened as governments crack down on civil society, then you may have democracy in name, but not in substance,” he said to applause.

While Obama articulated a U.S. role in building on that foundation, there were reminders that Africa now has other options and might not always be accepting of a strong U.S. hand. One example was the very building where Obama spoke: The African Union headquarters, with gilded emblems and wood detailing, was funded largely with Chinese money. And the organization is chaired by Robert Mugabe, the president of Zimbabwe, where the United States continues to impose sanctions against a regime it considers undemocratic.

In Kenya, the International Criminal Court’s indictment of President Kenyatta in 2012 led to a “huge chill” in bilateral relations, said former U.S. ambassador Scott Gration, who now runs a business working with investors in Kenya.

When the United States distanced itself from the Kenyan government after the indictment, Kenya promptly looked east, planning Chinese-funded infrastructure projects across the country.

“But the president’s visit reinforces that there’s been a reset of the relationship,” Gration said. “I think we’re over that hump that occurred because of the ICC.”

The charges against Kenyatta were dropped late last year.

‘The most urgent task’

In nearly every public setting, the president went out of his way to describe what young Africans can do to chart a better trajectory for their nations. And at times he singled out young people, such as 16-year-old Kenyan student Linet Momposhi.

Momposhi described how a friend of hers underwent genital mutilation at age 12, married a man twice her age and now has three children, whom she supports by milking cows each morning. Momposhi had a chance to attend boarding school instead.

“And now I would like to be a cardiologist and study at Harvard University,” she said. “Before joining the center, I never knew what I was going to do because I never had any hope in life.”

Obama — who told her, “I’m sure you’re going to be an excellent cardiologist” — said her experience underscored why he has focused on mentioning young people of color in the United States.

“And when they have a vision about what could happen, then suddenly they’re motivated, the same way that Linet is motivated,” he said. “And she starts having bigger ambitions about what’s possible.”

In 2014, Obama launched the Young African Leaders Initiative, which now has more than 140,000 members, connected digitally and through regional programs.

“Ultimately, the most powerful antidote to the old ways of doing things is this new generation of African youth,” the president said at the African Union.

In Ethi­o­pia, Obama attended a state dinner at the National Palace, where he got to see “Lucy,” the 3.2 million-year-old skeleton discovered in the country’s Afar region in 1974; it belonged to what was once considered the earliest known human ancestor.

But the president seemed more focused on Africa’s modernization than on its history.

More than half of Sub-Saharan Africa’s population is under the age of 25. With abject poverty commonplace and the burden of disease high, the continent’s future leaders will have massive challenges to confront.

“I suggest to you that the most urgent task facing Africa today and for decades ahead is to create opportunity for this next generation. And this will be an enormous undertaking,” Obama said at the African Union. “Africa will need to generate millions more jobs than it’s doing right now. And time is of the essence. The choices made today will shape the trajectory of Africa, and therefore the world, for decades to come.”

Carol D. Leonnig contributed to this story.