219 views
5 5 votes

What is the output of the following code?

#include <stdio.h>

int add(int n) {
    static int total = 1;

    total = total + n;

    return total;
}

int main() {
    int i, ans = 0;

    for (i = 1; i <= 3; i++) {
        ans = add(i);
    }

    printf("%d", ans);

    return 0;
}

3 Answers

1 1 vote

 

Here, $\texttt{total}$ is a static local variable.

A static local variable is initialized only once and keeps its value between function calls.

Initially, $\texttt{total = 1}$.

For $\texttt{i = 1}$, function call is $\texttt{add(1)}$.

So, $\texttt{total = 1 + 1 = 2}$ and $\texttt{ans = 2}$.

For $\texttt{i = 2}$, function call is $\texttt{add(2)}$.

Now $\texttt{total}$ starts from old value $\texttt{2}$.

So, $\texttt{total = 2 + 2 = 4}$ and $\texttt{ans = 4}$.

For $\texttt{i = 3}$, function call is $\texttt{add(3)}$.

Now $\texttt{total}$ starts from old value $\texttt{4}$.

So, $\texttt{total = 4 + 3 = 7}$ and $\texttt{ans = 7}$.

Therefore, the output is $\texttt{7}$.

• edited by
Answer:
Position:
Show:

Related questions

7 7 votes
2 2 answers
218
218 views
GO Classes asked Jun 11
218 views
What is the output of the following code?#include <stdio.h int x = 10; int main() { int x = 20; { extern int x; printf("%d", x); } return 0; }$\texttt{10}$ $\texttt{20}$ ...
8 8 votes
2 2 answers
240
240 views
GO Classes asked Jun 11
240 views
Given the following two files, what will happen when they are compiled and linked together?file1.c#include <stdio.h static void show() { printf("Hello"); }main.cvoid show...
7 7 votes
2 2 answers
266
266 views
GO Classes asked Jun 9
266 views
What is the output of the following code?#include <stdio.h void fun() { static int x = 1; x = x + 2; printf("%d ", x); } int main() { fun(); fun(); fun(); return 0; }$\te...
7 7 votes
2 2 answers
226
226 views
GO Classes asked Jun 11
226 views
What is the output of the following code?#include <stdio.h int x; int x; int main() { printf("%d", x); return 0; }$\texttt{0}$ Garbage value Compilation error Linker erro...