0% found this document useful (0 votes)
42 views27 pages

1) Data Types in C: CSE102-DSA Unit-I

The document discusses various C data types and data structures. It covers fundamental C data types like char, int, float, and double. It also discusses type qualifiers, user-defined functions including function declaration, definition, and call. Data structures covered include arrays, structures, and pointers. Arrays and structures can be passed as parameters to functions. Examples are provided to demonstrate passing simple variables, arrays, and structures by value and reference to functions.

Uploaded by

Prateek Sharma
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views27 pages

1) Data Types in C: CSE102-DSA Unit-I

The document discusses various C data types and data structures. It covers fundamental C data types like char, int, float, and double. It also discusses type qualifiers, user-defined functions including function declaration, definition, and call. Data structures covered include arrays, structures, and pointers. Arrays and structures can be passed as parameters to functions. Examples are provided to demonstrate passing simple variables, arrays, and structures by value and reference to functions.

Uploaded by

Prateek Sharma
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

CSE102- DSA UNIT-I 1) Data types in C

C offers a standard, minimal set of basic data types. Sometimes these are called "primitive" types. A lot of complex data structures can be developed from these basic data types. The C language defines four fundamental data types: character integer floating-point and double floating-point This data types are declared using the keywords char, int, float and double respectively. Typical memory requirements of the basic data types are given below

The size and range of these data types may vary among processor types and compilers. Data type qualifiers modify the behavior of variable type to which they are applied. Data type qualifiers can be classified into two types. 1. size qualifiers 2. sign qualifiers Size qualifiers: Size qualifiers alter the size of the basic data types. There are two size qualifiers that can be applied to integer: short and long. The minimum size of short int is 16 bit. The size of int must be greater than or equal to that of a short int. The size of long int must be greater than or equal to a short int. The minimum size of a long int is 32 bits.

Prepared by MNU, SCSE, VIT

Sign qualifiers: The keywords signed and unsigned are the two sign qualifiers that specify whether a variable can hold both ve and +ve numbers, or only +ve numbers. These qualifiers can be applied to the data types int and char only. Example: unsigned int i; The following table shows all valid data type combinations supported by C, along with their minimal ranges and typical memory size.

2) Components of user-defined functions


Let us assume that we are presently interested in first 3 categories of functions as above. Every user-defined function should have the following three components. i) function declaration or function prototype The purpose of it is to specify all information about the function to compiler. Its form/syntax is as below returntype function-name(list of arguments separated by commas along with data types) ii) function call The purpose of it is to invoke the function. Its syntax is as below function-name(arguments separated by commas) function definition The purpose is to specify the actual task of the function.

iii)

Prepared by MNU, SCSE, VIT

It will have two parts i) function header and ii) function body Its syntax is as below.

returntype function-name(list of arguments with their data types separated by commas) // Function Header { Program statements; // Function Body }

4) Data Structures in C
i) ii) iii) iv) Simple Variable containing single value Array Group Variable containing data items of same data type Structure Group Variable containing data items of different data type Pointer Special type of variable that contains address of another variable

5) Simple Variable
i) Definition: An identifier that stores single value. The value may change during the program ii) Declaration datatype variablename1, variablename2; iii) Initialization: datatype variablename1=value1, variabalename2=value2; iv) Assigning value to a variable Variablename1=value1; v) Passing simple variable as argument to function It is possible in the following two ways. a) call-by-value b) call-by-reference vi) The following example illustrates call-by-value and call-by-reference concepts a) CALL BY VALUE EXAMPLE #include<stdio.h> void main(){ int a, b=2; void modify(int , int); printf(Enter the value of a\n); scanf(%d,&a);

/* Function declaration */

Prepared by MNU, SCSE, VIT

printf( The value of a=%d and b=%d before function call\n, a , b); modify(a,b); /* Function call by call-by-value method A copy of variables a and b are passed to its function definition and arguments in the function call are called Actual arguments */ printf( The value of a=%d and b=%d after function call\n, a, b); system(pause); } void modify( int a, int b) /* Function definition and arguments in it are called Formal arguments */

{ a=a+2; b=b-1; printf(The value of a=%d and b=%d with in function definition, a, b); } Input/Output: Enter the value of a 7 The value of a=7 and b=2 before function call The value of a=9 and b=1 with in function definition The value of a=7 and b=2 after function call b) CALL BY REFERENCE EXAMPLE a) CALL BY VALUE EXAMPLE #include<stdio.h> void main(){ int a, b=2; void modify(int * , int *);

