Finding max value in a array - c++

I'm doing a program that finds the max value in a array. I done it but I found a strange bug.
#include<iostream>
using namespace std;
int main() {
int n; //input number of elements in
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i]; //input array's elements
} int max_value = arr[0];
for (int i = 1; i <= n; i++) {
if (arr[i] > max_value) {
max_value = arr[i];
}
} cout << max_value;
return 0;
}
When I put 5 as first line for the number of elements and 2, 7, 6, 8, 9 as the elements of the array. It returns 16 instead of 9. Please help

In Arrays the first index starts with 0 and ends in n - 1 assuming the array is of length n
so when looping from i = 1 to i <= n. n is now larger than n - 1.
the solution would be to start from 0 and end at i < n hence:
#include<iostream>
using namespace std;
int main() {
int n; //input number of elements in
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i]; //input array's elements
} int max_value = arr[0];
for (int i = 0; i < n; i++) {
if (arr[i] > max_value) {
max_value = arr[i];
}
}
cout << max_value;
return 0;
}
you could also use the std::max function like so:
for(int i = 0; i < n; i ++) {
max_value = max(max_value, arr[i]);
}

The other posts already pointed out problem in your code.
You should be aware of that int arr[n]; is not permitted in standard C++.
[GCC and CLANG compiler support it in C++ as an extension]
An alternative is to allocate memory dynamically:
int *arr = new int[n];
and to find maximum value you can use std::max_element:
int max_value = *(std::max_element(arr, arr + n));
Instead of dynamic array, its better to use vector STL (make yourself familiar with Containers Library). You can do:
std::vector <int> arr;
for (int i = 0; i < n; i++) {
int input;
std::cin >> input;
arr.push_back(input);
}
int max_value = *std::max_element(arr.begin(), arr.end());
std::cout << "Max element is :" << max_value << std::endl;

in your second for do this
for (int i = 1; i < n; i++) {
if (arr[i] > max_value) {
max_value = arr[i];
}
delete '=' from i <= n because i is index which start from 0
and instead of this
int arr[n];
do this
int *arr = new int[n];

Related

Sorting an array from Largest to smallest in C++

I wanna sort an array from largest to smallest number and make a new array which has it sorted...
so here is my code:
#include <iostream>
using namespace std;
int main()
{
int size, sum = 0, answer = 0,pos, max;
int array[size];
int array2[size];
cin >> size;
for (int i = 0; i < size; i++)
{
cin >> array[i];
sum+=array[i];
}
for (int i = 0; i < size; i++)
{
max = 0;
pos = 0;
for (int q = 0; q < size; q++)
{
if (array[q] > max)
{
max = array[q];
pos = q;
}
}
array2[i] = max;
array[pos] = 0;
}
for (int i = 0; i < size; i++)
{
cout << array2[i] << ", ";
}
return 0;
}
When I put my input:
5
1 2 3 4 5
The output I get is:
0, 0, 0, 0, 5,
but I expect it to be 5, 4, 3, 2, 1,
First of all always initialize a variable when you create it as by default it has some garbage value in C++,
Also you are trying to assign a size variable (as size for an array) that has nothing assign to it yet which will create problems, Secondly you are initializing an array first and then you are taking the size variable from user which is completely opposite of the flow, for creating arrays with dynamic size see How Dynamic Array works and is implemented in C++
Updated Code:
#include <iostream>
using namespace std;
int main()
{
int size=0, sum = 0, answer = 0,pos, max;
cin >> size;
int array[size];
int array2[size];
for (int i = 0; i < size; i++)
{
cin >> array[i];
sum+=array[i];
}
for (int i = 0; i < size; i++)
{
max = 0;
pos = 0;
for (int q = 0; q < size; q++)
{
if (array[q] > max)
{
max = array[q];
pos = q;
}
}
array2[i] = max;
array[pos] = 0;
}
for (int i = 0; i < size; i++)
{
cout << array2[i] << ", ";
}
return 0;
}
Here is the Output
Edit:
As Per #PaulMcKenzie method, the other way which is considered the appropriate one, uses the std::Vector method to initialize a dynamic array in C++, people who use the first method in visual studio might face errors,
Second Method Updated Code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int size=0, sum = 0, answer = 0,pos, max;
cin >> size;
std::vector<int> array(size), array2(size);
for (int i = 0; i < size; i++)
{
cin >> array[i];
sum+=array[i];
}
for (int i = 0; i < size; i++)
{
max = 0;
pos = 0;
for (int q = 0; q < size; q++)
{
if (array[q] > max)
{
max = array[q];
pos = q;
}
}
array2[i] = max;
array[pos] = 0;
}
for (int i = 0; i < size; i++)
{
cout << array2[i] << ", ";
}
return 0;
}
Second Output
The size of an array variable must be a compile-time constant. A user-supplied value at runtime is probably unknowable at compile time.so I recommend using std::vector instead of array.
#include <iostream>
#include<vector>
#include <algorithm>
int main()
{
int size=0, input=0;
std::cout << "enter size :";
std::cin >> size;
std::vector<int> vec;
for (size_t i{ 0 }; i < size; ++i)
{
std::cout << "enter "<<i<< ".input:";
std::cin >> input;
vec.push_back(input);
}
// Sort the elements of the vector in descending order
for (const auto& i : vec)
std::sort(vec.begin(), vec.end(), std::greater <>());
//Print the elements of the vector
for (const auto& i : vec)
std::cout << i << " ,";
return 0;
}
Output:
enter size :5
enter 0.input:1
enter 1.input:2
enter 2.input:3
enter 3.input:4
enter 4.input:5
5 ,4 ,3 ,2 ,1 ,

