0% found this document useful (0 votes)
15 views75 pages

En3es28 - Apc Lab Manual

The document is a lab manual for the Advance Programming with C course at Medi-Caps University, detailing various experiments related to pointers and memory management in C programming. It includes objectives, theoretical background, and sample programs for each experiment, covering topics such as pointer initialization, string manipulation, and file operations. The manual serves as a practical guide for students to enhance their programming skills through hands-on exercises.

Uploaded by

learningsonly14
Copyright
© © All Rights Reserved
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)
15 views75 pages

En3es28 - Apc Lab Manual

The document is a lab manual for the Advance Programming with C course at Medi-Caps University, detailing various experiments related to pointers and memory management in C programming. It includes objectives, theoretical background, and sample programs for each experiment, covering topics such as pointer initialization, string manipulation, and file operations. The manual serves as a practical guide for students to enhance their programming skills through hands-on exercises.

Uploaded by

learningsonly14
Copyright
© © All Rights Reserved
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/ 75

MEDI-CAPS UNIVERSITY

INDORE

DEPARTMENT
OF
COMPUTER SCIENCE & ENGINEERING

Lab Manual
Course: Advance Programming With C

Course Code: EN3ES28

Session: 2023-24
INDEX

S. Experiment Page
No No
1 Program to create, initialize, assign and access a pointer variable.
2 Program to swap two numbers using pointers.
3 Program to change the value of constant integer using pointers
4 Program to print a string using pointer.
5 Program to count vowels and consonants in a string using pointer.
6 Program to find sum of elements of array using pointer.
7 Program to Compare strings using pointer
8 Program to Find smallest number in array using pointer
9 Program to Find largest element in array using pointer.
10 Program to create a pointer array store elements in it and display
11 Program to demonstrate function pointers
12 Program to perform Addition Subtraction Multiplication Division using array of function
pointers.
13 Program to display details of student two (Name, roll no, marks) using structure.
14 Program to display details of employee using array of structure.
15 Program to access member of structures using pointers.
16 Program for passing structure to a function.
17 Program for returning a structure from a function
18 Program to display details of student two (Name, roll no, marks) with the help of union.
19 Program to demonstrate malloc and calloc.
20 Program to allocate memory of array at run time.
21 Program to print the day of week and month of a year
22 Program to calculate area of circle using macro
23 Program to calculate area of circle using macro
24 Program to create a header file and use it in a program.
25 Program to demonstrate file operation. a. Creating a new file b. Opening an existing file c.
Closing a file d. Reading from and writing information to a file
26 Program to count number of words, number of character and number of lines from a given
text file.
27 Program in C to delete a specific line from a file.
28 Write a program in C to copy a file in another name.
29 Write a program in C to merge two files and write it in a new file.
30 Write a program in C to encrypt a text file.
31 Write a program in C to decrypt a previously encrypted file
32 Write a program in C to remove a file from the disk
33 Write a program to draw a circle and fill blue color in it.
34 Write a program to move a circle using suitable animations.

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
1
EN3ES28: Advance Programming with C Experiment no- 1
Experiment Title: Program to create, initialize, assign and access a Page No. 2
pointer variable.

Objective
Understand the concept pointer initialization and declaration.

Theory
The pointer is a variable which stores the address of another variable. This variable can be of type
int, char, array, function, or any other pointer. The size of the pointer depends on the architecture.
However, in 32-bit architecture the size of a pointer is 2 byte.

Consider the following example to define a pointer which stores the address of an

integer.

int n = 10;
int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type
integer.

Program
int main()
{
int num; /*declaration of integer variable*/
int *pNum; /*declaration of integer pointer*/

pNum=& num; /*assigning address of num*/


num=100; /*assigning 100 to variable num*/

//access value and address using variable num


printf("Using variable num:\n");
printf("value of num: %d\naddress of num: %u\n",num,&num);
//access value and address using pointer variable num
printf("Using pointer variable:\n");
printf("value of num: %d\naddress of num: %u\n",*pNum,pNum);

return 0;
}

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
2
OUTPUT

Some Sample questions:


1. What is pointer.
2. What are different types of pointers.
3. Difference between pointer and variable.

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
3
EN3ES28: Advance Programming with C Experiment no- 2
Experiment Title: Program to swap two numbers using pointers. Page No. 4

Objective (s):
To Understand the concept how call by reference.

Theory

Call by reference method copies the address of an argument into the formal parameter. In this
method, the address is used to access the actual argument used in the function call. It means that
changes made in the parameter alter the passing argument. In this method, the memory allocation
is the same as the actual parameters. All the operations in the function are performed on the value
stored at the address of the actual parameter, and the modified value will be stored at the same
address. Means, both the actual and formal parameters refer to same locations, so any changes
made inside the function are actually reflected in actual parameters of caller.

Program

#include <stdio.h>

// function : swap two numbers using pointers


void swap(int *a,int *b)
{
int t;
t = *a;
*a = *b;
*b = t;
}

int main()
{
int num1,num2;

printf("Enter value of num1: ");


scanf("%d",&num1);
printf("Enter value of num2: ");
scanf("%d",&num2);

//print values before swapping


printf("Before Swapping: num1=%d, num2=%d\n",num1,num2);
Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University
4
//call function by passing addresses of num1 and num2
swap(&num1,&num2);

//print values after swapping


printf("After Swapping: num1=%d, num2=%d\n",num1,num2);

return 0;
}
OUTPUT

Some Sample questions:


i. What is call by value?
ii. What is call by Reference?

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
5
EN3ES28: Advance Programming with C Experiment no- 3
Experiment Title: Program to change the value of constant Page No. 6
integer using pointers

Objective:
Understand the concept of constant integer and pointer.

Theory
A constant in C language is a value that remains constant throughout the program and cannot be
changed during program execution. Constants in C can be of many types, including integer
constants, character constants, floating point constants, arithmetic constants, and array constants.
In other words, they are used in programs to represent constant values that will not change. For
example, if you're working on a program that requires a ‘Pi’ value, you can define ‘Pi’ as a
constant so its value doesn't change while the program is running.

Program

#include <stdio.h>

