0% found this document useful (0 votes)
14 views73 pages

Lab Assignment: Programming in C

coding pdf

Uploaded by

lethalop14
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views73 pages

Lab Assignment: Programming in C

coding pdf

Uploaded by

lethalop14
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 73

Programming in C

Lab Assignment

Bachelor of Technology

Submitted by

Name: Abhinav Yadav SAP ID: 590017740

Submitted to
Dr. Mahendra Kumar Srivas

UPES
Bidholi, Via Prem Nagar, Dehradun, Uttarakhand
July-Dec – 2024
INDEX

Experiment 1: Installation, Environment Setup and starting with C language

1. Write a C program to print “Hello World”.


2. Write a C program to print the address in multiple lines (new lines).
3. Write a C program that prompts the user to enter their name and age.
4. Write a C program to add two numbers, take number from user.

Experiment 2: Operators

1. WAP a C program to calculate the area and perimeter of a rectangle based on its length and width.
2. WAP a C program to Convert temperature from Celsius to Fahrenheit using the formula: F = (C *
9/5) + 32.

Experiment 3.1: Conditional Statements

1. WAP to take check if the triangle is valid or not. If the validity is established, do check if the
triangle is isosceles, equilateral, right angle, or scalene. Take sides of the triangle as input from a
user.
2. WAP to compute the BMI Index of the person and print the BMI values as per the following ranges.
You can use the following formula to compute BMI= weight(kgs)/Height(Mts)*Height(Mts).

BMI
Starvation <15
Anorexic 5.1 to 17.5
Underweight 17.6 to 18.5
Ideal 18.6 to 24.9
Overweight 25 to 25.9
Obese 30 to 39.9
Morbidity Obese 40.0 above

3. WAP to check if three points (x1,y1), (x2,y2) and (x3,y3) are collinear or not.
4. According to the Gregorian calendar, it was Monday on the date 01/01/01. If Any year is input
through the keyboard write a program to find out what is the day on 1st January of this year.
5. WAP using ternary operator, the user should input the length and breadth of a rectangle, one has to
find out which rectangle has the highest perimeter. The minimum number of rectangles should be
three.
Experiment 3.2: Loops

1. WAP to enter numbers till the user wants. At the end, it should display the count of positive,
negative, and Zeroes entered.
2. WAP to print the multiplication table of the number entered by the user. It should be in the correct
formatting. Num * 1 = Num
3. WAP to generate the following set of output.
a.
1
23
456

b.
1
11
121
1331
14641

4. The population of a town is 100000. The population has increased steadily at the rate of 10% per
year for the last 10 years. Write a program to determine the population at the end of each year in the
last decade.
5. Ramanujan Number is the smallest number that can be expressed as the sum of two cubes in two
different ways. WAP to print all such numbers up to a reasonable limit.

Experiment 4: Variable and Scope of Variable

1. Declare a global variable outside all functions and use it inside various functions to understand its
accessibility.
2. Declare a local variable inside a function and try to access it outside the function. Compare this with
accessing the global variable from within the function.
3. Declare variables within different code blocks (enclosed by curly braces) and test their accessibility
within and outside those blocks.
4. Declare a static local variable inside a function. Observe how its value persists across function
calls.

Experiment 5: Array

1. WAP to read a list of integers and store it in a single dimensional array. Write a C program to print
the second largest integer in a list of integers.
2. WAP to read a list of integers and store it in a single dimensional array. Write a C program to count
and display positive, negative, odd, and even numbers in an array.
3. WAP to read a list of integers and store it in a single dimensional array. Write a C program to find
the frequency of a particular number in a list of integers.
4. WAP that reads two matrices A (m x n) and B (p x q) and computes the product A and B. Read matrix
A and matrix B in row major order respectively. Print both the input matrices and resultant matrix
with suitable headings and output should be in matrix format only. Program must check the
compatibility of orders of the matrices for multiplication. Report appropriate message in case of
incompatibility.
Experiment 6: Functions
1. Develop a recursive and non-recursive function FACT(num) to find the factorial of a number, n!,
defined by FACT(n) = 1, if n = 0. Otherwise, FACT(n)
2. = n * FACT(n-1). Using this function, write a C program to compute the binomial coefficient.
Tabulate the results for different values of n and r with suitable messages.
3. Develop a recursive function GCD (num1, num2) that accepts two integer arguments. Write a C
program that invokes this function to find the greatest common divisor of two given integers.
4. Develop a recursive function FIBO (num) that accepts an integer argument. Write a C program that
invokes this function to generate the Fibonacci sequence up to num.
5. Develop a C function ISPRIME (num) that accepts an integer argument and returns 1 if the argument
is prime, a 0 otherwise. Write a C program that invokes this function to generate prime numbers
between the given ranges.
6. Develop a function REVERSE (str) that accepts a string argument. Write a C program that invokes
this function to find the reverse of a given string.

Experiment 7: Structures and Union

1. Write a C program that uses functions to perform the following operations:


a. Reading a complex number.
b. Writing a complex number.
c. Addition and subtraction of two complex numbers
Note: represent complex number using a structure.

2. Write a C program to compute the monthly pay of 100 employees using each employee‗s name, basic
pay. The DA is computed as 52% of the basic pay. Gross-salary (basic pay + DA). Print the
employees name and gross salary.
3. Create a Book structure containing book_id, title, author name and price. Write a C program to pass a
structure as a function argument and print the book details.
4. Create a union containing 6 strings: name, home_address, hostel_address, city, state and zip. Write a
C program to display your present address.

Experiment 8: Pointers

1. Declare different types of pointers (int, float, char) and initialize them with the addresses of
variables. Print the values of both the pointers and the variables they point to.
2. Perform pointer arithmetic (increment and decrement) on pointers of different data types. Observe
how the memory addresses change and the effects on data access.
3. Write a function that accepts pointers as parameters. Pass variables by reference using pointers and
modify their values within the function.

Experiment 9: File Handling in C

1. Write a program to create a new file and write text into it.
2. Open an existing file and read its content character by character, and then close the file.
3. Open a file, read its content line by line, and display each line on the console.

Experiment 10: Dynamic Memory Allocation

1. Write a program to create a simple linked list in C using pointer and structure.
2. Write a program to insert item in middle of the linked list.
Experiment 11: Bitwise Operator