Why does this selection sort code shows different output when running again as compared to first time

Firstly when I have code this program it was running perfectly but running it again, it is not showing expected output can someone tell what's wrong with it
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
int arr[n];
int loc,min;
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
for (int i = 0; i < n - 1;i++){
min = arr[i];
for (int j = i + 1; j < n; j++)
{
if(min>arr[j]){
min = arr[j];
loc = j;
}
swap(arr[loc],arr[i]);
}
}
for (int i = 0; i < n; i++){
cout << arr[i] << " ";
}
cout << endl;
}
Forgoing the fact that variable-length arrays are not part of standard C++ (and thus code tutorials that use them should be burned), the code has two main problems.
On an already sorted sequence, the inner-most if body will never be entered, and therefore loc will never receive a determinate value.
The swap is in the wrong place..
Explanation
Within your code...
using namespace std;
int main(){
int n;
cin >> n;
int arr[n];
int loc,min; // loc is INDETERMINATE HERE
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
for (int i = 0; i < n - 1;i++){
min = arr[i];
for (int j = i + 1; j < n; j++)
{
if(min>arr[j]){
min = arr[j];
loc = j; // loc ONLY EVER SET HERE
}
swap(arr[loc],arr[i]); // loc IS USED HERE EVEN IF NEVER SET
}
}
for (int i = 0; i < n; i++){
cout << arr[i] << " ";
}
cout << endl;
}
The purpose of the inner loop is to find the location (loc) of the most extreme value (smallest, largest, whatever you're using for your order criteria) within the remaining sequence. No swapping should be taking place in the inner loop, and the initial extreme value location (again, loc) should be the current index of the outer loop (in this case i)
Therefore...
We don't need min. It is pointless.
We must initialize loc to be i before entering the inner loop.
We swap after the inner loop, and then only if loc is no longer i.
The result looks like this.
int main()
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
for (int i = 0; i < n - 1; i++)
{
int loc = i;
for (int j = i + 1; j < n; j++)
{
if (arr[loc] > arr[j])
loc = j; // update location to new most-extreme value
}
// only need to swap if the location is no longer same as i
if (loc != i)
swap(arr[loc], arr[i]);
}
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
The line swap(arr[loc],arr[i]); should be outside the inner for loop, so move it one line down.
Also, you will want to initialize loc to i at the start of the outer for loop.
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
int arr[n];
int loc,min;
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
for (int i = 0; i < n - 1;i++){
min = arr[i];
loc=i;
for (int j = i + 1; j < n; j++)
{
if(min>arr[j]){
min = arr[j];
loc = j;
}
swap(arr[i],arr[loc]);
}
}
for (int i = 0; i < n; i++){
cout << arr[i] << " ";
}
cout << endl;
}