int main()
{
const int a=10; //declare and assign constant integer
int *p; //declare integer pointer
p=&a; //assign address into pointer p

printf("Before changing - value of a: %d",a);

//assign value using pointer


*p=20;

printf("\nAfter changing - value of a: %d",a);


printf("\nWauuuu... value has changed.");

return 0;
}

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
6
OUTPUT

Some Sample questions:

1. What is constant.
2. What is constant pointer.
3.

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
7
EN3ES28: Advance Programming with C Experiment no- 4
Experiment Title: Program to print a string using pointer. Page No. 8

Objective:
Understand the concept of Array, String and Pointer.

Theory
The string itself act as a pointer. The string name is a pointer to the first character in the string.

Accessing string using pointer


Using char* (character pointer), we can access the string.
Example
Declare a char pointer

Assign the string base address(starting address) to the char pointer.


char str[6] = "Hello";
char *ptr;
//string name itself base address of the string
ptr = str; //ptr references str

Program

#include <stdio.h>
int main()
{
char str[100];
char *ptr;

printf("Enter a string: ");


gets(str);

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
8
//assign address of str to ptr
ptr=str;

printf("Entered string is: ");


while(*ptr!='\0')
printf("%c",*ptr++);

return 0;
}

OUTPUT

Some Sample questions:


1. What is String?
2. What is difference between string and Array?

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
9
EN3ES28: Advance Programming with C Experiment no- 5
Experiment Title: Program to count vowels and consonants in a Page No. 10
string using pointer.

Objective
Program to count vowels and consonants in a string using pointer.
Theory
In this program, our task is to count the total number of vowels and consonants present in the
given string. As we know that, the characters a, e, i, o, u are known as vowels in the English
alphabet. Any character other than that is known as the consonant.

Program
#include <stdio.h>
#include <string.h>
int main()
{
char s[1000],*p;
int vowels=0,consonants=0;
printf("Enter the string : ");
gets(s);
p=s;
while(*p!='\0')
{
if( (*p>=65 && *p<=90) || (*p>=97 && *p<=122))
{
if(*p=='a'|| *p=='e'||*p=='i'||*p=='o'||*p=='u'||*p=='A'||*p=='E'||*p=='I'||*p=='O' ||*p=='U')
vowels++;
else
consonants++;
}
p++;
}
printf("vowels = %d\n",vowels);
printf("consonants = %d\n",consonants);
return 0;
}

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
10
OUTPUT

Some Sample questions:


1. What is Null Character?
2. What are different function for reading string.

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
11
EN3ES28: Advance Programming with C Experiment no- 6
Experiment Title: Program to find sum of elements of array using Page No 12
pointer

Objective
Understand the concept of array and Pointer.

Theory
Arrays and pointers are closely related in C. In fact an array declared as int A[10]; can be accessed
using its pointer representation. The name of the array A is a constant pointer to the first element
of the array. So, A can be considered a const int*. Since A is a constant pointer, A = NULL would
be an illegal statement. Arrays and pointers are synonymous in terms of how they use to access
memory. But, the important difference between them is that, a pointer variable can take different
addresses as value whereas, in case of array it is fixed.

Program
int main() {
int arr[100], size;
int *ptr, sum = 0;
printf("Enter the size of the array: ");
scanf("%d", &size);
printf("Enter array elements: ");
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
// Set address of first array element to *ptr
ptr = arr;
for (int i = 0; i < size; i++) {
sum = sum + *ptr;
ptr++; // Increment pointer by one to get next element
}
printf("The sum of array elements is: %d", sum);
return 0;
}

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
12
OUTPUT

Some Sample questions:


1. What is difference between array and pointer?
2. What is void pointer?
3. What is null pointer

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
13
EN3ES28: Advance Programming with C Experiment no- 7
Experiment Title: Write a program to Compare strings using Page No. 14
pointer.

Objective
Compare string using pointer.

Theory

Program
#include <stdio.h>
int main()
{
char string1[50],string2[50],*str1,*str2;
int i,equal = 0;
printf("Enter The First String: ");
gets(string1);
printf("Enter The Second String: ");
gets(string2);
str1 = string1;
str2 = string2;
while(*str1 == *str2)
{
if ( *str1 == '\0' || *str2 == '\0' )
break;
str1++;
str2++;
}
if( *str1 == '\0' && *str2 == '\0' )
printf("\n\nBoth Strings Are Equal.");
else
printf("\n\nBoth Strings Are Not Equal.");
}

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
14
OUTPUT

Some Sample questions:

1. What are different function available for string comparison?

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
15
EN3ES28: Advance Programming with C Experiment no- 8
Experiment Title: Write a Program to find smallest number in Page No 16
array using pointer.

Objective
To Find smallest number in array using pointer.

Theory
We ask the user to input N integer numbers and store it inside a[N]. Next, we assign base address
to pointer variable small. Next, we iterate through the array elements one by one using a for loop,
and check if any of the elements of the array is smaller than whatever the value present at *small.
If there is any element smaller than *small, we assign that value to *small. Once the control exits
the for loop, we print the value present in pointer variable *small, which holds the smallest
element in the array.

Program
#include<stdio.h>
void main()
{
int i,*ptr, n,a[100],small;
printf("Enter How many number you want?:\n") ;
scanf("%d",&n) ;
printf("Enter %d numbers\n",n) ;
for(i=0;i<n;i++)
{
scanf("%d",&a[i]) ;
}
ptr = a;
small= *ptr;
for(i=0;i<n;i++)
{
if(*ptr<small)
{
small=*ptr;
}
*ptr++;
}
printf("Smallest Number is : %d",small);
}

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
16
OUTPUT

Some Sample questions:


1. Write a program to convert string in upper case using pointer.
2. Write a program to count words in a given string using pointer.

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
17
EN3ES28: Advance Programming with C Experiment no- 9
Experiment Title: Write a Program to find largest element in array Page No 18
using pointer.

Objective
To Find largest element in array using pointer.

Theory
.

Program
#include<stdio.h>
int main()
{
int i,*ptr, n,a[100],max;

printf("Enter How many number you want?:\n") ;


scanf("%d",&n) ;

printf("Enter %d numbers\n",n) ;
for(i=0;i<n;i++)
{
scanf("%d",&a[i]) ;
}
ptr = a;
max= *ptr;
for(i=0;i<n;i++)
{
if(*ptr>max)
{
max=*ptr;
}
*ptr++;
}
printf("Largest Number is : %d",max);
return 0;
}

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
18
OUTPUT

