C++ Array passing to function with size [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am writing C++ code to get the maximum number from an array of integers using a function.
My code is as follows, but it's not working and I can't seem to fix it, I would like to know, if possible, what's wrong with it:
#include<iostream>
using namespace std;
int maxfunc(int myArr, int size);
int main()
{
int size;
cout<<"Enterv the size of array: "<<size;
int *arr=new int [size];
for(int i=0; i<size; i++)
{
cout<<"Value No. "<<i+1<<" : ";
cin>>arr[i];
}
int max = maxfunc(arr,size);
cout<<"max = "<<max;
}
int maxfunc(int myArr, int size)
{
int largest=myArr[0];
for(int i=1; i<size; i++)
{
if(largest<myArr[i])
{
largest=myArr[i];
}
}
return largest;
}

In
int maxfunc(int myArr, int size)
The argument int myArr is an integer but you are using it as an array of integers.
I would use a pointer to the original array:
int maxfunc(int *myArr, int size)
Another problem that stands out is that you are using size variable uninitalized, my gess is that you are missing a cin >> size;:
cout<<"Enterv the size of array: ";
cin >> size;
Finally, and this is opinion based, this is the kind of program you would use in C, for C++ there are better tools for storing a manipulating data. For this case I would recommend std::vector or if the array is ment to have fixed size, std::array.

You did not entered the size of the array
int size;
cout<<"Enterv the size of array: "<<size;
int *arr=new int [size];
So the program has undefined behavior.
Also the function implementation is wrong because in general the user can pass the second argument equal to or less than 0.
The function should be declared like
size_t maxfunc( const int myArr[], size_t size);
^^^^^^^^^^^^^^^^^
and it should return the index of the maximum element.
The function can be implemented like
size_t maxfunc( const int myArr[], size_t size )
{
size_t largest = 0;
for ( size_t i = 1; i < size; i++ )
{
if ( myArr[largest] < myArr[i] )
{
largest = i;
}
}
return largest;
}
And in main you can write
size_t max = maxfunc( arr, size );
cout << "max = " << arr[max] << '\n';
delete []arr;
Do not forget to free the allocated memory.
Pay attention to that in C++ there is the standard algorithm std::max_element declared in the header <algorithm> that does the task. It returns iterator that points to the maximum element.

Related

How do i set an array to have custom lenght? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am getting an error when i run this code. The error code is 0xC00000FD and I can't seem to find a fix for what i need. Can someone please help me? Here's the code:
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int n;
int arr[n];
int i;
int sum=0, avg=0;
cout<<"array lengh: ";
cin>>n;
cout<<"Enter "<<n<<" array elements: ";
for(i=0; i<n; i++)
{
cin>>arr[i];
sum = sum + arr[i];
}
cout<<"\nThe array elements are: \n";
for(i=0; i<n; i++)
{
cout<<arr[i]<<" ";
}
cout<<"\n\nSum of all elements is: "<<sum;
avg = sum/10;
cout<<"\nAnd average is: "<<avg;
getch();
return 0;
}
There are two major problems in your code. First, C++ does not have "variable length arrays" (VLAs), although some compilers support them as an extension.
More importantly, even if your compiler does support them, you are attempting to define the size of your arr before you have read the value of n.
To fix these issue you should: (a) use the std::vector container, rather than a plain array; and (b) only declare that after you have read in the value of n.
Here's a 'quick fix':
#include <iostream>
#include <conio.h>
#include <vector> // For the "std::vector" definition
using namespace std;
int main()
{
int n;
// int arr[n]; // Here, the value of "n" is undefined!
int i;
int sum=0, avg=0;
cout<<"array lengh: ";
cin>>n;
std::vector<int> arr(n); // This can now be used 'almost' like a plain array
cout<<"Enter "<<n<<" array elements: ";
for(i=0; i<n; i++)
{
cin>>arr[i];
sum = sum + arr[i];
}
cout<<"\nThe array elements are: \n";
for(i=0; i<n; i++)
{
cout<<arr[i]<<" ";
}
cout<<"\n\nSum of all elements is: "<<sum;
avg = sum/10;
cout<<"\nAnd average is: "<<avg;
getch();
return 0;
}
Standard C++ does not support variable length arrays. std::vector can accomplish what you want. It is also possible to allocate memory of the desired size with new int[size] and use a pointer to reference the data rather than an array. However, this doesn't have any bounds checking, so there is the possibility of memory corruption. And the allocated memory must be explicitly freed with delete[]. So std::vector is my preferred solution.

Unknown typename "vector" and "std" when forming an algorithm [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I am a beginner in C++, in this assignment, I've made a program that sorts the given array in ascending order using the bucket sort algorithm. I have encountered numerous errors regarding the use of the vector library and when expressing the variables used to contain the array.
Is there a simpler implementation of the bucket sort of natural numbers? The examples I found were using bucket sort to sort alphabets decimals...etc which made it confusing for me to understand the basics when applied to positive whole numbers.
#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
//function declaration
void display(int arr[], int size);
int getMax(int arr[], int size);
void bucketSort(int arr[], int size);
using namespace std;
void display(int arr[], int size) {
int i, m;
for(i = 0; i < size; i++) {
cout << m; {
m = arr[i];
}
}
return m;
}
void bucketSort(int arr[], int size) {
//variables
int max, bucket = 10, divider, i, j, k;
//10 buckets
vector B[bucket];
//find max and min
max = getMax(arr, size);
divider = ceil(float(max + 1) / bucket);
//insert element into bucket
for(i = 0; i < size; i++) {
j = floor( arr[i] / divider );
B[j].push_back(arr[i]);
}
//sort elements in the buckets
for(i = 0; i < bucket; i++) {
sort(B[i].begin(), B[i].end());
}
//append back the elements from the buckets
k = 0;
for(i = 0; i < bucket; i++) {
for(j = 0; j < B[i].size(); j++) {
arr[k++] = B[i][j];
}
}
}
int main(void) {
//unsorted elements
int arr[] = {22,45,12,8,10,6,72,81,33,18,50,14};
//size of the array
int n = sizeof(arr)/sizeof(arr[0]);
//output unsorted elements
display(arr, n);
//sort the elements
bucketSort(arr, n);
//display sorted elements
display(arr, n);
return 0;
}
You can't just ask for a vector... you have to tell it, a vector of what?
In your case it looks like you want an array of vectors of ints, so:
vector<int> B[bucket];
Your next problem is that you can't have an array of variable size.
Please refer to your C++ book for more information on all of this stuff.

nested for loop in a function array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am working on a c++ homework assignment for arrays and functions, and this is what I have so far and am not even sure if I am on the right path or not. These are the exact instructions..
Write a program to ask the user to enter a total of N numbers which you will store in main local array of Define N as a constant int and initialize it to 6. You will write the following functions:
FillArray( ) – accepts two inputs: (1) the array. (2) the array size. Returns nothing.
• Prompts the user to enter N elements (N = the array size and the variables you pass should have been defined as a constant int in main( )
• Use a for loop to enter and store the value of each element in the array
#include <iostream>
using namespace std;
int main(){
cout << "Enter 6 numbers for the array:" << endl;
FillArray();
return 0;
}
void FillArray(){
int n;
int array[6] = { 0, 0, 0, 0, 0, 0,};
void fillarray(const int n[], int size);
for (; n > 6; n++)
cin >> array[n];
cout << "Thank you\n";
}
Any suggestions or help would be appreciated.. thank you!
Write a program to ask the user to enter a total of N numbers which
you will store in main local array of Define N as a constant int and
initialize it to 6
int main()
{
const int N = 6;
int a[N];
//...
You will write the following functions: FillArray( ) – accepts two
inputs: (1) the array. (2) the array size.
//...
FillArray( a, N );
//...
void FillArray( int a[], int n )
{
cout << "Enter " << n << " numbers for the array: ";
for ( int i = 0; i < n; i++ )
{
cin >> a[i];
}
}
And the name of the function used in the program shall be declared before its using
void FillArray( int a[], int n );
int main()
{
//...

c++: I want to make a arithmetic progression using array, but it gives me messy code [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
#include<iostream>
using namespace std;
//prototype
void fillArray(int[], int, int);
void printArray(int[], int);
int main()
{
srand(time(0)); // initialize random number generator
const int size = 5, SIZE=10;
int ar1[size], ar2[size],inc;
cout << "Enter the first value and increment for ar1: ";
cin >> ar1[0] >> inc;
cout << "Enter the first value and increment for ar2: ";
cin >> ar2[0] >> inc;
cout << "(1) ar1:\n";
fillArray(ar1, size, inc);
printArray(ar1, size);
system("pause");
return 0;
}
void fillArray(int ar[], int size, int inc)
{
for (int i = 1; i < size; i++)
{
ar[i] = ar[0] + inc;
cout << ar[size];
}
}
void printArray(int ar[], int size)
{
for (int i = 0; i < size; i++) {
cout << ar[i] << ' ';
}
cout << endl;
}
Ask the user to input ar1[0] and inc.the first one ar1[0] is settled by user input, and the rest is increased by inc.So if I enter 4 3 ,it should return 4 7 10 13 16. My outcome is like this:
I know there is something wrong with the function fillArray but I don't know how to fix it. Can anyone tell me the solution? Thanks
Yes there's something wrong with your function fillArray. It assumes that the first element is initialized (which is, indeed) but then doesn't initialize the other elements in ascending order, because you always add inc to the value of the first element. Moreover it prints out ar[size] which is out of bounds at every step (the first strange numbers in your output). You can fix with this:
void fillArray(int ar[], int size, int inc)
{
for (int i = 1; i < size; i++)
{
ar[i] = ar[i-1] + inc;
}
}
Or you can decide to pass the first value as a parameter too.
I assume you wanted to use size, even if you also declare another similar variable named SIZE with a different value. You should also consider using std::vectors instead of arrays as a safer a more practical option.
Finally, in your code you ask the user to input inc twice (overwriting it) before using it.

how to initialize an array without any error? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
My code is following for finding maximum in an array
#include <iostream>
using namespace std;
int main(){
int i;
int array[i]={1,2,3,4,5}
int temp;
for(int i=0;i<6;i++)
{
if(array[i]>temp)
temp=A[i];
}
cout<<"the maximum number is "<<temp<<endl;
return 0;
}
but im getting error in line of initializing array why is that so? how do we initialize array?
You can't define the size of an array with a runtime variable.
To fix this you can use constexpr:
constexpr int i = 5;
int array[i]={1,2,3,4,5};
or:
int array[]={1,2,3,4,5};
In the latter the size is deduced by the compiler.
Otherwise, if you need a runtime size, you'll have to use std::vector or any other "dynamic" container from the standard library:
int i = ...;
std::vector<int> array(i); // reserve `i` cells
try this :
int array[]={1,2,3,4,5};
First of all variable i was not initialized
int i;
So it has some arbitrary value.
Secondly the size of a defined array shall be a constant exprssion. So even if i would be initialized this definition
int array[i]={1,2,3,4,5}
is also invalid. Moreover you forgot to place a semicolon after the closing brace.
Also you did not initialized variable temp
int temp;
And at last this control statement of the loop
for(int i=0;i<6;i++)
is also incorrect because the array has only 5 elements.
And one more identifier A was not declared
temp=A[i];
The correct code could look as
#include <iostream>
using namespace std;
int main()
{
const int N = 5;
int array[N] = { 1, 2, 3, 4, 5 };
int max = array[0];
for ( int i = 1; i < N; i++ )
{
if ( max < array[i] ) max = array[i];
}
cout << "the maximum number is " << max << endl;
return 0;
}