C - MODULE 4 and 5
C - MODULE 4 and 5
Language
ARRAYS
An array is a fixed-size sequenced collection of elements of the same data type. It is simply
a grouping of like-type data. An array can be used to represent a list of numbers, or a list of names.
An array is a collective name given to a group of homogeneous elements (same data type).
These similar quantities could be percentage marks of 100 students, or salaries of 300 employees
or ages of 25 students.
Declaration of an Array
Arrays must be declared before they can be used in the program.
Standard array declaration is as
type variable_name [size];
The type specifies the type of the elements that will be contained in the array, such as int,
float or char and the size indicates the maximum number of elements that can be stored inside the
array. In C Language, an array starts at position 0.
1. C Programming Arrays is the Collection of Elements
2. C Programming Arrays is collection of the Elements of the same data type.
3. All Elements are stored in the Contiguous memory
4. All elements in the array are accessed using the subscript variable (index).
Pictorial representation of C Programming Arrays
eg: int Age[5];
Age[0]
Age[1]
Age[2]
Age[3]
Age[4]
35
40
20
char name[10];
Here we declare the name as a character array (string) variable that can hold a maximum of
10 characters. Suppose we read the following string constant into the string variable name.
“WELL DONE”
Array will be like this
‘W’
‘E’
‘L’
‘L’
‘’
‘D’
‘O’
‘N’
‘E’
‘\0’
When compiler sees the character string, it terminates with an additional null character,
thus the element name[10] holds the null character ‘\0’ . When declaring character arrays, we must
allow one extra element space for the null terminator.
1. When Big Block of memory is reserved or allocated then that memory block is called as
Contiguous Memory Block.
Array Terminologies:
Size: Number of elements or capacity to store elements in an array. It is always mentioned in square
brackets [ ].
Type: Refers to data type. It decides which type of element is stored in the array. It is also
instructing the compiler to reserve memory according to the data type.
Index: The array name is used to refer to the array element. For example num[x], num is array and
x is index. The value of x begins from 0.The index value is always an integer value.
Range: Value of index of an array varies from lower bound to upper bound. For example in
num[100] the range of index is 0 to 99.
Characteristics of an array:
1. The declaration int a[5] is nothing but creation of five variables of integer types in memory
instead of declaring five variables for five values.
2. All the elements of an array share the same name and they are distinguished from one
another with the help of the element number.
3. The element number in an array plays a major role for calling each element.
4. Any particular element of an array can be modified separately without disturbing the other
elements.
5. Any element of an array a[ ] can be assigned or equated to another ordinary variable or array
variable of its type.
6. Array elements are stored in contiguous memory locations.
Types of Array
2. Multi-Dimensional Array
Single or One Dimensional array is used to represent and store data in a linear form.
Array having only one subscript variable is called One-Dimensional array.
It is also called as Single Dimensional Array or Linear Array.
int iarr[3];
char carr[20];
float farr[3];
Initializing 1-D Array is called as compiler time initialization if and only if we assign
certain set of values to array element before executing program. i.e. at compilation time.
In the above example we have specified the size of array as 5 directly in the initialization
statement. Compiler will assign the set of values to particular element of the array.
Explanation:
1. Compiler counts the number of elements written inside pair of braces and determines the size
of an array.
2. After counting the number of elements inside the braces, the size of array is considered as 5
during complete execution.
3. This type of Initialization Scheme is also called as “Compile Time Initialization”.
Example Program
#include <stdio.h>
void main()
int i;
for (i=0;i<5;i++)
getch();
Output:
Array Element num[0] =
= 8 Array Element
num[2] = 7 Array
Element num[3] = 6
2. Array can be accessed using array-name and subscript variable written inside pair of square
brackets [ ]. Consider the below example of an array
20 30 10 40 70
a[0] a[1] a[2] a[3] a[4]
a [0] = 20; a[1] = 30; a[2] = 10; a[3] = 40; a[4] = 70;
void main()
{
int a[5];
clrscr();
printf(“Enter a number\n”);
scanf(“%d”,&a[0]);
}
We can read number of elements in single statements by using for loop.
void main()
{
int i,a[5];
clrscr();
printf(“Enter five numbers\n”);
for(i=0;i<5;i++)
{
#include<stdio.h>
int main()
{
int arr[30], element, num, i,
location; printf("\nEnter no of
elements:"); scanf("%d", &num);
for (i = 0; i < num; i++)
{
scanf("%d", &arr[i]);
}
printf("\nEnter the element to be inserted:");
scanf("%d", &element);
printf("\nEnter the location");
scanf("%d", &location);
//Create space at the specified
location for (i = num; i >= location;
i--)
{
arr[i] = arr[i - 1];
9 Dept. of CS, IGCAS
Methodology of Programming & C BCA/BSc CS
Language
}
num++;
arr[location - 1] = element;
//Print out the result of
insertion for (i = 0; i < num; i+
+) printf("n %d", arr[i]);
return (0);
}
Output:
Enter no of elements: 5
12345
Enter the element to be inserted: 6
Enter the location: 2
1 62345
}
//Read the element to be searched printf("\
nEnter the element to be searched :");
scanf("%d", &ele);
//Search starts from the zeroth location
i = 0;
else
{
res[k] =
arr2[j]; k++;
j++;
}
}
/*Some elements in array 'arr1' are still remaining where as the array 'arr2' is exhausted*/
while (i < n1)
{
res[k] =
arr1[i]; i++;
k++;
}
1. Array having more than one subscript variable is called Multi-Dimensional array.
Example:
printf("%d",a[i][j]);
}
Matrices
STRINGS
A string is a sequence of character enclosed with in double quotes (“ ”) but ends with \0. The
compiler puts \0 at the end of string to specify the end of the string. To get a value of string
variable we can use the two different types of formats.
C library supports a large number of string handling functions. Those functions are stored
under the header file string.h in the program.
I. strlen() function
strlen() is used to return the length of the string , that means counts the number of
characters present in a string.
Syntax
integer variable = strlen (string variable);
Example:P27
void main()
{
char str[20];
int
strlength;
clrscr();
printf(“Enter String:”);
gets(str);
strlength=strlen(str);
printf(“Given String Length Is: %d",
strlength); getch();
}
Output:
Enter String
Welcome
Given String Length is:7
The strcat() is used to concatenate two strings. The second string will be appended to the end of
the first string. This process is called concatenation.
Syntax
void main()
{
char str1[20],str2[20];
clrscr();
printf(“Enter First String:”);
scanf(“%s”,str1);
printf(“Enter Second String:”);
scanf(“%s”,str2);
printf(“Concatenation String is:%s\n”, strcat(str1,str2));
getch();
}
Output:
Enter First String
Good
Enter Second
String Morning
Concatenation String is:
GoodMorning
strcmp() function is used to compare two strings. strcmp() function does a case sensitive
comparison between two strings. The two strings are compared character by character until there is
a mismatch or end of one of the strings is reached (whichever occurs first). If the two strings are
identical, strcmp( ) returns a value zero. If they’re not, it returns the numeric difference between
the ASCII values of the first non-matching pairs of characters.
Syntax
strcmp(StringVariable1, StringVariable2);
Example: P29
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[20], str2[20];
Note:
strcmpi() function
V. strlwr () function:
This function converts all characters in a given string from uppercase to lowercase letter.
Syntax
strlwr(StringVariable);
Example:P31
#include<stdio.h>
#include<conio.h>
void main()
{
char str[20];
clrscr();
printf(“Enter String:”);
gets(str);
printf(“Lowercase String : %s”, strlwr(str));
getch();
Example:P32
#include<stdio.h>
#include<conio.h>
void main()
{
char str[20];
clrscr();
printf(“Enter String:”);
gets(str);
printf(“Reverse String : %s”, strrev(str));
getch();
}
Output:
Enter String
WELCOME
Reverse String : EMOCLEW
Note:
strupr() function:
strupr() function is used to convert all characters in a given string
from lower case to uppercase letter.
Syntax
strupr(Stringvariable);
Pointers
Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known as
indirection pointer used to dereference a pointer.
By the help of * (indirection operator), we can print the value of pointer variable p
Eg P33:-
#include<stdio.h>
int main()
{
int number=50;
int *p;
p=&number; //stores the address of number variable
printf("Address of p variable is %x \n",p); // p contains the address of the
number printf("Value of p variable is %d \n",*p); // *p print the value of pointer
variable return 0;
}
Output
Address of p variable is
50
Eg P34:-Write a program to display the value of variable and its location using pointer
Void main()
clrscr();
p=&v;
Output
Address of
v=4060 Value of v
=10 Address of
p=4062
void main ()
int i,*k;
clrscr ();
k=&i;
Output
Enter a number: 15
Address of I is
4065 Value of I is
Eg P36:- write a program to add two numbers through variables and their pointers.
int a,b,c,d,*ap,*bp;
clrscr();
ap=&a;
bp=&b;
c=a+b;
d=*ap+*bp;
OUTPUT:
12 Advantage of pointer
1) Pointer reduces the code and improves the performance; it is used to retrieving strings, trees, etc.
and used with arrays, structures, and functions.
3) It makes you able to access any memory location in the computer's memory.
Usage of pointer
In C language, we can dynamically allocate memory using malloc() and calloc() functions where
the pointer is used.
NULL Pointer
A pointer that is not assigned any value but NULL is known as the NULL pointer. If you
don't have any address to be specified in the pointer at the time of declaration, you can assign
NULL value. It will provide a better approach.
int *p=NULL;
#include<stdio.h>
void main()
{
int a=10,b=20,*p1=&a,*p2=&b;
printf("Before swap: *p1=%d *p2=%d",*p1,*p2);
*p1=*p1+*p2;
*p2=*p1-*p2;
*p1=*p1-*p2;
printf("\nAfter swap: *p1=%d *p2=%d",*p1,*p2);
getch();
}
Output
A void pointer can point any type of variable with proper type casting. The size of a void
pointer displayed will be two. When a pointer is declared as void two bytes are allocated to it.
Later
WILD POINTERS
Pointers are used to store memory addresses. An improper use of pointer creates many
errors in the program. Hence, pointers should be handled cautiously. When a pointer points to an
unallocated memory location or data value whose memory is de-allocated, such a pointer is called
a wild pointer. That is uninitialized pointers are known as wild pointers. The wild pointer generates
garbage memory location and dependent reference. The pointer becomes wild due to the following
reasons:
void main()
int k,*x;
clrscr () ;
for(k=0;k<=3;k++)
printf("%u",x[k]);
OUTPUT:
7272 24 330 30 55 9 2 7 7 53
CONSTANT POINTERS
In the above example, it is not possible to modify the address of the pointer str.
Features of pointers
Arithmetic operations on pointer variables are also possible. Increment, decrement, prefix
and postfix operations can be performed with the pointers, The effects of these operations are
shown in Table.
From the table we can observe that, on increment of the pointer variable for integers, the
address incremented by two. i.e. 4046 is the original address and on increment its value will be
4048 because integers require two bytes.
Similarly, characters, floating point numbers and long integers require 1, 4 and 4 bytes,
respectively.
Eg:-P38. Write a program to show the effect of increment and decrement operators used as
prefix and suffix with the pointer variable.
void main ()
int i, *ii;
ii=&i;
OUTPUT:
Enter Value of i= 8
Address of i = 4060
Address of i = 4062
Address of i = 4062
Address of i = 4062
Address of i = 4062
Address of i = 4060
Eg:-P40write a program to display an array element with their addresses using array name
as a pointer
void main()
Int x[5]={2,4,6,8,10),k=0;
clrscr() ;
k++;
OUTPUT:
x[0] = 2 4056
x[1]= 4 4058
x[2]= 6 4060
x[3]= 8 4062
Eg: P41. Write a program to find the sum all the elements of an array. Use the array name
itself as pointer.
void main ( )
clrscr ;
while (i<5)
OUTPUT:
A[0] = 1 4056
A[1] = 2 4058
A[2] = 3 4060
A[3] = 4 4062
A[4] = 5 4064
Eg:-P42. Write a program to display array elements and their addresses using
int i, j=1,*p;
int a[3][3]={(1,2,13),(4,5,61),(7,8,9)}:
clrscr();
p=&a[0][0];
for(i=0;i<9;i++,j++)
p++;
if (j==3)
printf("\n");
j=0;
OUTPUT:
MODULE 5
FUNCTIONS
A function is a block of code that performs a specific task.
In C, we can divide a large program into the basic building blocks known as function. The function
contains the set of programming statements enclosed by {}. A function can be called multiple
times to provide reusability and modularity to the C program. In other words, we can say that the
collection of functions creates a program. The function is also known as procedure or subroutine in
other programming languages.
Advantage of functions in C
By using functions, we can avoid rewriting same logic/code again and again in a program.
We can call C functions any number of times in a program and from any place in a program.
We can track a large C program easily when it is divided into multiple functions
Reusability is the main achievement of C functions.
However, Function calling is always an overhead in a C program.
Function Aspects
Function declaration
All functions in a c program must be declared, before they are invoked. A function declaration (also
known as function prototype) consists of four parts.
Function type (return type).
Function name.
Parameter list.
Terminating semicolon.
The general format of function declaration is:
Function definition
Function definition, also known as function implementation includes the following elements;
Function name.
Function type.
List of parameters.
Local variable declaration.
Function statements; and
A return statement.
Function call
1. Library Functions:
Library functions are built-in functions in Library functions are the functions which are
declared in the C header files (stdio.h) such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.
2. User-defined functions:
User defined functions are the functions which are created by the C programmer, so that
he/she can use it many times. It reduces the complexity of a big program and optimizes the code.
Return Value
C function may or may not return a value from the function. If you don't have to return any
value from the function, use void for the return type.
Let's see a simple example of C function that doesn't return any value from the
function.
void hello()
{
printf("hello c");
}
If you want to return any value from the function, you need to use any data type such as
int, long, char, etc. The return type depends on the value to be returned from the function.
Let's see a simple example of C function that returns int value from the function.
int get()
{
return 10;
}
float get()
{
return 10.2;
}
Now, you need to call the function, to get the value of the function.
A function may or may not accept any argument. It may or may not return any value. Based
on these facts, there are four different aspects of function calls.
Example P43.
#include<stdio.h>
void printName();
void main ()
{
printf("Hello ");
printName();
}
void printName()
{
printf(" C programming");
}
Output
Hello C programming
#include<stdio.h>
void sum();
void main()
{
printf("\nGoing to calculate the sum of two numbers:");
sum();
}
void sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
printf("The sum is %d",a+b);
}
Output
Going to calculate the sum of two numbers:
Enter two
numbers 10
20
The sum is 30
Example for Function without argument and with return value
Example P45
#include<stdio.h>
#include<conio.h>
int sum();
void main()
{
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum();
printf("%d",result);
getch();
Example P46:
program to calculate the area of the square
#include<stdio.h>
float square();
void main()
{
printf("Going to calculate the area of the square\n");
float area = square();
printf("The area of the square: %f\n",area);
getch();
}
float square()
{
float side;
printf("Enter the length of the side in meters: ");
scanf("%f”,&side);
return side * side;
}
Output
Output
Going to calculate the sum of two
numbers: Enter two numbers
10
20
The sum is 30
Example P48:
float avg;
avg=(a+b+c+d+e)/5);
printf(“The average of five numbers=%f ”,avg);
}
Output
Going to calculate the average of five
numbers Enter five numbers
10
20
30
40
50
The average of five numbers= 30.000000
Call by value
Call by reference
Call by Value
In this type, the value of actual arguments is passed to the formal arguments and operation is
done on the formal arguments. Any change in the formal arguments made does not affect the actual
arguments because formal arguments are the photocopy of the actual argument. Hence, when a
function is called by the call by value method, it does not affect the actual contents of the
arguments. Changes made in the formal arguments are local to the block of the called function.
P50. Write a program to exchange values of two variables by using 'call by
value' to the function.
#include<stdio.h>
void swap(int x,int y);
main()
{
int a,b;
printf(“Enter the values:”);
a=10;
b=20;
swap(a,b);
printf(“a=%d b=%d”,a,b);
}
void swap(int x,int y)
{
int t;
t=x;
x=y;
y=t;
printf(“x=%d y=%d”,x,y);
}
Output
x=20 y=10
RECURSION
Types of Recursion
int num()
{
…….
sum();
int num() }
{
……… Int sum()
num(); {
………
} num();
}
Direct Recursion
Indirect Recursion
Tail Recursion
No Tail/ Head Recursion
Direct Recursion
When a function calls itself within the same function repeatedly, it is called the direct
recursion.
}
In the above structure of the direct recursion, the outer fun() function recursively calls the
inner fun() function, and this type of recursion is called the direct recursion.
Indirect Recursion
When a function is mutually called by another function in a circular manner, the function is
called an indirect recursion function.
In this structure, there are three functions, fun1(), fun2(), fun3() and fun4(). When the
fun1() function is executed, it calls the fun2() for its execution. And then, the fun2() function starts
its execution calls the fun3() function. In this way, each function leads to another function to
makes their execution circularly. And this type of approach is called indirect recursion.
Tail Recursion
A recursive function is called the tail-recursive if the function makes recursive calling
itself, and that recursive call is the last statement executes by the function. After that, there is no
function or statement is left to call the recursive function.
void fun1( int num)
{
// if block check the
condition if (num == 0)
return;
else
1. In recursion, it is essential to call a function itself, otherwise recursion would not take place.
2. Only the user-defined function can be involved in the recursion. Library function cannot be
involved in recursion because their source code cannot be viewed.
int num()
{
if (condition)
…………..
num();
}
The user-defined function main ( ) can be invoked recursively. To implement such recursion, it is
necessary to mention prototype of function main ( ).
Recursion versus iterations
Recursion Iteration
Recursion uses selection structure. Iteration uses repetition structure
Recursion is the term given to the mechanism of The block of statement is executed
defining a set or procedure in terms of itself. repeatedly using loops.
A conditional statement is required in the body of The iteration control statements itself
the function for stopping the function execution. contain statements for stopping the
iteration.
At some places, the use of recursion generates extra Iteration does not create any overhead
overhead
Recursion always applied to functions Iteration is applied to statements or loops
Recursion is slow in execution Iteration is fast in execution
Recursion reduces the size of code Iteration makes the code longer
Disadvantages
1. It requires extra storage space. The recursive calls and automatic variables are stored on the
stack. For every recursive calls, separate memory is allocated to automatic variables with
the same name.
2. If the programmer forgets to specify the exit condition in the recursive function, the
program will execute out of memory. In such a situation user has to press Ctrl+ break to
pause and s the function.
3. The recursion function is not efficient in execution speed and time.
4. If possible, try to solve a problem with iteration instead of recursion.
STORAGE CLASSES
There are two different ways to characterize variables: by data type, and by storage class.
Data type refers to the type of information represented by a variable, e.g., integer number, floating-
point number, character, etc.
Storage class refers to the performance of a variable, and its scope within the program.
Automatic variables
External variables
Static variables
Register variables
1. Automatic Variables
Automatic variables are declared inside a function in which they are to be utilized. They
are created when the function is called and destroyed automatically when the function is exited,
hence the name automatic. Automatic variables are therefore private (or local) to the function in
which they are declared. Because of this property, automatic variables are also referred to as local
or internal variables.
< Storage class specifier > < data type > < variable name > ;
A variable declared inside a function without storage class specification is, by default, an automatic
variable.
Example:-
main()
{
int i;
for(i=0; i<2; i++)
stat();
}
void stat()
{
int x=0;
x=x+1;
printf(“x=%d”,x);
}
Output
x=1
x=1
x=1
2. External variables
Variables that are both alive and active throughout the entire program are known as
external variables. They are also known as global variables. Unlike local variables, global variables
can be accessed by any function in the program. External variables are declared outside a function.
The ‘extern’ keyword is used for declaring external variables.
Example:1
int number; /* global
int count=50;
variables float length
=5.5; */ main()
}
Function1()
{
int count=0; /* take the value of count=0*/
}
Example:2
int no;
float length;
main()
{
}
func1()
{
}
Example:3
main()
{
y=5;
}
int y;
func1()
{
y=y+1
}
In example 3, as far as main is concerned, y is not declared. So main function cannot access
the variable y. This problem can be overcome by declaring the variable with the storage class extern.
extern int y;
}
func1()
{
extern int y;
}
int y;
Although the variable y has been defined after both the functions, the external declaration
of y inside the functions informs the compiler that y is an integer type defined somewhere else in
the program. The extern declaration does not allocate storage space for variables.
3. Static variables
The value of static variables persists until the end of the program. A variable can be declared static
using the keyword static.
static int x;
static float
y;
A static variable may be either an internal type or an external type depending on the place of
declaration. Internal static variables are those which are declared inside a function. An external
static variable is declared outside of all functions and is available to all the functions in that
program.
Example:
main ()
{
int i;
for (i=1; i<=3;i+
+) Function1 ();
}
Function1 ()
{
STRUCTURES
A structure is a collection of one or more variables of different data types, grouped together
under a single name. It is a user-defined data type because the user can decide the data types to be
included in the body of a structure. By using structures, we can make a group of variables, arrays,
pointers.
DEFINING A STRUCTURE
General syntax:
struct tag_name
{
data type
member1; data
type member2;
…
…
};
Example:
struct books
55 Dept. of CS, IGCAS
Methodology of Programming & C BCA/BSc CS
Language
{
char title[20];
char author[15];
int pages;
float price;
};
The keyword struct declares a structure to holds the details of four fields namely title, author,
pages and price. These are members of the structures. Each member may belong to different or
same data type.
DECLARING A STRUCTURE VARIABLES
A structure variable declaration is similar to the declaration of variables of any other data types. It
includes the following elements:
1. The keyword struct
2. The structure tag name.
3. List of variable names separated by commas.
4. Terminating semicolon.
For eg:
The statement
struct books book1, book2, book3;
Declares book1, book2 and book3 as variables of type struct books .
The complete declaration
struct books
{
char title[20];
char author[15];
int pages;
float price;
};
struct lib_books book1, book2, book3;
It is also allowed to combine both the structure definition and variable declaration in one statement.
struct books
{
POINTER TO STRUCTURE
We know that the pointer is a variable that holds the address of another data variable. The
variable may be of any data type, i.e. int, float or double. In the same way, we can also define
pointer to structure. Here, starting address of the member variables can be accessed. Thus, such
pointers are called structure pointers.
};
Example
union item
{
int m;
float x;
char c;
}code;
typedef
We can create new data type by using typedef. The statement typedef is to be used while defining
the new data type.
The syntax is as follows:
typedef type dataname;
Here, type is the datatype and dataname is the user-defined name for that type.
typedef int hours;
Here, hours are another name for int and now we can use hours instead of int in the program as
follows:
BIT FIELDS
In C, we can specify size (in bits) of structure and union members. The idea is to
use memory efficiently when we know that the value of a field or group of fields will never
exceed a limit or is within a small range.
For example, consider the following declaration of date without the use of bit fields.
#include <stdio.h>
// A simple representation of the
date struct date
{
unsigned int d;
unsigned int
m; unsigned
int y;
};
int main()
{
printf("Size of date is %lu bytes\n", sizeof(struct
date)); struct date dt = { 31, 12, 2014 };
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
}
Output:
Size of date is 12 bytes
Date is 31/12/2014
The above representation of ‘date’ takes 12 bytes on a compiler where an unsigned int takes
4 bytes. Since we know that the value of d is always from 1 to 31, the value of m is from 1 to 12,
we can optimize the space using bit fields.
#include <stdio.h>
// Bit field representation
64 Dept. of CS, IGCAS
Methodology of Programming & C BCA/BSc CS
Language
struct date
{
unsigned int d: 6;
unsigned int m : 5:
unsigned int y;
};
int main()
{
printf("Size of date is %lu bytes\n", sizeof(struct date));
struct date dt = { 31, 12, 2014 };
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
}
enumerated data type(enum)
The enum in C is also known as the enumerated type. It is a user-defined data type that
consists of integer values, and it provides meaningful names to these values. The use of enum in
C makes the program easy to understand and maintain. The enum is defined by using the enum
keyword.
Syntax
enum week{sun,mon,tues,wed,thur,fri,sat};
This statement creates a user-defined data type. The keyword enum is followed by the tag
name week. The enumerators are the identifiers sun,mon,tues,wed,
thur,fri. Their values are constant unsigned integers and starts from 0. The identifier sun refers
to 0, mon to 1 and so on. The identifiers are not to be enclosed with quotation marks. Please also
note that integer constants are also not permitted.
void main()
{
enum month (Jan=1, Feb, Mar, Apr, May, June, July, Aug, Sep, Oct,
Nov, Dec); clrscr();
printf("\nJan = %d",Jan);
printf("\nFeb = $d",Feb);
OUTPUT :
Jan = 1
Feb = 2
June = 6
Dec - 12
Dynamic memory allocation in C
The concept of dynamic memory allocation in c language enables the C programmer
to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4
functions of stdlib.h header file.
1. malloc()
2. calloc()
3. realloc()
4. free()
Before learning above functions, let's understand the difference between static memory
allocation and dynamic memory allocation.
Memory can't be increased while executing Memory can be increased while executing
program. program.
malloc() function in C
The malloc() function allocates single block of requested memory.
A memory block is allocated with a function called malloc( ) . In other words, the malloc ( )
function is used to allocate memory space in bytes to the variables of different data types. The
function reserves bytes of determined size and returns the base address to pointer variable.
The prototypes are declared in alloc . h and stdl b . h.
The format of the malloc( ) function is as follows:
pnt= (datatype*) malloc(given_size);
Here, from data type, compiler understands the pointer type and given size is the size to
reserve in the memory.
For example:
pnt=( int 4) malloc(20);
Here, in this declaration 20 bytes are allocated to pointer variable pnt of type int and base
address is returned to pointer pnt .
Let's see the example of malloc() function.
P55. #include<stdio.h>
#include<stdlib.h>
int main()
{
int n,i,*ptr,sum=0;
printf("Enter number of elements:
"); scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate
memory"); exit(0);
}
free() function in C
The memory occupied by malloc() or calloc() functions must be released by calling free() function.
Otherwise, it will consume memory until program exit.
Memory Models
TINY
SMALL
COMPACT
MEDIUM
LARGE
HUGE.
TINY Model:
All segment registers are initialized with the identical value and all addressing is
accomplished using 16 bits. This means that the code, data and stack all must fit with in the same
64-KB segment. Programs are executed quickly in this case.
SMALL Model:
All codes should fit in a single 64-KB segment and all data should fit in a second 64-KB
segment. All pointers are 16 bits in length. Execution speed is same as tiny model. In the SMALL
model all code is placed in one physical segment and all data in another physical segment.
COMPACT Model:
All codes should fit in 64 KB segment, but the data can use multiple segments. However, no data
item can surpass 64 KB. All pointers to data are 32 bits, but jumps and calls can use 16 bit
addresses. There is slow access to data quick code execution.
MEDIUM Model:
All data should be fit in a single 64-KB segment; however, the code is allowed to use
multiple segments. All pointers to data are 16 bits, but all jumps and calls require 32-bit addresses.
Fast access to data is observed, but slower program execution is noticed with this model.
LARGE Model:
In the LARGE model both code elements (procedures) and data elements (variables) are
allowed to use multiple segments. All pointers are 32 bits in length. However, no single data item
can exceed 64 KB. There is slower code execution.
HUGE Model:
B.Sc/BCA DEGREE(CBCS)REGULAR/IMPROVEMENT/REAPPEARANCE
EXAMINATIONS, FEBRUARY 2023
First Semester
CS1CRT02 - METHODOLOGY OF PROGRAMMING AND C LANGUAGE
Part A
Answer any ten questions.
Each question carries 2 marks.
1. What is an Assembler?
2. List out the characteristics of a good programming language.
24.Write a C program to check whether two strings are equal or not without using string
handling functions.
25. a) Explain storage classes in C with example
b) What is recursion? What are its different types? Write a recursive function to find the
factorial of a given integer. (2×15=30)
B.Sc/BCA DEGREE(CBCS)EXAMINATIONS, OCTOBER 2021
First Semester
METHODOLOGY OF PROGRAMMING AND C LANGUAGE
Part A
Answer any ten questions.
Each question carries 2 marks.
1. List out any three factors for selecting a programming language.
2. Draw a flow chart to find the average of three numbers.
3. List the three control structures with atleast one example for each.
4. Differentiate between keywords and identifiers.
5. What are different storage class specifiers in C?
Part C
Answer any two questions.
Each question carries 15 marks.
22. Explain about a) Linker b) Subprogram c) Differences between compiler and interpreter.
23. Explain in detail various data types used in C with example.
24. a) Write a C program using pointer to swap the values of two integer number.
b) Explain the relation between an array and a pointer. What is wild pointer in C?
25. Explain a) structure with sample program.
b) Explain Pointers to Structure. (2×15=30)
B.Sc.DEGREE (CBCS) EXAMINATION, NOVEMBER 2019
First Semester
Part B
Answer any six questions.
Each question carries 5 marks.
13) Discuss various bitwise operators in C.
14) What are strings? Explain 5 string handling functions.
15) What are structures in C? How is it different from Union? Give examples.
16) Discuss various arithmetic operations with pointers.
17) Explain the difference between entry controlled and exit controlled loops. Explain with
the help of example.
18) What are Language translators?
19) What is meant by dynamic memory allocation? Explain.
20) What is recursion? Explain direct and indirect recursion.
21) With the help of flowchart, explain any two decision statements in C. Give examples.
Part C
Answer any two questions.
List of Programs