In this post we are discussing about Explain with example how the count variable is introduced in the program to find the number of steps required by a program to solve the problems
we introduce a new variable count to the program which is initialized to zero. We also introduce statements to increment count by an appropriate amount into the program. So when each time original program executes, the count also incremented by the step count.
Consider the algorithm sum( ). After the introduction of the count the program will be as follows.
float Sum (float a [J , int n)
{
float s = 0.0;
count++; // count is global
for (int i=l; i<=n ; i++) {
count++; // For 'for'
s += a[i] ;
count++; // For assignment
}
count++; // For last time of C for'
count++; // For the return
return s;
}
From the above we can estimate that invocation of sum( ) executes total number of 2n+3 steps.
how the count
variable is used in the program:
float Sum(float a[], int n)
is a function that takes an arraya
and an integern
as its parameters and returns a float. Its purpose is to calculate the sum of elements in the array.- Inside the function, a local variable
s
of type float is declared and initialized to 0.0. This initialization doesn’t count as a step, so it’s not incremented incount
. count++
is used immediately after the declaration ofs
. This is done to increment thecount
variable to account for the operation of initializings
. This is a common practice when analyzing the time complexity of algorithms to count basic operations.- Next, there is a
for
loop that iterates fromi
equals 1 ton
, inclusive. a.count++
is incremented at the beginning of thefor
loop to count the operation of entering the loop. b. Inside the loop, there’s an addition operations += a[i]
, which calculates the sum of the elements in the array.count++
is incremented to count this addition operation. c. After the addition operation,count++
is again incremented to count the assignment operation associated with updating the value ofs
. - After the
for
loop, there is one morecount++
operation to account for the operation that occurs after the loop exits. - Finally, there is one more
count++
operation to account for thereturn s
statement at the end of the function.