0% found this document useful (0 votes)
3 views

PC Lab_Manual_(Programming in C)

The document provides an overview of programming in C, focusing on arrays, including one-dimensional and two-dimensional arrays, their advantages and disadvantages, syntax for declaration and initialization, and memory representation. It also covers string manipulation, including string declaration, initialization, input methods, and common string functions. Practical exercises and post-laboratory questions are included to reinforce learning and application of the concepts.

Uploaded by

tanishkansara77
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

PC Lab_Manual_(Programming in C)

The document provides an overview of programming in C, focusing on arrays, including one-dimensional and two-dimensional arrays, their advantages and disadvantages, syntax for declaration and initialization, and memory representation. It also covers string manipulation, including string declaration, initialization, input methods, and common string functions. Practical exercises and post-laboratory questions are included to reinforce learning and application of the concepts.

Uploaded by

tanishkansara77
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 103

Programming in 'C'

Practical: 1
Array:
An Array is defined as the collection of similar type of data (same data type) items
stored at contiguous memory locations (store multiple data in a single variable). The array is
the simplest data structure where each data element can be randomly accessed by using its
index number. Array indexes start with 0: [0] is the first element. [1] is the second element.

For example, if we want to store the marks of a student in 5 subjects, then we don't need to
define different variables for the marks in the different subject. Instead of that, we can define
an array which can store the marks in each subject at the contiguous memory locations.

Advantage
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
3) Random Access: We can access any element randomly using the array.

Disadvantage

1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed
the limit. So, it doesn't grow the size dynamically like LinkedList.

Syntax:
1. Declaration of Array:

datatype variable_name [size of array];

Example, int marks[4];

2. Initialization of Array:

datatype variable_name[] = {v1, v2,...vn};

OR

datatype variable_name[size] = {v1, v2..., vn};

Example, int marks[ ] = {70,80,45,59,68}; OR int marks[5] = { 70,80,45,59,68};

3. Access the Elements of an Array:

variable_name[index] = value;

1
Programming in 'C'

Example, marks[3] = 59;

Memory Representation:
int marks[4] = { 70, 80, 45, 59, 68};

marks[0] marks[1] marks[2] marks[3] marks[4]


70 80 45 59 68

2000 2004 2008 2012 2016

Base address is the address of the first element of an array, pointed by array name.

Address of (ith) index element = base_address + (i * sizeof(datatype));

Over here, base address = 2000.

Index Address

0 2000

1 2004

2 2008

3 2012

4 2016

2
Programming in 'C'

Practical: 1 (A)
Aim: Write a program to read 4 elements in 1D array and display it.
Code:

Output:

3
Programming in 'C'

Practical: 1 (B)
Aim: Write a program to read 4 elements in 2D array and display in matrix
form.

Code:

4
Programming in 'C'

Output:

5
Programming in 'C'

Practical: 1
Post Laboratory Questions

1. Declare one dimensional array having size 5 and type double.

2. Write a loop to access each element of an array with the size n.

3. An array can be initialized either at compile time or ________.

4. Identify errors, if any, in each of the following initialization statements.

i) int number [ ] = { 0 , 0 , 0 , 0, 0 } ;

ii) float item [ 3 ][ 2 ] = { 0 , 1 , 2 , 3 , 4 , 5 } ;

iii) char word [ ] = { ‘ A ’ , ‘ R ’ , ‘ R ’ , ‘ A ’ , ‘Y’ } ;

iv) float result [ 10 ] = 0 ;

5. Enlist types of Array.

6
Programming in 'C'

6. State whether the following statements are true or false.

i) An array can store infinite data of similar type.

ii) When an array is declared, C automatically initializes its elements to zero.

iii) Accessing an array outside it’s rang is a compile time error.

iv) Array index starts with -1.

Grade

Sign

7
Programming in 'C'

Practical: 2

Two- Dimensional Array


The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices
which can be represented as the collection of rows and columns. The two-dimensional (2D) array in
C programming is also known as matrix. However, 2D arrays are created to implement a relational
database lookalike data structure.

1. Declaration of 2D Array:

Syntax: datatype variable_name[rows][columns];


