| 1. |
Explain two types of variable according to its scope and life. |
|
Answer» 1. Local scope: A variable declared inside a block can be used only in the block. It cannot be used any other block. eg: #include<iostream> using namespace std; int sum(int n1 ,int n2) { int s; s = n1 + n2; return (s); } int main() { int n1 ,n2; cout<<“Enter 2 numbers cin>>n1>>n2; cout<<“The sum is “<<sum(n1 ,n2); } Here the variable s is declared inside the function sum and has local scope; 2. Global scope: A variable declared outside of all blocks can be used any where in the program. #include<iostream> using namespace std; int s; int sum(int n1,int n2) { s = n1 + n2; return(s); } int main() { int n1 ,n2; cout<<“Enter 2 numbers cin>>n1>>n2; cout<<“The sum is “<<sum(n1 ,n2); } Here the variable s is declared out side of all functions and we can use variable s any where in the program. |
|