1. Write a program to apply bitwise OR, AND and NOT operators on bit level.
2. Write a program to apply left shift and right shift operator.

Experiment 12: Preprocessor and Directives in C

1. Write a program to define some constant variable in preprocessor.


2. Write a program to define a function in directives.

Experiment 13: Macros in C

1. Write a program to define multiple macro to perform arithmetic functions.

Experiment 14: Static Library in C

1. Write a program to create a static library for performing arithmetic functions.


2. Write a program to use static library in other program.

Experiment 15: Shared Library in C

1. Write a program to create a shared library for performing arithmetic functions.


2. Write a program to use shared library in other program.

Experiment 16: Multithreading in C

1. Write a program to print 1-10 numbers five times using multithreading in C.

Experiment 17: Socket Programming in C

1. Write a program to implement socket programming using C.

Experiment 18: Testing and Debugging

1. Write a program and perform testing and debugging on same implementation

Experiment 1: Installation, Environment Setup and starting with C language


1. Write a C program to print “Hello World”.

Code
#include<stdio.h>
int main()
{
printf("Hello World");
return 0;
}

Output

2. Write a C program to print the address in multiple lines (new lines).


Code
#include<stdio.h>
int main()
{
printf("Energy Acres, UPES, \nBidholi, Dehradun, \nUttrakhand 248007\n");
return 0;
}

Output

3. Write a C program that prompts the user to enter their name and age.
Code
#include <stdio.h>
int main()
{
char name[50];
int age;

printf("Enter your name: ");


scanf("%s", name);

printf("Enter your age: ");


scanf("%d", &age);

printf("Name: %s, Age: %d\n", name, age);

return 0;
}

Output
4. Write a C program to add two numbers, take number from user.

Code
#include<stdio.h>
#include<math.h>

int main()
{
int a, b, c;

printf("Enter value a: ");


scanf("%d", &a);

printf("Enter value b: ");


scanf("%d", &b);

c = a + b;
printf("The required number is: %d\n", c);

return 0;
}

Output

Experiment 2: Operators
1. WAP a C program to calculate the area and perimeter of a rectangle based on its length and width.

Code
#include <stdio.h>

int main()
{
printf("Enter the length of the rectangle: ");
scanf("%f", &length);

printf("Enter the width of the rectangle: ");


scanf("%f", &width);

area = length * width;


perimeter = 2 * (length + width);

printf("Area of the rectangle: %.2f\n", area);


printf("Perimeter of the rectangle: %.2f\n", perimeter);
return 0;
}

Output

2. WAP a C program to Convert temperature from Celsius to Fahrenheit using the formula: F = (C *
9/5) + 32.
Code
#include <stdio.h>

int main()
{
float celsius, fahrenheit;

printf("Enter the temperature in Celsius: ");


scanf("%f", &celsius);

fahrenheit = (celsius * 9 / 5) + 32;


printf("Temperature in Fahrenheit: %.2f\n", fahrenheit);
return 0;
}

Output
Experiment 3.1: Conditional Statements

1. WAP to take check if the triangle is valid or not. If the validity is established, do check if the
triangle is isosceles, equilateral, right angle, or scalene. Take sides of the triangle as input from a
user.

Code
#include <stdio.h>
#include <math.h>

int main()
{
float a,b,c;

printf("Enter the length of side 1: ");


scanf("%f", &a);

printf("Enter the length of side 2: ");


scanf("%f", &b);

printf("Enter the length of side 3: ");


scanf("%f", &c);

f (a + b > c && a + c > b && b + c > a)


{ printf("The triangle is valid.\n"); }
if (a == b && b == c)
{ printf("The triangle is Equilateral.\n"); }
else if (a == b || b == c || a == c)
{ printf("The triangle is Isosceles.\n"); }
else
{ printf("The triangle is Scalene.\n"); }
return 0;
}

Output
2. WAP to compute the BMI Index of the person and print the BMI values as per the following ranges.
You can use the following formula to compute BMI= weight(kgs)/Height(Mts)*Height(Mts).
BMI
Starvation <15
Anorexic 5.1 to 17.5
Underweight 17.6 to 18.5
Ideal 18.7 to 24.9
Overweight 25 to 25.9
Obese 30 to 39.9
Morbidity Obese 40.0 above

Code
#include<stdio.h>
int main ()
{ float a, w, h;
printf("Weight (kg):");
scanf("%f", &w);
printf("Height (meter):");
scanf("%f", &h);
a = w / (h*h);
printf("BMI: %f\n",a);
if (a <= 15)
{printf("Starvation");}
else if (a >= 15.1 && a <=17.5)
{printf("Anorexic");}
else if (a >= 17.6 && a <= 18.5)
{printf("Underweight");}
else if (a >= 18.6 && a <= 24.9)
{printf("Ideal");}
else if (a >= 25 && a <= 25.9)
{printf("Overweight");}
else if (a >= 30 && a <= 39.9)
{printf("Obese");}
else
{printf("Morbidity Obese");}
return 0; }

Output

3. WAP to check if three points (x1,y1), (x2,y2) and (x3,y3) are collinear or not.
Code
#include<stdio.h>

int main()
{
int x1,x2,x3,y1,y2,y3;

printf("ENTER x1,x2,x3,y1,y2,y3:");
scanf("%d%d%d%d%d%d",&x1,&x2,&x3,&y1,&y2,&y3);

if(x1*y2-x1*y3-y1*x2+y1*x3+x2*y3-x3*y2 ==0)
{
printf("THE POINTS ARE COLLINEAR");
}
else
{
printf("THE POINTS ARE NOT COLLINEAR");
}
return 0;
}

Output
4. According to the Gregorian calendar, it was Monday on the date 01/01/01. If Any year is input
through the keyboard write a program to find out what is the day on 1st January of this year.

Code
#include <stdio.h>

int day_of_week(int year) {


if (year < 1) {
return -1; }

int month = 1;
int day = 1;
if (month == 1 || month == 2) {
month += 12;
year -= 1; }
int k = year % 100;
int j = year / 100;

int f = day + (13 * (month + 1)) / 5 + k + (k / 4) + (j / 4) - (2 * j);


int day_of_week = f % 7;

return day_of_week; }
int main() {
int year;
printf("Enter a year: ");
scanf("%d", &year);

int result = day_of_week(year);


if (result == -1) {
printf("Year must be greater than 0.\n");
return 0; }
char *days[] = {"Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday"};
printf("January 1st, %d is a %s.\n", year, days[result]);

return 0;
}