Example: int Matrix[5][4];

2. Initialization of 2D Array:

Example: int Matrix[5][4] = {{1,2,3,4},{2,3,4,5},{3,4,5,6},{4,5,6,7},{5,6,7,8}};

3. Access the Elements of a 2D Array: To access an element of a two-dimensional array, you must
specify the index number of both the row and column.

Syntax: variable_name[row][columns]=value;
Example: Matrix [0][2];
Output: 3

Memory representation:
int Matrix[4][3] = {{1,2,4},{2,3,4},{3,4,5},{4,5,6}};

Col_0 Col_1 Col_2


Row 0 M[0][0] M[0][1] M[0][2]
Row 1 M[1][0] M[1][1] M[1][2]
Row 2 M[2][0] M[2][1] M[2][2]
Row 3 M[3][0] M[3][1] M[3][2]
Row 4 M[4][0] M[4][1] M[4][2]

Column 0 Column 1 Column 2


Row 0 1 2 4
Row 1 2 3 4
Row 2 3 4 5
Row 3 4 5 6

8
Programming in 'C'

Practical: 2 (A)
Aim: Write a program to copy elements of one array to another.

Code:

9
Programming in 'C'

Output:

10
Programming in 'C'

Practical: 2 (B)
Aim: Write a program to calculate sum of array elements.

Code:

11
Programming in 'C'

Output:

12
Programming in 'C'

Practical: 2 (C)
Aim: Write a program to find out minimum and maximum number from 1D
array.

Code:

13
Programming in 'C'

Output:

14
Programming in 'C'

Practical: 2
Post Laboratory Questions

1. What are multidimensional arrays?

2. Write down syntax to declare two-dimensional array.

3. An array that uses more than two subscript is referred to as _______ array.

4. How initial values can be assigned to a multi-dimensional array?

Grade

Sign

15
Programming in 'C'

Practical: 3 (A)

Aim: Write a program to search an element from an array.

Code:

16
Programming in 'C'

Output:

17
Programming in 'C'

Practical: 3 (B)
Aim: Write a program to insert an element in array at particular position.

Code:

18
Programming in 'C'

Output:

19
Programming in 'C'

Practical: 3 (C)
Aim: Write a program to delete an element in array at particular position.

Code:

20
Programming in 'C'

Output:

21
Programming in 'C'

Practical: 3
Post Laboratory Questions

1. A one-dimensional array contains one-dimensional arrays is called_______________

2. Objects in a sequence that have the same type, is called________________________

3. An array can contain how many kinds of elements?

A. Only int type B. Only char type C. Char and int type D. All of them have same type

4. Index number of the last element of an array having 9 elements is _________

Grade

Sign

22
Programming in 'C'

Practical: 4 (A)
Aim: Write a program to sort an array in ascending and descending order.

Code:

23
Programming in 'C'

Output:

24
Programming in 'C'

Practical: 4 (B)
Aim: Write a program to read values of two matrices in 2D arrays and multiply
two matrices.

Code:

25
Programming in 'C'

Output:

26
Programming in 'C'

Practical: 4
Post Laboratory Questions

1. How we access the seventh element stored in array?

2. Output of this program will be ____?

#include<stdio.h>
int main()
{ char str[5] = “ABC”;
printf(str[3]);
printf(str);
return 0; }

Grade

Sign

27
Programming in 'C'

Practical: 5
String:
Strings are used for storing text/characters. For example, "Hello World" is a string
of characters. In C programming, a string is a one-dimensional array of characters that ends
with the special character ‘\0’. Character arrays or strings are used to manipulate text, such as
words or sentences. In strings, the termination character (‘\0’) is very important because it is
the only way to detect where the string ends. Strings can be written as character arrays or
string literals in the C language.

Syntax:
1. Declaration of String:

char str_name[size]; Example: char str[50];

2. Initializing of String:
Four Ways to Initialize a String in C.

1. Assigning a string literal without size: String literals can be assigned without size. Here,
the name of the string str acts as a pointer because it is an array.

char str[] = "ComputerEngineering";

