SlideShare une entreprise Scribd logo
1  sur  8
Télécharger pour lire hors ligne
C Programming – Functions/ Storage
Classes
By: JENISH BHAVSAR
1
Storage Class
Scope, Visibility and Lifetime of variables
 Scope: The scope of a variable determines over what region of the program a variable is accessible.
 Visibility: Refers to the accessibility of a variable from the memory.
 Longevity (Lifetime): refers to the period during which a variable retains a given value during
execution of a program.
Storage Class
 A storage class defines the scope (visibility) and life time of variables and/or functions within a C
Program. These specifiers precede the type that they modify.
 There are following storage classes which can be used in a C Program:
o Automatic Variables/ Internal Variables (auto)
o External Variables/ Global Variables (extern)
o Static Variables (static)
o Register Variables (register)
Automatic Variables/ Internal Variables (auto)
 The auto storage class is the default storage class for all local variables.
 The features of a variable defined to have an auto storage class are as under:
Storage Memory
Default initial value An unpredictable value, which is often called a garbage value.
Scope Local to the block in which the variable is defined.
Life Till the control remains within the block in which the variable is defined.
 Automatic variables are declared inside a function in which they are to be utilized. They are created
when the function is called and destroyed when the function is exited.
 Automatic variables are therefore private (local) to the function in which they are declared.
 All variables declared within a function are auto by default even if the storage class auto is not
specified.
#include <stdio.h>
void function1(void);
void function2(void);
void main( )
{
int m = 1000;
function2();
printf("%dn",m); /* Third output */
}
void function1(void)
{
int m = 10;
printf("%dn",m); /* First output */
}
void function2(void)
{
int m = 100;
function1();
printf("%dn",m); /* Second output */
}
 In the above example, int m is an auto variable in all the three functions main(), function1(),
function2().
C Programming – Functions/ Storage
Classes
By: JENISH BHAVSAR
2
 When executed, main calls function2 which in turn calls function1. When main is active m = 1000;
when function2 is called next m = 100 but within function2 function1 is called and hence m = 10
becomes active.
 Hence, the output will be first – 10 then call returned to function2 and hence 100 and then call
returned to main and hence 1000 gets printed.
External Variables/ Global Variables (extern)
 The extern storage class allows to declare a variable as a Global/ External variables.
 The variables of this class can be referred to as 'global or external variables.' They are declared
outside the functions and can be invoked at anywhere in a program.
 The features of a variable defined to have an extern storage class are as under:
Storage Memory
Default initial value Zero
Scope Global
Life As long as the program’s execution doesn’t come to an end.
 The extern storage class is used to give a reference of a global variable that is visible to ALL the
program files.
 When we use 'extern' the variable cannot be initialized as all it does is point the variable name at a
storage location that has been previously defined.
int fun1(void);
int fun2(void);
int fun3(void);
int x ; /* global */
void main( )
{
x = 10 ; /* global x */
printf("x = %dn", x);
printf("x = %dn", fun1());
printf("x = %dn", fun2());
printf("x = %dn", fun3());
}
int fun1(void)
{
x = x + 10;
}
int fun2(void)
{
int x; /* local */
x = 1;
return (x);
}
int fun3(void)
{
x = x + 10; /* global x */
}
 In the above example, the variable x is used in all functions but none except fun2, has a definition for
x.
 Because x has been declared 'above' all the functions, it is available to each function without having
to pass x as a function argument.
 Further, since the value of x is directly available, we need not use return(x) statements in fun1 and
fun3.
 However, since fun2 has a definition of x, it returns its local value of x and therefore uses a return
statement. In fun2, the global x is not visible. The local x hides its visibility here.
C Programming – Functions/ Storage
Classes
By: JENISH BHAVSAR
3
Static Variables (static)
 The value of static variables persists until the end of the program.
 A variable can be declared static using the keyword static. E.g.: static int x;
 A static variable may be either an internal or external type depending on the place of declaration.
 The features of a variable defined to have an static storage class are as under:
Storage Memory
Default initial value Zero
Scope Local to block in which the variable is defined
Life Value of variable persists between function calls
 Internal static variables are those which are declared inside a function. The scope of internal static
variables extends upto the end of the function in which they are defined.
 A static variable is initialized only once, when the program is compiled. It is never initialized again.
 An external static variable is declared outside of all functions and is available to all the functions in
