## Microsoft Interview Question for Software Engineer / Developers

• 0

Comment hidden because of low score. Click to expand.
0
of 0 vote

double computeAverage(double newVal) {
static int count=0;
static float average=0;
average = (average * count + newVal)/++count;
return average;
}

Every time the average is computed from the previous average and count. count is the number of values seen so far. Since we need the average and count to persist between function calls, we can declare them static.

Comment hidden because of low score. Click to expand.
0

This is correct logically but for the initialization steps.
You are reinitializing the static sount and average to zero which makes you lose the previous values.

So you need to remove " =0 " in the first 2 lines

Comment hidden because of low score. Click to expand.
0

shruti don't you think making them static avoids reinitialization ! ?

Comment hidden because of low score. Click to expand.
0
of 0 vote

Instead of static average, use static sum. If I'm not mistaken, the idea is to accumulate the numbers and then return the average.

double computeAverage(double newVal)
{
static int count=1;
static double sum=0;
sum+=newVal;
return sum/count++;
}

I believe a float allows a smaller mantissa so you may have a buffer overflow sooner.

Comment hidden because of low score. Click to expand.
0
of 0 vote

(previous average* previous number+new number)/(previous number+1)

Comment hidden because of low score. Click to expand.
0
of 0 vote

use static average and calculate the next average = (average + newVal)/2.0;

Comment hidden because of low score. Click to expand.
0

anon,

you are wrong Consider[1,2,3]
Actual avg -> 2
(1+2)/2 = 1.5
(1.5 + 3)/2 = 2.25 (WRONG!!!!!!)

Comment hidden because of low score. Click to expand.
0
of 0 vote

Look at this table:

Total nos seen Num Avg
1 2 2
2 4 3= prev avg+(4-prev no)/nos seen so far
3 6 4=3+(6-3)/3

Got it!!!

Comment hidden because of low score. Click to expand.
0
of 0 vote

in C++ this worked for me
double computeAverage(double newVal){
static int cnt;
double avg=newVal/++cnt;
return avg;
}

Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

### Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

### Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.