When I tried to run the code I was getting the 2nd output as garbage value. Can anyone tell fault in that code

#include <iostream> using namespace std; int main() { int T,i,j,N,K; cin >> T; int n[T],x; for(i=1; i<=T; i++) { cin >> N >> K; for(int j=1; j<=N; j++) { cin >> x; n[i]+=x/K; x=0; }N=0;K=0; } for(i=1; i<=T; i++) cout << n[i] << endl; return 0; }

question is "Your program will be tested on one or more test cases.The first line of the input will be a single integer T, the number of test cases (1 ≤ T ≤ 100). Followed by the test cases, each test case is on two lines. The first line of each test case contains two integers N, the number of different candies (1 ≤ N ≤ 100), and K, the minimum number of candies which will make a kid happy as described above (1 ≤ K ≤ 100). The second line of each test case contains N integers, separated by a single space, which are the available number of candies of each type. There will be at least 1 candy and at most 100 candies of each type."

sample input: 2 3 2 4 5 7 3 8 4 5 7 sample output: 7 0 when the i tried the above code the answer that i got like: input:2 3 2 5 6 8 2 2 9 1 output: 9 -880625041

When i tried to run the code i was getting the 2nd output as garbage value. Can anyone tell me the fault in that code


Here is the problem:


this is equivalent to n[i]=n[i]+x/K; So it uses a prior value of n[i]. However, you haven't set any prior value to elements of the array n. So, initialise the array to 0 first.

n[i] = 0;

Also, in this code:

for(int j=1; j<=N; j++)

are you sure that N will always be less than T, the size of array? (take care of 0-based indexing as well).

  1. Arrays in C and C++ are zero-based. Run your loops from 0 to N - 1 and T - 1.
  2. You don't initialise your array values before using them. Formally your program behaviour is undefined. (I think you mean n[i]= rather than n[i]+=.)
  3. Variable length arrays like int n[T] are compiler extensions. Do bear this in mind as it could affect portability.
Category:c# Time:2018-12-27 Views:6

Related post

Copyright (C) pcaskme.com, All Rights Reserved.

processed in 0.745 (s). 13 q(s)