Why the output is not showing?

My program is to find the smallest positive number missing from an array. With the following input I expect an output of 2.
6
0
-9
1
3
-4
5
My problem is that it does not give any output. Can anyone explain this please?
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
int array[n];
for (int i = 0; i < n; i++)
{
cin >> array[n];
}
int const N = 1e4+2;
bool indexarray[N];
for (int i = 0; i < N; i++)
{
indexarray[i] = false;
}
for (int i = 0; i < n; i++)
{
if (array[i] > 0)
{
indexarray[array[i]] = true;
}
}
int ans = -1;
for (int i = 1; i < N; i++)
{
if (indexarray[i] == false)
{
ans = i;
}
}
cout << ans << endl;
return 0;
}
I think because int array[n]; makes an array called array with n elements in it, with the first one starting at array[0].
cin >> array[n]; needs to modify array[n], but because the first element is array[0], the last element is array[n-1], and array[n] does not exist. Your code gave an error and exited.
Try changing
for (int i = 0; i < n; i++)
{
cin >> array[n];
}
to
for (int i = 0; i < n; i++)
{
cin >> array[i];
}
Also, I think variable length arrays are non-standard, so maybe try changing that. Replace it with std::vector<int> array(n) should work.

removing double elements in an array

I am trying to remove double elements in an array. I developed a simple code, but it is still not working. Is it possible to hint for some input maybe I haven't tried. I tried corner and test cases. The following is the problem statement:
A sequence of numbers given. Remove element’s doubles, leaving first copy.
Input: Contains a natural n (n ≤ 100000) – the n quantity numbers in a sequence, then n non-negative numbers – elements of the sequence which module is not greater than 999.
output: changed sequence.
It seems I can't get what might be the problem
#include <iostream>
//#include <cmath>
//#include <climits>
#define SIZE 100000
using namespace std;
int main()
{
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int n, k, p;
bool tag; tag = false;
cin >> n;
long long int *a = new long long int[n];
long long int b[SIZE];
for (int i = 0; i < n; i++) { cin >> a[i]; }
for (int i = 0; i < n; i++) { k = 0;
for (int j = i + 1; j < n; j++) {
if (a[i] == a[j]) { b[k] = j-k; k++; tag = true; }
}
if (tag) {
for (int i = 0; i < k; i++) {
p = b[i];
for (int i = p; i < n; i++) { a[i] = a[i + 1]; }
n--;
}
tag = false;
}
}
for (int i = 0; i < n; i++) { cout << a[i] << " "; }
return 0;
}
Input: 6 1 2 2 4 3 4 Output: 1 2 4 3
You can use unordered_set and vector
int n; cin >> n;
long long int x;
unordered_set<long long int>myset;
vector<long long int>v1;
for (int i = 0; i < n; i++)
{
cin>>x;
if(myset.find(x)==myset.end())
{
myset.insert(x);
v1.push_back(x);
}
}
for(int i=0;i<v1.size();i++)
{
cout<<v1[i]<<" ";
}
You could use in you advantage the fact that input values are in the range from 0 to 999.
A simple bool used[1000]{} could be used to flag if the current value has been used already before pushing it to cout, thus ensuring both O(n) complexity and limited memory usage (1000 bytes for the bool[]}.
Here's a sample solution around this idea:
#include<iostream>
#define MAX_VALUE 999
using namespace std;
int main() {
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
bool used[MAX_VALUE + 1]{};
size_t n;
cin >> n;
for (size_t num, i = 0; i < n; ++i) {
cin >> num;
if (!used[num]) {
cout << num << " ";
used[num] = true;
}
}
return 0;
}
You could try creating a second array of unique numbers as you go. I will demonstrate with a vector for the sake of simplicity.
std::vector<int> v;
for (int i = 0; i < n; i++) {
if (std::find(v.begin(), v.end(), arr[i]) == v.end()) {
v.push_back(arr[i]);
}
}
Then, you just write the contents of the vector to the output file.
Here is my version of O(n) complexity. Your solution may exceed time-limit ( if it is low )
bool check[2000];
for (int i = 0; i < 2000; i++) check[i] = 0;
for (int i = 0; i < n; i++) {
cin >> a[i];
// +999 to avoid negative numbers
check[a[i] + 999] = 1;
}
bool isPrint = false;
for (int i = 0; i < n; i++) {
if (check[a[i] + 999]) {
// mark false if already printed
check[a[i] + 999] = 0;
if (isPrint) printf(" ");
printf("%d", a[i]);
isPrint = true;
}
}

