0

Why the output is coming as zero?

#include <iostream> using namespace std; int main() { int const N= 5; int arr[N]={1,7}; int prod=1; for(int i=0;i<5;i++){ prod*=arr[i]; } cout<<prod; return 0; }

14th Apr 2018, 5:42 PM
Khushboo Gupta
Khushboo Gupta - avatar
6 Answers
0
I had a mistake in my answer. If you initialization an array this way all under values get set to 0. int arr[5] = {1, 7} -> 1 7 0 0 0 int arr[5]; -> 5x garbage value. So the answer to you question: prod = 1 * 1 * 7 * 0 * 0 * 0 The first 1 is the initial value.
14th Apr 2018, 7:30 PM
Alex
Alex - avatar
0
Here are your mistakes: 1st: Array indexes start with 0. You loop starts with 1. You need to change int i=1 to int i=0 [forget #2. It's wrong. See my other answer] [2nd: You just assign 2 values to the array and then put the unassigned values into your calculation. You should never use unassigned values. In this case there are 3 garbage values and one of them is a zero.] You can easily debug such a code with putting a cout << arr[i] << endl inside the for loop. That would've made the mistakes clearer.
14th Apr 2018, 6:21 PM
Alex
Alex - avatar
0
but it's a challenge round ques and there we can't change the code and check, so is this code wrong acc to you? PS. 'i' has initial value 0 only, I by mistake made it 1 .
14th Apr 2018, 7:09 PM
Khushboo Gupta
Khushboo Gupta - avatar
0
Oh okay ,but dis is working in C++ only ,as I have written parallel code for C and then it's giving me garbage value for unassigned values of an array
14th Apr 2018, 7:54 PM
Khushboo Gupta
Khushboo Gupta - avatar
0
thanks a lot 😊
15th Apr 2018, 6:09 AM
Khushboo Gupta
Khushboo Gupta - avatar