Some Sample questions:


i. Write a program to delete a specific element from array?
ii. Write a program to sort array element using pointer pointer?

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
19
EN3ES28: Advance Programming with C Experiment no- 10
Experiment Title: Write a Program to create a pointer array store Page No 20
elements in it and display.

Objective
Program to create a pointer array store elements in it and display.

Theory

Program
#include <stdio.h>
int main() {
int data[5];
printf("Enter elements: ");
for (int i = 0; i < 5; ++i)
scanf("%d", data + i);

printf("You entered: \n");


for (int i = 0; i < 5; ++i)
printf("%d\n", *(data + i));
return 0;
}

OUTPUT

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
20
EN3ES28: Advance Programming with C Experiment no- 11
Experiment Title: Write a Program to demonstrate function Page No 20
pointers

Objective
Program to demonstrate function pointers

Theory
The pointer variable that holds a function’s address is called a function pointer. The basic
advantage of a function pointer is that one function can be passed as a parameter to another
function. Function pointer calls are faster than normal functions. The code of a function always
resides in memory, which means that the function has some address. We can get the address of
memory by using the function pointer.

Declaration of a function pointer

Declaration of a function pointer

return type (*ptr_name)(type1, type2…);

For example:

int (*ip) (int);

Calling a function through a function pointer

result = (*fp)( a , b); // Calling a function using function pointer.

Program
#include <stdio.h>
int add(int,int);
int main()
{
int a,b;
int (*ip)(int,int);
int result;
printf("Demonstration of function Pointer\n");
printf("Enter the values of a and b : ");
scanf("%d %d",&a,&b);
ip=add;
result=(*ip)(a,b);
printf("Value after addition is : %d",result);
return 0;
}
int add(int a,int b)
Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University
21
{
int c=a+b;
return c;
}

OUTPUT

Some Sample questions:


i. What is function pointer?
ii. What are the application of function pointer?

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
22
EN3ES28: Advance Programming with C Experiment no- 12
Experiment Title: Write a Program to perform Addition Page No 23
Subtraction Multiplication Division using array of function
pointers.

Objective
Program to perform Addition Subtraction Multiplication Division using array of function pointers.

Theory
Function pointers are used in those applications where we do not know in advance which function
will be called. In an array of function pointers, array takes the addresses of different functions, and
the appropriate function will be called based on the index number.

Program

#include <stdio.h>
float add(float,int);
float sub(float,int);
float mul(float,int);
float div(float,int);
int main()
{
float x; // variable declaration.
int y;
float (*fp[4]) (float,int); // function pointer declaration.
fp[0]=add; // assigning addresses to the elements of an array of a function pointer.
fp[1]=sub;
fp[2]=mul;
fp[3]=div;
printf("Enter the values of x and y :");
scanf("%f %d",&x,&y);
float r=(*fp[0]) (x,y); // Calling add() function.
printf("\nSum of two values is : %f",r);
r=(*fp[1]) (x,y); // Calling sub() function.
printf("\nDifference of two values is : %f",r);
r=(*fp[2]) (x,y); // Calliung sub() function.
printf("\nMultiplication of two values is : %f",r);
r=(*fp[3]) (x,y); // Calling div() function.
printf("\nDivision of two values is : %f",r);
return 0;
}

float add(float x,int y)


{
float a=x+y;
Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University
23
return a;
}
float sub(float x,int y)
{
float a=x-y;
return a;
}
float mul(float x,int y)
{
float a=x*y;
return a;
}
float div(float x,int y)
{
float a=x/y;
return a;
}

OUTPUT

Some Sample questions:


i. What is array of function pointer?
ii. What are the application of array of function pointer?

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
24
EN3ES28: Advance Programming with C Experiment no- 13
Experiment Title: Write a Program to display details of student Page No 25
two (Name, roll no, marks) using structure.

Objective
Program to display details of student two (Name, roll no, marks) using structure.

Theory

Structure in c is a user-defined data type that enables us to store the collection of different data
types. Each element of a structure is called a member. Structures simulate the use of classes and
templates as it can store various information
The struct keyword is used to define the structure. Let's see the syntax to define the structure in c.
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};

Declaring structure variable

We can declare a variable for the structure so that we can access the member of the structure easily.
There are two ways to declare structure variable:

1. By struct keyword within main() function


2. By declaring a variable at the time of defining the structure.

Program
#include <stdio.h>
struct student {
char name[50];
int roll;
float marks;
} s;

int main() {
printf("Enter information:\n");
printf("Enter name: ");
fgets(s.name, sizeof(s.name), stdin);

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
25
printf("Enter roll number: ");
scanf("%d", &s.roll);
printf("Enter marks: ");
scanf("%f", &s.marks);

printf("Displaying Information:\n");
printf("Name: ");
printf("%s", s.name);
printf("Roll number: %d\n", s.roll);
printf("Marks: %.1f\n", s.marks);

return 0;
}

OUTPUT

Some Sample questions:


i. What is structure?
ii. What is difference between structure and Array?

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
26
EN3ES28: Advance Programming with C Experiment no- 14
Experiment Title: write a Program to display details of employee Page No 27
using array of structure.

Objective
Program to display details of employee using array of structure.

Theory
An array of structures in C can be defined as the collection of multiple structures variables where
each variable contains information about different entities. The array of structures in C are used to
store information about multiple entities of different data types. The array of structures is also
known as the collection of structures.

Program

#include<stdio.h>
struct employee
{
int id,age,salary;
char name[25];
}emp[100];

void main()
{
int i,n;
printf("Enter the no of employees\n");
scanf("%d",&n);
printf("Enter employee info as id , name , age , salary\n");
Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University
27
for(i=0;i<n;i++)
{
scanf("%d %s %d %d",&emp[i].id,emp[i].name,&emp[i].age,&emp[i].salary);
}
printf("\nEMP_NAME\tEMP_NAME\tEMP_AGE\t\tEMP_SAL\n");
for(i=0;i<n;i++)
{
printf("%d\t\t%s\t\t%d\t\t%d\n",emp[i].id,emp[i].name,emp[i].age,emp[i].salary);
}
}
OUTPUT

Some Sample questions:


