So I am trying so merge 2 sorted arrays into one and I get really weird numbers like an output. Here is my code:
#include<iostream>
using namespace std;
int* add(int first[],int second[], int sizeFirst, int sizeSecond)
{
int result[sizeFirst + sizeSecond];
int indexFirst = 0,indexSecond = 0;
for(int i = 0;i < sizeFirst + sizeSecond;i++)
{
if(indexFirst == sizeFirst || first[indexFirst] > second[indexSecond])
{
result[i] = second[indexSecond];
indexSecond++;
}
else
{
result[i] = first[indexFirst];
indexFirst++;
}
}
return result;
}
int main()
{
int n;
cin>>n;
int arr[n];
for(int i = 0;i < n;i ++)
cin>>arr[i];
int m;
cin>>m;
int arr2[m];
for(int i = 0;i < m;i ++)
cin>>arr2[i];
int *res;
res = add(arr,arr2,n,m);
for(int i = 0;i < n + m;i ++)
cout<<res[i]<<" ";
return 0;
}
Notes: It sorts it properly, so the mistake is not there. Also I need to do it as a function because I will need it later on for some other stuff.
return result;
You are returning a pointer to local array, which gets destroyed immediately after - this is undefined behavior. You should either allocate it using new or use std::vector (which is preferred).
Also, int result[sizeFirst + sizeSecond]; is not valid C++ because the standard doesn't allow variable sized arrays (but int* result = new int[sizeFirst + sizeSecond]; is valid).
Related
I am new to coding and I am unable to see what is wrong with this Logic.
I am unable to get the desired output for this program.
The Question is to find the minimum and maximum elements of an array.
The idea is to create two functions for minimum and maximum respectively and have a linear search to identify the maximum as well as a minimum number.
#include <iostream>
#include<climits>
using namespace std;
void maxElement(int a[], int b)
{
// int temp;
int maxNum = INT_MIN;
for (int i = 0; i < b; i++)
{
if (a[i] > a[i + 1])
{
maxNum = max(maxNum, a[i]);
}
else
{
maxNum = max(maxNum, a[i+1]);
}
// maxNum = max(maxNum, temp);
}
// return maxNum;
cout<<maxNum<<endl;
}
void minElement(int c[], int d)
{
// int temp;
int minNum = INT_MAX;
for (int i = 0; i < d; i++)
{
if (c[i] > c[i + 1])
{
minNum = min(minNum,c[i+1]);
}
else
{
minNum = min(minNum,c[i]);
}
// minNum = min(minNum, temp);
}
// return minNum;
cout<<minNum<<endl;
}
int main()
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
minElement(arr,n);
maxElement(arr,n);
return 0;
}
You are already comparing each element to the current max / min. It is not clear why in addition you compare to adjacent elements. Trying to access a[i+1] in the last iteration goes out of bounds of the array and causes undefined behavior. Just remove that part:
void maxElement(int a[], int b)
{
// int temp;
int maxNum = INT_MIN;
for (int i = 0; i < b; i++)
{
maxNum = max(maxNum, a[i]);
}
cout<<maxNum<<endl;
}
Similar for the other method.
Note that
int n;
cin >> n;
int arr[n];
is not standard C++. Variable length arrays are supported by some compilers as an extension, but you don't need them. You should be using std::vector, and if you want to use c-arrays for practice, dynamically allocate the array:
int n;
cin >> n;
int* arr = new int[n];
Also consider to take a look at std::minmax_element, which is the standard algorithm to be used when you want to find the min and max element of a container.
Last but not least you should seperate computation from output on the screen. Considering all this, your code could look like this:
#include <iostream>
#include <algorithm>
std::pair<int,int> minmaxElement(const std::vector<int>& v) {
auto iterators = std::minmax_element(v.begin(),v.end());
return {*iterators.first,*iterators.second};
}
int main()
{
int n;
std::cin >> n;
std::vector<int> input(n);
for (int i = 0; i < n; i++)
{
std::cin >> input[i];
}
auto minmax = minmaxElement(input);
std::cout << minmax.first << " " << minmax.second;
}
The method merely wraps the standard algorithm. It isnt really needed, but I tried to keep some of your codes structure. std::minmax_element returns a std::pair of iterators that need to be dereferenced to get the elements. The method assumes that input has at least one element, otherwise dereferencing the iterators is invalid.
Good evening, folks.
I'm currently experiencing difficulties with extracting pair numbers from an array. I have the following code:
#include <iostream>
using namespace std;
int *paire(int *d, int length) {
int counter = 0;
int position = 0;
for (int i=0; i<length; i++) {
if (d[i] % 2 ==0)
counter++;
}
int *k = new int[counter];
for (int i=0; i<length; i++) {
if (d[i] % 2 ==0) {
k[position] = d[i];
position++;
}
}
return k;
}
int main() {
int b[8] = {1,2,3,4,5,6,7,8};
int *array1 = paire(b,8);
for (int i=0; i<5; i++) { // how can I point here to the counter in paire() ?
cout<<array1[i];
}
delete[] array1;
return 0;
}
So I think I've got it right with initializing the new array in function paire, but I'm having difficulties to iterate through the array.
P.S. I'm first year in university, so I would really be thankful if you can keep the same simplicity in the answers. Thanks in advance!
It appears that you need to return 2 separate values: the number of even numbers in the array b, and the address of the newly allocated memory that is storing exclusively those even numbers.
Since you can not return multiple variables, one solution that does minimal modification to your code would be as follows.
int *paire(int *d, int length, int& counter) {
counter = 0;
// rest of your function remains unchanged
// ...
}
int main() {
int b[8] = {1,2,3,4,5,6,7,8};
int evenNumbers;
int *array1 = paire(b,8, evenNumbers);
for (int i=0; i<evenNumbers; i++) {
cout<<array1[i];
}
delete [] array1;
return 0;
}
Alternatively, you can return the value in counter and send the reference to the int* variable as an argument to paire function. Or, you can declare paire to have return type void and use references to pass back both the values.
You can further simplify your function by allocating to that of the length and returning the counter by an output parameter.
#include <iostream>
using namespace std;
int *paire(int *d, int length, int &counter) {
counter = 0;
int *k = new int[length]; // allocate for the maximum memory
for (int i = 0; i < length; ++i) {
if (d[i] % 2 == 0) {
k[counter++] = d[i];
}
}
return k;
}
int main() {
int b[8] = {1,2,3,4,5,6,7,8};
int counter = 0;
int *array1 = paire(b,8, counter);
for (int i=0; i<counter; i++) { // how can I point here to the counter in paire() ?
cout<<array1[i] << " ";
}
delete [] array1;
return 0;
}
But please note that as others have already pointed out this method is quite error prone in the sense that it leaves the responsibility to the client to delete the internal memory used by paire function.
I cant find out whats wrong with this part of my program, i want to find out most occuring number in my structure(array), but it finds only the last number :/
void Daugiausiai(int n)
{
int max = 0;
int sk;
for(int i = 0; i < n; i++){
int kiek = 0;
for(int j=0; j < n; j++){
if(A[i].datamet == A[j].datamet){
kiek++;
if(kiek > max){
max = kiek;
sk = A[i].datamet;
}
}
}
}
}
ps. its only a part of my code
You haven't shown us enough of your code, but it is likely that you are not looking at the real result of your function. The result, sk is local to the function and you don't return it. If you have global variable that is also named sk, it will not be touched by Daugiausiai.
In the same way, you pass the number of elements in your struct array, but work on a global struct. It is good practice to "encapsulate" functions so that they receive the data they work on as arguments and return a result. Your function should therefore pass both array length and array and return the result.
(Such an encapsulation doesn't work in all cases, but here, it has the benefit that you can use the same function for many different arrays of the same structure tape.)
It is also enough to test whether the current number of elements is more than the maximum so far after your counting loop.
Putting all this together:
struct Data {
int datamet;
};
int Daugiausiai(const struct Data A[], int n)
{
int max = 0;
int sk;
for (int i = 0; i < n; i++){
int kiek = 0;
// Count occurrences
for(int j = 0; j < n; j++){
if(A[i].datamet == A[j].datamet) kiek++;
}
// Check for maximum
if (kiek > max) {
max = kiek;
sk = A[i].datamet;
}
}
return sk;
}
And you call it like this:
struct Data A[6] = {{1}, {2}, {1}, {4}, {1}, {2}};
int n = Daugiausiai(A, 6);
printf("%d\n", n); // 1
It would be nice if you had english variable names, so I could read them a bit better ^^. What should your paramter n do? Is that the array-length? And what should yout funtion do? It has no return value or something.
int getMostOccuring(int array[], int length)
{
int current_number;
int current_count = 0;
int most_occuring_number;
int most_occuring_count = 0;
for (int i = 0; i < length; i++)
{
current_number = array[i];
current_count = 0;
for (int j = i; j < length; j++)
{
int test_number = array[j];
if (test_number == current_number)
{
current_count ++;
if (current_count > most_occuring_count)
{
most_occuring_number = current_number;
most_occuring_count = current_count;
}
}
}
}
return most_occuring_number;
}
this should work and return the most occuring number in the given array (it has a bad runtime, but is very simple and good to understand).
#include<stdio.h>
#include<stdlib.h>
int* getEvenNumbers(int arr[], int N)
{
int i, k = 0 , a[50], p;
for (i = 0; i < N; i++)
{
if (arr[i] % 2 == 0)
{
arr[k]=arr[i];
k++;
}
}
return arr[k];
}
int main ()
{
int i, arr[5000000], N, a[500000], k, *p;
printf("\nEnter your desired length of the array:\n\n");
scanf("%d", &N);
for (i = 0; i < N; i++)
arr[i]= rand();
getEvenNumbers (arr, N);
printf("\n\nEven numbers in the array are as follows:\n\n");
for (i = 0; i < N; i++)
{
a[i]= *(p+i);
printf("\n[%d] = %d", (i+1), a[i]);
}
}
please i know this is probably very easy for you guys but i need help figuring out how to return a pointer to the array without all my values of my array getting deleted, also i can't use global variables and it has to be a function that returns a pointer pointing to the array
First of all, decrease the size of those arrays, you don't need that much space. Second of all, you made your
getEvenNumbers
function return an int *, and not an int. arr[k] is not an int *. I also don't get why you are returning something if nothing is being assigned when you call the function. You can just change the return type to void.
void getEvenNumbers(int arr[], int N)
You also never allocate any memory for p. You can do
p = (int*) malloc(sizeof(int));
And since you never allocated any memory for p, the following line of code
a[i]= *(p+i);
is assigning a[i] to a random address. You should just try to rewrite this program. There a lot of errors in this program that I didn't even correct. Go on Google an look up finding even numbers in array program or something similar and look at the code of those examples.
EDIT:
I found some code examples for you to use. I hope it helps!
StackOverflow
sanfoundry.com
The caller already knows the address of the array, so you just need to return the new length. If we also remove the unused variables and take advantage of C++ declarations, we will have:
int getEvenNumbers(int* arr, int N)
{
for (int i = 0, k = 0; i < N; i++) {
if (arr[i] & 1 == 0) { // even if lowest bit is zero
arr[k] = arr[i];
k++;
}
}
return k;
}
Now you can print the even numbers easily:
int k = getEvenNumbers(arr, N);
printf("\n\nEven numbers in the array are as follows:\n\n");
for (i = 0; i < k; i++) {
printf("\n[%d] = %d", (i+1), arr[i]);
}
Dynamically allocate memory from heap.
int* a= new int [N];
//Now store the elements from index 1.
// at a[0] store the number of even number you have found in this function.
return a;
In main you know how many even numbers are there.
int *a1=getEvenNumbers(arr,n);
count_even=a1[0];
for(index=1;index<=count_even;index++)
cout<<a1[index];
The code is given here-
#include<stdio.h>
#include<stdlib.h>
int* getEvenNumbers(int arr[], int N)
{
int i, k = 1 , p;
int* a=new int[N+1];
for (i = 0; i < N; i++)
{
if (arr[i] % 2 == 0)
a[k++]=arr[i];
}
a[0]=k-1;
return a;
}
int main ()
{
int i, N;
printf("\nEnter your desired length of the array:\n\n");
scanf("%d", &N);
int arr[N];
for (i = 0; i < N; i++)
arr[i]= rand();
int *a=getEvenNumbers (arr, N);
printf("\n\nEven numbers in the array are as follows:\n\n");
for (i = 1; i <= a[0]; i++)
printf("\n[%d] = %d", (i), a[i]);
delete []a;
}
A better option is to use std::vector.You can read it here.
Let it be a create function for a dynamical allocated array:
void create(int *&a, int dim){
a=new int[dim];
for(int i=0;i<dim;i++){
a[i]=i+1;
}
Here, I need reference (&).
Now, I have a create function for a dynamical allocated matrix:
void create(int **&a,/* int**a, */ int lines,int rows){
...
}
I saw that reference is optional for dynamical allocated matrix create function. Why?
You need reference if you want to allocate the "outer" array - lines. Without it, you can allocate only "inner" arrays - rows (if "outer" array has been already allocated). So in your case, reference is mandatory.
void create(int **a, int lines, int rows)
{
a = new int*[lines]; // passed pointer to 'a' will point to an old address
for(int i = 0; i < lines; i++)
a[i] = new int[rows];
}
If you want to modify the pointer passed to a function inside the function, it needs to be passed by reference.
So no, the reference is not optional in your case. Wherever you saw that it's optional, was wrong.
My bad. I'm sorry.
I saw that refference in assignValues function isn't necessary so I thought that it is unnecessary for the create function, too.
Thank you all for replies.
Again, I'm sorry.
Here is my code:
#include <iostream>
#include <conio.h>
using namespace std;
void create(int **&a, int lines, int rows){
int i;
a = new int*[lines];
for (i = 0; i < lines; i++){
a[i] = new int[rows];
}
}
void assignValues(int **a, int lines, int rows){
int i,j,k = 1;
for (i = 0; i < lines; i++){
for (j = 0; j < rows; j++){
a[i][j] = k;
k++;
}
}
}
void print(int **a, int lines, int rows){
int i, j;
cout << "Matrix is: "<<endl;
for (i = 0; i < lines; i++){
for (j = 0; j < rows; j++){
printf("%3d",a[i][j]);
}
cout << endl;
}
}
int main()
{
int lines = 5;
int rows = 4;
int **a = 0;
create(a, lines, rows);
assignValues(a, lines, rows);
print(a, lines,rows);
_getch();
return 0;
}