SUMMER TRAINING Free Tutorials  Go To Your University  Placement Preparation 
Project Based Best Summer Training Courses in Jaipur
Join our Telegram Channel To take free Online Courses

1 Answer

0 like 0 dislike
by Goeduhub's Expert (7.1k points)
edited by
 
Best answer

Static Variable in C

Static variables in a program preserve there value even if program goes out of scope unlike local and global variable. For example a static variable can be used to count how many times a function is called in a program.

Static variables can not be assigned variable values they can be assigned only constant values.

A static variable is declared using static keyword.

Syntax :

static data_type variable_name = value;

Static variables are assigned memory in data memory instead of stack segment.

Example :

#include<stdio.h>
#include<conio.h>

//fun() function containing static variable count
int fun()
{

//Declaration of static variable count
static int count=0;
count++;
return count;
}
void main()
{
clrscr();
printf("\nCall to fun() %d times",fun());
printf("\nCall to fun() %d times",fun());
printf("\nCall to fun() %d times",fun());
getch();
}

Output :

Global Variable

The variables declared outside any function are called global variables. They are not limited to any function. Any function can access and modify global variables. Global variables are automatically initialized to 0 at the time of declaration.

Global variables are generally declared after header files so that they can be used be every function in the program.

Example :

#include<stdio.h>
#include<conio.h>

//Declaration of global variable
int count;

//Declaration of recursion variable
long int recursion(int n);
void main()
{
int n;
clrscr();
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, recursion(n));

//Printing value of global variable count
printf("\nRecursion function called %d time to calculate factorial",count);
getch();
}

long int recursion(int n)
{

//Increment in count
count++;
if (n>=1)
return n*recursion(n-1);
else
return 1;
}

Output :

Output of above program showing factorial of a number


For More GTU C Programming Lab Experiments Click Here

Our Mentors(For AI-ML)


Sharda Godara Chaudhary

Mrs. Sharda Godara Chaudhary

An alumna of MNIT-Jaipur and ACCENTURE, Pune

NISHA (IIT BHU)

Ms. Nisha

An alumna of IIT-BHU

Related questions

 Goeduhub:

About Us | Contact Us || Terms & Conditions | Privacy Policy || Youtube Channel || Telegram Channel © goeduhub.com Social::   |  | 
...