2. Assigning a string literal with a predefined size: String literals can be assigned with a
predefined size. But we should always account for one extra space which will be assigned to
the null character. If we want to store a string of size n then we should always declare a string
with a size equal to or greater than n+1.

char str[50] = "ComputerEngineering";

3. Assigning character by character with size: We can also assign a string character by
character. But we should remember to set the end character as ‘\0’ which is a null character.

char str[9] = { 'C','o','m','p','u','t','e','r', '\0'};

4. Assigning character by character without size: We can assign character by character


without size with the NULL character at the end. The size of the string is determined by the
compiler automatically.

char str[] = { 'C', 'o', 'm', 'p', 'u', 't', 'e', 'r','\0'};

28
Programming in 'C'

String Input from user:

Syntax Description

scanf(“%s”,str); Read the string until one white space is found, and store it in
str.

scanf(“%^[\n]”,str); %^[x] is format specification. It reads the string until character


x is encountered. (In example \n)

for(i=0;i<6;i++) It reads character by character and stored in str.


{
scanf(“%c”,&str[0]);
}

gets(str); It reads the line until a new line character is encountered. It


can read white spaces also.

String functions: All functions are included in string.h library.

Function Syntax Description

strlen() n=strlen(string); computes string's length

strcpy() strcpy(string1,string2); copies the content of string2 to


string1

strcat() strcat(string1,string2) string2 is appended to string1

strcmp() int strcmp(string1,string2) compares two strings

strrev() char[] strrev(string) Reverse the string

strstr() strstr(string1,string2) Finds the first occurrence of string2


into string1

29
Programming in 'C'

Practical: 5
Aim: Read a string “Hello Diwaliba!!!” from terminal using below functions:

 scanf (), Edit set command[^\n] , getchar(), gets() .Display above string
on terminal using below functions: printf() , putchar() ,puts().

Code:

30
Programming in 'C'

Output:

31
Programming in 'C'

Practical: 5
Post Laboratory Questions

Q. 1 Which function will you choose to join two words?

Q. 2 What will be the output of the following C code?


char str1[] = "Helloworld ";
char str2[] = "Hello";
len = strspn(str1, str2);
printf("Length of initial segment matching %d\n", len );

(A) 6 (B) 5 (C) 4 (D) No Match

Grade

Sign

32
Programming in 'C'

Practical: 6 (A)
Aim: Write a program to find length of the string and display on terminal.

Code:

Output:

33
Programming in 'C'

Practical: 6 (B)
Aim: Write a program to copy one string to another and display on terminal.

Code:

Output:

34
Programming in 'C'

Practical: 6 (C)
Aim: Write a program to compare two strings and display on terminal.

Output:

35
Programming in 'C'

Practical: 6
Post Laboratory Questions

1. Enlist the ways used to print the string on the terminal.

2. The function strcat(s1,s2) appends _____________ string to _________ string.

3. What is the output of the following code segment? How does it come?

printf(“%d”, strcmp(“push”,”pull”));

4. Assume string has the value “ Hello CGPIT.” What will be the output for following
segment:
a. printf(“%s”,string);

b. puts(string);

c. for(i=0;string[i]!=’ ‘;i++)
{ printf(“%c”,string[i]);}

36
Programming in 'C'

5. Write a program to take input character by character until ‘q’ is pressed.

Grade

Sign

37
Programming in 'C'

Practical: 7 (A)

Aim: Write a program to demonstrate the use of string manipulation / handling


functions (strlen, strcpy, strcat, strcmp).

38
Programming in 'C'

Output:

39
Programming in 'C'

Practical: 7 (B)
Aim: Write a program which reads your name from the keyboard and outputs
a list of ASCII codes which represent your name.

Output:

40
Programming in 'C'

Practical: 7

Post Laboratory Questions

Q. 1 What will be the output of the following C code?

char str1[15];
char str2[15];
int mat;
strcpy(str1, "abcdef");
strcpy(str2, "ABCDEF");
mat= strncmp(str1, str2, 4);
if(mat< 0)
printf("str1 is not greater than str2");
else if(mat> 0)
printf("str2 is is not greater than str1");
else
printf("both are equal");