i. What is array of structure?
ii. What are the application of array of structure?

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
28
EN3ES28: Advance Programming with C Experiment no- 15
Experiment Title: Write a Program to access member of Page No 29
structures using pointers.

Objective
Program to access member of structures using pointers

Theory
The pointers to a structure in C in very similar to the pointer to any in-built data type variable.

The syntax for declaring a pointer to structure variable is as follows:

struct structure_name *pointer_variable

struct Employee
{
char name[50];
int age;
float salary;
} employee_one;
struct Employee *employee_ptr;
We can use addressOf operator(&) to get the address of structure variable.

struct Employee *employee_ptr = &employee_one;

To access a member variable of structure using variable identifier we use dot(.) operator whereas
we use arrow(->) operator to access member variable using structure pointer.

employee_ptr->salary;

Program
#include <stdio.h>

struct employee {
char name[100];
int age;
float salary;
char department[50];
};

int main(){
struct employee employee_one, *ptr;

printf("Enter Name, Age, Salary and Department of Employee\n");


scanf("%s %d %f %s", &employee_one.name, &employee_one.age,
Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University
29
&employee_one.salary, &employee_one.department);

/* Printing structure members using arrow operator */


ptr = &employee_one;
printf("\nEmployee Details\n");
printf(" Name : %s\n Age : %d\n Salary = %f\n Dept : %s\n",
ptr->name, ptr->age, ptr->salary, ptr->department);

return 0;
}

OUTPUT

Some Sample questions:


i. What is operator is used to access variable of structure using structure pointer?
ii.

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
30
EN3ES28: Advance Programming with C Experiment no- 16
Experiment Title: Write a Program for passing structure to a Page No 31
function.

Objective
Program for passing structure to a function

Theory

• A structure can be passed to any function from main function or from any sub function.
• Structure definition will be available within the function only.
• It won’t be available to other functions unless it is passed to those functions by value or by
address(reference).
• Else, we have to declare structure variable as global variable. That means, structure
variable should be declared outside the main function. So, this structure will be visible to
all the functions in a C program.
PASSING STRUCTURE TO FUNCTION IN C:
It can be done in below 3 ways.
• Passing structure to a function by value
• Passing structure to a function by address(reference)
• No need to pass a structure – Declare structure variable as global

Program
#include <stdio.h>
#include <string.h>

struct student
{
int id;
char name[20];
float percentage;
};
void display(struct student record);
int main()
{
struct student record;

record.id=1607;
strcpy(record.name, "Shantilal Bhayal");
record.percentage = 86.5;

display(record);
return 0;
}
Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University
31
void display(struct student record)
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}

OUTPUT

Some Sample questions:


i. How structure is passed to function?
ii. What are the different way to pass structure to a function?

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
32
EN3ES28: Advance Programming with C Experiment no- 17
Experiment Title: Write a Program for returning a structure from Page No 33
a function.

Objective
Program for returning a structure from a function

Theory
To return a structure from a function the return type should be a structure only.
Returning a struct by value means that a function generates a copy of the entire struct and passes it
back to the caller. This approach is straightforward and effective for small or moderately sized
structs.

Program
#include <stdio.h>
struct student
{
char name[50];
int age;
};

// function prototype
struct student getInformation();

int main()
{
struct student s;

s = getInformation();

printf("\nDisplaying information\n");
printf("Name: %s", s.name);
printf("\nRoll: %d", s.age);

return 0;
}
struct student getInformation()
{
struct student s1;

printf("Enter name: ");


scanf ("%[^\n]%*c", s1.name);

printf("Enter age: ");


scanf("%d", &s1.age);
Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University
33
return s1;
}

OUTPUT

Some Sample questions:


i. How structure is return by reference?
ii.

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
34
EN3ES28: Advance Programming with C Experiment no- 18
Experiment Title: Write a Program to display details of student Page No 35
(Name, roll no, marks) with the help of union.

Objective
Program to display details of student two (Name, roll no, marks) with the help of union

Theory
A union is a user-defined type similar to structs in C except for one key difference.
Structures allocate enough space to store all their members, whereas unions can only hold one
member value at a time.
How to define a union?
We use the union keyword to define unions. Here's an example:
union car
{
char name[50];
int price;
};
The above code defines a derived type union car.
Create union variables
When a union is defined, it creates a user-defined type. However, no memory is allocated. To
allocate memory for a given union type and work with it, we need to create variables.
Here's how we create union variables.
union car
{
char name[50];
int price;
};
int main()
{
union car car1, car2, *car3;
return 0;
}
Another way of creating union variables is:
union car
{
char name[50];
int price;
} car1, car2, *car3;
In both cases, union variables car1, car2, and a union pointer car3 of union car type are created.

Access members of a union


We use the . operator to access members of a union. And to access pointer variables, we use the ->
operator.

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
35
Program

#include <stdio.h>
union student {
char name[50];
int roll;
float marks;
} u;

int main()
{
printf("Enter information:\n");
printf("Enter name: ");
fgets(u.name, sizeof(u.name), stdin);

printf("Enter roll number: ");


scanf("%d", &u.roll);
printf("Enter marks: ");
scanf("%f", &u.marks);

printf("Displaying Information:\n");
printf("Name: ");
printf("%s", u.name);
printf("Roll number: %d\n", u.roll);
printf("Marks: %.1f\n", u.marks);

return 0;
}
OUTPUT

Some Sample questions:


i. What is union?
ii. What is difference between union and structure?

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
36
EN3ES28: Advance Programming with C Experiment no- 19
Experiment Title: Write a Program to demonstrate malloc and Page No 37
calloc.

Objective
To Understand the concept of dynamic memory allocation

Theory
C malloc()
The name "malloc" stands for memory allocation.
The malloc() function reserves a block of memory of the specified number of bytes. And, it
returns a pointer of void which can be casted into pointers of any form.
Syntax of malloc()
ptr = (castType*) malloc(size);
Example
ptr = (float*) malloc(100 * sizeof(float));
The above statement allocates 400 bytes of memory. It's because the size of float is 4 bytes. And,
the pointer ptr holds the address of the first byte in the allocated memory.
The expression results in a NULL pointer if the memory cannot be allocated.
C calloc()
The name "calloc" stands for contiguous allocation.
The malloc() function allocates memory and leaves the memory uninitialized, whereas the calloc()
function allocates memory and initializes all bits to zero.
Syntax of calloc()
ptr = (castType*)calloc(n, size);
Example:
ptr = (float*) calloc(25, sizeof(float));
The above statement allocates contiguous space in memory for 25 elements of type float.

