Question #343668

1. Create a C++ program that asks the user to input full name 5times using for, do while and while loop. Then,display.

1.a. For loop

1.b. While loop

1.c Do while loop



Example display in console application


—-This program can accept 5 full names from the user——


Please enter five full names :

Carlo Adam

Justin Doe

Liam Baird

Mike Tan

John Davis


//Expected output:

You entered the following names:

Carlo Adam

Justin Doe

Liam Baird

Mike Tan

John Davis

Congratulations!


Expert's answer

1.a.

#include <iostream>
#include <string>


int main()
{
	std::string names[5];
	std::cout << "Please enter five full names:" << std::endl;
	for (int i = 0; i < 5; ++i)
	{
		std::getline(std::cin, names[i]);
	}
	std::cout << std::endl << "You entered the following names:" << std::endl;
	for (int i = 0; i < 5; ++i)
	{
		std::cout << names[i] << std::endl;
	}
	std::cout << "Congratulations!" << std::endl;

	return 0;
}

1.b.

#include <iostream>
#include <string>


int main()
{
	std::string names[5];
	std::cout << "Please enter five full names:" << std::endl;
	int i = 0;
	while (i < 5)
	{
		std::getline(std::cin, names[i]);
		++i;
	}
	std::cout << std::endl << "You entered the following names:" << std::endl;
	i = 0;
	while (i < 5)
	{
		std::cout << names[i] << std::endl;
		++i;
	}
	std::cout << "Congratulations!" << std::endl;

	return 0;
}

1.c.

#include <iostream>
#include <string>


int main()
{
	std::string names[5];
	std::cout << "Please enter five full names:" << std::endl;
	int i = 0;
	do
	{
		std::getline(std::cin, names[i]);
		++i;
	} while (i < 5);
	std::cout << std::endl << "You entered the following names:" << std::endl;
	i = 0;
	do
	{
		std::cout << names[i] << std::endl;
		++i;
	} while (i < 5);
	std::cout << "Congratulations!" << std::endl;

	return 0;
}
LATEST TUTORIALS
APPROVED BY CLIENTS