Output
5. WAP using ternary operator, the user should input the length and breadth of a rectangle, one has to
find out which rectangle has the highest perimeter. The minimum number of rectangles should be
three.

Code
#include <stdio.h>

int main() {
float length1, breadth1, length2, breadth2, length3, breadth3;
float perimeter1, perimeter2, perimeter3;

printf("Enter length and breadth of rectangle 1: ");


scanf("%f %f", &length1, &breadth1);

printf("Enter length and breadth of rectangle 2: ");


scanf("%f %f", &length2, &breadth2);

printf("Enter length and breadth of rectangle 3: ");


scanf("%f %f", &length3, &breadth3);

perimeter1 = 2 * (length1 + breadth1);


perimeter2 = 2 * (length2 + breadth2);
perimeter3 = 2 * (length3 + breadth3);

float max_perimeter = (perimeter1 > perimeter2) ?


((perimeter1 > perimeter3) ? perimeter1 : perimeter3) :
((perimeter2 > perimeter3) ? perimeter2 : perimeter3);

printf("The highest perimeter is: %.2f\n", max_perimeter);

return 0;
}

Output
Experiment 3.2: Loops

1. WAP to enter numbers till the user wants. At the end, it should display the count of positive,
negative, and Zeroes entered.

Code
#include <stdio.h>

int main() {
int number, positive_count = 0, negative_count = 0, zero_count = 0;
char choice;

do {
printf("Enter a number: ");
scanf("%d", &number);

if (number > 0) {
positive_count++;
} else if (number < 0) {
negative_count++;
} else {
zero_count++;
}

printf("Do you want to enter another number? (y/n): ");


scanf(" %c", &choice);
} while (choice == 'y' || choice == 'Y');

printf("Count of positive numbers: %d\n", positive_count);


printf("Count of negative numbers: %d\n", negative_count);
printf("Count of zeroes: %d\n", zero_count);

return 0;
}

Output
2. WAP to print the multiplication table of the number entered by the user. It should be in the correct
formatting. Num * 1 = Num

Code
#include <stdio.h>

int main() {
int number;

printf("Enter a number: ");


scanf("%d", &number);

printf("Multiplication Table of %d:\n", number);


for (int i = 1; i <= 10; i++) {
printf("%d * %d = %d\n", number, i, number * i);
}

return 0;
}

Output
3. WAP to generate the following set of output.

a.
1
23
456

Code

#include <stdio.h>

int main() {
int num = 1;

for (int i = 1; i <= 3; i++) {


for (int j = 1; j <= i; j++) {
printf("%d ", num);
num++;
}
printf("\n");
}

return 0;
}

Output
b.

1
11
121
1331
1 4641

Code
#include <stdio.h>

int main() {
int rows = 5;
int coef = 1;

for (int i = 0; i < rows; i++) {


coef = 1;
for (int j = 0; j <= i; j++) {
printf("%d ", coef);
coef = coef * (i - j) / (j + 1);
}
printf("\n");
}

return 0;
}

Output
4. The population of a town is 100000. The population has increased steadily at the rate of 10% per
year for the last 10 years. Write a program to determine the population at the end of each year in the
last decade.

Code
#include <stdio.h>

int main()
{
int population = 100000;
float rate = 0.10;
int year;

printf("Population at the end of each year in the last decade:\n");

for (year = 1; year <= 10; year++) {


population = (int)(population * (1 + rate));
printf("Year %d: %d\n", year, population);
}
return 0;
}

Output
5. Ramanujan Number is the smallest number that can be expressed as the sum of two cubes in two
different ways. WAP to print all such numbers up to a reasonable limit.

Code
#include <stdio.h>

int main() {
int limit = 2000; // You can change this limit as needed
int found = 0;

for (int i = 1; i <= limit; i++) {


for (int j = i; j <= limit; j++) {
int sum = i * i * i + j * j * j;
if (sum > limit) {
break;
}
for (int k = i; k <= limit; k++) {
for (int l = k; l <= limit; l++) {
if (k == i && l == j) {
continue;
}
if (k * k * k + l * l * l == sum) {
printf("%d = %d^3 + %d^3 = %d^3 + %d^3\n", sum, i, j, k, l);
found = 1;
}
}
}
}
}

if (!found) {
printf("No Ramanujan numbers found up to %d.\n", limit);
}

return 0;
}

Output
Experiment 4: Variable and Scope of Variable

1. Declare a global variable outside all functions and use it inside various functions to understand its
accessibility.

Code
#include <stdio.h>

int globalVar = 100;

void functionA() {
printf("Function A: Global variable = %d\n", globalVar);
}

void functionB() {
globalVar += 50;
printf("Function B: Global variable after modification = %d\n", globalVar);
}

void functionC() {
printf("Function C: Global variable = %d\n", globalVar);
}

int main() {
printf("Main: Initial global variable = %d\n", globalVar);

functionA();
functionB();
functionC();

return 0;
}

Output
2. Declare a local variable inside a function and try to access it outside the function. Compare this with
accessing the global variable from within the function.

Code
#include <stdio.h>

int globalVar = 50;

void myFunction() {
int globalVar = 25;
printf("Inside myFunction: Local variable = %d\n", globalVar);
printf("Inside myFunction: Global variable = %d\n", globalVar);
}

int main() {
myFunction();
printf("In main: Global variable = %d\n", globalVar);
printf("In main: Trying to access local variable = %d\n", globalVar);
return 0;
}

Output
3. Declare variables within different code blocks (enclosed by curly braces) and test their accessibility
within and outside those blocks.

Code
#include <stdio.h>

int main() {
{
int blockVar1 = 10;
printf("Inside first block: blockVar1 = %d\n", blockVar1);
}

{
int blockVar2 = 20;
printf("Inside second block: blockVar2 = %d\n", blockVar2);
}

printf("Trying to access blockVar1 = %d\n", blockVar1);


printf("Trying to access blockVar2 = %d\n", blockVar2);

return 0;
}

Output
4. Declare a static local variable inside a function. Observe how its value persists across function
calls.

Code
#include <stdio.h>

void myFunction() {
static int count = 0;
count++;
printf("Function called %d times\n", count);
}

int main() {
myFunction();
myFunction();
myFunction();
return 0;
}

