Answer to Question #271343 in C++ for vinn

Question #271343

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-11-25T07:04:52-0500
#include <iostream>
using namespace std;


int c=0;


void globalVariable();
int localVariable();


int main(){
    for(int i=0; i<10; i++){
        globalVariable();
    }
    for(int j=0; j<5; j++){
        localVariable();
    }
    int local = localVariable();
    cout << "Using global variable count = " << c << endl;
    cout << "Using local variable count = " << local << endl;
    return 0;
}


void globalVariable(){
    c++;
}


int localVariable(){
    static int local = 0;
    local++;
    return local;
}
Local variable cannot be used because it has no global access.

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