Reputation: 23
I am new to C++. Below is a program for converting integer into array. However the value of the array do not change from the initialized value.
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
int n,i=0;
cin >> n;
int arr[100]={0};
while(n){
arr[i]=n%10;
i++;
n=n/10;
cout<<arr[i];
}
return 0;
}
The value of arr[i]
printed is 0
. I do not understand what is the error. Can someone please tell what exactly is the error.
Upvotes: 0
Views: 270
Reputation: 54
While this is not the cause of the bug, please note that the statement:
int arr[100]={0};
This statement only initializes the first value of the array.
If you initialize it with something other than zero, and dump the contents of the array before the loop, you will see that only the first value (eg. a[0]) is modified.
Depending on the platform you run on, some systems do not initialize memory to zero, and the results of your application will be unstable.
Upvotes: 0
Reputation:
You're incrementing the value of i too soon. It should be at the end of the while-loop. Otherwise you're printing the next integer, which is always zero. When you're dealing with iteration, it is almost always better to use a for-loop.
Upvotes: 0