that program.
#include<stdio.h>
void stat(void);
void main()
{
int i;
for(i=1; i<=3; i++)
stat( );
}
void stat(void)
{
static int x = 0;
x = x+1;
printf("x = %dn", x);
}
 In the above example, the first call to stat(), increment value of x to 1. Because x is static, this value
persists and when loop iterates, the next call to stat() increments x to 2 and so on till the loop runs.
 If the same code was with int x instead of static int x; - all the three iterations of the loop would
have given the value 1 to the main function because x was not static.
Register Variables
 We can tell the compiler that a variable should be kept in one of the machine’s registers, instead of
keeping in the memory (RAM).
 Since a register access is much faster than a memory access, keeping the frequently accessed
variables in the register will lead to faster execution of programs.
 There is no waste of time, getting variables from memory and sending it to back again.
 Since only a few variables can be placed in the register, it is important to carefully select the
variables for this purpose.
 The features of a variable defined to have an regiser storage class are as under:
Storage CPU Registers
Default initial value Garbage Value
Scope Local to block in which the variable is defined
Life Till the control remains within the block in which the variable is defined
C Programming – Functions/ Storage
Classes
By: JENISH BHAVSAR
4
#include <stdio.h>
#include <conio.h>
void main()
{
register int i=10;
clrscr();
{
register int i=20;
printf("nt %d",i);
}
printf("nnt %d",i);
getch();
}
Operations on Arrays
 An array is a collection of items which can be referred to by a single name.
 An array is also called a linear data structure because the array elements lie in the computer
memory in a linear fashion.
 The possible operations on array are:
1. Insertion
2. Deletion
3. Traversal
4. Searching
5. Sorting
6. Merging
7. Updating
Insertion and Deletion
 Inserting an element at the end of the linear array can be easily performed, provided the memory
space is available to accommodate the additional element.
 If we want to insert an element in the middle of the array then it is required that half of the
elements must be moved rightwards to new locations to accommodate the new element and keep
the order of the other elements.
 Similarly, if we want to delete the middle element of the linear array, then each subsequent element
must be moved one location ahead of the previous position of the element.
Traversing
 Traversing basically means the accessing the each and every element of the array at least once.
 Traversing is usually done to be aware of the data elements which are present in the array.
 After insertion or deletion operation we would usually want to check whether it has been
successfully or not, to check this we can use traversing, and can make sure that whether the
element is successfully inserted or deleted.
Sorting
 We can store elements to be sorted in an array in either ascending or descending order.
Searching
 Searching an element in an array, the search starts from the first element till the last element.The
average number of comparisons in a sequential search is (N+1)/2 where N is the size of the array. If
the element is in the 1st position, the number of comparisons will be 1 and if the element is in the
last position, the number of comparisons will be N.
C Programming – Functions/ Storage
Classes
By: JENISH BHAVSAR
5
Merging
 Merging is the process of combining two arrays in a third array. The third array must have to be large
enough to hold the elements of both the arrays. We can merge the two arrays after sorting them
individually or merge them first and then sort them as the user needs.
#include<stdio.h>
#include<conio.h>
void main()
{
int ch,h[10],n,p,i,t,j;
printf("n ENTER ARRAY= ");
for(i=0;i<10;i++)
{
scanf("n %d",&h[i]);
}
do
{
printf("n1.traversing");
printf("n2.insertion");
printf("n3.deletion");
printf("n4.sorting");
printf("n5.searching");
printf("n6. exit");
printf("nenter choice");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("n display array");
for(i=0;i<10;i++)
{
printf("n %d",h[i]);
} getch();
break;
case 2:printf("n enter no & position ");
scanf("%d%d",&n,&p);
for(i=0;i<10;i++)
{
if(i==p)
{
h[i]=n;
}
else
{
printf("n position not found");
}
}
break;
case 3:
printf("n enter position for delete no");
scanf("%d",&n);
for(i=0;i<10;i++)
{
if(i==n)
{ h[i]=0;
}
else
{
printf("n position not found");
}
}
break;
case 4: printf("n sorting is==");
for(i=0;i<9;i++)
{
for(j=i+1;j<=9;j++)
{
if(h[i]<=h[j])
{
t=h[i];
h[i]=h[j];
h[j]=t;
}
}
}
for(i=0;i<10;i++)
{
printf("n%dn",h[i]); } getch();
break;
case 5: printf("n enter no for searching ");
scanf("%d",&n);
for(i=0;i<10;i++)
{
if(h[i]==n)
printf("n%d",h[i]);
} getch();
break;
case 6: exit();
}
}while(ch!=6);
getch();
}
C Programming – Functions/ Storage
Classes
By: JENISH BHAVSAR
6
Built-In Functions in C
Mathematical Functions in STDLIB.H
1. abs(): returns the absolute value of an integer. (Given number is an integer)
Syntax: abs(number) E.g.: a = abs(-5) O/p: 5
2. fabs(): returns the absolute value of a floating-point number. (Given number is a float number)
Syntax: fabs(number) E.g.: a = fabs(-5.3) O/p: 5.3
Mathematical Functions in MATH.H
3. pow(): Raises a number (x) to a given power (y).
Syntax: double power(double x, double y) E.g. : pow(3, 2) O/p: 9
4. sqrt() : Returns the square root of a given number.
Syntax: double sqrt (double x) E.g. : sqrt(9) O/p: 3
5. ceil() : Returns the smallest integer value greater than or equal to a given number.
Syntax: double ceil(double x) E.g. y = ceil(123.54) O/p: y = 124
6. floor() : Returns the largest integer value less than or equal to a given number.
Syntax: ceil(double x) E.g. y = floor(123.54) O/p: y = 123
7. log(): Returns the natural logarithm of a given number.
Syntax: double log(double x) E.g. y = log(1.00) O/p: 0.0000
8. exp(): Returns the value of e raised to the xth
power.
Syntax: double exp(double x) E.g. y = exp(1.00) O/p: 2.718282
Functions in CTYPE.H
The ctype header is used for testing and converting characters. A control character refers to a character
that is not part of the normal printing set.
The is... functions test the given character and return a nonzero (true) result if it satisfies the following
conditions. If not, then 0 (false) is returned.
1. isalnum() – Checks whether a given character is a letter (A-Z, a-z) or a digit(0-9) and returns true else
false. Syntax: int isalnum(int character);
2. isalpha() – Checks whether a given character is a letter (A-Z, a-z) and returns true else false.
Syntax: int isalnum(int character);
3. isdigit() – Checks whether a given character is a digit (0-9) and returns true else false.
Syntax: int isdigit(int character);
4. iscntrl() – Checks whether a given character is a control character (TAB, DEL)and returns true else
false. Syntax: int iscntrl(int character);
5. isupper() – Checks whether a given character is a upper-case letter(A-Z) and returns true else false.
Syntax: int isupper(int character);
C Programming – Functions/ Storage
Classes
By: JENISH BHAVSAR
7
6. islower() – Checks whether a given character is a lower-case letter(a-z) and returns true else false.
Syntax: int islower(int character);
7. isspace() – Checks whether a given character is a whitespace character (space, tab, carriage return,
new line, vertical tab, or formfeed)and returns true else false. Syntax: int isspace(int
character);
8. tolower() – If the character is an uppercase character (A to Z), then it is converted to lowercase (a to
z).
Syntax: int tolower(int character); E.g.: tolower(‘A’) O/p : a
9. toupper() – If the character is a lowercase character (a to z), then it is converted to uppercase (A to
Z).
Syntax: int toupper(int character); E.g.: toupper(‘a’) O/p : A
10. toascii() – Converts a character into a ascii value.
Syntax: short toascii(short character);
 What is the mean of #include <stdio.h>?
This statement tells the compiler to search for a file ‘stdio.h’ and place its contents at this point in
the program. The contents of the header file become part of the source code when it is compiled.
 Full form of the different library header file: -
File Name Full form
stdio.h Standard Input Output Header file. It contains different standard input
output function such as printf and scanf
math.h Mathematical Header file. This file contains various mathematical
function such cos, sine, pow (power), log, tan, etc.
conio.h Console Input Output Header file. This file contains various function
used in console output such as getch, clrscr, etc.
stdlib.h Standard Library Header file. It contains various utility function such as
atoi, exit, etc.
ctype.h Character TYPE Header file. It contains various character testing and
conversion functions
string.h. STRING Header file. It contains various function related to string
operation such as strcmp, strcpy, strcat, strlen, etc.
time.h TIME handling function Header file. It contains various function related
to time manipulation.
C Programming – Functions/ Storage
Classes
By: JENISH BHAVSAR
8
Different Library function: -
1. getchar( ): - This function is used to read simply one character from standard input device. The
format of it is: Syntax: variablename = getchar( ) ;
e.g char name;
name = getchar ( ) ;
Here computer waits until we enter one character from the input device and assign it to character
variable name. We have to press enter key after inputting one character, then we are getting the
next result. This function is written in ‘stdio.h’ file
2. getche( ): - This function is used to read the character from the standard input device. The format of
it is: Syntax: variablename = getche( ) ;
e.g char name;
name = getche( ) ;
Here computer waits until we enter one character from the input device and assign it to character
variable name. In getche( ) function there is no need to press enter key after inputting one character
but we are getting next result immediately while in getchar( ) function we must press the enter key.
This getche( ) function is written in standard library file ‘conio.h’.
3. getch( ): - This function is used to read the character from the standard input device but it will not
echo (display) the character which you are inputting. The format of it is:
Syntax: variablename = getche( ) ;
e.g char name;
name = getch( ) ;
Here computer waits until you enter one character from the input device and assign it to character
variable name. In getch( ) function there is no need to press enter key after inputting one character
but you are getting next result immediately while in getchar( ) function you must press the enter key
and also it will echo (display) the character which you are entering. This getch( ) function is written in
standard library file ‘conio.h’.
4. putchar( ): -This function is used to print one character on standard output device. The format of this
function is: Syntax: putchar(variablename) ;
e.g. char name;
name=’p’;
putchar(name);
After executing the above statement you get the letter ‘p’ printed on standard output device. This
function is written in ‘stdio.h’ file.

Contenu connexe

Tendances

Prsentation on functions
Prsentation on functionsPrsentation on functions
Prsentation on functions
Alisha Korpal
 
11 lec 11 storage class
11 lec 11 storage class11 lec 11 storage class
11 lec 11 storage class
kapil078
 

Tendances (20)

Storage class in C Language
Storage class in C LanguageStorage class in C Language
Storage class in C Language
 
User Defined Functions
User Defined FunctionsUser Defined Functions
User Defined Functions
 
Lecture 11 - Functions
Lecture 11 - FunctionsLecture 11 - Functions
Lecture 11 - Functions
 
Prsentation on functions
Prsentation on functionsPrsentation on functions
Prsentation on functions
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in C
 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmig
 
Lecture 14 - Scope Rules
Lecture 14 - Scope RulesLecture 14 - Scope Rules
Lecture 14 - Scope Rules
 
Storage class in c
Storage class in cStorage class in c
Storage class in c
 
Lecture 13 - Storage Classes
Lecture 13 - Storage ClassesLecture 13 - Storage Classes
Lecture 13 - Storage Classes
 
Function in c
Function in cFunction in c
Function in c
 
Storage classes in c language
Storage classes in c languageStorage classes in c language
Storage classes in c language
 
11 lec 11 storage class
11 lec 11 storage class11 lec 11 storage class
11 lec 11 storage class
 
User defined functions in C
User defined functions in CUser defined functions in C
User defined functions in C
 
Storage classes
Storage classesStorage classes
Storage classes
 
Storage class
Storage classStorage class
Storage class
 
Presentation on function
Presentation on functionPresentation on function
Presentation on function
 
Storage Class Specifiers in C++
Storage Class Specifiers in C++Storage Class Specifiers in C++
Storage Class Specifiers in C++
 
Unit 8
Unit 8Unit 8
Unit 8
 
Lecture20 user definedfunctions.ppt
Lecture20 user definedfunctions.pptLecture20 user definedfunctions.ppt
Lecture20 user definedfunctions.ppt
 
User defined functions
User defined functionsUser defined functions
User defined functions
 

En vedette

Presentation bca 1 c
Presentation   bca 1 cPresentation   bca 1 c
Presentation bca 1 c
gursharan914
 
PowerPoint presentation on Online Courses
PowerPoint presentation on Online Courses PowerPoint presentation on Online Courses
PowerPoint presentation on Online Courses
kireland31
 
Management process powerpoint
Management process powerpointManagement process powerpoint
Management process powerpoint
ElizabethLampson2
 