Output

Experiment 5: Array
1. WAP to read a list of integers and store it in a single dimensional array. Write a C program to print
the second largest integer in a list of integers.

CODE
#include <stdio.h>

int main() {
int n, i, largest, second_largest;
printf("Enter the number of integers: ");
scanf("%d", &n);

int arr[n];
printf("Enter %d integers: ", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

largest = second_largest = -2147483648;

for(i = 0; i < n; i++) {


if(arr[i] > largest) {
second_largest = largest;
largest = arr[i];
} else if(arr[i] > second_largest && arr[i] < largest) {
second_largest = arr[i];
}
}

printf("The second largest integer is: %d\n", second_largest);


return 0;
}

Output

2. WAP to read a list of integers and store it in a single dimensional array. Write a C program to count
and display positive, negative, odd, and even numbers in an array.
CODE
#include <stdio.h>

int main() {
int n, i, positive = 0, negative = 0, odd = 0, even = 0;
printf("Enter the number of integers: ");
scanf("%d", &n);

int arr[n];
printf("Enter %d integers: ", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

for(i = 0; i < n; i++) {


if(arr[i] > 0) {
positive++;
} else if(arr[i] < 0) {
negative++;
}

if(arr[i] % 2 == 0) {
even++;
} else {
odd++;
}
}

printf("Positive numbers: %d\n", positive);


printf("Negative numbers: %d\n", negative);
printf("Odd numbers: %d\n", odd);
printf("Even numbers: %d\n", even);

return 0;
}

Output
3. WAP to read a list of integers and store it in a single dimensional array. Write a C program to find the
frequency of a particular number in a list of integers

CODE
#include <stdio.h>

int main() {
int n, i, num, count = 0;
printf("Enter the number of integers: ");
scanf("%d", &n);

int arr[n];
printf("Enter %d integers: ", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

printf("Enter the number to find its frequency: ");


scanf("%d", &num);

for(i = 0; i < n; i++) {


if(arr[i] == num) {
count++;
}
}

printf("The frequency of %d is: %d\n", num, count);


return 0;
}

Output

4. WAP that reads two matrices A (m x n) and B (p x q) and computestheproduct A and B. Read matrix
A and matrix B in row major order respectively. Print both the input matrices and resultant matrix
with suitable headingsandoutput should be in matrix format only. Program must check the
compatibilityof orders of the matrices for multiplication. Report appropriate messageincase of
incompatibility

CODE
#include <stdio.h>

int main() {
int m, n, p, q;

printf("Enter the number of rows and columns for matrix A (m x n): ");
scanf("%d %d", &m, &n);

printf("Enter the number of rows and columns for matrix B (p x q): ");
scanf("%d %d", &p, &q);

if (n != p) {
printf("Matrices cannot be multiplied. Incompatible dimensions.\n");
return 0;
}

int A[m][n], B[p][q], C[m][q];

printf("Enter elements of matrix A in row major order:\n");


for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &A[i][j]);
}
}

printf("Enter elements of matrix B in row major order:\n");


for (int i = 0; i < p; i++) {
for (int j = 0; j < q; j++) {
scanf("%d", &B[i][j]);
}
}

for (int i = 0; i < m; i++) {


for (int j = 0; j < q; j++) {
C[i][j] = 0;
for (int k = 0; k < n; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}

printf("\nMatrix A:\n");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", A[i][j]);
}
printf("\n");
}

printf("\nMatrix B:\n");
for (int i = 0; i < p; i++) {
for (int j = 0; j < q; j++) {
printf("%d ", B[i][j]);
}
printf("\n");
}

printf("\nResultant Matrix C (A * B):\n");


for (int i = 0; i < m; i++) {
for (int j = 0; j < q; j++) {
printf("%d ", C[i][j]);
}
printf("\n");
}

return 0;
}

Output
Experiment 5: Array

1. WAP to read a list of integers and store it in a single dimensional array. Write a C program to print
the second largest integer in a list of integers.

Code
#include <stdio.h>
#include <limits.h>

int main() {
int n, i;
int arr[100];
int largest, second_largest;

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


scanf("%d", &n);

if (n < 2) {
printf("Please enter at least 2 integers.\n");
return 1; }

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


for (i = 0; i < n; i++) {
scanf("%d", &arr[i]); }

largest = second_largest = INT_MIN;

for (i = 0; i < n; i++) {


if (arr[i] > largest) {
second_largest = largest;
largest = arr[i];
} else if (arr[i] > second_largest && arr[i] != largest) {
second_largest = arr[i]; } }

if (second_largest == INT_MIN) {
printf("There is no second largest element.\n");
} else {
printf("The second largest integer is: %d\n", second_largest); }
return 0;
}

Output
2. WAP to read a list of integers and store it in a single dimensional array. Write a C program to count
and display positive, negative, odd, and even numbers in an array.

Code
#include <stdio.h>

int main() {
int n, i;
int arr[100];
int positive_count = 0, negative_count = 0, odd_count = 0, even_count = 0;

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


scanf("%d", &n);

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


for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

for (i = 0; i < n; i++) {


if (arr[i] > 0) {
positive_count++;
} else if (arr[i] < 0) {
negative_count++;
}
if (arr[i] % 2 == 0) {
even_count++;
} else {
odd_count++;
}
}

printf("Positive numbers: %d\n", positive_count);


printf("Negative numbers: %d\n", negative_count);
printf("Odd numbers: %d\n", odd_count);
printf("Even numbers: %d\n", even_count);

return 0;
}

Output
3. WAP to read a list of integers and store it in a single dimensional array. Write a C program to find the
frequency of a particular number in a list of integers.

Code
#include <stdio.h>

int main() {
int n, i, num, count = 0;
int arr[100];

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


scanf("%d", &n);

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


for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

printf("Enter the number to find its frequency: ");


scanf("%d", &num);

for (i = 0; i < n; i++) {


if (arr[i] == num) {
count++;
}
}

printf("Frequency of %d: %d\n", num, count);

return 0;
}

Output
4. WAP that reads two matrices A (m x n) and B (p x q) and computes the product A and B. Read matrix
A and matrix B in row major order respectively. Print both the input matrices and resultant matrix
with suitable headings and output should be in matrix format only. Program must check the
compatibility of orders of the matrices for multiplication. Report appropriate message in case of
incompatibility.

Code
#include <stdio.h>

