+ 2
Find The Largest Element Pro Challenge
Here’s what 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; } The issue is it only prints the input value instead of the max value in the array. What am I missing to get the code to print out the max value? Thanks for any and all assistance!
7 odpowiedzi
+ 5
👍🏻 I got it working now. Thanks for the assistance!
+ 2
Your nums array is only initialized with n. Where are the rest of the elements? Also, you can start i in the for loop with a value of 1. No need to compare nums[0] to itself.
+ 2
I appreciate the responses. To ChaoticDawg: The for loop code was provided. I did not create it, but your advice is duly noted.
If y’all don’t mind, I need a little more clarity to what I need to edit in my code. I learn best from examples more so than written instructions. You don’t have to give anything away - just something I can go by.
With that being said, this is what I gathered from the advice y’all provided:
I only needed to add a couple of lines to my code.
#include <iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int nums [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;
delete [] nums;
return 0;
}
I know something is still off because this code still doesn’t work, hence the need for some clarity.
Thank you.
+ 2
1. Use
int nums[n] = {};
Or
int *nums = new int[n];
Not both
Given that the challenge pertains to dynamic memory allocation use the latter.
2. This
*nums = n;
is wrong, it sets the array to n when you need a whole list of numbers.
You need to use a loop and initialize each element to a value that should be given as additional input(s). You'll have to re-read the challenge to figure this part out, since non-pro users can't see this info.
3. Now you can use the code that you already have to find the max.
4. To free up dynamic allocation of memory (i.e. pointers) just use:
delete pointer;
Where pointer is the name of the pointer variable. In this case nums
delete nums;
You can complete this challenge just using a single loop where you do both the receiving of the elements and the finding of the max element, but you may want to just try solving it with a loop for each stage first.
+ 1
Also don't forget to delete memory allication before end of main function 👍
delete [] nums;
0
Hey uhm i know this is not what you expected but can you show me what's wrong here:
#include<iostream>
using namespace std;
int main()
{ int age;
cout<< "how old are you? \n";
cout<< "i'm: ";
cin>> age;
if (age >= 18)
{cout<< "ok, "<<age<<" is enough for this job\n";}
else (age < 18);
{cout<< "sorry, you're too young for this job\n";}
Return 0;}
ps: nevermind i found it
0
I cant fix this problemm too is there anybody else send to code?
,