En vedette (12)

Presentation bca 1 c
Presentation   bca 1 cPresentation   bca 1 c
Presentation bca 1 c
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
 
Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)
 
PowerPoint presentation on Online Courses
PowerPoint presentation on Online Courses PowerPoint presentation on Online Courses
PowerPoint presentation on Online Courses
 
Management process powerpoint
Management process powerpointManagement process powerpoint
Management process powerpoint
 
Levels of management
Levels of managementLevels of management
Levels of management
 
C ppt
C pptC ppt
C ppt
 
INTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGINTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMING
 
Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programming
 
The Business of Social Media
The Business of Social Media The Business of Social Media
The Business of Social Media
 
Free Download Powerpoint Slides
Free Download Powerpoint SlidesFree Download Powerpoint Slides
Free Download Powerpoint Slides
 
Basic concept of management
Basic concept of managementBasic concept of management
Basic concept of management
 

Similaire à Storage classes arrays & functions in C Language

What is storage class
What is storage classWhat is storage class
What is storage class
Isha Aggarwal
 
S torage class in C
S torage class in CS torage class in C
S torage class in C
kash95
 
Latest C Interview Questions and Answers
Latest C Interview Questions and AnswersLatest C Interview Questions and Answers
Latest C Interview Questions and Answers
DaisyWatson5
 
C language presentation
C language presentationC language presentation
C language presentation
bainspreet
 
Data structure scope of variables
Data structure scope of variablesData structure scope of variables
Data structure scope of variables
Saurav Kumar
 

Similaire à Storage classes arrays & functions in C Language (20)

What is storage class
What is storage classWhat is storage class
What is storage class
 
S torage class in C
S torage class in CS torage class in C
S torage class in C
 
Storage class
Storage classStorage class
Storage class
 
Latest C Interview Questions and Answers
Latest C Interview Questions and AnswersLatest C Interview Questions and Answers
Latest C Interview Questions and Answers
 
C language presentation
C language presentationC language presentation
C language presentation
 
5.program structure
5.program structure5.program structure
5.program structure
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
 
Unit iii
Unit iiiUnit iii
Unit iii
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01
 
Functions struct&union
Functions struct&unionFunctions struct&union
Functions struct&union
 
Programming in c by pkv
Programming in c by pkvProgramming in c by pkv
Programming in c by pkv
 
Programming in C (part 2)
Programming in C (part 2)Programming in C (part 2)
Programming in C (part 2)
 
Advanced C Programming Notes
Advanced C Programming NotesAdvanced C Programming Notes
Advanced C Programming Notes
 
Data structure scope of variables
Data structure scope of variablesData structure scope of variables
Data structure scope of variables
 
Functions
FunctionsFunctions
Functions
 
C Programming Storage classes, Recursion
C Programming Storage classes, RecursionC Programming Storage classes, Recursion
C Programming Storage classes, Recursion
 
functions
functionsfunctions
functions
 
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
 FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM) FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
 
Function in c
Function in cFunction in c
Function in c
 
Python_UNIT-I.pptx
Python_UNIT-I.pptxPython_UNIT-I.pptx
Python_UNIT-I.pptx
 

Dernier

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Dernier (20)

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 

