Write a program which accepts as input a vector and displays the largest and smallest element in the vector in C++. Below are my coding.
#include<vector> #include<iostream> using namespace std; vector<int>v; int num; for(int i=0;i<num;i++) v.push_back(i); cout<<"Vector contains:"; vector<int>::iterator itr1=v.begin(); vector<int>::iterator itr2=v.end(); for(vector<int>::iterator itr=itr1; itr!=itr2;itr++) cout<<*itr<<" "; int max(itr1,itr2); int min(itr1,itr2); cout<<"The largest %d and smallest value are %d:",max, min); return 1; } is my code good? can u pls correct it? Thank you.
You would be better off breaking the problem down into smaller sub-problems, and break those down into sub-sub-problems if needed. Solve each of the small problems, and write a main() function to kind of "glue" it all together.
Hello rsmith, thanks for your reply, but i have still no idea how to break them into smaller sub-problems. Can you help me in the coding pls?
We're not supposed to write people's code for them. As far as breaking it down, you need to get the input, you probably want to store it in a vector. You need to search through your vector, checking whether this vector[value] is greater than the largest or less than the smallest. Once you have the largest and smallest values, you have to output them. Deal with each of these separately. You can start by using each sentence as the comment that describes what each piece of code is going to do. Doing it like this makes the problem less daunting.
@Turinglunch
Join our real-time social learning platform and learn together with your friends!