What will be the output of following program int incr (int i) { static int count = 0;
count = count i; return (count); } main ({intij; for (i = 0; i <=4i--)j-incr(i); }
Answers
REQUIRED OUTPUT :
1
2
3
:) STAY HAPPY AND SAFE
Answer:
On successful execution of the given program, the output will be
Static Variables:
- Static is a storage class in C++
- The keyword static is used to declare a variable as static.
- When a variable is declared as static, it is initialized only once in the entire program.
- If the value of the variable is altered further in the program, then that value is retained in the next iteration.
- The compiler persists the variable till the end of the program.
incr function:
- The incr function declared at the beginning of the code returns the value of the count variable whenever it is called in the main function.
- The return data type of this function is an integer.
- The incr function includes a variable called count of the integer data type having storage class as static.
- When the incr function is called, it increments the value of count by the value of variable i from the main function, and returns the incremented value of count to the calling function.
Main function:
- The main function consists of two variables i and j, of integer data type.
- In the next line, for loop is declared to perform five iterations with the value of variable i going from zero to four.
- The for loop calls the incr function and assigns the value returned from the incr function to the variable j.
Explanation:
Step 1:
When the incr function is called in the first iteration , the value of count will be zero.
This value is returned to the main function and assigned to j.
So, after first iteration and
Step 2:
When the incr function is called in the second iteration , the value of count will become one, i.e.,
This value is returned to the main function and assigned to j.
So, after the second iteration and
Step 3:
When the incr function is called in the third iteration , the value of count will become 3, i.e.,
This value is returned to the main function and assigned to j.
So, after the third iteration and
Step 4:
When the incr function is called in the fourth iteration , the value of count will become 6, i.e.,
This value is returned to the main function and assigned to j.
So, after the fourth iteration and
Step 5:
When the incr function is called in the fifth iteration , the value of count will become 10, i.e.,
This value is returned to the main function and assigned to j.
So, after the fifth iteration and
Therefore, the output of the program will be
#SPJ3