Answer to Question #171769 in C++ for ADITYA MATHUR

Question #171769

Write a function that, when you call it, displays a message telling how many times it has been called: “I have been called 3 times”, for instance. Write a main()program that calls this function at least 10 times. Try implementing this function in two different ways. First, use a global variable to store the count. Second, use a local static variable. Which is more appropriate? Why can’t you use a local variable.


1
Expert's answer
2021-03-15T12:14:47-0400

Fix typo

#include <iostream>
using namespace std;


int funCalls=0;


void fun1() {
    funCalls++;
    cout << "I am fun1 and I have been called " << funCalls << " times" << endl;
}


void fun2() {
    static int funCalls=0;
    funCalls++;
    cout << "I am fun2 and I have been called " << funCalls << " times" << endl;
}


int main() {
    for (int i=0; i<10; i++)
        fun1();


    cout << endl;
    for (int i=0; i<10; i++)
        fun2();
}
// The second approach is more suitable as nobody can't change the value 
// of the variable count. 
// A local variable can't be used as it "forgot" its value everytime 
// the functon is called.

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS