Why the output is not showing? - c++

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.

Related

Finding max value in a array

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];

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;
}

print duplicate elements in array

I want to find duplicate elements in a dynamic array. In most cases it works, but how can it work for this case. I'm finding duplicate elements in a given array. But there is one problem that my duplicate elements can repeat too. How can I solve that part.
#include <iostream>
int main() {
unsigned n;
std::cin >> n;
int count = 0;
int* dynArr = new int[n];
for (int i = 0; i < n; i++) {
std::cin >> dynArr[i];
}
for(int i = 0; i < n; i++){
for(int j = i + 1; j < n; j++){
if(dynArr[j] == dynArr[i]){
std::cout<<dynArr[j]<<" ";
break;
}
}
}
}
I have a problem with this part. When I'm inputting a my array length 6, and elements {1,1,2,1,2,2}.
I got (1,1,2,2).
But I need to get only 1,2.
input 6
1 1 2 1 2 2
output 1 1 2 2
but must be
output 1 2
Here's a simple and fast solution.
std::map<int,size_t> element_count;
for(int i = 0; i < n; i++){
if ( ++element_count[dynArr[i]] == 2 ){
// Only report on the second occurrance
std::cout<<dynArr[j]<<" ";
}
}
const int listSize = 5;
int list1[listSize] = {0,0,1,1,3};
bool dupList[listSize] = {false};
for (int index = 0; index < listSize; index++) {
int val = list1[index];
for (int i = 0; i < listSize; i++) {
if (i != index) {
if (list1[i] == val) {
dupList[index] = true;
}
}
}
}
int printList[listSize];
int addNum = 0;
for (int index = 0; index < listSize; index++) {
if (dupList[index] == true) {
bool run = true;
int print = list1[index];
for (int i = 0; i < listSize; i++) {
if (printList[i] == print) {
run = false;
}
}
if (run == true) {
std::cout << print << " ";
printList[addNum] = print;
addNum++;
}
}
}
Note this code will NOT run quickly at all only use it if the operation does not need to get run very many times but it will only display the single numbers that are duplicates. It will defernatly need to get optimised more
You can simply get it done using two std::set<int>s.
#include <set>
#include <iostream>
int main() {
unsigned n;
std::cin >> n;
int count = 0;
std::set<int> all;
std::set<int> redundant;
for (int i = 0; i < n; i++) {
int input = 0;
std::cin >> input;
// You cant enter the entry because its present. This will return a std::pair<,> with the second value false.
if (!all.insert(input).second)
redundant.insert(input); // We store this in another set so we dont duplicate the redundant entries.
}
for (auto itr = redundant.begin(); itr != redundant.end(); itr++)
std::cout << *itr << " ";
}

Frequency of arrays in C++

I'm trying to write a code which works like this:
it first gets an int from the user which presents the number of array indexes the user would like to own (n), then the code creates an array with n number of indexes. It then has to print the frequency of every entered number.
Running my below code results in a segmentation fault. Any solution will in advance be appreciated.
My code:
int main()
{
int n, index;
cin>>n;
int ar[n];
int freq[100]={0};
for (int i = 0; i < n; i++)
{
cin>>ar[i];
}
for (int i = 0; i < 100; i++)
{
index=ar[i];
freq[index]++;
}
for (int i = 0; i < 100; i++)
{
cout<<freq[i]<<' ';
}
return 0;
}
NOTE: 1<=n<=100
I would do something like this:
int main ()
{
int n, input;
while (n > 100 || n < 1)
cin >> n;
// indexes 0 - 99
int freq[100] = { 0 };
for (int i = 0; i < n; i++)
{
cout << "number: ";
cin >> input;
if (input > 0 && input <= 100)
freq[input - 1]++;
}
for (int i = 0; i < n; i++)
if (freq[i] != 0)
cout << i + 1 << "-->" << freq[i] << &endl;
return 0;
}
try it here

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;
}
}