0
Dynamic Memory C++ The Largest Element
Can someone give me the answer to this exercise so I can learn from it.
7 RĂ©ponses
+ 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 đ€.
+ 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. đđ
+ 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?
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.
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.
0
Thanks for the response.