to binary ecc

#include<bits/stdc++.h>

using namespace std;

void fun(int x ){
int a[10000];
int cont=0;
if(x==0){
cout<<0;
}
else {
int cnt=0;
for(int i=0; x>0; i++){
a[i]=x%2;
cnt++;
x=x/2;

}
for(int i=cnt-1; i>=0; i--){

if(a[i]==1){
cont++;
}

}
cout<<','<<cont;
}


}

int main(){
int x;
cin>>x;

int arr[x];
for(int i=0; i<=x; i++){
arr[i]=i;
fun(i);
}
}
to binary ecc



Last edited on
> #include<bits/stdc++.h>

There is no such standard C++ header.
These are the standard libray headers: https://en.cppreference.com/w/cpp/header

To use the standard stream objects, #include <iostream>
Also:
1
2
3
4
5
int main(){
    int x;
    cin>>x;

    int arr[x];

That's not C++. It's using C99 extensions, and those have leaked into your C++ compiler.

And:
1
2
void fun(int x ){
    int a[10000];

That's not great either, allocating 10,000 elements of 4 or 8 bytes on the stack.

A better alternative for both is to use a vector, which allocates memory off the heap.
1
2
3
4
5
int main(){
    std::size_t x;
    cin>>x;

    std::vector<int> arr(x, 0);

And:
1
2
void fun(int x ){
    std::vector<int> a(10000, 0);
Last edited on
Possibly:

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
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <vector>

using namespace std;

void fun(size_t x) {
	vector<int> a;

	if (x == 0)
		cout << 0;
	else {
		for (size_t i = 0; x > 0; ++i, x /= 2)
			a.push_back(x % 2);

		size_t cont{};

		for (const auto& b : a)
			cont += b == 1;

		cout << ", " << cont;
	}
}

int main() {
	size_t x {};
	cin >> x;

	vector<int> arr(x);

	for (size_t i = 0; i < x; ++i) {
		arr[i] = i;
		fun(i);
	}
}

Topic archived. No new replies allowed.