0% found this document useful (0 votes)
2 views22 pages

IA2 LAB Syllabus Program

The document outlines various C programming exercises focused on string manipulation, array operations, and dynamic memory management. It includes detailed instructions and sample outputs for tasks such as string concatenation, comparison, word counting, password validation, and swapping values in arrays, strings, and structures. Each exercise is accompanied by function prototypes and code snippets to guide implementation.
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)
2 views22 pages

IA2 LAB Syllabus Program

The document outlines various C programming exercises focused on string manipulation, array operations, and dynamic memory management. It includes detailed instructions and sample outputs for tasks such as string concatenation, comparison, word counting, password validation, and swapping values in arrays, strings, and structures. Each exercise is accompanied by function prototypes and code snippets to guide implementation.
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/ 22

Advanced C Programming and Applications Lab

8.1,8.2,8.3,8.4
10.1,10.2,10.3,10.4
11.1, 11.3
14.1

8.1. Write a C program to concatenate two strings using user-defined functions. The
program should accept two strings from the user and pass them to a function that
performs the concatenation. (strings, while/do while)
Function prototype:
void input(char *str);
void concatenate_strings(char *str1, char *str2);
void display(char *str);
#include <stdio.h>
#include <string.h>

#define SIZE 100

// Function prototypes
void input(char *str);
void concatenate_strings(char *str1, char *str2);
void display(char *str);

int main() ,
char str1*SIZE+, str2*SIZE+;

printf("Enter the first string: ");


input(str1);

printf("Enter the second string: ");


input(str2);

concatenate_strings(str1, str2);

printf("Concatenated string: ");


display(str1);

return 0;
-

// Function to take input from the user using fgets


void input(char *str) ,
fgets(str, SIZE, stdin);

// Remove trailing newline if present


// Remove newline character if present
int i = 0;
while (str*i+ != '\0') ,
if (str*i+ == '\n') ,
str*i+ = '\0';
break;
-
i++;
-
-

// Function to concatenate str2 to str1


void concatenate_strings(char *str1, char *str2) ,
int i = 0, j = 0;

// Move i to the end of str1


while (str1*i+ != '\0') ,
i++;
-

// Append str2 to str1


while (str2*j+ != '\0') ,
str1*i+++ = str2*j+++;
-

// Null terminate the result


str1*i+ = '\0';
-

// Function to display the string


void display(char *str) ,
int i = 0;
while (str*i+ != '\0') ,
putchar(str*i+++);
-
printf("\n");
-
Sample Output:
Enter the first string: Hello
Enter the second string: World
Concatenated string: HelloWorld
8.2. Write a C program to compare two strings using user-defined functions. The
program should return:
 0 if both strings are equal
 1 if the first string is lexicographically greater
 -1 if the second string is lexicographically greater
Function prototype:
void inputStrings(char str1*+, char str2*+);
int compareStrings(char str1*+, char str2*+);
void output(int result);
#include <stdio.h>

#define SIZE 100

// Function prototypes
void inputStrings(char str1*+, char str2*+);
int compareStrings(char str1*+, char str2*+);
void output(int result);

int main() ,
char str1*SIZE+, str2*SIZE+;
int result;

inputStrings(str1, str2);
result = compareStrings(str1, str2);
output(result);

return 0;
-

// Function to input two strings using fgets and your newline removal logic
void inputStrings(char str1*+, char str2*+) ,
printf("Enter the first string: ");
fgets(str1, SIZE, stdin);

// Remove newline character if present


int i = 0;
while (str1*i+ != '\0') ,
if (str1*i+ == '\n') ,
str1*i+ = '\0';
break;
-
i++;
-

printf("Enter the second string: ");


fgets(str2, SIZE, stdin);

// Remove newline character if present


i = 0;
while (str2*i+ != '\0') ,
if (str2*i+ == '\n') ,
str2*i+ = '\0';
break;
-
i++;
-
-

// Function to compare two strings lexicographically


int compareStrings(char str1*+, char str2*+) ,
int i = 0;
while (str1*i+ != '\0' && str2*i+ != '\0') ,
if (str1*i+ < str2*i+)
return -1;
else if (str1*i+ > str2*i+)
return 1;
i++;
-

if (str1*i+ == '\0' && str2*i+ == '\0')


return 0;
else if (str1*i+ == '\0')
return -1;
else
return 1;
-

// Function to display result


