0

Plz help me why this code isn't printing the right values in 2nd loop

#include <iostream> using namespace std; int main() { int digits[3]; cout<<"enter 4 values: "; for(int i =0;i<=3;i++) { cin>>digits[i]; cout<<digits[i]<<endl; } for(int i=0;i<=3;i++) { cout<<digits[i]; } return 0; }

29th Mar 2020, 8:14 PM
Teddy
Teddy - avatar
2 Respostas
+ 1
You declared array of size 3. So you can store maximum 3 values in array index starting from 0 to 2. (0,1,2) If you access anything beyond this you get garbage values in c++. So either change size as int digits[4]; Or access from 0 to 2 only( i<3; //not i<=3)
29th Mar 2020, 8:18 PM
Jayakrishna 🇮🇳
+ 1
Oh thanks😂😂 ...i just came back to c++ from vb.net and got confused.. Thanks again
29th Mar 2020, 8:21 PM
Teddy
Teddy - avatar