int main() {
int m, n, p, q;
int A[10][10], B[10][10], C[10][10];

printf("Enter the number of rows and columns for matrix A (m n): ");
scanf("%d %d", &m, &n);

printf("Enter the number of rows and columns for matrix B (p q): ");
scanf("%d %d", &p, &q);

if (n != p) {
printf("Matrices cannot be multiplied. Incompatible dimensions.\n");
return 0;
}

printf("Enter elements of matrix A (%d x %d):\n", m, n);


for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &A[i][j]);
}
}

printf("Enter elements of matrix B (%d x %d):\n", p, q);


for (int i = 0; i < p; i++) {
for (int j = 0; j < q; j++) {
scanf("%d", &B[i][j]);
}
}

for (int i = 0; i < m; i++) {


for (int j = 0; j < q; j++) {
C[i][j] = 0;
for (int k = 0; k < n; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}

printf("\nMatrix A:\n");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", A[i][j]);
}
printf("\n");
}
printf("\nMatrix B:\n");
for (int i = 0; i < p; i++) {
for (int j = 0; j < q; j++) {
printf("%d ", B[i][j]);
}
printf("\n");
}

printf("\nResultant Matrix C (A * B):\n");


for (int i = 0; i < m; i++) {
for (int j = 0; j < q; j++) {
printf("%d ", C[i][j]);
}
printf("\n");
}

return 0;
}

Output
Experiment 6: Functions

1. Develop a recursive and non-recursive function FACT(num) to find the factorial of a number, n!,
defined by FACT(n) = 1, if n = 0. Otherwise, FACT(n)

Code
#include <stdio.h>

unsigned long long FACT_recursive(int num) {


if (num == 0) {
return 1;
} else {
return num * FACT_recursive(num - 1);
}
}

unsigned long long FACT_non_recursive(int num) {


unsigned long long result = 1;
for (int i = 1; i <= num; i++) {
result *= i;
}
return result;
}

int main() {
int num;
printf("Enter a non-negative integer: ");
scanf("%d", &num);

if (num < 0) {
printf("Factorial is not defined for negative numbers.\n");
return 1;
}

unsigned long long factorial_recursive = FACT_recursive(num);


printf("Factorial of %d (recursive): %llu\n", num, factorial_recursive);

unsigned long long factorial_non_recursive = FACT_non_recursive(num);


printf("Factorial of %d (non-recursive): %llu\n", num, factorial_non_recursive);

return 0;
}

Output
2. = n * FACT(n-1). Using this function, write a C program to compute the binomial coefficient.
Tabulate the results for different values of n and r with suitable messages.

Code
#include <stdio.h>

unsigned long long factorial(int n) {


if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}

unsigned long long binomial_coefficient(int n, int r) {


if (r > n) {
return 0;
}
return factorial(n) / (factorial(r) * factorial(n - r));
}

int main() {
int max_n, r;
printf("Enter the maximum value of n: ");
scanf("%d", &max_n);

printf("\nTabulating Binomial Coefficients C(n, r):\n");


printf("---------------------------------------------------\n");
printf(" n | r | C(n, r)\n");
printf("---------------------------------------------------\n");

for (int n = 0; n <= max_n; n++) {


for (r = 0; r <= n; r++) {
printf("%2d | %2d | %llu\n", n, r, binomial_coefficient(n, r));
}
}

return 0;
}

Output
3. Develop a recursive function GCD (num1, num2) that accepts two integer arguments. Write a C
program that invokes this function to find the greatest common divisor of two given integers.

Code
#include <stdio.h>

int factorial(int n) {
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}

int binomialCoefficient(int n, int r) {


if (r > n) {
return 0;
}
return factorial(n) / (factorial(r) * factorial(n - r));
}

int main() {
int n, r;
printf("Enter the maximum value of n: ");
scanf("%d", &n);

printf("n\t r\t C(n, r)\n");


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

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


for (int j = 0; j <= i; j++) {
printf("%d\t %d\t %d\n", i, j, binomialCoefficient(i, j));
}}

return 0;
}

Output
4. Develop a recursive function FIBO (num) that accepts an integer argument. Write a C program that
invokes this function to generate the Fibonacci sequence up to num.

Code
#include <stdio.h>

int factorial(int n) {
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}

int binomialCoefficient(int n, int r) {


if (r > n) {
return 0;
}
return factorial(n) / (factorial(r) * factorial(n - r));
}

int main() {
int n, r;
printf("Enter the maximum value of n: ");
scanf("%d", &n);

printf("n\t r\t C(n, r)\n");


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

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


for (int j = 0; j <= i; j++) {
printf("%d\t %d\t %d\n", i, j, binomialCoefficient(i, j));
}
}

return 0;
}

Output
5. Develop a C function ISPRIME (num) that accepts an integer argument and returns 1 if the argument
is prime, a 0 otherwise. Write a C program that invokes this function to generate prime numbers
between the given ranges.

Code
#include <stdio.h>

int ISPRIME(int num) {


if (num <= 1) {
return 0;
}
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return 0;
}
}
return 1;
}

int main() {
int start, end;
printf("Enter the range (start and end): ");
scanf("%d %d", &start, &end);

printf("Prime numbers between %d and %d are:\n", start, end);

for (int i = start; i <= end; i++) {


if (ISPRIME(i)) {
printf("%d ", i);
}
}

printf("\n");
return 0;
}

Output
6. Develop a function REVERSE (str) that accepts a string argument. Write a C program that invokes
this function to find the reverse of a given string.

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

void REVERSE(char str[]) {


int length = strlen(str);
for (int i = 0; i < length / 2; i++) {
char temp = str[i];
str[i] = str[length - i - 1];
str[length - i - 1] = temp;
}
}

int main() {
char str[100];

printf("Enter a string: ");


fgets(str, sizeof(str), stdin);

str[strcspn(str, "\n")] = '\0'; // Remove the newline character from the string

REVERSE(str);

printf("Reversed string: %s\n", str);

return 0;
}

Output
Experiment 7: Structures and Union

1. Write a C program that uses functions to perform the following operations:


a. Reading a complex number.
b. Writing a complex number.
c. Addition and subtraction of two complex numbers
Note: represent complex number using a structure.

Code
#include <stdio.h>

struct Complex {
float real;
float imag;
};

