Dynamic Memory C++ The Largest Element | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Dynamic Memory C++ The Largest Element

Can someone give me the answer to this exercise so I can learn from it.

22nd Jan 2021, 6:03 PM
Joshua Birdine
Joshua Birdine - avatar
6 Answers
+ 3
#include <iostream> using namespace std; int main() { int n; cin>>n; int *nums = new int[n]; // *nums = new n; for(int j= 0; j< n; j++) { cin>>nums[j]; } int max=0; for(int i=0; i<n; i++) { if(nums[i]>max){ max = nums[i]; } } cout<<max; return 0; } This is my solution I hope it helps. But try it yourself you will get it better from trial and error 🤗.
19th Jun 2022, 12:44 PM
Nikola Kirov
Nikola Kirov - avatar
+ 2
Dynamic Memory C++ The Largest Element #include <iostream> using namespace std; int main() { int n; cin>>n; //size of the array // your code goes here int *nums = new int[n]; int Max = nums[0]; for(int i=0; i<n; i++) { cin >> nums[i]; if(nums[i]>max) max = nums[i]; } cout<<max; return 0; } This is my solution I hope it helps. 😊😊
10th Feb 2023, 9:09 AM
Abhishek Gangwar
Abhishek Gangwar - avatar
+ 1
Even if I wanted to, non-PRO users don't have access to the exercise. How about you copy your attempted code into a Playground project and share that here, so that we can have a look together for what might be wrong with your approach?
22nd Jan 2021, 6:07 PM
Shadow
Shadow - avatar
0
Here is my code I have so far: #include <iostream> using namespace std; int main() { int n; cin>>n; int *nums = new int[n]; *nums = n; int max=nums[0]; for(int i=0; i<n; i++) { if(nums[i]>max){ max = nums[i];} } cout<<max; return 0; } It only prints out the input value instead of the max value in the array. I’m stuck here trying to figure out what’s missing. Thanks for any and all assistance.
31st Jan 2021, 9:29 PM
Jon Scoggins
Jon Scoggins - avatar
0
Jon Scoggins The issue is here: *nums = n; This line assigns 'n' to the first element in the "nums" array, but all other elements remain uninitialized. You simply forgot to get the numbers to be stored in the array from the input stream.
31st Jan 2021, 10:32 PM
Shadow
Shadow - avatar
0
Thanks for the response.
1st Feb 2021, 12:39 AM
Jon Scoggins
Jon Scoggins - avatar