Unit – II
(second)
Dr. Harjender Singh
Asstt. Professor
Storage Classes and Scope
• Every variable in ‘C’ associated a characteristic
called its storage class.
• Storage Classes defines the scope and life time
of variable declare in a function.
• TYPES OF STORAGES CLASSES:
– Auto ( Automatic ) storage class
– Static storage class
– Extern ( External ) storage class
– Register storage class
S. Storage Keyw Memory Default Value Scope Example
No class ord
specifier
1.
Automatic auto Ram Garbage With in auto int a, b, c;
block
2.
External extern Ram 0 Any where extern float x,
in the y;
program X=20;
3.
Static static Ram 0 With in static int i = 0;
block
4.
Register registe Register garbage With in the register char
r block ch;
AUTOMATIC VARIABLES
• Auto variables have local scope.
• All the variables declared in function are auto, by
default.
• We can declare same variables in different functions
as well.
• It will exists only within the block in which it is
declared
• The auto keyword is optional; there is no need to
write it.
• All the formal arguments have auto scope.
• If not initialized auto variables have garbage value.
• The value is lost after the execution of function
• Syntax of auto storage class
auto Data-type Variable-name OR Data-type Variable-name;
• Example :
#include<stdio.h>
int add();
main()
{
add();
printf("the sum is %d",a+b);
}
add()
{
int a=10,b=20;
printf("Addition is %d",a+b);
}
REGISTER SPECIFIER:
• Normally the variables are stored in the main memory of a
computer, but some program variable whose values are stored in
the CPU registers; such variables are called registers variables.
• These are special storage areas in a computer.
• The scope and lifetime of storage variables are same as that of
auto variables.
• Some of key points are
– These variables are stored in registers. If registers are not available
values are stored in main memory.
– Register variables works faster than other kind of variables because
register memory is faster then main memory.
– Address operator '&' can't be used with these variables.
– Pointer to register variables is not allowed.
– These variables are used for loops to increase efficiency.
– The variables declared using register storage class has no default value.
– These variables are often declared at the beginning of a program.
• Syntax :
– register Data-type Variable-name;
– Example :
• #include<stdio.h>
• main()
• {
• register int a;
• printf("A value is %d\n",a);
• auto int b;
• printf("B value is %d\n",b);
• }
EXTERNAL VARIABLES:
• The extern storage class can do the linking b/w the global
variable in two or more files.
• The scope of external variable is global.
• These variable are declared outside all functions i.e. they
are declared at the beginning of the program.
• Some of the points are :
– The extern keyword is optional, there is no need to write it.
– The scope of external variable is the entire program.
– If not initialized, by default the external variable is assigned a
zero value.
– The value is not lost after the execution of function.
Syntax :
extern Data-type Variable-name;
• // file1.c
• #include<stdio.h>
• #include<conio.h>
• int a;
• extern void fun();
• main()
• {
• a=200;
• fun();
• }
• // file2.c
• #include "file1.c"
• int a;
• void fun()
• {
• printf("The value of a is %d ",a);
• }
• #include<stdio.h>
• #include<conio.h>
• int call1();
• int call2();
• main()
• {
• auto int v=10;
• call2();
• printf("\n v=%d",v);
• }
• call1()
• {
• auto int v=20;
• printf("\n v=%d",v);
• }
• call2()
• {
• auto int v=30;
• call1();
• printf("\n v=%d",v);
• }
• #include<stdio.h>
• #include<conio.h>
• main()
• {
• auto int i=3;
• {
• auto int i=6;
• printf("\n in inner block i=%d \n",i);
• }
• printf("\n in outer block i=%d \n",i);
• }
Static storage class
• The static variables are used within function/ file as static
variables.
• Static variables have the property of preserving their value even
after they are out of their scope.
• So, a static variable preserves its previous value in its previous
scope and is not initialized again in the new scope.
• A static int variable remains in memory while the program is
running. A normal or auto variable is destroyed when a function
call.static variables are accessible only to the particular part of a
code.
• A variable which is declared or initialized using static keyword
always contains zero as a default value.
• in C, static variables can only be initialized using constant literals.
• Eg :
– static int i = initializer(); // invalid syntax
there are two ways in which static keyword works
• The static keyword inside a function.
– Declaration of the variable within a function is associated
with the compile-time and storage duration of the variable
within a function call.
– variables defined as static, extends their scope for multiple
function calls and once declared cannot loose its scope till
the end of the program execution finishes.
• The static keyword outside a function.
– Once the static keyword is declared outside a function it
limits its scope of the variable and becomes visible to the
current file only which means the function will get its scope
limited to its source file itself.
• #include<stdio.h>
• int run();
• int main ()
• {
• run();
• run();
• run();
• }
• run ()
• {
• int a=1;
• static int running = 0;
• printf ("The function \"run\" was called %d times.\n", running);
• printf("the value of a is %d",a);
• a++;
• running++;
• }
• #include<stdio.h>
• //static int sleep= 0;
• static void sleep ()
• {
• static int sleeping = 0;
• ++ sleeping;
• printf ("the function \ “sleep\” was called %d times.\n", sleeping);
• }
• main()
• {
• sleep();
• sleep();
• sleep();
• }
• #include<stdio.h>
• void staticStorageClass()
• {
• int i = 0;
•
• printf("\nDemonstrating static class\n\n");
• printf("\nLoop started:\n");
•
• for (i = 1; i < 5; i++)
• {
• // Declaring the static variable 'y'
• static int y = 5;
• // Declare a non-static variable 'p'
• int p = 10;
• // Incrementing the value of y and p by 1
• y++;
• p++;
•
• // printing value of y at each iteration
• printf("\n The value of 'y', " "declared as static, in %d "
• "iteration is %d\n",i, y);
• // printing value of p at each iteration
• printf("The value of non-static variable 'p', " "in %d iteration is %d\n",
• i, p);
• }
• printf("\nLoop ended:\n");
• printf("--------------------------------");
• }
•
• int main()
• {
• printf("A program to demonstrate" " Storage Classes
in C\n\n");
• // To demonstrate static Storage Class
• staticStorageClass();
• // exiting
• printf("\n\nStorage Classes demonstrated");
• return 0;
• }
• #include<stdio.h>
• int samplefunc()
• {
• static int a;
• a = a+2;
• return a;
• }
• int main()
• {
• int result1 = samplefunc();
• int result2 = samplefunc();
• printf("%d\n", result1);
• printf("%d\n", result2);
• }
• #include <stdio.h> /* function declaration */
• void next();
• static int counter = 7; /* global variable */
• main()
• {
• while(counter<10)
• {
• next();
• counter++;
• }
• return 0;
• }
• void next()
• { /* function definition */
• static int iteration = 13; /* local static variable */
• iteration ++;
• printf("iteration=%d and counter= %d\n", iteration, counter);
• }
ARRAYS
• An array can be defined as an finite ordered set of
homogeneous element of the same data type by a single
variable name.
• These elements may be of int, float, char or double.
• These entire elements are stored in consecutive/sequential
memory location.
• Each element in an array has a different index number which are
sequential number starting from 0 to (n-1) where n is an index
number.
• Each individual array element can be referred by specifying the
array name, followed by a subscript, enclosed in square
brackets.
• An array can be one dimensional, two dimensional or
multidimensional depending upon the subscript used.
• A[10], a[2][3]
ARRAY DECLARATION
• Array must be declared before it appears in the program.
• The general form of declaration of one dimensional array is
• Data – type array – name [size];
• Where
• Data-type indicates the types of values that are to be stored in array.
• Array-name : name of array
• Size: maximum no elements that can be stored in inside the array.
• The array declaration provide the following information to the compiler.
– Name of the array
– Types of elements to be stored in array
– Number of subscript it has
– Array size
• Example :
– int a[10]; 0,1,2,3,4 (n-1) a[0]=101 ------ a[9]=1000
– char name[20];
– float xyz[10];
– double d[100];
• #include<stdio.h>
• void main()
• {
• int array [5];
• int i;
• printf("\nEnter number : "); //Input arrray from user.
• for(i=0;i<5;i++)
• {
•
• scanf("%d",&array [i]);
• }
• for(i=0;i<5;i++)
• printf("%d, ",array [i]); //Output arrray to console.
printf("%d, ",array [i]);
• }
• Initializer List:
• To initialize an array in C with the same value,
the naive way is to provide an initializer list.
We use this with small arrays.
• int num[5] = {1, 1, 1, 1, 1};
• We may also ignore the size of the array:
• int num[ ] = {1, 1, 1, 1, 1}
• // Different ways to initialize two-dimensional
array :
• int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};
• int c[][3] = {{1, 3, 0}, {-1, 5, 9}};
• int c[2][3] = {1, 3, 0, -1, 5, 9};
TWO DIMENSIONAL ARRAY
• It is an ordered set of homogeneous element. It is commonly
known as matrix. It is a combination of rows and columns. Two
dimensional array are identified by two subscript.
• Syntax:
• The syntax of two dimensional array in ‘C’ is
• Data – type array – name [row] [columns] ;
•
• [0,1,2] [0,1,2]
Static int matrix [3] [3] = {1, 1, 1, 2, 2, 2,3,3,3}
• Then the first 6 element of the matrix will be
• Matrix[0] [0] = 1 Matrix[0] [1] = 1 Matrix[0] [2] = 1
• Matrix[1] [0] = 2 Matrix[1] [1] = 2 Matrix[1] [2] = 2
• Matrix[2] [0] = 3 Matrix[2] [1] = 3 Matrix[2] [2] = 3
• // C program to find the sum of two matrices of order 2*2
• #include <stdio.h>
• int main()
• {
• float a[2][2], b[2][2], result[2][2];
• // Taking input using nested for loop
• printf("Enter elements of 1st matrix\n");
• for (int i = 0; i < 2; ++i)
• for (int j = 0; j < 2; ++j)
• {
• printf("Enter a%d%d: ", i + 1, j + 1);
• scanf("%f", &a[i][j]);
• }
• // Taking input using nested for loop
• printf("Enter elements of 2nd matrix\n");
• for (int i = 0; i < 2; ++i)
• for (int j = 0; j < 2; ++j)
• {
• printf("Enter b%d%d: ", i + 1, j + 1);
• scanf("%f", &b[i][j]);
• }
• // adding corresponding elements of two arrays
• for (int i = 0; i < 2; ++i)
• for (int j = 0; j < 2; ++j)
• {
• result[i][j] = a[i][j] + b[i][j];
• }
• // Displaying the sum
• printf("\nSum Of Matrix:");
• for (int i = 0; i < 2; ++i)
• for (int j = 0; j < 2; ++j)
• {
• printf("%.1f\t", result[i][j]);
• if (j == 1)
• printf("\n");
• }
• return 0;
• }
Pointer
• A pointer is a variable that stores the address of another variable. Pointers are powerful tools
that allow direct memory access and manipulation.
• Eg :
– #include<stdio.h>
– main()
– {
– int var = 10;
– int *p;
– p = &var;
– printf("The value of p is %d",*p);
– }
– Note : The memory address of the first element is the same as the name of the array.
– Eg :
– #include<stdio.h>
– main()
– {
– int myNumbers[4] = {25, 50, 75, 100};
– // Get the memory address of the myNumbers array
– printf("%p\n", myNumbers);
– // Get the memory address of the first array element
– printf("%p\n", &myNumbers[0]);
– }
• To access the rest of the elements in array, you can increment the pointer/array (+1,
+2, etc):
• Eg :
• #include<stdio.h>
• main()
• {
• int myNumbers[4] = {25, 50, 75, 100};
• int *ptr = myNumbers;
• // Get the value of the second element in myNumbers
• printf("First Number is : %d\n", *(myNumbers + 1));
• // Get the value of the third element in myNumbers
• printf("Second Number is : %d\n", *(myNumbers + 2));
• // to access all values from array
• printf("The Array's Values are \n : ");
• for (int i = 0; i < 4; i++)
• {
• printf(" Values are : %d\n", *(ptr + i));
• }
•
}
ARRAY OF POINTER
• Array is a collection of values of similar type. It can also be a collection of
references of similar type.
• Syntax
• Data-type * array [size];
• #include<stdio.h>
• void main()
• {
• int x=10,y=20,z=30;
• int *arr[3]; // Declaring array of three pointer
• arr[0] = &x; // Assigning reference of x to array 0th position
• arr[1] = &y; // Assigning reference of y to array 1th position
arr[2] = &z; // Assigning reference of z to array 2nd position
printf("\nValues : ");
• for(int a=0;a<3;a++)
• printf("%d, ",*arr[a]);
• }
int main()
{
// declaring some temp variables
int a[]={10,20,30,40};
// array of pointers to integers
int* p[4];
int i;
printf("output via Pointer : \n");
printf("Addrsss \t Value ");
// traversing using loop
for (int i = 0; i < 4; i++)
{
p[i]=&a[i];
printf("\n %p ",p[i]);
printf("%d ",*p[i]);
}
return 0;
}
ARRAY OF STRUCTURE
• Structure is collection of different data type.
• An object of structure represents a single record in
memory, if we want more than one record of structure
type, we have to create an array of structure or object.
• struct struct-name
• {
• datatype var1; int x,
• datatype var2; float y,
• - - - - - - - - - - char z[20],
• - - - - - - - - - - double p;
• datatype varN;
• }; struct struct-name obj [ 3];
• A[3]
• #include<stdio.h>
• struct Employee
• {
• int Id;
• char Name[25];
• int Age;
• long Salary;
• };
• void main()
• {
• int i;
• struct Employee Emp[ 3 ]; //Statement 1
• for(i=0;i<3;i++)
• {
• printf("\nEnter details of %d Employee",i+1);
• printf("\n\tEnter Employee Id : ");
• scanf("%d",&Emp[i].Id);
• printf("\n\tEnter Employee Name : ");
• scanf("%s",&Emp[i].Name);
• printf("\n\tEnter Employee Age : ");
• scanf("%d",&Emp[i].Age);
• printf("\n\tEnter Employee Salary : ");
• scanf("%ld",&Emp[i].Salary);
• }
• printf("\nDetails of Employees");
• for(i=0;i<3;i++)
• printf("\n%d\t%s\t%d\t%ld",Emp[i].Id,Emp[i].Name,Emp[i].Age,Emp[i].Salary);
• }
STRING:
• A string is a one dimensional array of character.
• For example : “SURAJMAL” is a string of 8
character and stored in computer in this way.
S U R A J M A L
• A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7]
• : char name[10] = {‘F’, ‘A’, ‘M’, ‘E’ ‘\0’};
• Note : The last element is assigned a null character which ends the end of string.
• Reading and Writing the String:
– A string can be read and write using I/O function.
– Reading String: The following function can be used to read the string.
– Scanf() function
– Gets () function
– Getchar () function.
• Writing String: A string or group of string can be written using the following output function.
– Printf () function
– Puts () function
– Putchar () function()
Find the Frequency of Characters
• #include <stdio.h>
• void main()
• {
• char str[1000], ch;
• int i, frequency = 0;
• printf("Enter a string: ");
• gets(str);
• printf("Enter a character to find the frequency: ");
• scanf("%c",&ch);
• for(i = 0; str[i] != '\0'; ++i)
• {
• if(ch == str[i])
• ++frequency;
• }
• printf("Frequency of %c = %d", ch, frequency);
• }
program to sum of elements of array
• #include<stdio.h>
• int main()
• {
• //let's assume the maximum array size as 100.
• //initialize sum as 0. Otherwise, it will take some garbage value.
• int arr[100], size, i, sum = 0;
•
• //Get size input from user
• printf("Enter array size\n");
• scanf("%d",&size);
•
• //Get all elements using for loop and store it in array
• printf("Enter array elements\n");
• for(i = 0; i < size; i++)
• scanf("%d",&arr[i]);
•
• //add all elements to the variable sum.
• for(i = 0; i < size; i++)
• sum = sum + arr[i]; // same as sum += arr[i];
•
• //print the result
• printf("Sum of the array = %d\n",sum);
•
• return 0;
• }
program for sum of odd and even element from array
• #include<stdio.h>
• #include<conio.h>
• void main()
• {
• int num[20];
• int i,esum=0,odsum=0,n;
• printf("enter size of array \n");
• scanf("%d",&n);
• printf("enter elements \n");
• for(i=0;i<n;i++)
• {
• scanf("%d",&num[i]);
• }
• for(i=0;i<n;i++)
• {
• if((num[i]%2)==0)
• esum+=num[i];
• else
• odsum+=num[i];
• }
• printf("sum of even no %d \n",esum);
• printf("sum of odd no %d \n",odsum);
• }
program to calculate elements of array
• #include<stdio.h>
• #include<conio.h>
• void main()
• {
• //clrscr();
• int i,count=0;
• int
x[]={10,20,30,40,50,60,70,80,90,100,101,102};
• count=sizeof(x)/sizeof(x[0]);
• printf("no of elements in array are %d \n",count);
• }
program to arrange the elements in ascending order
• #include<stdio.h>
• #include<conio.h>
• void main()
• {
• int array[20];
• int i,j,n,temp;
• printf("enter size of array \n");
• scanf("%d",&n);
• printf("enter elements \n");
• for(i=0;i<n;i++)
• scanf("%d",&array[i]);
• for(i=0;i<n;i++)
• {
• for(j=i+1;j<n;j++)
• {
• if(array[i]>array[j])
• {
• temp=array[i];
• array[i]=array[j];
• array[j]=temp;
• }}}
• printf("sorted elements are");
• for(i=0;i<n;i++)
• printf("%d\n",array[i]);
• }