Answer to Question #300340 in C++ for Kelly

Question #300340

How to execute this using vector



#include <iostream>



int main() {



int size, index, largest, smallest;



std::cout << "How many intergers you want to input? ";


std::cin >> size;



int myarray[size];



std::cout << "Input the elements of the array: ";


for (index = 0; index < size; index++)


std::cin >> myarray[index];



largest = myarray[0];


smallest = myarray[0];



for (index = 0; index < size; index++) {


// largest


if (myarray[index] > largest)


largest = myarray[index];



// smallest


if (myarray[index] < smallest)


smallest = myarray[index];


}



std::cout << "The largest element in the array is: " << largest << ".\n";


std::cout << "The smallest element in the array is: " << smallest << ".\n";



return 0;


}

1
Expert's answer
2022-02-20T14:40:28-0500
#include <iostream>
#include <vector>

int main()
{
	int size, index, largest, smallest;
	std::cout << "How many intergers you want to input? ";
	std::cin >> size;
	std::vector<int>myvec;
	int value;
	std::cout << "Input the elements of the array: ";
	for (index = 0; index < size; index++)
	{
		std::cin >> value;
		myvec.push_back(value);
	}
	largest = myvec[0];
	smallest = myvec[0];
	for (index = 0; index < size; index++) 
	{
		// largest
		if (myvec[index] > largest)
			largest = myvec[index];
		// smallest
		if (myvec[index] < smallest)
			smallest = myvec[index];
	}
	std::cout << "The largest element in the array is: " << largest << ".\n";
	std::cout << "The smallest element in the array is: " << smallest << ".\n";
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog