here is code for counting sorting
#include <iostream>
using namespace std;
int main(){
int a[]={2,3,1,2,3};
int n=sizeof(int)/sizeof(int);
int max=a[0];
for (int i=1;i<n;i++) {
if (a[i]>max) {
max=a[i];
}
}
int *output=new int[n];
for (int i=0;i<n;i++) {
output[i]=0;
}
int *temp=new int[max+1];
for (int i=0;i<max+1;i++) {
temp[i]=0;
}
for (int i=0;i<n;i++){
temp[a[i]]=temp[a[i]]+1;
}
for (int i=1;i<max+1;i++) {
temp[i]=temp[i]+temp[i-1];
}
for (int i=n-1;i>=0;i--) {
output[temp[a[i]]-1]=a[i];
temp[a[i]]=temp[a[i]]-1;
}
for (int i=0;i<n;i++) {
cout<<output[i]<<" ";
}
return 0;
}
but output is just 2,only one number. what is wrong i can't understand please guys help me
int n=sizeof(int)/sizeof(int);
is wrong. That just assigns 1 to n.
You mean
int n=sizeof(a)/sizeof(int);
I've not looked beyond this. No doubt there are more problems, but this is the most significant.
This is the kind of thing you can work out very easily with a debugger.
Look at this expression:
int n=sizeof(int)/sizeof(int);
What do you think the value of n is after this? (1)
Is that the appropriate value? (no, the value should be 5)
Does that explain the output you are seeing? (yes, that explains why only one number is shown)
My advice would be that if you're going to do this in C++, you actually try to use what's available in C++ to do it. I'd look up std::max_element to find the largest element in the input, and use an std::vector instead of messing with dynamic allocation directly.
When you want the number of elements in an array in C++, you might consider a function template something like this:
template <class T, size_t N>
size_t num_elements(T const (&x)[N]) {
return N;
}
Instead of dumping everything into main, I'd also write the counting sort as a separate function (or, better, a function template, but I'll leave that alone for now).
// warning: Untested code:
void counting_sort(int *input, size_t num_elements) {
size_t max = *std::max_element(input, input+num_elements);
// allocate space for the counts.
// automatically initializes contents to 0
std::vector<size_t> counts(max+1);
// do the counting sort itself.
for (int i=0; i<num_elements; i++)
++counts[input[i]];
// write out the result.
for (int i=0; i<counts.size(); i++)
// also consider `std::fill_n` here.
for (int j=0; j<counts[i]; j++)
std::cout << i << "\t";
}
int main() {
int a[]={2,3,1,2,3};
counting_sort(a, num_elements(a));
return 0;
}
Related
I am trying to fill an array with different integers, but it doesn't work as expected.
#include <iostream>
using namespace std;
int main(){
int i=0;
int num;
int MyArray[]={};
while (true) {
cout<<"sayi giriniz"<<endl;
cin>>num;
MyArray[i]=num;
i++;
for (int j=0; j<i; j++) {
cout<<MyArray[j]<<endl;
}
}
return 0;
}
https://imgur.com/a/tANGpSY
When I enter the 3rd value it gives an unexpected result.
int MyArray[]={};
Now, MyArray has a size of 0, so any indexes that you tried to access MyArray will cause undefined behavior.
If you want to make an array that is dynamically in size, use std::vector in the <vector> header.
Change
int MyArray[]={};
to
std::vector<int> MyArray;
This:
MyArray[i]=num;
i++;
To this:
MyArray.push_back(num); // you don't even need i
This
for (int j=0; j<i; j++) {
cout<<MyArray[j]<<endl;
}
To this:
for(const auto &i : MyArray) // range based for loop, recommend
{
std::cout << i << '\n';
}
Also, using namespace std; is bad, so don't use it.
If you want to take input and are unsure about the number of elements, you should use a vector. The array which you have made is of 0 size. It will surely give you an error.
How I will pass a 2D array in a function. I take input from keyboard but when I pass it into function it doesn't work.
for example
#include<bits/stdc++.h>
using namespace std;
void printGrid(int M, int N, int arr[][N])
{
for(int i=0; i<M; i++)
{
for(int j=0; j<N; j++)
{
printf("%d ",arr[i][j]);
}
printf("\n");
}
}
int main()
{
int M,N;
scanf("%d %d",&M,&N);
int arr[M][N];
printGrid(M,N,arr);
return 0;
}
This solution doesn't work. It says N was undeclared on this scope.
Is there any way to work with 2D array in Function ?
You are compiling your code the wrong way. int arr[][N] is a variable-length array (VLA). This is a feature that was introduced in the C language in the year 1999. If you use a compiler which is older than that, or if you use a C++ compiler, you will get the error described.
Make sure to compile your code with a standard-compliant C compiler! You need to use a compiler which supports the C99 standard or later. For example you could use the GCC compiler version 5.x. Or if you use an older version of that compiler, set the compiler option gcc -std=c99.
Why don't you try something like this:
#include <iostream>
#include <vector>
using namespace std;
void print(const vector<vector<int>>& arr) {
for(auto& subArr : arr) {
for(auto& element : subArr) {
cout << element << ' ';
}
cout << '\n';
}
}
int main() {
int M,N;
cin >> M >> N;
vector<vector<int>> arr(M, vector<int>(N));
print(arr);
}
This piece of code doesn't do much - it just initializes the 2D array to zeroes and prints it - but that's not the point. It shows some techniques that you should use if you're coding using modern C++. Besides it solves your problem of printing a 2D array in this case implemented as a vector of vectors.
I would recommend reading about std::vector: cppreference.com - std::vector
Solution of my Problem...
Thanks for you guys response..
#include<stdio.h>
#define MAX 500
int arr[MAX][MAX];
void printGrid(int M, int N)
{
for(int i=0; i<M; i++)
{
for(int j=0; j<N; j++)
{
printf("%d ",arr[i][j]);
}
printf("\n");
}
}
int main()
{
int M,N;
scanf("%d %d",&M,&N);
printGrid(M,N);
return 0;
}
this code work the limitation you give for the array
My compiler keeps saying that 'small' and 'x' were not declared in this scope, how do I fix my array so that they are accurately displayed? overall the code is supposed to find the smallest positive nonzero value stored in the array.
#include <iostream>
#include <string>
using namespace std;
int findthesmall( int small[x], int y)
{
for(int i=0; i< y; i++){
for(int j=0; j< y; j++){
int temp = small[i];
if( small[i] > small[j] )
small[i] = small[j];
small[j] = temp;
}
}
return small[0];
}
int main(){
return 0;
}
I think you need:
int findthesmall( int* small, int y) {
Try this:
int findthesmall( int small[], int y) {
for(int i=0; i< y; i++){
for(int j=0; j< y; j++){
int temp = small[i];
if( small[i] > small[j] )
small[i] = small[j];
small[j] = temp;
}
}
return small[0];
}
int main(){
return 0;
}
int small[x]
This is illegal for 2 reasons.
Like your compiler says, X is undefined
Size of the array cannot be set to the value of a non compile time constant.
To fix this you can do what #ajon suggested( pass array as pointer + length), it is historically the way to pass arrays.
There are other better ways in C++ though.
You can consider using std::array or std::vector. Both of them can be passed as you would any other variable, know their own size, and can be accessed like a normal array
Or you could use template code to capture the size of the array automatically.
template<int len>
int findthesmall(int (&small)[len]){
The 2nd option maybe a little convoluted and more complex than other options, especially now that you have got your answer, I'm just including it here for completeness.
Apart from other answers, there is also a bug in the logic. If your function is just to find the smallest element as function name indicated, one for loop should be enough.
Sample code presented below:
int findthesmall( int small[], int y)
{
int temp = small[0];
for(int i=1; i< y; i++)
{
if( temp > small[i] )
temp = small[i];
}
return temp;
}
Or you could use std::min_element algorithm as well
std::cout << *std::min_element(small, small+y) << std::endl;
I've tried many time to pass the array to a function then do some calculation such as getting the total of the columns, the problem is I don't know how to call the result form the function, usually I get errors.
this is just one code I'm trying to solve it from yesterday :
#include <iostream>
using namespace std;
//prototype
int get_total(int whatever[][2], int row);
int main ()
{
const int row=2;
const int col=3;
int marks[row][col];
// this is prompt the user to input the values
for (int i=0; i<row;i++)
{
for (int p=0; p<col; p++)
{
cin >> marks[i][p];
}
cout << endl;
}
// this is just display what the user input as a table
for (int x=0; x< row ; x++)
{
for (int y=0; y<col ; y++)
{
cout << marks[x][y] << " ";
}
cout << endl;
}
int sum;
// this is the most important thing I want to know,
// how to call the function :(
sum=get_total(marks,row);
return 0;
}
// to get the total of each columns
const int row=3;
// not sure if the declaration is correct or not :(
int get_total(int whatever[][2], int row)
{
for (int i=0; i < 2; i++)
{
for (int p=0; p < 3; p++)
int total=0;
//this line is completly wrong, How can I calculate the total of columns?
total+=get_total[2][p];
}
// do we write return total ?
// I'm not sure because we need the total for each column
return total;
}
sorry for the mess, and I appreciate any help to explain passing the multidimensions arry to a function as parameter and how to call the function>
Arrays decay to pointers when calling functions.
You can do 2 things:
Pass the number of lines and columns as arguments to the function.
Use std::vector instead. I suggest you take a look at it, it'll do the trick and you'll learn something new and very useful.
Also, your function should do this:
int get_total(int** whatever)
{
//total is 0 at the beginning
int total=0;
for (int i=0; i < 2; i++)
{
for (int p=0; p < 3; p++)
//go through each element and add it to the total
total+=whatever[i][p];
}
return total;
}
This will return the total for the whole matrix, I'm assuming that's what you mean by getting the total of the columns
int marks[row][col]
This means that marks has type int[2][3].
int get_total(int whatever[][2], int row);
You've however declared get_total to accept an int(*)[2]. int[2][3] can decay to int(*)[3] but that is not compatible with int(*)[2], hence why you can't pass marks to get_total. You can instead declare get_total to accept an int(*)[3]:
int get_total(int whatever[][3], int row);
// equivalent to:
int get_total(int (*whatever)[3], int row);
If you instead decide to declare get_total to accept an int** or an int*, then you can't legally pass marks to it in the former case, and you can't legally iterate over the whole multidimensional array in the latter. Consider not using arrays, it's simpler this way.
Like the question says, I am trying to pass multi-dimensional arrays into a function to print it to a file for an engineering project. The format for which the data is inputted CANNOT be changed, so please don't suggest I just input it as a different datatype.
This particular function anticipates a two-dimensional array (although I have others with three dimensions after this one), where nothing is known about the size of the array until run-time. I know I must use pointers to point to each row of the array separately, but I have NO idea what the syntax is for passing it to the function. In the following code, the array in question is 'block'. The main function is just a little testing example I made to try to make it work:
#include<fstream>
using namespace std;
void of_write_blocks(string filename, string block_type[], int **block,
int grid[][3], string grade_type[], int grade[][3], int n_blocks, int m[])
{
ofstream file_out(filename.c_str(),ios::app);
file_out<<"\nblocks\n(\n";
for(int i=0;i<n_blocks;++i) {
file_out<<" "<<block_type[i]<<" ( ";
for(int j=0;j<m[i];++j)
file_out<<block[i][j]<<" ";
file_out<<") ( ";
file_out<<grid[i][0]<<' '<<grid[i][1]<<' '<<grid[i][2]<<" ) ";
file_out<<grade_type[i]<<" ( ";
file_out<<grade[i][0]<<' '<<grade[i][1]<<' '<<grade[i][2]<<" )\n";
}
file_out<<");\n";
}
//testing example:
int main()
{
int block[6][9];
for(int i=0; i<6;++i)
for(int j=0; i<9;++j)
block[i][j] = i*j;
int grid[6][3];
for(int i=0; i<6;++i)
for(int j=0; i<3;++j)
block[i][j] = i*j;
int grade[6][3];
for(int i=0; i<6;++i)
for(int j=0; i<3;++j)
block[i][j] = i*j;
string grade_type[6] = {"simpleGrading"};
string block_type[6] = {"hex"};
int m[6] = {8};
int n_blocks = 6;
of_write_blocks("name",block_type,block,grid,grade_type,grade,n_blocks,m);
}
any help is appreciated!
You can't. Multidimensional arrays are syntactic sugar, and are compiled directly into the code that does manipulations on the array, which is a single memory block. The dimensions are not passed into the function as parameters or anything like that as part of the array, as things are done in e.g. Java or C#.
If you need the dimensions of the array in your function, you'll need to just accept a pointer to the first element of the array, and the dimensions, and do the multiplies and adds to get the right index yourself.
Alternately, use something like a std::vector<std::vector<block>>, which pass the dimensions as part of the object, rather than a built in array.
If you have Boost installed, check out Boost Multi-Array.
For clarity I removed all the irrelevant code from your example.
#include <iostream>
#include <fstream>
using namespace std;
void of_write_blocks(int **block, int bh, int bw){
for(int i = 0; i < bh; ++i)
for(int j = 0; j < bw; ++j)
cout << block[i][j] << " ";
cout << endl;
}
int main(){
int bh, bw;
cin >> bh >> bw;
int** block;
block = new int*[bh];
for(int k = 0; k < bh; k++)
block[k] = new int[bw];
// initialize the array
for(int i = 0; i < bh; i++)
for(int j = 0; j < bw; j++)
block[i][j] = (i*bw) + j;
of_write_blocks( block, bh, bw);
}
In the main we are creating a 2D array and initializing it. Then we pass it to of_write_block, which prints the array. Is that what you wanted to do?
Why can't use a reference of array. See below example:
char c[10];
int i[10][20];
double d[10][20][30];
Write a wrapper function like this:
template<typename T, int SIZE>
void Array (T (&a)[SIZE])
{}
template<typename T, int SIZE1, int SIZE2>
void Array (T (&a)[SIZE1][SIZE2])
{}
template<typename T, int SIZE1, int SIZE2, int SIZE3>
void Array (T (&a)[SIZE1][SIZE2][SIZE3])
{}
This is just an example to demonstrate the syntax which will elegantly receive the array without any copying and also avoids confusing pointers. Also, if you are aware that you are going to use only for int then simply remove the typename and explicitly mention int. i.e.
template<int SIZE>
void Array (int (&a)[SIZE]); // explicitly mention int