void output(int result) ,
if (result == 0)
printf("Both strings are equal.\n");
else if (result == 1)
printf("The first string is lexicographically greater.\n");
else
printf("The second string is lexicographically greater.\n");
-
Sample Output1:
Enter the first string: apple
Enter the second string: banana
The second string is lexicographically greater.
Sample Output2:
Enter the first string: zebra
Enter the second string: apple
The first string is lexicographically greater.
Sample Output3:
Enter the first string: hello
Enter the second string: hello
Both strings are equal.
8.3. Write a C program to count how many words in a given sentence. Use a user-
defined function to perform the counting. The sentence may contain multiple
words separated by spaces. (strings, while/do while)
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define MAX 200

// Function prototypes
void input(char *str);
int count_words(char *str);
void display(char *str, int count);

int main() ,
char sentence*MAX+;
int word_count;

input(sentence);
word_count = count_words(sentence);
display(sentence, word_count);

return 0;
-

// Function to input the sentence


void input(char *str) ,
printf("Enter a sentence: ");
fgets(str, MAX, stdin); // safer than gets(), reads spaces
size_t len = strlen(str);
if (len > 0 && str*len - 1+ == '\n') ,
str*len - 1+ = '\0'; // remove newline character
-
-

// Function to count words using while loop


int count_words(char *str) ,
int i = 0, count = 0;
int in_word = 0;

while (str*i+ != '\0') ,


if (!isspace(str*i+)) ,
if (!in_word) ,
count++;
in_word = 1;
-
- else ,
in_word = 0;
-
i++;
-
return count;
-
// Function to display sentence and word count
void display(char *str, int count) ,
printf("\nSentence: \"%s\"\n", str);
printf("Number of words: %d\n", count);
-
Sample Output1:
Enter a sentence: Hello world this is C programming

Sentence: "Hello world this is C programming"


Number of words: 6
Sample Output2:
Enter a sentence: This sentence has extra spaces

Sentence: "This sentence has extra spaces"


Number of words: 5
Sample Output3:
Enter a sentence:

Sentence: ""
Number of words: 0

8.4 Write a C program to validate a password entered by the user based on the following
rules:
i. Password must be at least 8 characters long. // Use strlen() function
ii. It must contain at least one uppercase letter, one lowercase letter, and one
digit.
Use a user-defined function to check these conditions and return whether the
password is valid. (strings, for loop)
Function prototype:
void input(char *str);
int is_valid(char *str);
int is_upper(char c); // Sub function of is_valid()
int is_lower(char c); // Sub function of is_valid()
int is_digit(char c); // Sub function of is_valid()
void display(char *str, int res);

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

#define SIZE 100

// Function prototypes
void input(char *str);
int is_valid(char *str);
int is_upper(char c);
int is_lower(char c);
int is_digit(char c);
void display(char *str, int res);
int main() ,
char password*SIZE+;
int result;

input(password);
result = is_valid(password);
display(password, result);

return 0;
-

// Function to input password


void input(char *str) ,
printf("Enter your password: ");
fgets(str, SIZE, stdin);

// Remove newline character if present


int i = 0;
while (str*i+ != '\0') ,
if (str*i+ == '\n') ,
str*i+ = '\0';
break;
-
i++;
-
-

// Function to check if the password is valid


int is_valid(char *str) ,
int has_upper = 0, has_lower = 0, has_digit = 0;

if (strlen(str) < 8)
return 0;

for (int i = 0; str*i+ != '\0'; i++) ,


if (is_upper(str*i+)) has_upper = 1;
else if (is_lower(str*i+)) has_lower = 1;
else if (is_digit(str*i+)) has_digit = 1;
-

return has_upper && has_lower && has_digit;


-

// Sub function: check for uppercase


int is_upper(char c) ,
return (c >= 'A' && c <= 'Z');
-

// Sub function: check for lowercase


int is_lower(char c) ,
return (c >= 'a' && c <= 'z');
-

// Sub function: check for digit


int is_digit(char c) ,
return (c >= '0' && c <= '9');
-

// Function to display result


void display(char *str, int res) ,
if (res)
printf("Password \"%s\" is VALID.\n", str);
else
printf("Password \"%s\" is INVALID.\n", str);
-

Sample Output1:
Enter your password: Hello123
Password "Hello123" is VALID.

Sample Output2:
Enter your password: hello
Password "hello" is INVALID.
10.1 Write a program to swap two numbers.
Function prototype:
void swap(int *a, int *b);
#include <stdio.h>

void swap(int *a, int *b) ,


int temp = *a;
*a = *b;
*b = temp;
-

int main() ,
int x, y;
printf("Enter two integers: ");
scanf("%d %d", &x, &y);

swap(&x, &y);

printf("After swap: x = %d, y = %d\n", x, y);