/* Function declaration and * in the declaration specifies that the variable is pointer type */

printf(Enter the value of a\n); scanf(%d,&a); printf( The value of a=%d and b=%d before function call\n, a , b); modify(&a,&b); /* Function call by call-by-reference

Prepared by MNU, SCSE, VIT

Addresses of variables a and b are passed to its function definition and arguments in the function call are called Actual arguments */ printf( The value of a=%d and b=%d after function call\n, a, b); system(pause); } void modify( int *a, int *b) /* Function definition and symbol * specifies the variables as pointer type and arguments in it are called Formal arguments */

{ *a = *a + 2; / * Symbol * in these two statements *b = *b - 1; means value at address */ printf(The value of a=%d and b=%d with in function definition, a, b); }

Input/Output: Enter the value of a 7 The value of a=7 and b=2 before function call The value of a=9 and b=1 with in function definition The value of a=9 and b=1 after function call

6) Array
Definition: An identifier that represents group of data items of same data type. Types: There are 3 types of array. They are i) ii) iii) 1D Array 2D Array Multi-dimensional Array (MD Array)

For each of the array type you have to recollect the topics, namely, i) Declaration ii) Initialization iii) Assigning values to the elements of an array iv) Displaying values of elements of an array and so on. Also recollect the problems done on arrays in subject CSE101 of semester I iv) Passing 1D array as one of the parameters to a function Let us discuss this with the following example. Making a program to find the biggest element of an 1D array using function biggest

Prepared by MNU, SCSE, VIT

#include<stdio.h> void biggest(int a[10], int ); void main() { int a[10],i,n; printf(Enter size of an array\n); scanf(%d,&n); printf(Enter the elements of an array\n); for(i=0;i<n;i++) scanf(%d,a[i]); biggest(a,n); system(pause); } void biggest(int x[10],int m) { int i,big=0; for(i=0;i<m;i++) if(big<a[i]) big=a[i]; printf(The biggest element of an array is %d\n,big); } Some more programs: i) Reverse the array by passing array variable as parameter to function reverse() ii) Sort array of elements by passing array variable as parameter to function sort() iii) Search for a particular element in an array by passing array variable as parameter to function search() Passing 2D array as one of the parameters to a function Let us discuss this with the following example. Making a program to display the elements of an 2D array using function display #include<stdio.h> void display(int a[10][10], int, int); void main(){ int a[10][10],i,j,m,n; printf(Enter size of a matrix\n); scanf(%d%d,&m,&n); printf(Enter elements of an array\n); for(i=0;i<m;i++) for(j=0;j<n;j++) v)

Prepared by MNU, SCSE, VIT

scanf(%d,&a[i][j]); display(a,m,n); system(pause); } void display(int x[10][10], int m, int n) { int i,j; printf(The matrix is\n); for(i=0;i<m;i++){ for(j=0;j<n;j++) printf(%d ,a[i][j]); printf(\n);} } Some more programs: i) Find the transpose of a matrix by passing 2D array variable as parameter to function transpose() ii) Find the addition / subtraction of two matrices by passing 2D array variables as parameter to function addition() / subtraction() iii) Find the trace of a matrix by passing 2D array variable as parameter to function trace()

7) Structure
Definition: It is a concept that groups data items of different data types. Each data item of structure is also known as member of a structure. To make use of structure in programs we have to do three things, namely, structure template definition, structure variable declaration and accessing members of a structure using dot operator. Types: The following is the list of different types of structure i) Array of structure ii) Nested structure iii) Self referential structure Recollect the programs done on structure in subject CSE101 of semester I iv) Passing simple structure variable as one of the parameters of the function This is explained by the following program Making a program to display the total cost of product of a structure product with fields pname, price and quantity using function total_cost() #include<stdio.h> struct product { char pname[20]; int price;

Prepared by MNU, SCSE, VIT

