Answer to Question #243944 in C++ for ASAD

Question #243944

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-09-29T01:32:45-0400

Using the global variable to store the count

#include<iostream>
using namespace std;


int n = 0 ;
int functionCalled(){
	n++;
	return n;
}


int main(){
int x = 0; 
	for(int i=0; i<10; i++){
		 x = functionCalled();
	}
	cout<<"I have been called "<<x<<"  times";
}

Using a local static variable to store the count

#include<iostream>
using namespace std;




int functionCalled(){
	static int n = 0 ;
	n++;
	return n;
}


int main(){
int x = 0; 
	for(int i=0; i<10; i++){
		 x = functionCalled();
	}
	cout<<"I have been called "<<x<<"  times";
}

Local variables cannot be used because they cannot be accessed outside the function.


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