return 0;
-
Sample Output:
Enter two integers: 5 10
After swap: x = 10, y = 5
10.2. Write a program to swap two arrays.
Function prototype:
void swap_array(int n, int a*n+,int b*n+);
#include <stdio.h>

void swap_array(int n, int a*n+, int b*n+) ,


for (int i = 0; i < n; i++) ,
int temp = a*i+;
a*i+ = b*i+;
b*i+ = temp;
-
-

int main() ,
int n;
printf("Enter size of arrays: ");
scanf("%d", &n);

int a*n+, b*n+;


printf("Enter elements of array A:\n");
for (int i = 0; i < n; i++)
scanf("%d", &a*i+);

printf("Enter elements of array B:\n");


for (int i = 0; i < n; i++)
scanf("%d", &b*i+);

swap_array(n, a, b);

printf("After swapping:\nArray A: ");


for (int i = 0; i < n; i++)
printf("%d ", a*i+);

printf("\nArray B: ");
for (int i = 0; i < n; i++)
printf("%d ", b*i+);

printf("\n");
return 0;
-
Sample Output:
Enter size of arrays: 3
Enter elements of array A:
123
Enter elements of array B:
456
After swapping:
Array A: 4 5 6
Array B: 1 2 3
10.3. Write a program to swap two strings.
Function prototype:
void swap(char *a, char *b) ;
#include <stdio.h>
#include <string.h>

void swap(char *a, char *b) ,


char temp*100+;
strcpy(temp, a);
strcpy(a, b);
strcpy(b, temp);
-

int main() ,
char str1*100+, str2*100+;
printf("Enter first string: ");
fgets(str1, sizeof(str1), stdin);

printf("Enter second string: ");


fgets(str2, sizeof(str2), stdin);

// Remove trailing newlines


str1*strcspn(str1, "\n")+ = '\0';
str2*strcspn(str2, "\n")+ = '\0';

swap(str1, str2);

printf("After swapping:\nString 1: %s\nString 2: %s\n", str1, str2);


return 0;
-
Sample Output:
Enter first string: Hello
Enter second string: World
After swapping:
String 1: World
String 2: Hello
10.4. Write a program to swap two structures.
typedef struct , char name*50+; int age; - Person;
Function prototype:
void swap_person(Person *p1, Person *p2);
#include <stdio.h>
#include <string.h>

typedef struct ,
char name*50+;
int age;
- Person;

void swap_person(Person *p1, Person *p2) ,


Person temp = *p1;
*p1 = *p2;
*p2 = temp;
-

int main() ,
Person p1, p2;

printf("Enter name and age for Person 1: ");


fgets(p1.name, sizeof(p1.name), stdin);
p1.name*strcspn(p1.name, "\n")+ = '\0'; // Remove newline
scanf("%d", &p1.age);
getchar(); // Clear newline from buffer

printf("Enter name and age for Person 2: ");


fgets(p2.name, sizeof(p2.name), stdin);
p2.name*strcspn(p2.name, "\n")+ = '\0';
scanf("%d", &p2.age);

swap_person(&p1, &p2);

printf("After swapping:\n");
printf("Person 1: Name = %s, Age = %d\n", p1.name, p1.age);
printf("Person 2: Name = %s, Age = %d\n", p2.name, p2.age);

return 0;
-
Sample Output:
Enter name and age for Person 1: Alice
25
Enter name and age for Person 2: Bob
30
After swapping:
Person 1: Name = Bob, Age = 30
Person 2: Name = Alice, Age = 25

11.1. Write a modular C program to perform the following operations on an integer array
using dynamic memory allocation:
(i). Create an integer array of size n (user input) using malloc.
(ii). Initialize the array elements by reading from the user.
(iii). Print all array elements.
(iv). Delete the array by freeing the dynamically allocated memory.
Use the following function prototypes for each of the above operations:
int* create_array(int n);
void initialize_array(int *arr, int n);
void print_array(int *arr, int n);
void delete_array(int **arr);

#include <stdio.h>

#include <stdlib.h>

// Function Prototypes

int* create_array(int n);

void initialize_array(int *arr, int n);

void print_array(int *arr, int n);

void delete_array(int **arr);

int main() ,

int n;

int *arr = NULL;

// Step (i): Get size from user

printf("Enter the number of elements: ");

scanf("%d", &n);

// Step (i): Create array

arr = create_array(n);
// Step (ii): Initialize array

initialize_array(arr, n);

// Step (iii): Print array

print_array(arr, n);

// Step (iv): Delete array

delete_array(&arr);

// Confirm deletion

if (arr == NULL) ,

printf("Array memory successfully freed.\n");