Program
#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));

// if memory cannot be allocated


if(ptr == NULL) {

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
37
printf("Error! memory not allocated.");
exit(0);
}

printf("Enter elements: ");


for(i = 0; i < n; ++i) {
scanf("%d", ptr + i);
sum += *(ptr + i);
}

printf("Sum = %d", sum);

// deallocating the memory


free(ptr);

return 0;
}

OUTPUT

// Program to calculate the sum of n numbers entered by the user-Calloc()

#include <stdio.h>
#include <stdlib.h>

int main() {
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);

ptr = (int*) calloc(n, sizeof(int));


if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University
38
}

printf("Enter elements: ");


for(i = 0; i < n; ++i) {
scanf("%d", ptr + i);
sum += *(ptr + i);
}

printf("Sum = %d", sum);


free(ptr);
return 0;
}

Some Sample questions:


i. What is dynamic memory allocation?
ii. What is malloc() and calloc()?

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
39
EN3ES28: Advance Programming with C Experiment no- 20
Experiment Title: Write a Program to allocate memory of array at Page No 40
run time.

Objective
Program to allocate memory of array at run time.

Theory
An array is a collection of a fixed number of values. You can't change the size of an array once it's
been declared.It's possible that the size of the Array you declared is insufficient at times. You can
manually set RAM during runtime to remedy this problem. In C programming, we called it
dynamic memory allocation. Malloc(), calloc(), and realloc() are library functions that are used to
allocate memory dynamically.
C malloc() method
In C, the "malloc" or "memory allocation" method is used to allocate a single huge block of
memory with the specified size dynamically. It returns a void pointer that can be cast into any
other type of pointer. Because it does not initialize memory at runtime, each block is initially set
to the default garbage value.

Syntax
ptr = (cast-type*) malloc(byte-size)
For Example:
ptr = (int*) malloc(100 * sizeof(int));

Program

#include <stdio.h>
#include <stdlib.h>
int main() {
int* ptr;
int n, i;
printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements: %d\n", n);
ptr = (int*)malloc(n * sizeof(int));
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
printf("Memory successfully allocated using malloc.\n");
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
40
}
}
return 0;
}

OUTPUT

Some Sample questions:


i. What is dynamic Array?
ii. What are the different function used for memory allocation?

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
41
EN3ES28: Advance Programming with C Experiment no- 21
Experiment Title: Write a Program to print the day of week and Page No 42
month of a year.

Objective
To understand the concept of Enum.

Theory
Enum in C
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.

The following is the way to define the enum in C:

enum flag{integer_const1, integer_const2,.....integter_constN};

In the above declaration, we define the enum named as flag containing 'N' integer constants. The
default value of integer_const1 is 0, integer_const2 is 1, and so on. We can also change the default
value of the integer constants at the time of the declaration.

For example:
enum fruits{mango, apple, strawberry, papaya};
The default value of mango is 0, apple is 1, strawberry is 2, and papaya is 3.

Program

include<stdio.h> //including a header file


enum week{Mon=1, Tue, Wed, Thur, Fri, Sat, Sun}; //using enum
enum year{jan,feb,march,april,may,june,july,aug,sept,oct,nov,dec}; //using enu
int main() //integer datatype of main function
{
enum week day; //enum variable
day = Wed;
printf("Day of Week=%d\n",day); //printing
enum year month; //enum variable
month = june;
printf("Month of Year =%d",month); //printin
return 0;
}

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
42
OUTPUT

Some Sample questions:


i. What is Enum?
ii. What is the use of Enum?

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
43
EN3ES28: Advance Programming with C Experiment no- 22
Experiment Title: Write a Program to calculate area of circle Page No 44
using macro.

Objective
To Understand the concept of Macro

Theory
C macros provide a potent method for code reuse and simplification. They let programmers
construct symbolic names or phrases that are changed to certain values before the compilation
process begins. The use of more macros makes code easier to comprehend, maintain, and makes
mistakes less likely. In this article, we'll delve deeper into the concept of C macros and cover their
advantages, ideal usage scenarios, and potential hazards.

A macro is a segment of code which is replaced by the value of macro. Macro is defined by
#define directive.
There are two types of macros:

• Object-like Macros
• Function-like Macros

Object-like Macros
The object-like macro is an identifier that is replaced by value. It is widely used to represent
numeric constants. For example:

#define PI 3.14

Program

#include<stdio.h>

#define PI 3.14

int main()
{
float r, area;

printf("Enter Radius of Circle\n");


scanf("%f", &r);

area = PI * r * r;

printf("Area of Circle is %f\n", area);

return 0;
Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University
44
}

OUTPUT

Some Sample questions:


i. What is macro?
ii. What is difference between enum and macro?

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
45
EN3ES28: Advance Programming with C Experiment no- 23
Experiment Title: Write a Program to calculate area of circle Page No 46
using macro function.

Objective
To Understand the concept of macro with argument.

Theory
A simple macro always stands for exactly the same text, each time it is used. Macros can be more
flexible when they accept arguments. Arguments are fragments of code that you supply each time
the macro is used. These fragments are included in the expansion of the macro according to the
directions in the macro definition. A macro that accepts arguments is called a function-like macro
because the syntax for using it looks like a function call.