Q.2 The______ function returns the number of characters that are present before the
terminating null character.

(a) strlength(), (b) strlen(), (c) strlent(), (d) strchr()

Q.3 The ______ function appends not more than n characters.

(a) strcat(), (b) strcon(), (c) strncat(), (d) memcat()

Grade

Sign

41
Programming in 'C'

Practical: 8
Functions:
➢ A function is a block of code that performs a specific task.
➢ We can divide a large program into the basic building blocks known as function.
➢ Functions are used to perform certain actions, and they are important for reusing code:
Define the code once, and use it many times.
➢ C allows you to define functions according to your need. These functions are known as
user-defined functions.
➢ Any function (library or user-defined) has 3 things

1. Function declaration
2. Function calling
3. Function definition

➢ Function declaration:
Syntax: return data_typefunction_name (arguments list);
➢ Function Definition:
Syntax:
return data_typefunction_name (argument list)
{
Body;
}
➢ Function Calling:
Syntax: Function_name (param_list);
➢ Formal Arguments: The arguments which are given at the time of function declaration or
function definition are called formal arguments.
➢ Actual Arguments:
➢ The arguments which are given at the time of function calling are called actual arguments.

Example:

#include <stdio.h>
#include <conio.h>
void CGPIT(); /* Function Declaration */
void main()
{
CGPIT(); /* Function Calling */
}

void CGPIT() /* Function Definition*/

42
Programming in 'C'

{
printf("\n WELCOME TO THE WORLD OF CGPIT");
}

How to pass arguments to function?

#include<stdio.h>
int add(int , int );
int main()
{
………..
Sum=add(x , y);
……
}
int add(int n1, int n2 )
{
………..
………..
}

43
Programming in 'C'

Practical: 8 (A)
Aim: Write a program using user-defined function for addition of N numbers.

Code:

Output:

44
Programming in 'C'

Practical: 8 (B)
Aim: Write a program using user-defined function which accepts two
arguments and return the power of them.

Code:

Output:

45
Programming in 'C'

Practical: 8 (C)
Aim: Write a program using user-defined function which calculates area of
circle.

Code:

Output:

46
Programming in 'C'

Practical: 8
Post Laboratory Questions

1. What is the use of the function in C?

2. How many arguments can be passed to a function in C?

3. By default, ______ is the return type of a C function.

4. The main is a user-defined function. How does it differ from other user-defined
functions?

5. Find errors in the following function calls:

i) void xyz( )

ii) xyz( )

Grade

Sign

47
Programming in 'C'

Practical: 9
Recursion:
➢ When a function is calling itself is called recursion.
➢ Recursion is the process of repeating items in a self-similar way. In programming
languages, if a program allows you to call a function inside the same function, then it
is called a recursive call of the function.
➢ It has two things normally: Steps to repeat and terminating condition.

Example:

int m1(int a)
{
if(a==1)
return -1;
else
return a-m1(a-1);
}

The function is called as m1(4), how does it work?

m1(4) m1(3) m1(2) m1(1)

Result:4 -1
0 3

48
Programming in 'C'

Practical: 9
Aim: Write a program using user-defined function which finds the sum of digits
of a number using recursion.

Code:

Output:

49
Programming in 'C'

Practical: 9
Post Laboratory Questions
1. What is the output of following code:

main ( )

printf( “ Hello World \n ” ) ;

main ( ) ;

2. The ________________ data structure used to implement recursive function calls.

3. In the absence of an exit condition in a recursive function, the following error is


given __________ .

4. What will be the output for following code?

#include<stdio.h>
main()
{
int n,i;
n=f(6);
printf("%d",n);
}
f(int x)
{
if(x==2)
return 2;
else
{

50
Programming in 'C'

printf("+");
f(x-1);
}
}

Grade

Sign

51
Programming in 'C'

Practical: 10
Structure
➢ Structure is a group of variables of different data types represented by a single name.
➢ Lets say we need to store the data of students like student name, age, address, id etc. One
way of doing this would be creating a different variable for each attribute, however when
you need to store the data of multiple students then in that case, you would need to create
these several variables again for each student.
➢ We can solve this problem easily by using structure. We can create a structure that has
members for name, id, address and age and then we can create the variables of this
structure for each student.