int quantity; }; void total_cost(struct product); void main() { struct product prod; printf("Enter product name\n"); scanf("%s",prod.pname); printf("Enter price of a product\n"); scanf("%d",&prod.price); printf("Enter quantity of a product\n"); scanf("%d",&prod.quantity); total_cost(prod); system("pause"); } void total_cost(struct product p1) { printf("Product name=%s\n",p1.pname); printf("Product price=%d\n",p1.price); printf("Product quantity=%d\n",p1.quantity); printf("product total-cost=%d\n",p1.price*p1.quantity); } Passing array of structure variable as one of the parameters of the function This is explained by the following program #include<stdio.h> struct product{ char pname[20]; int price; int quantity; }; void total_cost(struct product p[10],int ); void main() { struct product prod[10]; int i,n; printf("Enter number of products\n"); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter product name\n"); scanf("%s",prod[i].pname); printf("Enter price of a product\n"); v)

Prepared by MNU, SCSE, VIT

scanf("%d",&prod[i].price); printf("Enter quantity of a product\n"); scanf("%d",&prod[i].quantity); } total_cost(prod , n); system("pause"); } void total_cost(struct product p1[10], int m) { int i; for(i=0;i<m;i++) { printf("Product name=%s\n",p1[i].pname); printf("Product price=%d\n",p1[i].price); printf("Product quantity=%d\n",p1[i].quantity); printf("prod total-cost=%d\n",p1[i].price*p1[i].quantity); } }

8) Unions (Recollect this topic studied in semester I) 9) Structures Vs Unions (or) Comparisons between structure and union (Recollect this topic too studied in semester I) 10) Pointers
Definition: Pointer is a derived data type. Another name to this concept is Aliasing. Pointer is a variable that contains the address of another variable. It serves as another name to the variable that it points to. i) Syntax for declaration of a pointer variable datatype *prointer_variable; Examples: int *p1; char *p2; float *p3; Note: In declaration statement pointer variable can be distinguished from other variables by * preceding to it. ii) syntax for initialization of a pointer variable

Prepared by MNU, SCSE, VIT

datatype *pointer_variable=address of another variable;

Examples: int a, *p1=&a, b[10], *p2=b; char ch, *p3=&ch; float f, *p4=&f; iii) Operators in pointers There are two operators in pointers. They are a) address operator denoted by & b) indirection or value at address operator denote by * iv) Chain of pointers The pointer variable p2 contains the address of the pointer variable p1, which points a variable a whose content is 5. Such a concept is known as chain of pointers Example: Variable is a and its content is 5 p1 is a pointer pointing to the location of a and p2 is another pointer pointing to the pointer variable p1 Then *p1 gives content of a i.e., 5 **p2 also gives content of a i.e., 5 as == > == > *(*&p1) *p1 which denotes the content of a i.e., 5

v) Pointer Expressions: Let us assume that p is pointer variable pointing to a variable of some data type. a) We can use increment / decrement operator with this pointer variable but the increment or decrement is done based on scale of factor of data type of a variable that the pointer points to. In 32 bit environment scale factors for various data types are as below char int float double 2 bytes 4 bytes 8 bytes 16 bytes

Suppose p is a pointer to variable a of int type and its address is assumed as 2110

Prepared by MNU, SCSE, VIT

10

Then p++ (or) ++p 2110-4=2006;

will give 2110+4 = 2114 ; (or)

p--

(or) -- p will give

b)

Note the following expressions

