UNIT3
UNIT3
UNIT3
Whenever we are solving large programs first, we must understand the problem as a whole, then we must break it in to simpler, understandable parts. We call each of these parts of a program a module and the process of sub dividing a problem into manageable parts top-down design. Figure: Structure Chart
The principles of top-down design and structured programming dictate that a program should be divided into a main module and its related modules. The division of modules proceeds until the module consists only of elementary process that is intrinsically understood and cannot be further subdivided. This process is known as factoring. Top-down design is usually done using a visual representation of the modules known as a structured chart.
FUNCTIONS:
Definition: Modules in C are called functions. A function in C is defined to be the program segment that carries out some specific, well defined task. A function is a block of code that has a name and it has a property that it is reusable i.e. it can be executed from as many different points in a C Program as required. C regards main() as a function. The void function provides a way of not returning any value through function name There are two types of functions: Library functions: C standard library provides a rich collection of functions for performing I/O operations, mathematical calculations, string manipulation operations etc.For example, sqrt(x) is
a function to calculate the square root of a number provided by the C standard library and included in the <math.h>header file. Note that each program in C has a function called main which is used as the root function of calling other library functions. Structure of a function: There are two main parts of the function. The function header and the function body. type fun_name(parameter along with type) { local declarations; body; } Function Header In the first line of the above code int sum(int x, int y) It has three main parts 1. The name of the function i.e. sum 2. The parameters of the function enclosed in parenthesis 3. Return value type i.e. int Function Body Whatever is written with in { } in the above example is the body of the function. type : It is the type of value returned by the function and can be basic type or user defined return-type: Specifies the type of value that a function returns using the return statement. It can be any valid data type. If no data type is specified the function is assumed to return an integer result. return statement is used in the body of a function to pass the result back to the calling program. function-name: Must follow same rules of variable names in C. No two functions have the same name in a C program. argument declaration: Is a comma-separated list of variables that receive the values of the argument when function is called. If there are no argument declaration the bracket consists of keyword void. Consider the following example: int sum(int x, int y) { int ans = 0; ans = x + y; return ans }
Programmer Defined functions: In C, the programmers can write their own functions and use them in their programs. The user defined function can be explained with three elements. 1. Function definition 2. Function call 3. Function declaration The function definition is an independent program module that is specially written to implement the requirements of the function. In order to use this function we need to invoke it at a required place in the program. This is known as function call. The program that calls the function is known as calling program or calling function. The calling program should declare any function that is to be used later in the program. This is known as the function declaration or the function prototype. 1. Function Declaration (or) Prototype: The ANSI C standard expands the concept of forward function declaration. This expanded declaration is called a function prototype. A function prototype performs two special tasks. 1. First it identifies the return type of the function so that the compile can generate the correct code for the return data. 2. Second, it specifies the type and number of arguments used by the function. The general form of the prototype is
return_type function_name (type1 name1, type2 name2,..., typen namen) R eturn type and parameter types mus t be provided in the prototype
S emi-colon indicates that this is only the function prototype, and that its definition will be found els ewhere
Note: The prototype normally goes near the top of the program and must appear before any call is made to the function.
2. The Function Call: A function call is a postfix expression. The operand in a function is the function name. The operator is the parameter lists (), which contain the actual parameters. Example: void main () { sum (a, b); } When the compiler encounters the function call ,the control is transferred to the function sum().The functions is executed line by line and outputs the sum of the two numbers and returns to main when the last statement in the following has executed and conceptually, the functions ending } is encountered. 3. Function Definition: The function definition contains the code for a function. It is made up of two parts: The function header and the function body, the compound statement is must.
Advantages Of User-Defined Functions: Modular Programming It facilitates top down modular programming. In this programming style, the high level logic of the overall problem is solved first while the details of each lower level functions is addressed later. 1. Reduction of source code The length of the source program can be reduced by using functions at appropriate places. This factor is critical with microcomputers where memory space is limited. 2. Easier Debugging It is easy to locate and isolate a faulty function for further investigation. 3. Code Reusability a program can be used to avoid rewriting the same sequence of code at two or more locations in a program. This is especially useful if the code involved is long or complicated. 4. Function sharing Programming teams does a large percentage of programming. If the program is divided into subprograms, each subprogram can be written by one or two team members of the team rather than having the whole team to work on the complex program Categories of functions: A function depending on whether arguments are present or not and whether value is returned or not, may belong to one of the following categories: 1. Functions with no arguments and no return values 2. Functions with arguments and no return values 3. Functions with arguments and a return value 4. Functions with no arguments but a return value 1. Functions with no arguments and no return values: This type of function has no arguments, meaning that it does not receive any data from the calling function. Similarly this type of function will not return any value. Here the calling function does not receive any data from the called function. In effect, there is no data transfer between the calling function and the called function.
Observe from the figure 3.5 that the function greeting () do not receive any values from the function main () and it does not return any value to the function main ().Observe the transfer of control between the functions indicated with arrows. //C program to find sum of two numbers using functions with no arguments and no return values
#include<stdio.h> void sum (); void main () { clrscr (); sum (); /*calling function */ getch (); } void sum () { int x, y, z; printf (\n Enter the values of x and y: ); scanf (%d%d, &x, &y); z=x+y; printf (\n The sum = %d,z); }
4. Functions with no arguments but a return value: There are two ways that a function terminates execution and returns to the caller. 1. When the last statement in the function has executed and conceptually the functions ending } is encountered. 2. Whenever it faces return statement. The Return Statement The return statement is the mechanism for returning a value from the called function to its caller. The general form of the return statement is return expression; The calling function is free to ignore the returned value. Further more, there need not be expression after the return. In any case if a function fails to return a value, its value is certain to be garbage. The return statement has two important uses 1. It causes an immediate exit of the control from the function. That is ,it causes program execution to return to the calling function. 2. It returns the value present in the expression. example: return(x+y); return (6*8); return (3); return;
In this category, there is no data transfer from the calling function to the called function. But, there is data transfer from called function to the calling function. In the above example, observe from the figure 3.6 that the function getQuantity () do not receive any value from the function main ().But, it accepts data from the keyboard, and returns the value to the calling function. // C program to find sum of two numbers using functions with no arguments and return values
#include<stdio.h> int sum (); void main () { int c; clrscr (); c=sum (); /*calling function */ printf (\n The sum = %d, c); getch (); } int sum () { int x, y; printf (\n Enter the values of x and y: ); scanf (%d%d, &x, &y); return x+y; }
Returning Values from Main () When we use a return statement in main (), some program returns a termination code to the calling process (usually to the O.S).The return values must be an integer. For many Operating Systems, a return value of 0 indicates that the program terminated normally. All other values indicate that some error occurred. For this reason, it is good practice to use an explicit return statement. 2. Functions with arguments and no return values: In this category there is data transfer from the calling function to the called function using parameters. But, there is no data transfer from called function to the calling function. Local Variables variables that are defined within a function are called local variables.A local variable comes into existence when the function is entered and is destroyed upon exit. Function arguments The arguments that are supplied in to two categories 1. actual arguments/parameters 2. formal arguments/parameters Actual arguments/parameters Actual parameters are the expressions in the calling functions. These are the parameters present in the calling statement (function call). formal arguments/parameters formal parameters are the variables that are declared in the header of the function definition. These list defines and declares that will contain the data received by the function. These are the value parameters, copies of the values being passed are stored in the called functions memory area. Note: Actual and Formal parameters must match exactly in type, order, and number. Their names however, do not need to match
Figure :Functions with arguments and no return values Observe from the figure that the function printOne () receives one value from the function main (), display the value copy of a. //C program to find sum of two numbers using functions with arguments and no return values
#include<stdio.h> void sum (int ,int ); void main () { int a, b; clrscr (); printf (\n Enter the values of a and b: ); scanf (%d%d, &a, &b); sum (a, b); /*calling function */ getch (); } void sum (int x, int y) { int z; z=x+y; printf (\n The Sum =%d, z); }
3. Functions with arguments and a return value: In this category there is data transfer between the calling function and called function.
Figure :Functions with arguments and return values Observe from the above figure the function sqrt receive one value from the function main (), finds the square of the number and sends the result back to the calling function. //C program to find sum of two numbers using functions with arguments and return values
#include<stdio.h> int sum (int ,int );
void main () { int a, b; clrscr (); printf (\n Enter the values of a and b: ); scanf (%d%d, &a, &b); c=sum (a, b); /*calling function */ printf (\n The Sum =%d, c); getch (); }
Note: Generally we are using functions with arguments and return values (category 4) in our applications. Why because the job of a function is to perform a well-defined task, it carrys inputs
int sum (int x, int y) { int z;
and sends result after executed. In real world the programming teams codes the modules (functions) according to the input (arguments) given by the team coordinators. Passing Parameters to Functions / Parameter Passing Mechanisms: There are two ways of passing parameters to the functions. 1. Call by value 2. Call by reference Call by Value When a function is called with actual parameters, the values of actual parameters are copied into the formal parameters. If the values of the formal parameters changes in the function, the values of the actual parameters are not changed. This way of passing parameters is called call by value (pass by value).
// C program illustrates call by value #include<stdio.h> void swap (int , int ); void main () { int a, b; clrscr (); printf (\n Enter the values of a and b: ); scanf (%d%d, &a, &b); swap (a, b); /*calling function */ printf (\nFrom main The Values of a and b a=%d, b=%d , a, b); } void swap (int x, int y) { int temp; temp=x; x=y; y=temp; printf (\n The Values of a and b after swapping a=%d, b =%d, x, y); } OUTPUT
In the above example, the values of the arguments to swap () 10 and 20 are copied into the parameters x and y.Note that the values of x and y are swaped in the function. But, the values of actual parameters remain same before swap and after swap. Call by Reference Instead of passing the values of the variables to the called function, we pass their addresses, so that the called function can change the values stored in the calling routine. This is known as "call by reference", since we are referencing the variables. Here the addresses of actual arguments in the calling function are copied into formal arguments of the called function. Here The formal parameters should be declared as pointer variables to store the address. The following shows the swap function modified from a "call by value" to a "call by reference". Note that the values are now swapped when the control is returned to main function.
Observe the following points when the program is executed, The address of actual parameters a and b are copied into formal parameters pa and pb. In the function header of swap (), the variables a and b are declared as pointer variables. The values of a and b accessed and changed using pointer variables pa and pb.
Call by Value
Call by Reference
1.When Function is called the values of 1.When a function is called address of variables are passed. variables is passed.
2.Formal parameters contain the value of 2.Formal parameters contain the address of actual parameters. actual parameters. 3.Change of formal parameters in the function 3.The actual parameters are changed since the will not affect the actual parameters in the formal parameters indirectly manipulate the calling function actual parameters 4.Execution is slower since all the values have 4.Execution is faster since only addresses are to be copied into formal parameters. copied.
Nesting of Functions: C permits nesting of functions, main can call function1, which calls function2, which calls function3 .., There is no limit as how deeply functions can be b=nested . consider the following example: In the below example ,when the main() function executes it finds the function call sum(), then the control is transferred from main() to the function sum(),here we are calling the function read(), then the control transferred to read() function, then the body of the function read() executes, the control transferred from read to sum() and once again the same is done for reading some other value. Then the addition is performed this value is carried from sum() to main().Observe the chain of control transfers between the nested functions.
#include<stdio.h> int read (); int sum (int, in t); void main () { int a, b; printf (%d, sum ()); } int sum (int x, int y) { x=read (); y=read (); return x+y; } int read () { int p; printf (\n Enter any value: ); Scanf (%d, &p); return p; }
Although the calling and called functions are two separate entities, they need to communicate to exchange data. The data flow between the calling and called functions can be divided into three strategies:
1. A downward flow from the calling to the called function, 2. An upward flow from the called to the calling function 3. A bidirectional flow from both the directions. Downward flow: Here the calling function sends data to the called function. No data flows in the opposite direction.
Upward flow: This occurs when the called function sends data back to the called function with out receiving any data from it.
Bi-direcitonal flow: This occurs when the calling function sends data down to the called function. During or at the end of its processing, the called function then sends data up to the calling function.
Recursion:
Recursion is a process in which a function calls itself. Example: Recursion() { printf("Recursion !"); Recursion(); } In C, functions can call themselves .A function is recursive if a statement of the function calls the function that contains it. This process is some times called circular definition. Recursion is a repetitive process, where the function calls itself. Concept of recursive function: A recursive function is called to solve a problem The function only knows how to solve the simplest case of the problem. When the simplest case is given as an input, the function will immediately return with an answer. However, if a more complex input is given, a recursive function will divide the problem into 2 pieces: a part that it knows how to solve and another part that it does not know how
to solve. The part that it does not know how to solve resembles the original problem, but of a slightly simpler version. Therefore, the function calls itself to solve this simpler piece of problem that it does now know how to solve. This is what called the recursion step. The statement that solves problem is known as the base case. Every recursive function must have a base case. The rest of the function is known as the general case. The recursion step is done until the problem converges to become the simplest case. This simplest case will be solved by the function which will then return the answer to the previous copy of the function. The sequence of returns will then go all the way up until the original call of the function finally return the result.
Features : There should be at least one if statement used to terminate recursion. It does not contain any looping statements. Advantages : It is easy to use. It represents compact programming structures. Disadvantages : It is slower than that of looping statements because each time function is called.
Example: Recursive factorial function //C program to find the factorial using recursion #include <stdio.h> long factorial (long); void main (void) { int i; i=4; printf (%2d! = %1d\n, i, factorial (i)); } long factorial (long number) {
Output:
4! = 24
if (number ==0) return 1; else return (number * factorial (number-1)); } designing a recursive function: In the above program, once the base condition has reached, the solution begins. The program has found one part of the answer and can return that part to the next more general statement. Thus, after calculating factorial (0) is 1, and then it returns 1.That leads to solve the next general case,
The program now returns the value of factorial (1) to next general case, factorial (2), factorial (2) 2*factorial (1) 2*1 2 As the program solves each general case in turn, the program can solve the next higher general case, until it finally solves the most general case, the original problem. The following are the rules for designing a recursive function: 1. First, determine the base case. 2. Then, determine the general case. 3. Finally, combine the base case and general case in to a function. Difference between Iteration and Recursion
ITERATION Iteration explicitly uses repetition structure. Iteration is terminated when the loop condition fails
RECURSION Recursion achieves repetition by calling the same function repeatedly. Recursion is terminated when base case is satisfied.
May have infinite loop if the loop condition never fails Iterative functions execute much faster and occupy less memory space.
Recursion is infinite if there is no base case or if base case never reaches. Recursive functions are slow and takes a lot of memory space compared to iterative functions
Iteration definition fact (n) =1 =n*(n-1)*(n-2).3*2*1 Recursion definition fact (n) =1 if n=0 if n=0 if n>0
Program : /* Program to demonstrate recursion */. #include <stdio.h> int fact(int x); void main() { int a,f; clrscr(); printf(Enter any integer:); scanf(%d,&a); f=fact(a); printf(The factorial of %d is %d,a,f); } int fact(int x) { if(x==0) return 1; else return(x*fact(x-1)); } Output: Enter any integer:5 The factorial of 5 is 120
Features : There should be at least one if statement used to terminate recursion. It does not contain any looping statements. Advantages : It is easy to use. It represents compact programming structures. Disadvantages : It is slower than that of looping statements because each time function is called.
Standard Functions:
C provides a rich collection of standard functions whose definitions have been written and are ready to be used in our programs. Absolute value function: An absolute value is the positive rendering of the value regardless of its sign. E.g: abs(3) returns 3 Ceiling function: A ceiling is the smallest integral value greater than or equal to a number. E.g: ceil(3.001)=4 Floor function: floor(1.2) returns 1.0 Truncate function: The truncate functions return the integral in the direction of 0. They are the same as the floor function for positive numbers and the same as ceiling function for negative numbers. E.g: trunc(-1.1) returns -1.0 , trunc(1.9) returns 1.0 Round function: The round functions return the nearest integral value. E.g: round(1.9)=2.0 Power function: The power (pow) function returns the value of the raised to the power y. E.g: pow(3.0,4.0) return 81.0 Square root function: The square root functions return the non negative square root of a number. An error occurs if the number is negative. E.g: sqrt(25) returns 5.0 Preprocessor Commands : The C compiler is made of two functional parts: a preprocessor and a translator. The preprocessor is a program which processes the source code before it passes through the compiler. The translator converts the C statements into machine code that in places in an object module. Compilation
Source Program
Preproc-essor
Translation unit
Translator
Object code
The preprocessor is a collection of special statements called commands or preprocessor directives. Each directive is examined by the preprocessor before the source program passes through the compiler. Statements beginning with # are considered preprocessor directives. Preprocessor directives indicate certain things to be done to the program code prior to compilation. It includes certain other files when compiling, replace some code by other code. Only white space characters before directives on a line. Preprocessor commands can be placed anywhere in the program. There are three major tasks of a preprocessor directive 1. Inclusion of other files (file inclusion) 2. Definition of symbolic constants and macros(macro definition) 3. Conditional compilation of program code/Conditional execution of preprocessor directives File Inclusion: The first job of a preprocessor is file inclusion ,the copying of one or more files into programs. The files are usually header files and external files containing functions and data declarations. General form is, #include filename it has two different forms 1. #include <filename> it is used to direct the preprocessor to include header files from the system library. in this format , the name of the header file is enclosed in pointed brackets. Searches standard library only for inclusion of a file. example #include<stdio.h> In the above example ,the preprocessor directive statements searches for content of entire code of the header file stdio.h in the standard library ,if it finds there includes the contents of the entire code at the place where the statement is in the source program before the source program passes through the compiler.
Note : here we cant include user files why because it searches for the files in the standard library only. 2. #include filename it is used to direct the preprocessor look for the files in the current working directory, standard library Use for inclusion of user-defined files, also includes standard library files. Searches current directory, then standard library for the inclusion of a file. in this format , the name of the file is enclosed in double quotes. we can also include macros. The included file or the program either may contain main() function but not the both. Example #include header.h In the above example ,the preprocessor directive statement directs the preprocessor to include content of entire code of the file header.h which is in the current directory at the place where the statement is in the source program before the source program passes through the compiler. note : We can also include file that is not present in the current directory by specifying the complete path of the file like #include e:\muc.h //C Program illustrates file inclusion
In the above example the file mac.h is stored in E: Drive of the computer. After finding the include command by the preprocessor the contents of the file are copied in to the program then send for the compilation. Macro Definition: A macro definition command associates a name with a sequence of tokens. The name is called the macro name and the tokens are referred to as the macro body. The following syntax is used to define a macro: #define macro_name(<arg_list>) macro_body #define is a define directive, macro_name is a valid C identifier.macro_body is used to specify how the name is replaced in the program before it is compiled. Example #define CIRCLE_AREA( x ) ( PI * ( x ) * ( x ) ) would cause area = CIRCLE_AREA( 4 ); to become area = ( 3.14159 * ( 4 ) * ( 4 ) ); Use parenthesis for coding macro_body,Without them the macro #define CIRCLE_AREA( x ) PI * ( x ) * ( x ) would cause area = CIRCLE_AREA( c + 2 ); to become area = 3.14159 * c + 2 * c + 2; We can also supply Multiple arguments like #define RECTANGLE_AREA( x, y ) ( ( x ) * ( y ) ) would cause rectArea = RECTANGLE_AREA( a + 4, b + 7 ); to become rectArea = ( ( a + 4 ) * ( b + 7 ) );
macro must be coded on a single line. we can use backslash(\) followed immediately by a new line to code macro in multiple lines. Performs a text substitution no data type checking. W need to carefully code the macro body .Whenever a macro call is encounter ,the preprocessor replaces the call with the macro body. If body is not created carefully it may create an error or undesired result. For example the macro definition #define Mac =0 .. a=Mac; . will result in num==0; This is unwanted.
//C program Illustrating usage of Macro #include<stdio.h> #define square(x) (x*x) int main() { int a=10; printf("\nThe square of %d=%d",a,square(a)); return 0 ; } OUTPUT The square of 10=100
Symbolic Constants: Macro definition without arguments is referred as a constant. The body of the macro definition can be any constant value including integer, float, double, character, or string. However, character constants must be enclosed in single quotes and string constants in double quotes.
Example #define PI 3.14159 Here PI replaces with "3.14159" Nested Macros It is possible to nest macros. C handles nested macros by simply rescanning a line after macro expansion. Therefore, if an expansion results in a new statement with a macro ,the second macro will be properly expanded. For example, #define sqre(a) (a*a) #define cube(a) (sqre(a)*a) The expansion of x=cube(4); results in the following expansion: x=(sqre(4)*4); this after rescanning becomes x=((4*4)*4); Undefining Macros: Once defined, a macro command cannot be redefined. Any attempt to redefine it will result in a compilation error. However, it is possible to redefine a macro by first undefining it, using the #undef command and the defining it again. Example #define Val 30 #undef Val
#define val 50
Predefined Macros: C language provides several predefined macros .these macros cannot be undefined using the undef command. Some of the predefined macros are Meaning Command __DATE__ Provides a string constant in the form mm dd yyyy containing the date of translation.
__FILE__
Provides a string constant in the form hh:mm:ss containing the time of the translation. __TIME__ Provides an integer constant containing the current statement number in the source file. __LINE__ Table :List of Predefined Macros in C //C program Demonstrating Predefined macros
String Converting Operator(#): It is a macro operation Causes a replacement text token to be converted to a string surrounded by quotes. The statement #define HELLO( x ) printf( Hello, #x \n ); would cause HELLO( John ) to become printf( Hello, John \n ); Strings separated by whitespace are concatenated when using printf statement. The Defined Operator The defined operator can be used only in a conditional compilation . It can be used in macros. The value of defined(macro-name) is o if the name is not defined and 1 if it is defined.
For example, after #define val 24 the value of defined(val) is 1 and the value of !defined(val) is 0.
Conditional Compilation Commands: It allows us to control the compilation process by including or excluding statements. Cast expressions, size of, enumeration constants cannot be evaluated in preprocessor directives. Its structure similar to if statement. Syntax #if expression1 code to be included for true
#elif expression2 code to be included for true #else code to be included false #endif Example, #if !defined( NULL ) #define NULL 0 #endif
Determines if symbolic constant NULL has been defined If NULL is defined, defined( NULL ) evaluates to 1,If NULL is not defined, and this function defines NULL to be 0. Every #if must end with #endif. #ifdef short for #if defined( name ). #ifndef short for #if !defined( name ). Command #if expression Meaning When expression is true, the code that follows is included for compilation.
#endif
#else
#elif
#ifdef name Tests whether macro is not defined . #ifndef name Table : Conditional Compilation Commands
Storage Classes:
A storage class defines the scope (visibility) and life time of variables and/or functions within a C Program. Scope: The scope of variable determines over what region of the program a variable is actually available for use. Visibility: The programs ability to access a variable from the memory. Lifetime: Life time refers to the period during which a variable retains a given value during the execution of a program. Scope rules: 1. The scope of a global variable is the entire program file. 2. The scope of a local variable begins at point of declaration and ends at the end of the block or function in which it is declared.\ 3. The scope of a formal function argument is its own function.
4. The life time of an auto variable declared in main is the entire program execution time, although its scope is only the main function. 5. The life of an auto variable declared in a function ends when the function is exited. 6. All variables have visibility in their scope , provided they are not declared again. 7. A variable is re declared within its scope again, it loses its visibility in the scope of the re declared variable. These are following storage classes which can be used in a C Program: auto register static extern auto - Storage Class: auto is the default storage class for all local variables and the local variable is known only to the function in which it is declared. If the value is not assigned to the variable of type auto the default value is garbage value. Syntax : auto [data_type] [variable_name]; Example : auto int a; Program : /* Program to demonstrate automatic storage class.*/ #include <stdio.h> #include <conio.h> void main() { auto int i=10; clrscr(); { auto int i=20; printf("\n\t %d",i); } printf("\n\n\t %d",i); getch(); } Output : 20 10
register - Storage Class: Register is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and cant have the unary '&' operator applied to it (as it does not have a memory location). If the value is not assigned to the variable of type register the default value is garbage value. Syntax : register [data_type] [variable_name]; Example : register int a; When the calculations are done in CPU, the value of variables are transferred from main memory to CPU. Calculations are done and the final result is sent back to main memory. This leads to slowing down of processes. Register variables occur in CPU and value of that register variable is stored in a register within that CPU. Thus, it increases the resultant speed of operations. There is no waste of time, getting variables from memory and sending it to back again.It is not applicable for arrays, structures or pointers.It cannot be used with static or external storage class. Program : /* Program to demonstrate register storage class.*/ #include <stdio.h> #include <conio.h> void main() { register int i=10; clrscr(); { register int i=20; printf("\n\t %d",i); } printf("\n\n\t %d",i); getch(); } Output : 20 10 static - Storage Class: static is the default storage class for global variables. As the name suggests the value of static variables persists until the end of the program.Static can also be defined within a function. If this is done the variable is initalised at run time but is not reinitalized when the function is called.
This inside a function static variable retains its value during vairous calls. If the value is not assigned to the variable of type static the default value is zero. Syntax : static [data_type] [variable_name]; Example : static int a; There are two types of static variables: a) Local Static Variable b) Global Static Variable Static storage class can be used only if we want the value of a variable to persist between different function calls. Program : /* Program to demonstrate static storage class. */ #include <stdio.h> #include <conio.h> void main() { int i; void incre(void); clrscr(); for (i=0; i<3; i++) incre(); getch(); } void incre(void) { int avar=1; static int svar=1; avar++; svar++; printf("\n\n Automatic variable value : %d",avar); printf("\t Static variable value : %d",svar); } Output : Automatic variable value : 2 Static variable value : 2 Automatic variable value : 2 Static variable value : 3 Automatic variable value : 2 Static variable value : 4 extern - Storage Class: Variables that are both alive and active throughout the entire program are known as external variables. extern is used to give a reference of a global variable that is visible to all the program files. If the value is not assigned to the variable of type static the default value is zero. Syntax : extern [data_type] [variable_name];
Example : extern int a; 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. Program : /* Program to demonstrate external storage class.*/ #include <stdio.h> #include <conio.h> extern int i=10; void main() { int i=20; void show(void); clrscr(); printf("\n\t %d",i); show(); getch(); } void show(void) { printf("\n\n\t %d",i); } Output : 20 10 Class auto register static(extern) static(linkage) extern Scope block block block file file Extent automatic automatic static static static Linkage internal internal internal internal external Initial Value indeterminate indeterminate Zero Zero indeterminate
Type qualifiers: The type qualifier adds three special attributes to types: constant , volatile and restrict. Constants: The keyword for the constant type qualifier is const. A constant object must be initialized when it is declared because it cannot be changed later. A simple constant is shown below: const double PI=3.1415926
Volatile: The volatile qualifier tells the computer that an object value may be changed by entities other than this program. volatile int x; Restricted: The restrict qualifier which is used only with pointers, indicates that the pointer is only the initial way to access the dereferenced data. restrict int *ptr;
ARRAYS:
In C a variable of a particular data type is declared using the required primary data type. For instance to represent the marks of a student in different (say 6) subjects it requires 6 same data type variables. int marks1,marks2,marks3,marks4,marks5,marks6; An array can be defined as group of related data items that have same common data type. For example to represent above 6 subject marks use arrays as int marks[6]; In above example marks is a variable of int data type, with 6 elements, where each can be used as marks[0],marks[1],marks[2],marks[3],marks[4],marks[5]. In arrays the value in set brackets ([]) is called index number or subscript. The index starts from 0 to n-1 if n is given in brackets.
It is little complex to access, if number of subjects gets increased. To overcome this problem in C language there is a derived data type called arrays.
Introduction: Often we need many different variables that are of the same type and play a similar role in the program For example, suppose we have a temperature reading for each day of the year and need to manipulate these values several times within a program. With simple variables, o We would need to declare 365 variables. o We would not be able to loop over these variables. An array is a numbered collection of variables of the same type. An array is a homogeneous collection of data. The variables in an array share the same name and are distinguished from one another by their numbers or subscripts. We can loop through the variables of an array by using a variable for the subscript. The subscripts are always 0,1,, size-1 Array Characteristics: An array represents a group of related data. An array has two distinct characteristics: An array is ordered: data is grouped sequentially. In other words, here is element 0, element 1, etc.
An array is homogenous: every value within the array must share the same data type. In other words, an int array can only hold ints, not doubles. Definition: An array is a collective name given to a group of similar elements. These similar elements could be all integers or all floats or all characters etc. Usually, the array of characters is called a string, where as an array of integers or floats is called simply an array. All elements of any given array must be of the same type i.e we cant have an array of 10 numbers, of which 5 are ints and 5 are floats. Declaration of an Array: Arrays must be declared before they can be used in the program. Standard array declaration is as: type variable_name[lengthofarray]; Here type specifies the variable type of the element which is going to be stored in the array. Ex:double height[10]; float width[20]; In C Language, array starts at position 0. The elements of the array occupy adjacent locations in memory. C Language treats the name of the array as if it was a pointer to the first element This is important in understanding how to do arithmetic with arrays. Any item in the array can be accessed through its index, and it can be accesed any where from with in the program. So m=height[0]; variable m will have the value of first item of array height. Initializing Arrays: The following is an example which declares and initializes an array of nine elements of type int. Array can also be initialized after declaration. int scores[9]={23,45,12,67,95,45,56,34,83};
One-dimensional Arrays: A list of items can be given one variable name using only one subscript and such a variable is called single-subscripted variable or a one-dimensional array. Declaration of arrays: The array variable declaration can be given as type variable-name [size]; The type specifies the data type of the elements contained in the array. For example, int var1[10]; char var2[5]; //var2 is a character array and also called as string. Initialization of arrays: The initialization of elements of arrays can be done same as ordinary variables. The general form is type variable-name[size] = {list of values}; For example, Int var1[5] = {1,2,3,4,5};
Eg. Copy one array into another: There is no such statement in C language which can directly copy an array into another array. So we have to copy each item separately into another array. The following program illustrates the copying of elements of one array to another array: #include <stdio.h> int main() { int iMarks[4]; short newMarks[4]; iMarks[0]=78; iMarks[1]=64; iMarks[2]=66; iMarks[3]=74; for(i=0; i<4; i++) newMarks[i]=iMarks[i]; for(j=0; j<4; j++) printf("%d\n", newMarks[j]); return 0; } To summarize, arrays provide a simple mechanism where more than one elements of same type are to be used. We can maintain, manipulate and store multiple elements of same type in one array variable and access them through index.
Two dimensional Arrays: C allows us to define the table of items by using two dimensional arrays.
Figure:Two-dimensional Array representation In one-dimensional array all subjects marks of a student can be stored in using one variable. For instance to save n students m subjects marks it requires n one dimensional arrays. But this can be achieved in C language using two-dimensional arrays. Declaration of two-dimensional arrays: The two-dimensional array variable declaration can be given as type variable-name [row-size][column-size]; The type specifies the data type of the elements contained in the array. For example, int var1[5][10]; char var2[2][5]; Initialization of two-dimensional arrays: The initialization of elements of twodimensional arrays can be done same as ordinary variables. The general form is type variable-name[size] = {list of values}; For example, int var1[2][5] = { {9,8,7,6,5} , {1,2,3,4,5} }; main ( ) { int stud [4] [2]; int i, j; for (i =0; i < =3; i ++) { printf ("\n Enter roll no. and marks"); scanf ("%d%d", &stud [i] [0], &stud [i] [1] ); } for (i = 0; i < = 3; i ++) printf ("\n %d %d", stud [i] [0], stud [i] [1]): }
the graphical representation of a two-dimensional array in memory is: byte=size of 1st index * size of 2nd index * size of (index base type) for eg., assuming 2byte integers as integer with dimension 4,3 would have 4*3*2=24 bytes. Multidimensional Arrays: C allows arrays of three or more dimensions. The general form of multidimensional array is type array_name[s1][s2]..[s3]; where si is the size of ith dimension.. Ex: int a[10][3][2]; survey is a 3 dimensional array.
Inter function communication: a) Functions With Arrays / Passing arrays through functions: Like the values of simple variables, it is also possible to pass the values of an array to a function. To pass an array to a called function, it is sufficient to list the name of the array, without any subscripts and the size of the array as arguments. Ex: largest(a,n); will pass all the elements contained in the array a of size n. The called function expecting this call must be appropriately defined. Example program: main() { float largest(); static float value[4]={10,-4,2,-3}; printf(%f,largest(value,4)); } float largest(a,n) float a[]; int n; { int i; float max; max=a[0];
for(i=1;i<n;i++) if(max<a[i]) max=a[i]; return(max); } To process arrays in a large program, we have to be able to pass them to functions. We can pass arrays in two ways: pass individual elements or pass the whole array. b) Array of Strings: Consider, for example, the need to store the days of the week in their textual format. We could create a two-dimensional array of seven days by ten characters, but this wastes space Program to print Days of the Week
Array applications: There are two array applications: frequency arrays ,histograms and Random Number Permutations. A frequency array shows the number of elements with an identical value found in a series of numbers. A histogram is a pictorial representation of a frequency array. Instead of printing the values of the elements to show the frequency of each number, we print a histogram in the form of a bar chart.
Shubham Bhavatu