How to create a structure?

struct struct_name {
DataType member1_name;
DataType member2_name;
DataType member3_name;

};
How to declare variable of a structure?
struct struct_namevar_name;
or
struct struct_name {
DataType member1_name;
DataType member2_name;
DataType member3_name;

} var_name;

How to access data members of a structure using a struct variable?


Structure members are accessed using dot (.) operator.
var_name.member1_name;
var_name.member2_name;

52
Programming in 'C'

Practical: 10
Aim: Define a structure called time_struct containing three members integer
hour, integer minute and integer second. Develop a program that would assign
values to individual members and display the time in the following format:
18:30:25.
Code:

53
Programming in 'C'

Output:

54
Programming in 'C'

Practical: 10
Post Laboratory Questions

1. What are structure types in C?

2. What is the structure?

3. The variable declared in a structure definition are called its ________.

4. How does a structure differ from an array?

5. Write two different ways of assigning values to structure members with example.

Grade

Sign

55
Programming in 'C'

Practical: 11
Aim: Define a structure called bank containing account no., holder name and
balance and display them for N holders whose balance is less than 5000.

Code:

56
Programming in 'C'

Output:

57
Programming in 'C'

Practical: 11
Post Laboratory Questions

Q.1 What will be the output of the C program?


#include<stdio.h>
struct
{ int i;
float ft;
}decl;
int main()
{
decl.i = 4;
decl.ft = 7.96623;
printf("%d %.2f", decl.i, decl.ft);
return 0;
}

Grade

Sign

58
Programming in 'C'

Practical: 12

Aim: Define a structure called student_record containing name, date of birth and
total marks obtained. Use the date structure to represent the date of birth. Develop
a program to read data for 10 students in a class and list them rank-wise.

Code:

59
Programming in 'C'

Output:

60
Programming in 'C'

Practical: 12
Post Laboratory Questions

Q.1 What will be the output of the C program?


#include<stdio.h>
int main()
{
struct bitfields
{
int bits_1: 2;
int bits_2: 4;
int bits_3: 4;
int bits_4: 3;
}bit = {2, 3, 8, 7};
printf("%d %d %d %d", bit.bits_1, bits.bit_2, bit.bits_3, bits.bit_4);
}

Grade

Sign

61
Programming in 'C'

Practical: 13
Pointers:
➢ Pointers are special variables used to store the address of a variable.
➢ The address of any variable can be found using the special operator (&).
➢ For example: address of variable a is identified using &a.
➢ To declare any variable as pointer, the specified operator (*) will be used.

Pointer declaration:
➢ Syntax: data type * variable_name;
➢ Example:
○ int *p1;
○ int* p1;
○ int * p1;

Assigning address:
int a=10;
int *p1=&a;
Variable a is declared as integer and has the value 10.
Variable p1 is declared as a pointer to integer and has the address of variable a.