Storage classes arrays & functions in C Language

  • 1. C Programming – Functions/ Storage Classes By: JENISH BHAVSAR 1 Storage Class Scope, Visibility and Lifetime of variables  Scope: The scope of a variable determines over what region of the program a variable is accessible.  Visibility: Refers to the accessibility of a variable from the memory.  Longevity (Lifetime): refers to the period during which a variable retains a given value during execution of a program. Storage Class  A storage class defines the scope (visibility) and life time of variables and/or functions within a C Program. These specifiers precede the type that they modify.  There are following storage classes which can be used in a C Program: o Automatic Variables/ Internal Variables (auto) o External Variables/ Global Variables (extern) o Static Variables (static) o Register Variables (register) Automatic Variables/ Internal Variables (auto)  The auto storage class is the default storage class for all local variables.  The features of a variable defined to have an auto storage class are as under: Storage Memory Default initial value An unpredictable value, which is often called a garbage value. Scope Local to the block in which the variable is defined. Life Till the control remains within the block in which the variable is defined.  Automatic variables are declared inside a function in which they are to be utilized. They are created when the function is called and destroyed when the function is exited.  Automatic variables are therefore private (local) to the function in which they are declared.  All variables declared within a function are auto by default even if the storage class auto is not specified. #include <stdio.h> void function1(void); void function2(void); void main( ) { int m = 1000; function2(); printf("%dn",m); /* Third output */ } void function1(void) { int m = 10; printf("%dn",m); /* First output */ } void function2(void) { int m = 100; function1(); printf("%dn",m); /* Second output */ }  In the above example, int m is an auto variable in all the three functions main(), function1(), function2().
  • 2. C Programming – Functions/ Storage Classes By: JENISH BHAVSAR 2  When executed, main calls function2 which in turn calls function1. When main is active m = 1000; when function2 is called next m = 100 but within function2 function1 is called and hence m = 10 becomes active.  Hence, the output will be first – 10 then call returned to function2 and hence 100 and then call returned to main and hence 1000 gets printed. External Variables/ Global Variables (extern)  The extern storage class allows to declare a variable as a Global/ External variables.  The variables of this class can be referred to as 'global or external variables.' They are declared outside the functions and can be invoked at anywhere in a program.  The features of a variable defined to have an extern storage class are as under: Storage Memory Default initial value Zero Scope Global Life As long as the program’s execution doesn’t come to an end.  The extern storage class is used to give a reference of a global variable that is visible to ALL the program files.  When we use 'extern' the variable cannot be initialized as all it does is point the variable name at a storage location that has been previously defined. int fun1(void); int fun2(void); int fun3(void); int x ; /* global */ void main( ) { x = 10 ; /* global x */ printf("x = %dn", x); printf("x = %dn", fun1()); printf("x = %dn", fun2()); printf("x = %dn", fun3()); } int fun1(void) { x = x + 10; } int fun2(void) { int x; /* local */ x = 1; return (x); } int fun3(void) { x = x + 10; /* global x */ }  In the above example, the variable x is used in all functions but none except fun2, has a definition for x.  Because x has been declared 'above' all the functions, it is available to each function without having to pass x as a function argument.  Further, since the value of x is directly available, we need not use return(x) statements in fun1 and fun3.  However, since fun2 has a definition of x, it returns its local value of x and therefore uses a return statement. In fun2, the global x is not visible. The local x hides its visibility here.
  • 3. C Programming – Functions/ Storage Classes By: JENISH BHAVSAR 3 Static Variables (static)  The value of static variables persists until the end of the program.  A variable can be declared static using the keyword static. E.g.: static int x;  A static variable may be either an internal or external type depending on the place of declaration.  The features of a variable defined to have an static storage class are as under: Storage Memory Default initial value Zero Scope Local to block in which the variable is defined Life Value of variable persists between function calls  Internal static variables are those which are declared inside a function. The scope of internal static variables extends upto the end of the function in which they are defined.  A static variable is initialized only once, when the program is compiled. It is never initialized again.  An external static variable is declared outside of all functions and is available to all the functions in that program. #include<stdio.h> void stat(void); void main() { int i; for(i=1; i<=3; i++) stat( ); } void stat(void) { static int x = 0; x = x+1; printf("x = %dn", x); }  In the above example, the first call to stat(), increment value of x to 1. Because x is static, this value persists and when loop iterates, the next call to stat() increments x to 2 and so on till the loop runs.  If the same code was with int x instead of static int x; - all the three iterations of the loop would have given the value 1 to the main function because x was not static. Register Variables  We can tell the compiler that a variable should be kept in one of the machine’s registers, instead of keeping in the memory (RAM).  Since a register access is much faster than a memory access, keeping the frequently accessed variables in the register will lead to faster execution of programs.  There is no waste of time, getting variables from memory and sending it to back again.  Since only a few variables can be placed in the register, it is important to carefully select the variables for this purpose.  The features of a variable defined to have an regiser storage class are as under: Storage CPU Registers Default initial value Garbage Value Scope Local to block in which the variable is defined Life Till the control remains within the block in which the variable is defined
  • 4. C Programming – Functions/ Storage Classes By: JENISH BHAVSAR 4 #include <stdio.h> #include <conio.h> void main() { register int i=10; clrscr(); { register int i=20; printf("nt %d",i); } printf("nnt %d",i); getch(); } Operations on Arrays  An array is a collection of items which can be referred to by a single name.  An array is also called a linear data structure because the array elements lie in the computer memory in a linear fashion.  The possible operations on array are: 1. Insertion 2. Deletion 3. Traversal 4. Searching 5. Sorting 6. Merging 7. Updating Insertion and Deletion  Inserting an element at the end of the linear array can be easily performed, provided the memory space is available to accommodate the additional element.  If we want to insert an element in the middle of the array then it is required that half of the elements must be moved rightwards to new locations to accommodate the new element and keep the order of the other elements.  Similarly, if we want to delete the middle element of the linear array, then each subsequent element must be moved one location ahead of the previous position of the element. Traversing  Traversing basically means the accessing the each and every element of the array at least once.  Traversing is usually done to be aware of the data elements which are present in the array.  After insertion or deletion operation we would usually want to check whether it has been successfully or not, to check this we can use traversing, and can make sure that whether the element is successfully inserted or deleted. Sorting  We can store elements to be sorted in an array in either ascending or descending order. Searching  Searching an element in an array, the search starts from the first element till the last element.The average number of comparisons in a sequential search is (N+1)/2 where N is the size of the array. If the element is in the 1st position, the number of comparisons will be 1 and if the element is in the last position, the number of comparisons will be N.
  • 5. C Programming – Functions/ Storage Classes By: JENISH BHAVSAR 5 Merging  Merging is the process of combining two arrays in a third array. The third array must have to be large enough to hold the elements of both the arrays. We can merge the two arrays after sorting them individually or merge them first and then sort them as the user needs. #include<stdio.h> #include<conio.h> void main() { int ch,h[10],n,p,i,t,j; printf("n ENTER ARRAY= "); for(i=0;i<10;i++) { scanf("n %d",&h[i]); } do { printf("n1.traversing"); printf("n2.insertion"); printf("n3.deletion"); printf("n4.sorting"); printf("n5.searching"); printf("n6. exit"); printf("nenter choice"); scanf("%d",&ch); switch(ch) { case 1: printf("n display array"); for(i=0;i<10;i++) { printf("n %d",h[i]); } getch(); break; case 2:printf("n enter no & position "); scanf("%d%d",&n,&p); for(i=0;i<10;i++) { if(i==p) { h[i]=n; } else { printf("n position not found"); } } break; case 3: printf("n enter position for delete no"); scanf("%d",&n); for(i=0;i<10;i++) { if(i==n) { h[i]=0; } else { printf("n position not found"); } } break; case 4: printf("n sorting is=="); for(i=0;i<9;i++) { for(j=i+1;j<=9;j++) { if(h[i]<=h[j]) { t=h[i]; h[i]=h[j]; h[j]=t; } } } for(i=0;i<10;i++) { printf("n%dn",h[i]); } getch(); break; case 5: printf("n enter no for searching "); scanf("%d",&n); for(i=0;i<10;i++) { if(h[i]==n) printf("n%d",h[i]); } getch(); break; case 6: exit(); } }while(ch!=6); getch(); }
  • 6. C Programming – Functions/ Storage Classes By: JENISH BHAVSAR 6 Built-In Functions in C Mathematical Functions in STDLIB.H 1. abs(): returns the absolute value of an integer. (Given number is an integer) Syntax: abs(number) E.g.: a = abs(-5) O/p: 5 2. fabs(): returns the absolute value of a floating-point number. (Given number is a float number) Syntax: fabs(number) E.g.: a = fabs(-5.3) O/p: 5.3 Mathematical Functions in MATH.H 3. pow(): Raises a number (x) to a given power (y). Syntax: double power(double x, double y) E.g. : pow(3, 2) O/p: 9 4. sqrt() : Returns the square root of a given number. Syntax: double sqrt (double x) E.g. : sqrt(9) O/p: 3 5. ceil() : Returns the smallest integer value greater than or equal to a given number. Syntax: double ceil(double x) E.g. y = ceil(123.54) O/p: y = 124 6. floor() : Returns the largest integer value less than or equal to a given number. Syntax: ceil(double x) E.g. y = floor(123.54) O/p: y = 123 7. log(): Returns the natural logarithm of a given number. Syntax: double log(double x) E.g. y = log(1.00) O/p: 0.0000 8. exp(): Returns the value of e raised to the xth power. Syntax: double exp(double x) E.g. y = exp(1.00) O/p: 2.718282 Functions in CTYPE.H The ctype header is used for testing and converting characters. A control character refers to a character that is not part of the normal printing set. The is... functions test the given character and return a nonzero (true) result if it satisfies the following conditions. If not, then 0 (false) is returned. 1. isalnum() – Checks whether a given character is a letter (A-Z, a-z) or a digit(0-9) and returns true else false. Syntax: int isalnum(int character); 2. isalpha() – Checks whether a given character is a letter (A-Z, a-z) and returns true else false. Syntax: int isalnum(int character); 3. isdigit() – Checks whether a given character is a digit (0-9) and returns true else false. Syntax: int isdigit(int character); 4. iscntrl() – Checks whether a given character is a control character (TAB, DEL)and returns true else false. Syntax: int iscntrl(int character); 5. isupper() – Checks whether a given character is a upper-case letter(A-Z) and returns true else false. Syntax: int isupper(int character);
  • 7. C Programming – Functions/ Storage Classes By: JENISH BHAVSAR 7 6. islower() – Checks whether a given character is a lower-case letter(a-z) and returns true else false. Syntax: int islower(int character); 7. isspace() – Checks whether a given character is a whitespace character (space, tab, carriage return, new line, vertical tab, or formfeed)and returns true else false. Syntax: int isspace(int character); 8. tolower() – If the character is an uppercase character (A to Z), then it is converted to lowercase (a to z). Syntax: int tolower(int character); E.g.: tolower(‘A’) O/p : a 9. toupper() – If the character is a lowercase character (a to z), then it is converted to uppercase (A to Z). Syntax: int toupper(int character); E.g.: toupper(‘a’) O/p : A 10. toascii() – Converts a character into a ascii value. Syntax: short toascii(short character);  What is the mean of #include <stdio.h>? This statement tells the compiler to search for a file ‘stdio.h’ and place its contents at this point in the program. The contents of the header file become part of the source code when it is compiled.  Full form of the different library header file: - File Name Full form stdio.h Standard Input Output Header file. It contains different standard input output function such as printf and scanf math.h Mathematical Header file. This file contains various mathematical function such cos, sine, pow (power), log, tan, etc. conio.h Console Input Output Header file. This file contains various function used in console output such as getch, clrscr, etc. stdlib.h Standard Library Header file. It contains various utility function such as atoi, exit, etc. ctype.h Character TYPE Header file. It contains various character testing and conversion functions string.h. STRING Header file. It contains various function related to string operation such as strcmp, strcpy, strcat, strlen, etc. time.h TIME handling function Header file. It contains various function related to time manipulation.
  • 8. C Programming – Functions/ Storage Classes By: JENISH BHAVSAR 8 Different Library function: - 1. getchar( ): - This function is used to read simply one character from standard input device. The format of it is: Syntax: variablename = getchar( ) ; e.g char name; name = getchar ( ) ; Here computer waits until we enter one character from the input device and assign it to character variable name. We have to press enter key after inputting one character, then we are getting the next result. This function is written in ‘stdio.h’ file 2. getche( ): - This function is used to read the character from the standard input device. The format of it is: Syntax: variablename = getche( ) ; e.g char name; name = getche( ) ; Here computer waits until we enter one character from the input device and assign it to character variable name. In getche( ) function there is no need to press enter key after inputting one character but we are getting next result immediately while in getchar( ) function we must press the enter key. This getche( ) function is written in standard library file ‘conio.h’. 3. getch( ): - This function is used to read the character from the standard input device but it will not echo (display) the character which you are inputting. The format of it is: Syntax: variablename = getche( ) ; e.g char name; name = getch( ) ; Here computer waits until you enter one character from the input device and assign it to character variable name. In getch( ) function there is no need to press enter key after inputting one character but you are getting next result immediately while in getchar( ) function you must press the enter key and also it will echo (display) the character which you are entering. This getch( ) function is written in standard library file ‘conio.h’. 4. putchar( ): -This function is used to print one character on standard output device. The format of this function is: Syntax: putchar(variablename) ; e.g. char name; name=’p’; putchar(name); After executing the above statement you get the letter ‘p’ printed on standard output device. This function is written in ‘stdio.h’ file.