0

#include <iostream> using namespace std; int main() { int a[]={3,5,2,1}; for(int i=1;i<5;i++) { a[0]=a[i]+1; } cout<<a[0];

its output is 5...how?? can somebody provide dry run for it??

23rd Dec 2016, 1:46 PM
Sumit Lokhande
Sumit Lokhande - avatar
10 odpowiedzi
+ 1
as i tried some checks for i<2 a[0]=6 for i<3 a[0]=3 for i<4 a[0]=2 for i<5 a[0]=5 upto 4 i got how values come but after 4 i couldn't evaluate it
23rd Dec 2016, 5:24 PM
Sumit Lokhande
Sumit Lokhande - avatar
0
it is can not be 5. when i = 4 it is out of the massive
23rd Dec 2016, 2:29 PM
Maria Milovanova
Maria Milovanova - avatar
0
@maria milovanova run the code and check it
23rd Dec 2016, 3:31 PM
Sumit Lokhande
Sumit Lokhande - avatar
0
I checked it. There is an error
23rd Dec 2016, 3:37 PM
Maria Milovanova
Maria Milovanova - avatar
0
#include <iostream> using namespace std; int main() { int a[]={3,5,2,1}; for(int i=1;i<5;i++) { a[0]=a[i]+1; } cout<<a[0]; return 0; } run this one
23rd Dec 2016, 3:38 PM
Sumit Lokhande
Sumit Lokhande - avatar
0
I know that there should be "return 0". As I said, there is an error in the conditions of the loop. Array starts with 0, the size of this massive is 4. And that is why you can not initialize element a[4], it is more then the arrays size. P.S. sorry for mistakes. I don't know english well
23rd Dec 2016, 3:46 PM
Maria Milovanova
Maria Milovanova - avatar
0
that's the problem in this code. Even though array size is 3 ,how can i goes upto 5??? 😎
23rd Dec 2016, 3:52 PM
Sumit Lokhande
Sumit Lokhande - avatar
0
even if conditions will changed on i<4, it cannot be 5, it should be 2
23rd Dec 2016, 4:01 PM
Maria Milovanova
Maria Milovanova - avatar
0
it is because, when you out of the massive, it adds 1 to num, thet lies beyond the array
24th Dec 2016, 9:43 AM
Maria Milovanova
Maria Milovanova - avatar
0
actually the on mobile app this code produces answer as 5 but on pc it produces the garbage values. 😂
29th Dec 2016, 1:24 PM
Sumit Lokhande
Sumit Lokhande - avatar