Digital Sorting or C++ VS Pascal

Hello, everybody! Can anyone write how to realize this code in C++;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int d[-100..100]={0...0};

read(n);

for i=1..n{
  read(x);
  d[x]=d[x]+1;
}

for x=-100..100{
  for i=1..d[x]{
    write(x, ' ');
  }
}


MY C++ code, but it does not work:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ifstream fin("input.txt");
    ofstream fout("output.txt");
    int d[200];
    for(int i=-100; i<101; i++) d[i]=0;
    int n, t, i=0;
    fin>>n;
    while(i<n){fin>>t; d[t]++; i++;}
    for(t=-100; t<101; t++)
     for(i=0; i<d[t]; i++) fout<<t<<" ";
    
}
Last edited on
You need to adjust your logical array index to conform to the actual 0-199 range:

 
for(int i=-100; i<100; i++) d[i + 100]=0;


The same applies elsewhere.
This should work:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <fstream>
using namespace std;

int main(){
    ifstream fin("input.txt");
    ofstream fout("output.txt");

    int d[200] = {0}; //this sets every element of your array to 0
    
    int n, x, i;
    fin>>n;

    for(i = 0; i < n; i++){//your code here was fine, but for loop here is more appropriate
        fin>>x;
        d[x]++;//note that user will have to enter integer in range [0; 200)
        //if you want to expect range [-100; 100) write d[x+100]++;
    }

    for(x = 0; x < 200; x++)//note that in c++ arrays always start from 0.
        for(i = 0; i < d[x]; i++)
            fout<<x<<' ';//you may want to make this <<x-100 instead..

    return 0;//int main() must return an integer
}
Thanks a lot!!!
Isn't -100..100 201 elements?
Last edited on
Topic archived. No new replies allowed.