To define a macro that uses arguments, you write a `#define' directive with a list of argument
names in parentheses after the name of the macro. The argument names may be any valid C
identifiers, separated by commas and optionally whitespace. The open-parenthesis must follow the
macro name immediately, with no space in between.

For example, here is a macro that computes the minimum of two numeric values, as it is defined in
many C programs:

#define min(X, Y) ((X) < (Y) ? (X) : (Y))

Program

#include<stdio.h>
#include<conio.h>
#define AREA(x) 3.14*x*x
int main()
{
float r1,r2,area;
printf("Enter 1st radius of circle :-");
scanf("%f",&r1);
area=AREA(r1);
printf("Area of circle =%.2f",area);
printf("\nEnter 2st radius of circle :-");
scanf("%f",&r2);
area=AREA(r2);
printf("Area of circle =%.2f",area);
return 0;
}

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
46
OUTPUT

Some Sample questions:


i. What is macro with arguments?
ii. What are the different type of macros?

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
47
EN3ES28: Advance Programming with C Experiment no- 24
Experiment Title: Program to create a header file and use it in a Page No 48
program

Objective
Program to create a header file and use it in a program

Theory
The files with .h extension are called header files in C. These header files generally contain
function declarations which we can be used in our main C program, like for e.g. there is need to
include stdio.h in our C program to use function printf() in the program.
Creating myhead.h : Write the below code and then save the file as myhead.h or you can give any
name but the extension should be .h indicating its a header file.
Including the .h file in other program
Program

Myhead.h

void add(int a, int b)


{
printf("Added value=%d\n", a + b);
}
void multiply(int a, int b)
{
printf("Multiplied value=%d\n", a * b);
}
// C program to use the above created header file
#include <stdio.h>
#include "myhead.h"
int main()
{
add(4, 6);

/*This calls add function written in myhead.h


and therefore no compilation error.*/
multiply(5, 5);

// Same for the multiply function in myhead.h


printf("BYE!See you Soon");
return 0;
}

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
48
OUTPUT

Some Sample questions:


i. What is header file?
ii. How to create a header file?

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
49
EN3ES28: Advance Programming with C Experiment no- 25
Experiment Title: Write a Program to demonstrate file operation. Page No 50
a. Creating a new file b. Opening an existing file c. Closing a file
d. Reading from and writing information to a file

Objective
Demonstration of File Operation

Theory
File handing in C is the process in which we create, open, read, write, and close operations on a
file. C language provides different functions such as fopen(), fwrite(), fread(), fseek(), fprintf(),
etc. to perform input, output, and many different C file operations in our program.
C File Operations
C file operations refer to the different possible operations that we can perform on a file in C such
as:
1. Creating a new file – fopen() with attributes as “a” or “a+” or “w” or “w+”
2. Opening an existing file – fopen()
3. Reading from file – fscanf() or fgets()
4. Writing to a file – fprintf() or fputs()
5. Moving to a specific location in a file – fseek(), rewind()
6. Closing a file – fclose()
File Pointer in C
A file pointer is a reference to a particular position in the opened file. It is used in file handling to
perform all file operations such as read, write, close, etc. We use the FILE macro to declare the
file pointer variable. The FILE macro is defined inside <stdio.h> header file.
Syntax of File Pointer
FILE* pointer_name;
File Pointer is used in almost all the file operations in C.
Open a File in C
For opening a file in C, the fopen() function is used with the filename or file path along with the
required access modes.
Syntax of fopen()
FILE* fopen(const char *file_name, const char *access_mode);

Program

#include <stdio.h>

int main(void) {
// creating a FILE variable
FILE *fptr;
// integer variable
int id, score;
Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University
50
int i, s;
// character variable
char name[255];
char n[255];
// open the file in write mode
fptr = fopen("student", "w");
if (fptr != NULL) {
printf("File created successfully!\n");
}
else {
printf("Failed to create the file.\n");
// exit status for OS that an error occured
return -1;
}
// get student detail
printf("Enter student name: ");
gets(name);
printf("Enter student ID: ");
scanf("%d", &id);
printf("Enter student score: ");
scanf("%d", &score);

// write data in file


fprintf(fptr, "%d %d %s", id, score, name);
// close connection
fclose(fptr);
// open file for reading
fptr = fopen("student", "r");
// display detail
printf("\nStudent Details:\n");
fscanf(fptr, "%d %d %[^\n]s", &i, &s, n);
printf("ID: %d\n", i);
printf("Name: %s\n", n);
printf("Score: %d\n", s);
printf("\nEnd of file.\n");
// close connection
fclose(fptr);

return 0;
}

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
51
OUTPUT

Some Sample questions:


i. What is File handling?
ii. What are the different function used for file handling?

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
52
EN3ES28: Advance Programming with C Experiment no- 26
Experiment Title: Write a Program to count number of words, Page No 53
number of character and number of lines from a given text file.

Objective
Program to count number of words, number of character and number of lines from a given text file

Theory
Logic to count characters, words and lines in a file
Step by step descriptive logic to count characters, words and lines in a text file.

1. Open source file in r (read) mode.


2. Initialize three variables characters = 0, words = 0 and lines = 0 to store counts.
3. Read a character from file and store it to some variable say ch.
4. Increment characters count.
Increment words count if current character is whitespace character i.e. if (ch == ' ' || ch == '\t'
|| ch == '\n' || ch == '\0').
Increment lines count if current character is new line character i.e. if (ch == '\n' || ch == '\0').
5. Repeat step 3-4 till file has reached end.
6. Finally after file has reached end increment words and lines count by one if total characters
> 0 to make sure you count last word and line.
Program
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * file;
char fileName[100], ch;
int characters, words, lines;
printf("Enter the file name: ");
scanf("%s", fileName);
// open file in read mode
file = fopen(fileName, "r");
if (file == NULL)
{
printf("Unable to open the file");
exit(EXIT_FAILURE);
}

characters = words = lines = 0;


while ((ch = fgetc(file)) != EOF)
{
characters++;

//check for lines


Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University
53
if (ch == '\n' || ch == '\0')
lines++;

//check for words


if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')
words++;
}

if (characters > 0)
{
words++;
lines++;
}

//Display
printf("\nTotal Number of characters: %d", characters);
printf("\nTotal Number of words: %d", words);
printf("\nTotal Number of lines: %d", lines);

fclose(file);

return 0;
}

OUTPUT

Some Sample questions:


i. What is the purpose of fopen() function?
ii. What is the use us of fgetc() function?

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
54
EN3ES28: Advance Programming with C Experiment no- 27
Experiment Title: Write a Program in C to delete a specific line Page 55 of
from a file.

Objective
Program in C to delete a specific line from a file

Theory
Then rewind() function is used to set the file position to the beginning of the file of the given
stream. Enter the line number of the line to be deleted using ‘delete_line’ variable.
Then ‘fileptr2’ variable is used to open the new file in write mode. While loop is used to print the
number of characters present in the file. if condition statement is used to copy except the line to be
deleted. The file.Putc() function is used to copy all lines in file replica.c.
Then close the files and rename the file replica.c to original name. Using while loop print the
contents of the file after being modified.
Program
#include <stdio.h>
int main()
{
FILE *fileptr1, *fileptr2;
char filename[40];
char ch;
int delete_line, temp = 1;
printf("Enter file name: ");
scanf("%s", filename);
//open file in read mode
fileptr1 = fopen(filename, "r");
ch = getc(fileptr1);
while (ch != EOF)
{
printf("%c", ch);
ch = getc(fileptr1);
}
//rewind
rewind(fileptr1);
printf(" \n Enter line number of the line to be deleted:");
scanf("%d", &delete_line);
//open new file in write mode
fileptr2 = fopen("replica.c", "w");
ch = getc(fileptr1);
while (ch != EOF)
{
ch = getc(fileptr1);
if (ch == '\n')

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
55
temp++;
//except the line to be deleted
if (temp != delete_line)
{
//copy all lines in file replica.c
putc(ch, fileptr2);
}
}
fclose(fileptr1);
fclose(fileptr2);
remove(filename);
//rename the file replica.c to original name
rename("replica.c", filename);
printf("\n The contents of file after being modified are as follows:\n");
fileptr1 = fopen(filename, "r");
ch = getc(fileptr1);
while (ch != EOF)
{
printf("%c", ch);
ch = getc(fileptr1);
}
fclose(fileptr1);
return 0;
}

OUTPUT

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
56
Some Sample questions:
i. What is rewind() function?
ii. How to delete specific line number?

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
57
EN3ES28: Advance Programming with C Experiment no- 28
Experiment Title: Write a program in C to copy a file in another Page No 58
name.

Objective
Write a program in C to copy a file in another name.

Theory
Operations on files

The operations that can be carried out on files in C language are as follows −

• Naming the file.


• Opening the file.
• Reading from the file.
• Writing into the file.
• Closing the file.

Syntax
The syntax for opening and naming file is as follows −
FILE *File pointer;

For example, FILE * fptr;

File pointer = fopen ("File name”, "mode”);

For example, fptr = fopen ("sample.txt”, "r”);

FILE *fp;
fp = fopen ("sample.txt”, "w”);

The syntax for reading from file is as follows −

int fgetc( FILE * fp );// read a single character from a file

The syntax for writing into file is as follows −

int fputc( int c, FILE *fp ); // write individual characters to a stream

With the help of these functions, we can copy the content of one file into another file.

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
58
Program

#include <stdio.h>
#include <stdlib.h>

void main()
{
FILE *fptr1, *fptr2;
char ch, fname1[20], fname2[20];

printf("\n\n Copy a file in another name :\n");


printf("----------------------------------\n");
printf(" Input the source file name : ");
scanf("%s",fname1);

fptr1=fopen(fname1, "r");
if(fptr1==NULL)
{
printf(" File does not found or error in opening.!!");
exit(1);
}
printf(" Input the new file name : ");
scanf("%s",fname2);
fptr2=fopen(fname2, "w");
if(fptr2==NULL)
{
printf(" File does not found or error in opening.!!");
fclose(fptr1);
exit(2);
}
while(1)
{
ch=fgetc(fptr1);
if(ch==EOF)
{
break;
}
else
{
fputc(ch, fptr2);
}
}
printf(" The file %s copied successfully in the file %s. \n\n",fname1,fname2);
fclose(fptr1);
fclose(fptr2);
getchar();
}

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
59
OUTPUT

Some Sample questions:


i. Which function is used to copy content?
ii. How to close a file?

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
60
EN3ES28: Advance Programming with C Experiment no- 29
Experiment Title: Write a program in C to merge two files and Page No 61
write it in a new file

Objective
Write a program in C to merge two files and write it in a new file

Theory
Merging two files means the content of any two files (entered by user at runtime) gets merged into
the third file in a way that, the content of first source file gets copied to the target file, and then the
content of second source file gets appended to the target file.
Let the given two files be file1.txt and file2.txt.
The following are steps to merge.
1) Open file1.txt and file2.txt in read mode.
2) Open file3.txt in write mode.
3) Run a loop to one-by-one copy characters of file1.txt to file3.txt.
4) Run a loop to one-by-one copy characters of file2.txt to file3.txt.
5) Close all files.
To successfully run the below program file1.txt and fil2.txt must exist in same folder.

Program

#include <stdio.h>
#include <stdlib.h>

void main()
{
FILE *fold1, *fold2, *fnew;
char ch, fname1[20], fname2[20], fname3[30];

printf("\n\n Merge two files and write it in a new file :\n");


printf("-------------------------------------------------\n");

printf(" Input the 1st file name : ");


scanf("%s",fname1);
printf(" Input the 2nd file name : ");
scanf("%s",fname2);
printf(" Input the new file name where to merge the above two files : ");
scanf("%s",fname3);
fold1=fopen(fname1, "r");
fold2=fopen(fname2, "r");
if(fold1==NULL || fold2==NULL)
{
// perror("Error Message ");
printf(" File does not exist or error in opening...!!\n");
exit(EXIT_FAILURE);
Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University
61
}
fnew=fopen(fname3, "w");
if(fnew==NULL)
{
// perror("Error Message ");
printf(" File does not exist or error in opening...!!\n");
exit(EXIT_FAILURE);
}
while((ch=fgetc(fold1))!=EOF)
{
fputc(ch, fnew);
}
while((ch=fgetc(fold2))!=EOF)
{
fputc(ch, fnew);
}
printf(" The two files merged into %s file successfully..!!\n\n", fname3);
fclose(fold1);
fclose(fold2);
fclose(fnew);
}

OUTPUT

Some Sample questions:


i. Write a program in C to display the last modification time of a file?
ii. Write a program in C language to find the size of a given file.?

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
62
EN3ES28: Advance Programming with C Experiment no- 30
Experiment Title: Write a program in C to encrypt a text file. Page No 63

Objective
To Understand the concept of encryption.

Theory
Encrypting a file means, we will convert the plaintext (original content of file) to ciphertext. So
that our credential information stored in a file gets converted into ciphertext. Whereas decrypting
a file means getting our content back to original form. To encrypt a file in C programming, you
have to open that file and start reading the file character by character. At the time of reading,
create some algorithm to encrypt the content of the file, and place the content in a temporary file,
character by character. Finally, copy the content of the temporary file to the original file as shown
in the program given below:

Program

#include <stdio.h>
#include <stdlib.h>

void main()
{
char fname[20], ch;
FILE *fpts, *fptt;

printf("\n\n Encrypt a text file :\n");


printf("--------------------------\n");

printf(" Input the name of file to encrypt : ");


scanf("%s",fname);

fpts=fopen(fname, "r");
if(fpts==NULL)
{
printf(" File does not exists or error in opening..!!");
exit(1);
}
fptt=fopen("temp.txt", "w");
if(fptt==NULL)
{
printf(" Error in creation of file temp.txt ..!!");
fclose(fpts);
exit(2);
}
while(1)
{
Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University
63
ch=fgetc(fpts);
if(ch==EOF)
{
break;
}
else
{
ch=ch+100;
fputc(ch, fptt);
}
}
fclose(fpts);
fclose(fptt);
fpts=fopen(fname, "w");
if(fpts==NULL)
{
printf(" File does not exists or error in opening..!!");
exit(3);
}
fptt=fopen("temp.txt", "r");
if(fptt==NULL)
{
printf(" File does not exists or error in opening..!!");
fclose(fpts);
exit(4);
}
while(1)
{
ch=fgetc(fptt);
if(ch==EOF)
{
break;
}
else
{
fputc(ch, fpts);
}
}
printf(" File %s successfully encrypted ..!!\n\n", fname);
fclose(fpts);
fclose(fptt);
}

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
64
OUTPUT

Some Sample questions:


i. What is encryption?
ii. ?

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
65
EN3ES28: Advance Programming with C Experiment no- 31
Experiment Title: Write a program in C to decrypt a previously Page No 66
encrypted file.

Objective
To Understand the concept of decryption.

Theory

Decryption: Decryption is the process of converting a meaningless message (Ciphertext) into its
original form (Plaintext). It works by applying the conversion algorithm opposite of the one that is
used to encrypt the data. The same key is required to decrypt the information back to its normal
form.
Program

#include <stdio.h>
#include <stdlib.h>

void main()
{
char ch, fname[20];
FILE *fpts, *fptt;

printf("\n\n Decrypt a text file :\n");


printf("--------------------------\n");

printf(" Input the name of file to decrypt : ");


scanf("%s",fname);

fpts=fopen(fname, "w");
if(fpts==NULL)
{
printf(" File does not exists or error in opening..!!");
exit(1);
}
fptt=fopen("temp.txt", "r");
if(fptt==NULL)
{
printf(" File does not exists or error in opening..!!");
fclose(fpts);
exit(1);
}
while(1)
{
ch=fgetc(fptt);
if(ch==EOF)
{
Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University
66
break;
}
else
{
ch=ch-100;
fputc(ch, fpts);
}
}
printf(" The file %s decrypted successfully..!!\n\n",fname);
fclose(fpts);
fclose(fptt);
}

OUTPUT

Some Sample questions:


i. What is decryption?
ii. ?

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
67
EN3ES28: Advance Programming with C Experiment no- 32
Experiment Title: Write a program in C to remove a file from the Page No 68
disk.

Objective
Write a program in C to remove a file from the disk.

Theory

remove is a function in C programming language that removes a certain file. It is included in the C
standard library header file stdio.h.

The prototype of the function is as follows:

int remove ( const char * filename );


If successful, the function returns zero. Nonzero value is returned on failure and errno variable is
set to corresponding error code.

Program
#include <stdio.h>

void main()
{
int status;
char fname[20];
printf("\n\n Remove a file from the disk :\n");
printf("----------------------------------\n");
printf(" Input the name of file to delete : ");
scanf("%s",fname);
status=remove(fname);
if(status==0)
{
printf(" The file %s is deleted successfully..!!\n\n",fname);
}
else
{
printf(" Unable to delete file %s\n\n",fname);
}
}

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
68
OUTPUT

Some Sample questions:


i. How to delete line from file?
ii. ?

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
69
EN3ES28: Advance Programming with C Experiment no- 33
Experiment Title: Write a program to draw a circle and fill blue Page No 70
color in it

Objective
Write a program to draw a circle and fill blue color in it

Theory
The header file graphics.h contains circle() function which draws a circle with center at (x, y)
and given radius.
Syntax :
circle(x, y, radius);

where, (x, y) is center of the circle. 'radius' is the Radius of the circle.

The header file graphics.h contains setfillstyle() function which sets the current fill pattern and fill
color. floodfill() function is used to fill an enclosed area. Current fill pattern and fill color is used
to fill the area.
Syntax :

void setfillstyle(int pattern, int color)

void floodfill(int x, int y, int border_color)

Program

#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<dos.h>
int main()
{
int gdriver = DETECT,gmode;
initgraph(&gdriver,&gmode,"C:\\TC\\BGI");
setfillstyle(SOLID_FILL,BLUE);
circle(200,200,50);
floodfill(202,202,WHITE);
getch();
}

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
70
OUTPUT

Some Sample questions:


i. What is GUI?
ii. Which function is used to draw a circle?

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
71
EN3ES28: Advance Programming with C Experiment no- 34
Experiment Title: Write a program to move a circle using suitable Page No 72
animations

Objective
Write a program to move a circle using suitable animations

Theory

Program

//moving a circle
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<dos.h>
void main()
{
clrscr();
int gdriver, gmode; //variables declaration
gdriver=DETECT; // detection of graphics driver
int move_location=20; //first location for circle to start
initgraph(&gdriver, &gmode, "c:\\tc\\BGI");
while(!kbhit()) //Checks for currently available keystrokes
{
circle(move_location,210,70);//draws circle
setcolor(BLUE); //sets the color blue of circle
delay(100); //delays of 1/10th of second
cleardevice(); //clears the previous screen/graphics
move_location++;
if(move_location>=600)
{
move_location=0; //repeating the motion.
cleardevice(); //clears the graphics screen
}
}
getch(); //gets one character from user and closes the graphics.
closegraph(); //closes graphics.h
}

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
72
OUTPUT

Some Sample questions:


i. What is header file?
ii. How to create a header file?

Department of Computer Science Engineering


Faculty of Engineering
Medi-Caps University
73

You might also like