- else ,

printf("Memory not freed properly.\n");

return 0;

// Function to create array

int* create_array(int n) ,

int *arr = (int*) malloc(n * sizeof(int));

if (arr == NULL) ,
printf("Memory allocation failed.\n");

exit(1);

return arr;

// Function to initialize array

void initialize_array(int *arr, int n) ,

printf("Enter %d elements:\n", n);

for (int i = 0; i < n; i++) ,

printf("Element %d: ", i + 1);

scanf("%d", &arr*i+);

// Function to print array

void print_array(int *arr, int n) ,

printf("Array elements are:\n");

for (int i = 0; i < n; i++) ,

printf("%d ", arr*i+);

printf("\n");

-
// Function to delete (free) array

void delete_array(int **arr) ,

if (*arr != NULL) ,

free(*arr);

*arr = NULL; // Avoid dangling pointer

-
-
Sample Output:

Enter the number of elements: 5

Enter 5 elements:

Element 1: 10

Element 2: 20

Element 3: 30

Element 4: 40
Element 5: 50

Array elements are:

10 20 30 40 50
Array memory successfully freed
11.3 Write a modular C program to perform the following operations on a singly
linked list:
(i). Create a list and a node
(ii). Insert elements at the beginning of the list
(iii). Insert elements at the end of the list
(iv). Display the list
typedef struct Node ,
int data;
struct Node* next;
- Node;
typedef struct List ,
Node* head;
int size;
- List;
Function prototype:
List* createList();
Node* createNode(int data);
void insertAtBeginning(List* list, int data);
void insertAtEnd(List* list, int data);
void displayList(List* list);
#include <stdio.h>
#include <stdlib.h>

// Node structure
typedef struct Node ,
int data;
struct Node* next;
- Node;

// List structure
typedef struct List ,
Node* head;
int size;
- List;

// Function prototypes
List* createList();
Node* createNode(int data);
void insertAtBeginning(List* list, int data);
void insertAtEnd(List* list, int data);
void displayList(List* list);

int main() ,
List* myList = createList();
int choice, value;

