Madhurya Krishnan
Madhurya Krishnan

Reputation: 53

Not getting the actual output for the following code:

import java.util.*;
public class Main {

       Scanner input = new Scanner (System.in);
       int n = 0, tn = 0, time = 0;int sum=0;
       int t = input.nextInt(); //no. of test cases
       for (int i =0; i<t; i++)
       {  
          n = input.nextInt();//no. of timings           
          for (int j = 0; j<n; j++)
           {   
               tn = input.nextInt(); //individual time

               sum=0;
               sum+=tn;
               sum*=2;
           }
          System.out.println(t+". "+sum);
        }

    }
}

My output

output I am supposed to get

Can anyone tell me where I went wrong?

Upvotes: 0

Views: 44

Answers (1)

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

1.) You are setting every time sum=0 while taking new input so you are losing the previous values hence last time

sum=30
sum= 30*2 = 60

so reset the sum=0 when you are done with your first case input

2.) You need to do the multiplication after you add-up all the values so simply do the multiplication when you have the sum of all individual time values

for (int i = 0; i < t; i++) {
    n = input.nextInt();// no. of timings
    for (int j = 0; j < n; j++) {
        tn = input.nextInt(); // individual time
        // add all values first
        sum += tn;
    }
    // multiply the total of values with 2
    System.out.println(i + ". " + (sum * 2));

    // now set sum=0 for next case
    sum = 0;
}

Test case Output :

2
3
10
20
30
2. 120 // output of first case
2
100
50
2. 300 // output of second case

Upvotes: 1

Related Questions