Static Counter Demo

Static Counter Demo

Easy C Variables 21 views
Explanation Complexity

Problem Statement

Create a function that counts the number of times it has been called on each call. Implement it using a static variable. Call main 10 times and display the count.

Input Format

A number n representing how many times the function is called.
(Here n = 10, hard-coded or assumed)

Output Format

The call count printed on each function call.

Example

10
1
2
3
4
5
6
7
8
9
10

Constraints

• n > 0

• Static variable used inside function

• Same function called multiple times

Concept Explanation

The function uses a static variable.
A static variable is created only once and keeps its value between calls.

Step-by-Step Explanation

1.Read value n.

2.Create a function countCalls().

3.Inside the function, declare static int count = 0.

4.On every call, increase count by 1 and print it.

5.In main(), call countCalls() exactly n times.

Concept Explanation

The function uses a static variable.
A static variable is created only once and keeps its value between calls.

Step-by-Step Explanation

1.Read value n.

2.Create a function countCalls().

3.Inside the function, declare static int count = 0.

4.On every call, increase count by 1 and print it.

5.In main(), call countCalls() exactly n times.

Input / Output Format

Input Format
A number n representing how many times the function is called.
(Here n = 10, hard-coded or assumed)
Output Format
The call count printed on each function call.
Constraints
• n > 0

• Static variable used inside function

• Same function called multiple times

Examples

Input:
10
Output:
1 2 3 4 5 6 7 8 9 10

Example Solution (Public)

C
#include <stdio.h>

void callCounter() {
    static int count = 0;   // static variable
    count++;
    printf("Function called %d timesn", count);
}

int main() {
    int i;

    for (i = 1; i <= 10; i++) {
        callCounter();
    }

    return 0;
}

Official Solution Code

#include <stdio.h>

void callCounter() {
    static int count = 0;   // static variable
    count++;
    printf("Function called %d timesn", count);
}

int main() {
    int i;

    for (i = 1; i <= 10; i++) {
        callCounter();
    }

    return 0;
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.