0

can we assign value 0 in index x in array

I am trying to assign 0 at x place in array but if I write a[x]=0; then, it will take the value 0 at every index and I want to give 0 at only x th index( since x is Dynamics), if you know how to write it, please let me know

5th Feb 2020, 4:37 AM
vishal shivhare
11 Respostas
+ 2
array[x] = 0; should only assign zero to the element having <x> as index, except you use <x> in a loop counter. But what did you mean by "x is dynamic"? I suggest to share your code link in Description to be clear 👍
5th Feb 2020, 4:55 AM
Ipang
+ 1
#include <iostream> #include<cmath> using namespace std; int main() { int s; cin>>s; while(s>0) { int temp,n,l,x,t,d,p,i,y; cin>>n; p =ceil(log2(n+1)); x=p; if(p=1){ x=p+1;} else if (p%2!=0){ x=p+1;} bool arr[x]; bool ar[x]; temp=n,i=0; while(temp>1) {arr[i]=temp%2; temp=temp/2; i++; } arr[i]=1; if(p%2!=0) ar[p+1]=0; for(l=0;l<=x;l=l+2) { t=arr[l]; ar[l]=arr[l+1]; ar[l+1]=t; } for(d=0;d<=x;d++) { y=y+(pow(2,d)*ar[d]); } cout<<y<<endl; y=0; s--; }return 0; }
5th Feb 2020, 4:58 AM
vishal shivhare
+ 1
I posted a picture of elaborated question, can you please check that
5th Feb 2020, 5:05 AM
vishal shivhare
+ 1
vishal shivhare Check the code again bro, and see if this is really what you meant to do, it looks odd to me ... if (p = 1)// p == 1? { x = p + 1; }
5th Feb 2020, 5:26 AM
Ipang
+ 1
Ya bro that is the mistake, thanks for that, but the question I asked remains same ?
5th Feb 2020, 5:29 AM
vishal shivhare
+ 1
Bro arr is storing the bits but in reverse order
5th Feb 2020, 6:03 AM
vishal shivhare
+ 1
Yeah bro, I see that. It seems to be the problem. Because that way, the bits to be swapped are from wrong index. And the way a number is formed by the lines for (d = 0; d <= x; d++) { y = y + (pow(2, d) * ar[d]); } Starts from 0th bit, while actually it was not the 0th bit in the number.
5th Feb 2020, 6:09 AM
Ipang
0
This is the code to swipe the bits of no. Then print the no.( Of changed bits)
5th Feb 2020, 4:59 AM
vishal shivhare
0
Swipe the bits? can you elaborate on that please? this is first time I hear bit swiping. An example might help to understand better 👌
5th Feb 2020, 5:02 AM
Ipang
0
Can you tell me in which part of the code the problem is bro? I am checking the code, but I see the <arr> isn't storing the bits as they should be. I think this is where the problem begins. You should check whether the bits in <arr> are correct. After this is good we can move on to swapping the bits 👍
5th Feb 2020, 5:51 AM
Ipang