void readComplex(struct Complex *c) {


printf("Enter real part: ");
scanf("%f", &c->real);
printf("Enter imaginary part: ");
scanf("%f", &c->imag);
}

void writeComplex(struct Complex c) {


if (c.imag >= 0) {
printf("%.2f + %.2fi\n", c.real, c.imag);
} else {
printf("%.2f - %.2fi\n", c.real, -c.imag);
}
}

struct Complex addComplex(struct Complex c1, struct Complex c2) {


struct Complex result;
result.real = c1.real + c2.real;
result.imag = c1.imag + c2.imag;
return result;
}

struct Complex subtractComplex(struct Complex c1, struct Complex c2) {


struct Complex result;
result.real = c1.real - c2.real;
result.imag = c1.imag - c2.imag;
return result;
}

int main() {
struct Complex c1, c2, sum, difference;

printf("Enter first complex number:\n");


readComplex(&c1);

printf("Enter second complex number:\n");


readComplex(&c2);

printf("First complex number: ");


writeComplex(c1);

printf("Second complex number: ");


writeComplex(c2);

sum = addComplex(c1, c2);


difference = subtractComplex(c1, c2);

printf("Sum: ");
writeComplex(sum);

printf("Difference: ");
writeComplex(difference);

return 0;
}

Output
2. Write a C program to compute the monthly pay of 100 employees using each employee‗s name, basic
pay. The DA is computed as 52% of the basic pay. Gross-salary (basic pay + DA). Print the
employees name and gross salary.

Code
#include <stdio.h>

#define MAX_EMPLOYEES 100

struct Employee {
char name[50];
float basicPay;
float grossSalary;
};

void calculateGrossSalary(struct Employee *emp) {


float DA = 0.52 * emp->basicPay; // Calculate DA as 52% of basic pay
emp->grossSalary = emp->basicPay + DA; // Calculate gross salary
}

int main() {
struct Employee employees[MAX_EMPLOYEES];
int i;

for (i = 0; i < MAX_EMPLOYEES; i++) {


printf("Enter name of employee %d: ", i + 1);
scanf("%s", employees[i].name);
printf("Enter basic pay of employee %d: ", i + 1);
scanf("%f", &employees[i].basicPay);
calculateGrossSalary(&employees[i]); // Calculate gross salary
}

printf("\nEmployee Name\tGross Salary\n");


printf("------------------------------------\n");
for (i = 0; i < MAX_EMPLOYEES; i++) {
printf("%s\t\t%.2f\n", employees[i].name, employees[i].grossSalary);
}

return 0;
}

Output

3. Create a Book structure containing book_id, title, author name and price. Write a C program to pass a
structure as a function argument and print the book details.
Code
#include <stdio.h>

#define MAX_TITLE_LENGTH 50
#define MAX_AUTHOR_NAME_LENGTH 50

struct Book {
int book_id;
char title[MAX_TITLE_LENGTH];
char author_name[MAX_AUTHOR_NAME_LENGTH];
float price;
};

void printBookDetails(struct Book book) {


printf("Book ID: %d\n", book.book_id);
printf("Title: %s\n", book.title);
printf("Author: %s\n", book.author_name);
printf("Price: %.2f\n", book.price);
}

int main() {
struct Book myBook = {1, "The Catcher in the Rye", "J.D. Salinger", 9.99};

printBookDetails(myBook);

return 0;
}

Output
4. Create a union containing 6 strings: name, home_address, hostel_address, city, state and zip. Write a
C program to display your present address.

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

#define MAX_LENGTH 100

struct Address {
char name[MAX_LENGTH];
char home_address[MAX_LENGTH];
char hostel_address[MAX_LENGTH];
char city[MAX_LENGTH];
char state[MAX_LENGTH];
char zip[MAX_LENGTH];
};

int main() {
struct Address address;

printf("Enter your name: ");


fgets(address.name, MAX_LENGTH, stdin);
address.name[strcspn(address.name, "\n")] = 0;

printf("Enter your home address: ");


fgets(address.home_address, MAX_LENGTH, stdin);
address.home_address[strcspn(address.home_address, "\n")] = 0;

printf("Enter your hostel address: ");


fgets(address.hostel_address, MAX_LENGTH, stdin);
address.hostel_address[strcspn(address.hostel_address, "\n")] = 0;

printf("Enter your city: ");


fgets(address.city, MAX_LENGTH, stdin);
address.city[strcspn(address.city, "\n")] = 0;

printf("Enter your state: ");


fgets(address.state, MAX_LENGTH, stdin);
address.state[strcspn(address.state, "\n")] = 0;

printf("Enter your zip code: ");


fgets(address.zip, MAX_LENGTH, stdin);
address.zip[strcspn(address.zip, "\n")] = 0;

printf("\nYour Present Address:\n");


printf("Name: %s\n", address.name);
printf("Home Address: %s\n", address.home_address);
printf("Hostel Address: %s\n", address.hostel_address);
printf("City: %s\n", address.city);
printf("State: %s\n", address.state);
printf("Zip Code: %s\n", address.zip);

return 0;
}
Output
Experiment 8: Pointers

1. Declare different types of pointers (int, float, char) and initialize them with the addresses of
variables. Print the values of both the pointers and the variables they point to.

Code
#include<stdio.h>

int main() {
int intVar = 16;
float floatVar = 12.5;
char charVar = 'X';

int *intPtr = &intVar;


float *floatPtr = &floatVar;
char *charPtr = &charVar;

printf("Address of intVar: %p, Value: %d\n", intPtr, *intPtr);


printf("Address of floatVar: %p, Value: %.2f\n", floatPtr, *floatPtr);
printf("Address of charVar: %p, Value: %c\n", charPtr, *charPtr);

return 0;
}

Output
2. Perform pointer arithmetic (increment and decrement) on pointers of different data types. Observe
how the memory addresses change and the effects on data access.

Code
#include <stdio.h>

int main() {
int intVar = 16;
float floatVar = 12.5;
char charVar = 'X';

int *intPtr = &intVar;


float *floatPtr = &floatVar;
char *charPtr = &charVar;

printf("Initial address of intPtr: %p\n", intPtr);


printf("Initial address of floatPtr: %p\n", floatPtr);
printf("Initial address of charPtr: %p\n", charPtr);

intPtr++;
floatPtr++;
charPtr++;

printf("Address of intPtr after increment: %p\n", intPtr);


printf("Address of floatPtr after increment: %p\n", floatPtr);
printf("Address of charPtr after increment: %p\n", charPtr);

return 0;
}

Output
3. Write a function that accepts pointers as parameters. Pass variables by reference using pointers and
modify their values within the function.

Code
#include <stdio.h>

void modifyValues(int *intPtr, float *floatPtr, char *charPtr) {


*intPtr += 10;
*floatPtr += 5.5;
*charPtr = 'V';
}

int main() {
int intVar = 16;
float floatVar = 12.5;
char charVar = 'X';

printf("Before modification:\n");
printf("intVar: %d, \nfloatVar: %.2f, \ncharVar: %c\n", intVar, floatVar, charVar);

modifyValues(&intVar, &floatVar, &charVar);

printf("\nAfter modification:\n");
printf("intVar: %d, \nfloatVar: %.2f, \ncharVar: %c\n", intVar, floatVar, charVar);

return 0;
}

Output
Experiment 9: File Handling in C

1. Write a program to create a new file and write text into it.

Code
#include <stdio.h>

int main() {
FILE *file;
file = fopen("example.txt", "w");
if (file == NULL) {
return 1;
}
fprintf(file, "Hello, this is a text file.\n");
fclose(file);
return 0;
}

Output
2. Open an existing file and read its content character by character, and then close the file.

Code
#include <stdio.h>

int main() {
FILE *file;
char ch;

file = fopen("example.txt", "r");


if (file == NULL) {
return 1;
}

while ((ch = fgetc(file)) != EOF) {


putchar(ch);
}

fclose(file);
return 0;
}

Output
3. Open a file, read its content line by line, and display each line on the console.

Code
#include <stdio.h>

int main() {
FILE *file;
char line[256];

file = fopen("example.txt", "r");


if (file == NULL) {
return 1;
}

while (fgets(line, sizeof(line), file)) {


printf("%s", line);
}

fclose(file);
return 0;
}

Output
Experiment 10: Dynamic Memory Allocation

1. Write a program to create a simple linked list in C using pointer and structure.

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

struct Node {
int data;
struct Node* next;
};

struct Node* createNode(int data) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}

void appendNode(struct Node** head, int data) {


struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return;
}
struct Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}

void displayList(struct Node* head) {


struct Node* temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}

int main() {
struct Node* head = NULL;

appendNode(&head, 10);
appendNode(&head, 20);
appendNode(&head, 30);
appendNode(&head, 40);

printf("Linked List: ");


displayList(head);

struct Node* current = head;


struct Node* nextNode;
while (current != NULL) {
nextNode = current->next;
free(current);
current = nextNode;
}

return 0;
}

Output
2. Write a program to insert item in middle of the linked list.

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

struct Node {
int data;
struct Node* next;
};

struct Node* createNode(int data) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}

void insertMiddle(struct Node** head, int data) {


struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return;
}
struct Node* slow = *head;
struct Node* fast = *head;
struct Node* prev = NULL;
while (fast != NULL && fast->next != NULL) {
prev = slow;
slow = slow->next;
fast = fast->next->next;
}
if (prev != NULL) {
prev->next = newNode;
newNode->next = slow;
} else {
newNode->next = *head;
*head = newNode;
}
}

void displayList(struct Node* head) {


struct Node* temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}

int main() {
struct Node* head = NULL;

insertMiddle(&head, 10);
insertMiddle(&head, 20);
insertMiddle(&head, 30);
insertMiddle(&head, 40);
insertMiddle(&head, 25);

printf("Linked List: ");


displayList(head);

struct Node* current = head;


struct Node* nextNode;
while (current != NULL) {
nextNode = current->next;
free(current);
current = nextNode;
}

return 0;
}

Output
Experiment 11: Bitwise Operator

1. Write a program to apply bitwise OR, AND and NOT operators on bit level.

Code
#include <stdio.h>

int main() {
int a = 12; // 1100 in binary
int b = 10; // 1010 in binary

int bitwise_or = a | b;
int bitwise_and = a & b;
int bitwise_not_a = ~a;
int bitwise_not_b = ~b;

printf("a = %d, b = %d\n", a, b);


printf("Bitwise OR (a | b) = %d\n", bitwise_or);
printf("Bitwise AND (a & b) = %d\n", bitwise_and);
printf("Bitwise NOT (~a) = %d\n", bitwise_not_a);
printf("Bitwise NOT (~b) = %d\n", bitwise_not_b);

return 0;
}

Output
2. Write a program to apply left shift and right shift operator.

Code
#include <stdio.h>

int main() {
int num = 5;

int left_shift = num << 1;


int right_shift = num >> 1;

printf("Original number: %d\n", num);


printf("Left shift (num << 1): %d\n", left_shift);
printf("Right shift (num >> 1): %d\n", right_shift);

return 0;
}

Output
Experiment 12: Preprocessor and Directives in C

1. Write a program to define some constant variable in preprocessor.

Code
#include <stdio.h>

#define PI 3.14
#define MAX_SIZE 100
#define GREETING "Hello, World!"

int main() {
float area;
int radius = 5;

area = PI * radius * radius;

printf("%s\n", GREETING);
printf("Area of the circle with radius %d: %.2f\n", radius, area);
printf("Maximum size allowed: %d\n", MAX_SIZE);

return 0;
}

Output
2. Write a program to define a function in directives.

Code
#include <stdio.h>

#define SQUARE(x) ((x) * (x))

int main() {
int num = 4;
int result = SQUARE(num);

printf("The square of %d is %d\n", num, result);

return 0;
}

Output
Experiment 13: Macros in C

1. Write a program to define multiple macro to perform arithmetic functions.

Code
#include <stdio.h>

// Define macros for arithmetic operations


#define ADD(x, y) ((x) + (y))
#define SUBTRACT(x, y) ((x) - (y))
#define MULTIPLY(x, y) ((x) * (y))
#define DIVIDE(x, y) ((y) != 0 ? (x) / (y) : 0) // Prevent division by zero

int main() {
int a = 10;
int b = 5;

printf("Arithmetic Operations:\n");
printf("%d + %d = %d\n", a, b, ADD(a, b));
printf("%d - %d = %d\n", a, b, SUBTRACT(a, b));
printf("%d * %d = %d\n", a, b, MULTIPLY(a, b));
printf("%d / %d = %d\n", a, b, DIVIDE(a, b));

return 0;
}