Example:
void main()
{
int a=300; // a has the value 300.
int *p=&a; // p is the pointer storing the address of variable a.

printf(“%d\n”,a); //300
printf(“%d\n”,&a); //Address of a

printf(“%d\n”,p); // Address of p

printf(“%d\n”,*p); // Value of a (300)

printf(“%d\n”,&p); // Address of p

62
Programming in 'C'

Practical: 13 (A)
Aim: Write a program that demonstrate the use of address (&) and pointer (*)
operators.

Code:

Output:

63
Programming in 'C'

Practical: 13 (B)
Aim: Write a program using user-defined function to interchange the value of two
variables using pointer.

Code:

Output:

64
Programming in 'C'

Practical: 13
Post Laboratory Questions

1. What is pointer?

2. A pointer variable contains as its value the ________ of another variable.

3. What are the arithmetic operators that are permitted on pointer?

4. What is the output of the following code?


int m [ 2 ] ;

*( m + 1 ) = 100 ;

*m=*(m+1);

printf( “ % d ” , m [ 0 ] ) ;

5. Write down benefits of pointers.

65
Programming in 'C'

6. Find error, if any


a. int *y=10;

b. int a, *b=&a;

c. int m;

int **x=&m;

7. Consider the following declarations:

int x=18,y=10;

int *p1=&x, *p2=&y;

What is the value of each of the following expressions?

a. (*p1)++
b. *p1+(*p2)--
c. (*p1)-x+(*p2)-y

Grade

Sign

66
Programming in 'C'

Practical: 14 (A)
Aim: Write a program to compute the sum of all elements stored in an array using
pointers.

Code:

67
Programming in 'C'

Output:

68
Programming in 'C'

Practical: 14 (B)

Aim: Write a program to copy one string to another using pointer and display on
terminal.
Code:

69
Programming in 'C'

Output:

70
Programming in 'C'

Practical: 14 (C)

Aim: Write a program to join two strings using pointer and display on terminal.
Code:

71
Programming in 'C'

Output:

72
Programming in 'C'

Practical: 14

Post Laboratory Questions

Q.1 What will be the output of following program?

#include <stdio.h>
int main()
{
int iVal;
char cVal;
void *ptr; // void pointer
iVal=50; cVal=65;

ptr=&iVal;
printf("value =%d,size= %d\n",*(int*)ptr,sizeof(ptr));

ptr=&cVal;
printf("value =%d,size= %d\n",*(char*)ptr,sizeof(ptr));
return 0;
}

Grade

Sign

73
Programming in 'C'

Practical: 15

Aim: Write a program that demonstrate pointer to pointer concept.


Code:

74
Programming in 'C'

Output:

75
Programming in 'C'

Practical: 15

Post Laboratory Questions

Q.1 What will be the output of following program?

#include <stdio.h>
void fun(int *ptr)
{
*ptr=100;
}
int main()
{
int num=50;
int *pp=#
fun(& *pp);
printf("%d,%d",num,*pp);
return 0;
}

Grade

Sign

76
Programming in 'C'

Practical: 16
File Management:
File Handling is the storing of data in a file using a program. In C programming language, the programs
store results, and other data of the program to a file using file handling in C. Also, we can extract/fetch
data from a file to work with it in the program.

Different operations that can be performed on a file are:

1. Creating a new file


2. Opening an existing file
3. Reading data from an existing file
4. Writing data to a file
5. Moving data to a specific location on the file
6. Closing the file

Functions for file handling:

No. Function Description


1 fopen() opens new or existing file
2 fprintf() write data into the file
3 fscanf() reads data from the file
4 fputc() writes a character into the file
5 fgetc() reads a character from file
6 fclose() closes the file
7 fseek() sets the file pointer to given position
8 fputw() writes an integer to file
9 fgetw() reads an integer from file
10 ftell() returns current position
sets the file pointer to the beginning of the
11 rewind()
file

1. Opening File: fopen()

We must open a file before it can be read, write, or update. The fopen() function is used to open a
file. The syntax of the fopen() is given below.
➢ FILE *fopen( const char * filename, const char * mode );

77
Programming in 'C'

The fopen() function accepts two parameters:

The file name (string). If the file is stored at some specific location, then we must mention the path
at which the file is stored. For example, a file name can be like "c://some_folder/some_file.ext".
The mode in which the file is to be opened. It is a string.
We can use one of the following modes in the fopen() function.

Mode Description
r opens a text file in read mode
w opens a text file in write mode
a opens a text file in append mode
r+ opens a text file in read and write mode
w+ opens a text file in read and write mode
a+ opens a text file in read and write mode
rb opens a binary file in read mode
wb opens a binary file in write mode
ab opens a binary file in append mode
opens a binary file in read and write
rb+
mode
opens a binary file in read and write
wb+
mode
opens a binary file in read and write
ab+
mode

Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()


The concept of dynamic memory allocation in c language enables the C programmer to allocate
memory at runtime.
• malloc() : allocates single block of requested memory.
• calloc() : allocates multiple block of requested memory.
• realloc() : reallocates the memory occupied by malloc() or calloc() functions.
• free() : frees the dynamically allocated memory.

Difference between static memory allocation and dynamic memory allocation.

STATIC MEMORY ALLOCATION DYNAMIC MEMORY ALLOCATION


Memory is allocated at compile time. Memory is allocated at run time.
Memory can't be increased while executing Memory can be increased while executing
program. program.
Used in array. Used in linked list.

78
Programming in 'C'

1. malloc() function:
The malloc() function allocates single block of requested memory. It doesn't initialize memory at
execution time, so it has garbage value initially. It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

ptr=(cast-type*)malloc(byte-size)

2. calloc() function:
The calloc() function allocates multiple block of requested memory. It initially initialize all bytes to
zero. It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:

ptr=(cast-type*)calloc(number, byte-size)

3. realloc() function
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc()
function. In short, it changes the memory size.

the syntax of realloc() function.

ptr=realloc(ptr, new-size)

4. free() function
The memory occupied by malloc() or calloc() functions must be released by calling free() function.
Otherwise, it will consume memory until program exit.

The syntax of free() function.

free(ptr)

79
Programming in 'C'

Practical: 16 (A)

Aim: Write a program to find sum of n elements and allocate memory dynamically
using malloc () function.
Code:

80
Programming in 'C'

Output:

81
Programming in 'C'

Practical: 16 (B)

Aim: Write the above program using calloc () function.


Code:

82
Programming in 'C'

Output:

83
Programming in 'C'

Practical: 16 (C)

Aim: Write the above program using realloc() function.


Code:

84
Programming in 'C'

Output:

85
Programming in 'C'

Practical: 16

Post Laboratory Questions

Q. 1 Which header file should be included to use functions like malloc() and calloc()?

Q. 2 What function should be used to free the memory allocated by calloc() ?

Q. 3 How will you free the memory allocated by the following program?
#include<stdio.h>
#include<stdlib.h>
#define MAXROW 3
#define MAXCOL 4

int main()
{
int **p, i, j;
p = (int **) malloc(MAXROW * sizeof(int*));
return 0;
}

Grade

Sign

86
Programming in 'C'

Practical: 17 (A)

Aim: Write a program to create a file and check whether exist or not.
Code:

87
Programming in 'C'

Output:

88
Programming in 'C'

Practical: 17 (B)

Aim: Write a program to read the content of a file and display it on terminal.
Code:

89
Programming in 'C'

Output:

90
Programming in 'C'

Practical: 17 (C)

Aim: Write a program to read string from keyboard and store the string content in
a file.
Code:

91
Programming in 'C'

Output:

92
Programming in 'C'

Practical: 17

Post Laboratory Questions

Q. 1 Which of the following mode argument is used to truncate?

Q. 2 For binary files, a ___ must be appended to the mode string.

Q. 3 If there is any error while opening a file, fopen will return?

Grade

Sign

93
Programming in 'C'

Practical: 18 (A)

Aim: Write a program to read content of a file and append the same content in
another file.
Code:

94
Programming in 'C'

Output:

95
Programming in 'C'

Practical: 18 (B)

Aim: Write a program to copy the content of source file into destination file.
Code:

96
Programming in 'C'

Output:

97
Programming in 'C'

Practical: 18 (C)

Aim: Write a program that compares two files and return 0 if they are equal and 1
is they are not.
Code:

98
Programming in 'C'

Output:

99
Programming in 'C'

Practical: 18

Post Laboratory Questions

Q. 1 What is the output of this program?

#include <stdio.h>
int main(){
FILE *fp;
char *str;
fp=fopen("demo.txt","r");// demo.txt :you are a good programmer
while(fgets(str,6,fp)!=NULL)
puts(str);
fclose(fp);
return 0;
}

Q. 2 What is the meant by 'a' in the following operation?


fp = fopen("letsfindcourse.txt", "a");

Grade

Sign

100
Programming in 'C'

Practical: 19

Aim: Write a program to read content of file and display last n character on
terminal.
Code:

101
Programming in 'C'

Output:

102
Programming in 'C'

Practical: 19

Post Laboratory Questions

Q. 1 What is the function of FILE *tmpfile(void)?

Q.2 Difference between getc() and fgetc()

Q.3 what is the function of fputs()?

Q. 4 Which function will return the current file position for stream?

Grade

Sign

103

You might also like