while (1) ,
printf("\nMenu:\n");
printf("1. Insert at Beginning\n");
printf("2. Insert at End\n");
printf("3. Display List\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) ,
case 1:
printf("Enter value to insert at beginning: ");
scanf("%d", &value);
insertAtBeginning(myList, value);
break;

case 2:
printf("Enter value to insert at end: ");
scanf("%d", &value);
insertAtEnd(myList, value);
break;

case 3:
printf("Linked List Contents:\n");
displayList(myList);
break;

case 4:
printf("Exiting...\n");
return 0;

default:
printf("Invalid choice. Try again.\n");
-
-

return 0;
-

// (i) Create a list


List* createList() ,
List* list = (List*) malloc(sizeof(List));
list->head = NULL;
list->size = 0;
return list;
-

// (i) Create a node


Node* createNode(int data) ,
Node* newNode = (Node*) malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
-

// (ii) Insert at beginning


void insertAtBeginning(List* list, int data) ,
Node* newNode = createNode(data);
newNode->next = list->head;
list->head = newNode;
list->size++;
-

// (iii) Insert at end


void insertAtEnd(List* list, int data) ,
Node* newNode = createNode(data);

if (list->head == NULL) ,
list->head = newNode;
- else ,
Node* current = list->head;
while (current->next != NULL) ,
current = current->next;
-
current->next = newNode;
-

list->size++;
-

// (iv) Display the list


void displayList(List* list) ,
if (list->head == NULL) ,
printf("List is empty.\n");
return;
-

Node* current = list->head;


while (current != NULL) ,
printf("%d -> ", current->data);
current = current->next;
-
printf("NULL\n");
-
Output:
Menu:
1. Insert at Beginning
2. Insert at End
3. Display List
4. Exit
Enter your choice: 1
Enter value to insert at beginning: 10

Menu:
1. Insert at Beginning
2. Insert at End
3. Display List
4. Exit
Enter your choice: 2
Enter value to insert at end: 20
Menu:
1. Insert at Beginning
2. Insert at End
3. Display List
4. Exit
Enter your choice: 2
Enter value to insert at end: 30

Menu:
1. Insert at Beginning
2. Insert at End
3. Display List
4. Exit
Enter your choice: 1
Enter value to insert at beginning: 5

Menu:
1. Insert at Beginning
2. Insert at End
3. Display List
4. Exit
Enter your choice: 3
Linked List Contents:
5 -> 10 -> 20 -> 30 -> NULL

14.1. Write a modular C program to perform the following tasks using file handling
functions:
(i). Read the details of n students from the user and store them in an array of
structures.
(ii). Write the array of structures to a text (ASCII) file using fprintf().
(iii). Read the data back from the ASCII file into a second array using fscanf() and
display it.
(iv). Display the array of structures.
(v). Write the original array of structures to a binary file using fwrite().
(vi). Read the binary file into a third array of structures using fread().
(vii). Display the array of structures.
typedef struct ,
int id;
char name*50+;
float marks;
- Student;

Function prototypes:
void inputStudents(Student students*+, int n);
void writeToTextFile(Student students*+, int n, const char *filename);
int readFromTextFile(Student students*+, const char *filename);
void writeToBinaryFile(Student students*+, int n, const char *filename);
int readFromBinaryFile(Student students*+, const char *filename);
void printStudents(Student students*+, int n);
#include <stdio.h>
typedef struct ,
int id;
char name*50+;
float marks;
- Student;
// Function declarations
void inputStudents(Student students*+, int n);
void writeToTextFile(Student students*+, int n, const char *filename);
int readFromTextFile(Student students*+, const char *filename);
void writeToBinaryFile(Student students*+, int n, const char *filename);
int readFromBinaryFile(Student students*+, const char *filename);
void printStudents(Student students*+, int n);
// Main
int main() ,
int n;
printf("Enter the size:\n");
scanf("%d”",&n);
Student students*n+;
Student textRead*n+;
Student binaryRead*n+;
// 1. Input
inputStudents(students, n);
// 2. Write to ASCII file
writeToTextFile(students, n, "students.txt");
// 3. Read from ASCII file
int textCount = readFromTextFile(textRead, "students.txt");

// 4. Print read data


printf("\n--- Students read from ASCII file ---\n");
printStudents(textRead, textCount);

// 5. Write to binary file


writeToBinaryFile(students, n, "students.dat");

// 6. Read from binary file


int binCount = readFromBinaryFile(binaryRead, "students.dat");

// 7. Print read data


printf("\n--- Students read from Binary file ---\n");
printStudents(binaryRead, binCount);

return 0;
-
// Function Definitions
void inputStudents(Student students*+, int n) ,
for (int i = 0; i < n; i++) ,
printf("Enter ID, Name, and Marks for student %d:\n", i + 1);
scanf("%d", &students*i+.id);
scanf(" %*^\n+", students*i+.name);
scanf("%f", &students*i+.marks);
-
-

void writeToTextFile(Student students*+, int n, const char *filename) ,


FILE *fp = fopen(filename, "w");
if (fp == NULL) ,
printf("Error opening text file for writing.\n");
return;
-
for (int i = 0; i < n; i++) ,
fprintf(fp, "%d %s %.2f\n", students*i+.id, students*i+.name, students*i+.marks);
-
fclose(fp);
-
int readFromTextFile(Student students*+, const char *filename) ,
FILE *fp = fopen(filename, "r");
if (fp == NULL) ,
printf("Error opening text file for reading.\n");
return 0;
-
int count = 0;
while (!feof(fp)) ,
if (fscanf(fp, "%d %s %f", &students*count+.id, students*count+.name,
&students*count+.marks) == 3) ,
count++;
-
-

fclose(fp);
return count;
-
void writeToBinaryFile(Student students*+, int n, const char *filename) ,
FILE *fp = fopen(filename, "wb");
if (fp == NULL) ,
printf("Error opening binary file for writing.\n");
return;
-
fwrite(students, sizeof(Student), n, fp);
fclose(fp);
-
int readFromBinaryFile(Student students*+, const char *filename) ,
FILE *fp = fopen(filename, "rb");
if (fp == NULL) ,
printf("Error opening binary file for reading.\n");
return 0;
-
int count = 0;
while (!feof(fp)) ,
if (fread(&students*count+, sizeof(Student), 1, fp) == 1) ,
count++;
-
-
fclose(fp);
return count;
-
void printStudents(Student students*+, int n) ,
for (int i = 0; i < n; i++) ,
printf("ID: %d, Name: %s, Marks: %.2f\n", students*i+.id, students*i+.name,
students*i+.marks);
-
-;

Sample Output:
Enter the number of students: 2

Enter ID, Name, Marks for Student1:


101
Alice
88.5

Enter ID, Name, Marks for Student2:


102
Bob
91.0

--- Students read from ASCII file ---


ID: 101 Name: Alice Marks: 88.50
ID: 102 Name: Bob Marks: 91.00

--- Students read from Binary file ---


ID: 101 Name: Alice Marks: 88.50
ID: 102 Name: Bob Marks: 91.00

You might also like