Output
Experiment 14: Static Library in C

1. Write a program to create a static library for performing arithmetic functions.

Code
#include <stdio.h>

int add(int x, int y) {


return x + y;
}

int subtract(int x, int y) {


return x - y;
}

int multiply(int x, int y) {


return x * y;
}

double divide(int x, int y) {


if (y != 0) {
return (double)x / y;
} else {
return 0;
}
}

int main() {
int a = 10, b = 5;

printf("Addition: %d\n", add(a, b));


printf("Subtraction: %d\n", subtract(a, b));
printf("Multiplication: %d\n", multiply(a, b));
printf("Division: %.2f\n", divide(a, b));

return 0;
}

Output
2. Write a program to use static library in other program.

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

int add(int x, int y);


int subtract(int x, int y);
int multiply(int x, int y);
double divide(int x, int y);

int add(int x, int y) {


return x + y;
}

int subtract(int x, int y) {


return x - y;
}

int multiply(int x, int y) {


return x * y;
}

double divide(int x, int y) {


if (y != 0) {
return (double)x / y;
} else {
return 0;
}
}

int main() {
int a = 10, b = 5;

printf("Addition: %d\n", add(a, b));


printf("Subtraction: %d\n", subtract(a, b));
printf("Multiplication: %d\n", multiply(a, b));
printf("Division: %.2f\n", divide(a, b));

return 0;
}

Output
Experiment 15: Shared Library in C

1. Write a program to create a shared library for performing arithmetic functions.

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

int add(int x, int y);


int subtract(int x, int y);
int multiply(int x, int y);
double divide(int x, int y);

int add(int x, int y) {


return x + y;
}

int subtract(int x, int y) {


return x - y;
}

int multiply(int x, int y) {


return x * y;
}

double divide(int x, int y) {


if (y != 0) {
return (double)x / y;
} else {
fprintf(stderr, "Error: Division by zero\n");
exit(EXIT_FAILURE);
}
}

int main() {
int a = 10, b = 5;

printf("Addition: %d\n", add(a, b));


printf("Subtraction: %d\n", subtract(a, b));
printf("Multiplication: %d\n", multiply(a, b));
printf("Division: %.2f\n", divide(a, b));

return 0;
}

Output
2. Write a program to use shared library in other program.

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

int add(int x, int y);


int subtract(int x, int y);
int multiply(int x, int y);
double divide(int x, int y);

int add(int x, int y) {


return x + y;
}

int subtract(int x, int y) {


return x - y;
}

int multiply(int x, int y) {


return x * y;
}

double divide(int x, int y) {


if (y != 0) {
return (double)x / y;
} else {
fprintf(stderr, "Error: Division by zero\n");
exit(EXIT_FAILURE);
}
}

int main() {
int a = 10, b = 5;

printf("Addition: %d\n", add(a, b));


printf("Subtraction: %d\n", subtract(a, b));
printf("Multiplication: %d\n", multiply(a, b));
printf("Division: %.2f\n", divide(a, b));

return 0;
}

Output
Experiment 16: Multithreading in C

1. Write a program to print 1-10 numbers five times using multithreading in C.

Code
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

#define NUM_PRINTS 5
#define MAX_NUMBER 10

void* print_numbers(void* arg) {


for (int i = 0; i < NUM_PRINTS; i++) {
for (int j = 1; j <= MAX_NUMBER; j++) {
printf("%d ", j);
}
printf("\n");

usleep(100000);
}
return NULL;
}

int main() {
pthread_t thread1, thread2;

pthread_create(&thread1, NULL, print_numbers, NULL);


pthread_create(&thread2, NULL, print_numbers, NULL);

pthread_join(thread1, NULL);
pthread_join(thread2, NULL);

return 0;
}

Output
Experiment 17: Socket Programming in C

1. Write a program to implement socket programming using C.

Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <pthread.h>

void* server_function(void* arg) {


int server_fd, new_socket;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};

server_fd = socket(AF_INET, SOCK_STREAM, 0);


setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(8080);

bind(server_fd, (struct sockaddr *)&address, sizeof(address));


listen(server_fd, 3);

new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen);


read(new_socket, buffer, 1024);
printf("Message from client: %s\n", buffer);

close(new_socket);
close(server_fd);
return NULL;
}

void* client_function(void* arg) {


int sock = 0;
struct sockaddr_in serv_addr;
char *message = "Hello from client";

sock = socket(AF_INET, SOCK_STREAM, 0);


serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(8080);

inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr);


connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr));

send(sock, message, strlen(message), 0);


close(sock);
return NULL;
}
int main() {
pthread_t server_thread, client_thread;

pthread_create(&server_thread, NULL, server_function, NULL);


sleep(1); // Ensure the server is up before starting the client
pthread_create(&client_thread, NULL, client_function, NULL);

pthread_join(server_thread, NULL);
pthread_join(client_thread, NULL);

return 0;
}

Output
Experiment 18: Testing and Debugging

1. Write a program and perform testing and debugging on same implementation

Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <pthread.h>

void* server_function(void* arg) {


int server_fd, new_socket;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};

server_fd = socket(AF_INET, SOCK_STREAM, 0);


setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(8080);

if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {


perror("Bind failed");
exit(EXIT_FAILURE);
}

if (listen(server_fd, 3) < 0) {
perror("Listen failed");
exit(EXIT_FAILURE);
}

new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen);


if (new_socket < 0) {
perror("Accept failed");
exit(EXIT_FAILURE);
}

read(new_socket, buffer, 1024);


printf("Message from client: %s\n", buffer);

close(new_socket);
close(server_fd);
return NULL;
}

void* client_function(void* arg) {


int sock = 0;
struct sockaddr_in serv_addr;
char *message = "Hello from client";
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
perror("Socket creation error");
return NULL;
}

serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(8080);

if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {


perror("Invalid address/ Address not supported");
return NULL;
}

if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {


perror("Connection failed");
return NULL;
}

send(sock, message, strlen(message), 0);


close(sock);
return NULL;
}

int main() {
pthread_t server_thread, client_thread;

pthread_create(&server_thread, NULL, server_function, NULL);


sleep(1);
pthread_create(&client_thread, NULL, client_function, NULL);

pthread_join(server_thread, NULL);
pthread_join(client_thread, NULL);

return 0;
}

Output

You might also like