Let us assume that p1 and p2 are two pointer variables i) ii) iii) iv) v) vi) vii) viii) ix) x) p1 + p2 is invalid p1 * p2 is invalid p1 / p2 is invalid p1 2, p1 +2 are valid p1 * 2, p1/ 2 are invalid p1 p2 is valid if both points to the same array and p1 points to last location and p2 points to first location of the array With p1 and p2 we can use all relational operators provided if they point to same variable (atomic or composite) *p1 + *p2 is valid *p1 - *p2 is valid *p1/*p2 is invalid as /* can be treated of starting of comment. The right way to write this expression is as below *p1 / *p2 *p1 * *p2 is valid

xi)

vi) Pointer and arrays i) Pointer to 1D array The usage of pointer to 1D array is illustrated by the following example #include<stdio.h> void biggest(int *p, int); void main() { int a[10],i,n,*p1; p1=a; printf("Enter number of elements in an array\n"); scanf("%d",&n); printf("Enter %d elements into an array\n",n); for(i=0;i<n;i++) scanf("%d",p1+i); printf("Array elements\n") ; for(i=0;i<n;i++) printf("%d\n",*(p1+i)); biggest(p1,n); system("pause");

Prepared by MNU, SCSE, VIT

11

void biggest(int *p, int n) { int i,big; big=0; for(i=0;i<n;i++) if(big < *(p+i)) big=*(p+i); printf("The biggest element in an array is %d\n",big); }

ii) Pointer to 2D array The usage of pointer to 2D array is illustrated by the following example #include<stdio.h> void display(int *p, int, int); void main() { int a[10][10],i,j,r,c,*p2; p2=a; printf("Enter number of rows of a matrix\n"); scanf("%d",&r); printf("Enter number of columns of a matrix\n"); scanf("%d",&c); printf("Enter a matrix\n"); for(i=0;i<r;i++) for(j=0;j<c;j++) scanf("%d",(p2+i*c+j)); display(p2,r,c); system("pause"); } void display(int *p,int m, int n) { int i,j; printf("The matrix is\n"); for(i=0;i<m;i++) { for(j=0;j<n;j++)

Prepared by MNU, SCSE, VIT

12

printf("%d ",*(p+i*n+j)); printf("\n"); } } NOTE: Given that p2 is a pointer to a[10][10] i.e., p2=a Let us assume that actual number of rows and columns of the matrix a is m and n. i.e., number of rows in a is m and number of columns in a is n Then note the following statements 1) (p2+i *n +j) denotes location of (i,j)th cell where n denotes number of columns, i denotes row number and j denotes column number *(p2+i *n+j) denotes the content of (i,j)th cell where n denotes number of columns, i denotes row number and j denotes column number 2) The above two statements can be rewritten in the following equivalent form *(p2+i) +j denotes the location of (I,j)th cell where i denotes row number and j denotes the column number *(*(p2+i) + j) denotes the content of (i.j)th cell where i denote row number and j denotes the column number vii) Pointers and structures i) Pointer to simple structure The usage of pointer to simple structure is illustrated by the following example #include<stdio.h> struct product{ char pname[20]; int price; int quantity; }; void total_cost(struct product *p); void main() { struct product prod,*p; int i,n; p=&prod; printf("Enter product name\n"); scanf("%s",p->pname); printf("Enter price of a product\n"); scanf("%d",&p->price); printf("Enter quantity of a product\n");

Prepared by MNU, SCSE, VIT

13

scanf("%d",&p->quantity); total_cost(p); system("pause"); } void total_cost(struct product *ptr) { printf("Product name=%s\n",ptr->pname); printf("Product price=%d\n",ptr->price); printf("Product quantity=%d\n",ptr->quantity); printf("product total_cost=%d\n",ptr->price*ptr->quantity); }

NOTE : pointer-to-structure -> membername is equivalent to (*pointer-to-structure). membername Some more programs: 2) Write a program to display total amount to be paid by the customer as electricity charge by passing pointer to a structure electricity with fields, namely, meterno, cname, units as parameter to function total_chagre()

3) Write a program to display display grade of a student by passing pointer to a structure student with fields, namely, regno, name, m1, m2, m3, m4, m5 as parameter to function grade() ii) Pointer to array of structure The usage of pointer to an array of structure is illustrated by the following example #include<stdio.h> struct product{ char pname[20]; int price; int quantity; }; void total_cost(struct product *p); void main() { struct product prod[10],*p; int i,n; printf("Enter number of products\n"); scanf("%d",&n);

Prepared by MNU, SCSE, VIT

14

for(p=prod;p<prod+n;p++) { printf("Enter product name\n"); scanf("%s",p->pname); printf("Enter price of a product\n"); scanf("%d",&p->price); printf("Enter quantity of a product\n"); scanf("%d",&p->quantity); total_cost(p); } system("pause"); }

void total_cost(struct product *ptr){ printf("Product name=%s\n",ptr->pname); printf("Product price=%d\n",ptr->price); printf("Product quantity=%d\n",ptr->quantity); printf("product total-cost=%d\n",ptr->price*ptr->quantity); } Some more programs : 2) Write a program to display total amount to be paid by the customer as electricity charge by passing pointer to an array of structure electricity with fields, namely, meterno, cname, units as parameter to function total_chagre() 3) Write a program to display display grade of a student by passing pointer to an array of structure student with fields, namely, regno, name, m1, m2, m3, m4, m5 as parameter to function grade() viii) Pointers and strings i) Pointer to 1D Strings This is illustrated by the following examples. Example1: Make a program to print all characters of a string in reverse order by using pointer to the string #include<stdio.h> #include<string.h> void main() { char uni[15]="VIT UNIVERSITY",*sptr; strrev(uni);

Prepared by MNU, SCSE, VIT

15

sptr=uni; printf("The reverse of the string displayed character by character manner \n"); while(*sptr !='\0'){ printf("%c",*sptr); getch(); sptr++; } system("pause"); } Some more programs : Example 2: Make a program to print length of a string by using pointer to the string #include<stdio.h> void main() { char name[15]="VIT UNIVERSITY",*sptr; int length; sptr=name; while(*sptr !='\0') sptr++; length=sptr-name; printf("The length of string %s is %d\n", name, length); system("pause"); } Example 3: Make a program to find whether the read string is palindrome or not using pointer to a string #include<stdio.h> #include<string.h> void palindrome(char *p); void main() { char str1[20],*sptr; printf("Enter the string\n"); gets(str1); sptr=str1; palindrome(sptr); system("pause"); }

Prepared by MNU, SCSE, VIT

16

void palindrome(char *p) { char rstr[20]; strcpy(rstr,p); strrev(rstr); if(strcmp(rstr,p)==0) printf("%s is a palindrom\n",p); else printf("%s is not a palindrome\n",p); } ii) Pointers to 2D strings (Array of pointers) This concept is also known as array of pointers. This results in ragged arrays concept which saves space. Ragged array is an array that stores string of variable lengths as it is. The following example illustrates it. #include<stdio.h> void main() { char *name[5]={"VIT","BITS","IIT","Anna","Osmania"}; int i; printf("Display list of university names\n"); for(i=0;i<5;i++) printf("%s\n",name[i]); system("pause"); } ix) Passing pointer variables as parameters to function In all previous programs we did this x) Functions returning pointers This is illustrated by the following program #inlcude<stdio.h> int *bigger(int *, int *); void main(){ int x=20,y=15; int *z ;

Prepared by MNU, SCSE, VIT

17

z=bigger(&x,&y) ; printf(Largest value is %d\n,*z); system(pause); } int *bigger(int *p, int *q){ If(*p < *q) return(p); else return(q); } xi) Advantages of Pointers: 2) Pointer supports dynamic memory allocation which avoids memory wastage 3) Make operations on linked list, linked stack, linked queue, linked priority queue, trees, and graphs so simple and flexible.

11) Dynamic memory allocation


Most often we face situations in programming where the data is dynamic in nature. That is, the number of data items keep changing either growing or shrinking during execution of the program. This may lead to either wastage or shortage of memory. Such situations can be handled more easily and effectively by using a concept called dynamic memory allocation Dynamic memory allocation can be done using the following functions. i) malloc() ii) calloc() iii) realloc() and iv) free() The memory that gets allocated to variables when we use these functions is known as heap. If memory from heap is allocated to a variable it has to be deallocted explicitly by the user once the job is done. Otherwise the variable remains for ever causing heap wastage. Let us see the syntax of each of the above functions one by one as below i)Syntax of malloc() ptr = ( data type * ) malloc (byte_size); where ptr is a pointer containing starting address of the block. Through malloc() single block of byte_size memory gets allocated to a variable pointed out by pointer ptr.

ii) Syntax of calloc() ptr = ( data type * ) calloc ( n * byte_size); where ptr is a pointer containing starting address of the block. Through calloc() n blocks each of byte_size memory gets

Prepared by MNU, SCSE, VIT

18

allocated to a variable pointed out by pointer ptr.

iii) Syntax of realloc() It is likely that we discover later, the previously allocated memory is not sufficient and we need additional space for more elements. It is also possible that the memory allocated is much larger than necessary and we want to reduce it. In both the cases, we can change the memory size already allocated with the help of the function realloc(). This process is called the reallocation of memory. For example, if the original allocation is done by the statement ptr = (data type *) malloc(byte_size); then reallocation of space may be done by the statement ptr = realloc(ptr, new_byte_size); This function allocates a new memory space of size new_byte_size to the pointer variable ptr and returns a pointer to the first byte of the new memory block. The new_byte_size may be larger or smaller than the old_byte_size. Remember the new memory block may or may not begin at the same place as the old one. iv) Syntax of free() When we no longer need the data stored in a block of memory, and we do not intend to use that block for storing any other information, we may release that block of memory for future use, using the function free() free(ptr); ptr is a pointer to a memory block which has already been created by malloc() or calloc(). Use of an invalid pointer in the call may create problems and cause system crash. The applications of malloc() and free() can be seen when we discuss linked list concept. v) Advantages: Static Memory Allocation 1) Memory to a variable is allocated at the compile time itself 2) Size of the memory block cannot be reduced or expanded as required later. Thus memory wastage results in. 3) Memory gets deallocated once explicitly control reaches out of scope of a variable

Dynamic Memory Allocation 1) Memory to a variable is allocated at the run time 2) Size of the memory block can be reduced or expanded as required later. Thus no memory wastage results in. 3) Memory is to be deallocated

using free()

Prepared by MNU, SCSE, VIT

19

4) The operations of data structures such array, list, stack, queue etc., are not so simple and effective

4) The operations of data structures such as array, list, stack, queue etc., are simple and effective

12) Storage Classes


Variables in C differ in behavior from those in most other languages. For example, in a BASIC program, a variable retains its value throughout the program. It is not always the case in C. It all depends on the storage class a variable may assume. In C not only do all variables have a data type, they also have a storage class. The following variable storage classes most relevant to functions: i) Automatic variables ii) Static variables iii) External variables iv) Register variables Storage class of a variable specify the following two things of a variable. i) Scope of a variable ii) Life time of a variable Scope of a variable: It specify over what region of the program a variable is actually available for use or active Life time of a variable: It specify how long a variable retains its content i) Automatic Variables: i) Local to a function and hence called as local variables ii) Scope == > with in the function in which it is declared iii) Life time == > Till the end of the function in which it is declared iv) Gets initialized every time the control enters the function in which it is declared. v) These variables are initialized by some garbage by default vi) If storage class of a variable is not specified, by default it is considered as automatic vii) Automatic storage class is specified by the keyword auto The following program illustrates the concepts of automatic storage class variables Program: void fun1(); void main() { fun1();

Prepared by MNU, SCSE, VIT

20

fun1(); fun1(); } void fun1(){ int x=0; /* Storage class of x is not specified. By default it is considered as auto */ /* or we can declare it as auto int x=0 */ printf(%d\n,x++); } Output: 0 0 0 Explanation: Since automatic storage class variable gets initialized every time the function is called. Thus for every call to fun1() displays 0. ii) Static variables: i) Local to a function and hence called as local variables ii) Scope == > with in the function in which it is declared iii) Life time == > variable retains its value between function calls till the end of the program iv) Gets initialized only once when the control enters the function for the first time in which it is declared. v) These variables are initialized by some garbage by default vi) Static storage class is specified by the keyword static The following program illustrates the concepts of static storage class variable Program: void fun1(); void main() { fun1(); fun1(); fun1(); } void fun1(){ static int x=0; once during the

/* Storage class of x is static and so gets initialized only first call. During subsequent calls the variable retains its

Prepared by MNU, SCSE, VIT

21

previous value */ printf(%d\n,x++); } Output: 0 1 2 Explanation: Since static storage class variable gets initialized only once during the first call to the function fun1(). In subsequent calls to fun1() the variable retains its previous value. Thus the output will be 0 1 and 2 iii) External variables: i) ii) iii) iv) v) vi) These variables can be treated as global variables. Hence the global variables by default treated as external variables. Scope == > Throughout the program Life time == > Throughout the program These variables will get initialized by default by either zero or null once declared The keyword that is used with these type of variables is extern If both global and local variables have the same name then local variable will get priority over the global one.

The following program illustrates the concepts of external variables Program: int x=10; /* Global or External variable */ void main() { extern int y=20; int x=40; /* Both local and global variables have the same name. Then local variable will have the priority over global one */ printf( x=%d\n, x); /* local variable x value gets printed */ printf(y=%d\n,y); printf(z=%d\n,z); /* Local to fun1(). To make it global precede its declaration by extern in function fun1() */ } void fun1(){ extern int z=30; printf(x=%d\n,x); /* global variable x value get printed */ printf(y=%d\n,y); /* Local to main(). To make it global precede its declaration

Prepared by MNU, SCSE, VIT

22

by extern in function main() */ printf(z=%d\n,z); } Output and Explanation: 40 (Local x value gets printed instead global x value) 20 30 10 (Global x value gets printed) 20 30

iv)

Register variables: i) Stored in register rather than in memory ii) Accessing is so fast iii) Very frequently used variables are stored in registers iv) The syntax is as below register int count; v) Initialized by some garbage by default

13) Recursion
i) Definition: A concept by which a function calls itself repeatedly finite number of times to accomplish certain task ii) Recursive version each problem will have two cases a) Base case b) General case Note: 1) Recursive programs get halted either they encounter base case or memory gets exhausted finally 2) Stack is used to store each function call details, variables and their contents, intermediate results and so on iii) Recursion Vs Iteration _______________________________________________________________________ Recursion Iteration 1) Code looks so simple and compact 2) Works slower due to creation of stack, pushing and popping the details of each function call from the stack, pushing and popping intermediate results from 1) Code looks little bit length 2) Works quicker

Prepared by MNU, SCSE, VIT

23

the stack and so on issues. 3) Needs extra memory in the form of stack Iv) Programs on recursion 1. 2. 3. 4. 5. 1) Recursive Version of Factorial Recursive Version of Fibonacci Recursive Version of GCD ( Greatest Common Divisor) Recursive Version of Sum of the digits of a 5-digit number Recursive Version of Reverse a 5-digit number 3) Needs no extra memory

Recursive version of Factorial problem factorial(n) = = 0 n * factorial(n-1) If n<0 or n=0 if n>1 (base case) (general case)

Program: int factorial(int); void main() { int n, result; printf(Enter an integer\n); scanf(%d, &n); result=factorial(n); printf(Factorial of %d is %d\n, n, result); system(pause); } int factorial(int n) { If(n<0 || n==0) return 1; else return n * factorial(n-1); } Showing its working diagrametrically: Please refer class notes 2) Recursive version of Fibonacci problem fibo(n) = = 0 1 if n=0 if n=1 (above two are base cases i.e., fibo(n) =n in base case)

Prepared by MNU, SCSE, VIT

24

if n>1 (general case) where n number of terms in the Fibonacci series Program: int fibo(int); int fibo(int n) { if(n==0 || n==1) return} n; else return fibo(n-2) + fibo(n-1); } void main() { int n,i; printf(Enter number of terms in the series\n); scanf(%d,&n); for(i=0;i<n;i++) printf(%d, fib(i)); system(pause); } Sowing its working diagrametrically: Please refer class notes c) Recursive version of GCD(Greatest Common Divisor) problem gcd(a,b) = = b if (a%b ==0) gcd(b, a%b) otherwise (base case) (general case)

fibo(n-2) + fibo(n-1)

Program: int a,b; int gcd(int, int); void main() { printf(Enter two integer numbers\n) scanf(%d%d, &a,&b); printf(The GCD of %d and %d is %d\n, a, b, gcd(a,b)); system(pause); } int gcd(int a, int b) {

Prepared by MNU, SCSE, VIT

25

if(a % b = = 0) return b; else return gcd(b, a % b); } Working: Let us consider two numbers 18 and 48. Take a=18 and b=48 Find a % b = 18 % 48 =18 which is not equal to zero, So go to else part and execute gcd(48, 18) Find 48 %18 = 3 again it is not equal to zero. So go to else part and execute gcd(18,3) Find 18 % 3 = 0 and as remainder is zero hence b=3 which will be the GCD of the given two numbers 18 and 48. Thus the result. d) Recursive version of sum of digits and reverse of 5-digit number Program: int rsum(int); int rrev (int); void main() { int num; printf(Enter non-zero 5-digit number\n); scanf(%d, &num); printf(Sum=%d\t and Reverse=%d\n, rsum(num), rrev(sum)); system(pause); } int rsum(int num) { static int sum=0; int digit; digit = num % 10; sum = sum + digit; num = num / 10; if(num !=0) rsum(num); return sum; } int rrev(int num) { static int rev =0; int digit;

Prepared by MNU, SCSE, VIT

26

digit = num % 10; rev = rev *10 + digit; num = num / 10; if(num!=0) rrev(num); return rev; } Output 123 Sum = 6 Reverse=321

===================

UNIT I CONCLUDED

==================

Prepared by MNU, SCSE, VIT

27

You might also like