Memory Limit Exceeded while reading integers into the vector

I am trying to read integer values from text file into a vector.
Input file ip1.txt has the following content:
4
-1000 -2000 -3000 -4000
int maxsub(vector<int> a, int size)
{
a.erase(a.begin());
vector<int> sum;
for(vector<int>::iterator w=a.begin(); w <= a.begin()+size-1; ++w)
{
int j;
int s=*w;
for(int t=0; t <= size-1; t++)
{
j = s + a[t];
sum.push_back(j);
}
a.pop_back();
}
std::sort(sum.begin(),sum.end());
int u = sum.size()-1;
int m = sum.at(u);
return m;
}
int main()
{
std::vector<int> nums( (std::istream_iterator<int>(std::cin)),
std::istream_iterator<int>() );
int k = nums[0];
int u = maxsub(nums,k);
cout << u <<endl;
}
I am getting Warning message as 'Memory Limit Exceeded'
How can i resrict vector to read only till -4000 in the input file,I am using file redirection
*./123 < ip1.txt *
Bug at the source code.
All loops in maxsub()
for(vector<int>::iterator w=a.begin(); w <= a.begin()+size-1; ++w)
for(int t=0; t <= size-1; t++)
has iterations from 0 to size-1 elements (=size all in all elements), but after code
a.erase(a.begin());
vector 'a' has only (size-1) elements.
Therefore, all for-operators is 'outside-the-boundary'.
I think, it's cause of warning message.
If you know that the first number will be the length of your vector, why not take advantage of it?:
int length = 0;
std::cin >> length;
std::vector<int> numbers;
numbers.reserve(length);
then you can just use simple for loop that checks whether the number has been successfully extracted from the stream and also prevents more than specific amount of numbers being read:
int number;
for (int i = 0; (i < length) && (std::cin >> number); ++i)
{
numbers.push_back(number);
}
Don't forget to #include <iostream>, #include <sstream> and #include <vector>. Also note that std::cin can be easily replaced with file stream :)
Write a for loop
std::vector<int> nums;
int size;
std::cin >> size;
for (int i = 0; i < size; ++i)
{
int val;
std::cin >> val;
nums.push_back(val);
}
'a.begin()+size-1' is before begin():
Having
for(vector<int>::iterator w=a.begin(); w <= a.begin()+size-1; ++w)
and
int k = nums[0];
int u = maxsub(nums,k);
and
nums[0] = -1000;
size is -1000
If you want to exclude the first and last element:
if( ! a.empty()) {
// Not erasing the first element: a.erase(a.begin());
for(vector<int>::size_type i = 1; i < a.size() - 1; ++i);
}