Harekam Bhatia (590014459) C Programming (1)
Harekam Bhatia (590014459) C Programming (1)
Lab Assignment
Bachelor of Technology
Submitted by
Name- Harekam Bhatia
Sap ID- 590014459
Submitted to
Dr. Mahendra Kumar Shrivas
UPES
Bidholi, Via Prem
Nagar ,Dehradun ,Uttarakhand
July-Dec-2024
1|Page
Lab ASSIGNMENT 1
Solution:
#include<stdio.h> Output:
int main()
Coding
2|Page
Q2. Write a c program to print the address in
multiple lines.
Solution:
Coding
#include<stdio.h> Output:
int main()
printf(“hello
UPES\n”);
printf(“I am
Priyanshu”);
}
3|Page
Q3. Write a program that prompts the user to enter
their name and age.
Solution:
Coding
#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|Page
Q4. Write a c program to add two numbers,
take number from the user.
Solution:
Coding
#include <stdio.h>
int main ()
{
int a, b, s;
printf("enter any two numbers: ");
scanf("%d %d",&a,&b);
s=a+b;
printf("sum of two numbers is: %d",s);
return 0;
}
Output:
5|Page
Question 1: Write a C program to calculate the area and perimeter
of a rectangle based on its length and width.
Solution:
Coding Output
#include<stdio.h>
void main(){
int l, b;
float peri , area;
printf("Enter the length and breadth
of a rectangle\n");
scanf("%d" ,&l);
scanf("%d" ,&b);
peri=2*(l+b);
area=l*b;
printf("AREA OF RECTANGLE IS:\n
%f",area);
printf("\n PERIMETER OF RECTANGLE
IS:\n %f",peri );
}
6|Page
Question 2: Write a C program to convert
temperature from Celsius to Fahrenheit using the
formula: F=(C*9/5) + 32.
Solution:
Coding Output
#include<stdio.h>
int main(){
float cel,far;
printf(“Enter the
temperature in Celsius\n”);
scanf(“%f”,&cel);
far=(cel*(float)9/5)+32;
printf("Celsius to
fahrenheit is %.2f\n",far);
}
7|Page
Experiment 3.1: Conditional Statements
Question 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.
Solution:
Coding Output
#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);
if (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 ||
8|Page
a == c)
{
printf("The triangle is
Isosceles.\n");
}
else {
printf("The triangle is
Scalene.\n");
}
return 0;
}
Question 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 15.1 to
17.5
Underweight 17.6 to
18.5
Overweight 25 to 25.9
Obese 30 to 39.9
9|Page
Solution:
Coding Output
#include<stdio.h>
int main ()
{
float a, w, h;
// a stands for BMI, w
stands for weight in kg
and h stands for height
in meters
printf("Weight (kg):");
scanf("%f", &w);
printf("Height
(meter):");
scanf("%f", &h);
a = w / (h*h);
printf("BMI: %f\n",a);
if (a <= 15)
10 | P a g e
{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;
}
11 | P a g e
Question3: WAP to check if three points (x1,y1),
(x2,y2) and (x3,y3) are collinear or not.
Solution:
Coding Output
#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
12 | P a g e
COLLINEAR");
}
return 0;
}
13 | P a g e
scanf("%d",&year);
nyear= year - 2000;
leapyr= nyear/4;
nonleapyr= nyear -
leapyr;
if (year%4==0){
days =
nonleapyr*(365) + (leapyr-
1)*366+365;
}
else {
days = leapyr*366 +
(nonleapyr)*365+365;
}
if (days%7==0){
printf("It is a sunday on
1st january of %d ",year);
}
else if (days%7==1){
printf("It is a monday on
1ST january of %d ",year);
}
else if (days%7==2){
printf("It is a tuesday on
14 | P a g e
1ST january of %d ",year);
}
else if (days%7==3){
printf("It is a wednesday
on 1ST january of %d
",year);
}
else if (days%7==4){
printf("It is a thrusday on
1ST january of %d ",year);
}
return 0;
}
16 | P a g e
perimeter is:\n");
if (highest_perimeter == 2 * (l1 + b1)) {
printf("Rectangle 1\n");
} else if (highest_perimeter == 2 * (l2 +
b2)) {
printf("Rectangle 2\n");
} else {
printf("Rectangle 3\n");
}
return 0;
}
17 | P a g e
Coding Output
#include <stdio.h>
int main() {
int number;
int 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+
+;
}
18 | P a g e
printf("Do you
want to enter
another number?
(y/n): ");
scanf(" %c",
&choice);
} while (choice ==
'y' || choice == 'Y');
printf("\nCount 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;
}
19 | P a g e
Question 2: WAP to print the multiplication table of
the number entered by the user. It should be in the
correct formatting. Num * 1 = Num
Solution:
Coding Output
#include
<stdio.h>
int main() {
int num;
printf("Enter a
number to print its
multiplication
table: ");
scanf("%d",
&num);
printf("Multiplicati
on Table of %d:\n",
num);
for (int i = 1; i
<= 10; i++) {
printf("%d *
20 | P a g e
%d = %d\n", num,
i, num * i);
}
return 0;
}
b. 1
11
121
1331
14641
Solution:
a.
Coding Output
#include <stdio.h>
int main() {
21 | P a g e
int rows = 3;
int number = 1;
for (int i = 1; i <=
rows; i++) {
for (int j = 1; j
<= i; j++) {
printf("%d ",
number);
number++;
}
printf("\n");
}
return 0;
}
b.
Coding Output
#include <stdio.h>
int main() {
int rows = 5;
for (int i = 0; i <
rows; i++) {
22 | P a g e
int num = 1;
for (int j = 0; j <=
i; j++) {
printf("%d ",
num);
num = num * (i -
j) / (j + 1);
}
printf("\n");
}
return 0;
}
Solution:
Coding Output
#include <stdio.h>
23 | P a g e
#include <math.h>
int main() {
int initial_population =
100000;
float growth_rate =
0.10;
int years = 10;
printf("Year\
tPopulation\n");
printf("-------------------\
n");
for (int i = 1; i <=
years; i++) {
int population =
initial_population * pow(1
+ growth_rate, i);
printf("%d\t%d\n", i,
population);
}
return 0;
}
Solution:
Coding Output
#include <stdio.h>
int main() {
int limit = 20;
int found = 0;
printf("Ramanujan
numbers (up to %d):\n",
limit);
for (int i = 1; i <=
limit; i++) {
for (int j = i; j <=
limit; j++) {
int sum1 = i * i * i
+ j * j * j;
25 | P a g e
for (int k = 1; k
<= limit; k++) {
for (int l = k; l
<= limit; l++) {
if (i == k &&
j == l) continue;
int sum2 = k
* k * k + l * l * l;
if (sum1 ==
sum2) {
if (!found)
{
printf("%d can be
expressed as:\n", sum1);
found =
1;
}
printf("%d^3 + %d^3
and %d^3 + %d^3\n", i,
j, k, l);
}
}
}
26 | P a g e
}
}
if (!found) {
printf("No
Ramanujan numbers
found up to %d.\n",
limit);
}
return 0;
}
29 | P a g e
Solution:
Coding Output
#include <stdio.h>
int globalVar = 10;
void myFunction() {
int localVar = 5;
printf("Inside
myFunction: localVar
= %d\n", localVar);
printf("Inside
myFunction:
globalVar = %d\n",
globalVar);
}
int main() {
myFunction();
printf("Outside
myFunction:
globalVar = %d\n",
globalVar);
return 0;
}
30 | P a g e
Question 3: Declare variables within different code
blocks (enclosed by curly braces) and test their
accessibility within and outside those blocks
Solution:
Coding Output
#include <stdio.h>
int main() {
{
int blockVar1 =
20;
printf("Inside
first block: blockVar1
= %d\n", blockVar1);
}
{
int blockVar2 =
30;
printf("Inside
second block:
blockVar2 = %d\n",
blockVar2);
}
int mainVar = 40;
printf("Inside
main: mainVar = %d\
n", mainVar);
31 | P a g e
return 0;
}
Question 4: Declare a static local variable inside a
function. Observe how its value persists across
function calls.
Solution:
Coding Output
#include <stdio.h>
void countCalls() {
static int callCount
= 0;
callCount++;
printf("Function
called %d times\n",
callCount);
}
int main() {
countCalls();
countCalls();
countCalls();
return 0; }
32 | P a g e
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
CODING OUTPUT
#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;
}
33 | P a g e
Coding Output
#include<stdio.h>
struct complex{
float real;
float imag;
};
int main()
{
struct complex n1 = {9,
7};
34 | P a g e
struct complex n2 = {5,
11};
struct complex sum =
{0};
complexsum(n1, n2,
sum);
return 0;
}
int main() {
int n, i;
//pc is positive count, nc
35 | P a g e
is negative count, oc is
odd count, ec is even
count
int pc = 0, nc = 0, oc =
0, ec = 0;
printf("Enter the
number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d
integers:\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
if (arr[i] > 0)
{
pc++;
} else if (arr[i] < 0)
{
nc++;
}
if (arr[i] % 2 == 0)
36 | P a g e
{
ec++;
} else
{
oc++;
}
}
printf("Positive count:
%d\n", pc);
printf("Negative count:
%d\n", nc);
printf("Even count: %d\
n", ec);
printf("Odd count: %d\
n", oc);
return 0;
}
37 | P a g e
frequency =0;
printf("enter the
number of integers:");
scanf("%d", &a);
int arr[a];
printf("enter %d
integers:", a);
for(int i = 0; i<a; i++)
{
scanf("%d", &arr[i]);
}
38 | P a g e
frequency);
return 0;
}
if (y != z) {
printf("Matrix
multiplication not
39 | P a g e
possible\n. Number of
columns of a must be
equal to number of rows of
b.\n");
return 1;
}
int a[x][y], b[z][t], c[x][t];
// Read matrix a
printf("Enter elements of
matrix a:\n");
for (i = 0; i < x; i++) {
for (j = 0; j < y; j++) {
scanf("%d", &a[i][j]);
}
}
// Read matrix b
printf("Enter elements of
matrix b:\n");
for (i = 0; i < z; i++) {
for (j = 0; j < t; j++) {
scanf("%d", &b[i][j]);
}
}
for (i = 0; i < x; i++) {
for (j = 0; j < t; j++) {
c[i][j] = 0;
}
}
40 | P a g e
for (i = 0; i < x; i++) {
for (j = 0; j < t; j++) {
for (k = 0; k < y; k++) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
printf("\nMatrix a:\n");
for (i = 0; i < x; i++)
{
for (j = 0; j < y; j++)
{
printf("%d ", a[i][j]);
}
printf("\n");
}
printf("\nMatrix b:\n");
for (i = 0; i < z; i++)
{
for (j = 0; j < t; j++)
{
printf("%d ", b[i][j]);
}
printf("\n");
}
printf("\nfinal Matrix (a *
b):\n");
41 | P a g e
for (i = 0; i < x; i++)
{
for (j = 0; j < t; j++)
{
printf("%d ", c[i][j]);
}
printf("\n");
}
return 0;
}
int fact(int n)
{
if (n==0)
{return 1;}
int factnm1 = fact (n-1);
int factn = factnm1 * n;
}
int main()
{
printf("factorial is: %d\
n", fact(4));
return 0;
}
int main()
{
int num1, num2;
printf("num 1 and num2
are :");
scanf("%d %d", &num1,
&num2);
printf("the greatest
common divisor of %d and
%d is: %d", num1, num2,
44 | P a g e
GCD(num2, num1 %
num2));
return 0;
}
int fib(int n)
{
if (n==0)
{return 0;}
if (n==1)
{return 1;}
45 | P a g e
{
printf("fibonachi is: %d\
n", fib(4));
return 0;
}
46 | P a g e
}
int main()
{
int s, e;// s stands for start
and e stands for end
printf("Enter starting
range: ");
scanf("%d", &s);
printf("Enter ending
range: ");
scanf("%d", &e);
printf("Prime numbers
between %d and %d are: \
n", s, e);
for (int i = s; i <= e; i++)
{
if (ISPRIME(i)) //function
call
{
printf("%d ", i);
}
}
printf("\n");
return 0;
}
47 | P a g e
Question 5: 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.
Solution:
Coding Output
#include <stdio.h>
#include <string.h>
while (s < e)
{
temp = str[s];
str[s] = str[e];
str[e] = temp;
s++;
e--;
}
48 | P a g e
}
int main()
{
char _strr[100];
printf("Enter a string: ");
fgets(_strr, sizeof(_strr),
stdin);
_strr[strcspn (_strr, "\n")]
= '\0';
reverse(_strr);// function
call
printf("Reversed string:
%s\n", _strr);
return 0;
}
49 | P a g e
Lab Assignment 7 (Structure and Union)
Question 1: Write a C program that uses functions to perform the
following operations:
a. Reading a complex number.
Solution:
Coding Output
#include<stdio.h>
struct complex{
float real;
float imag;
};
int main()
{
struct complex n1 = {9,
7};
struct complex n2 = {5,
11};
struct complex sum =
{0};
complexsum(n1, n2,
sum);
return 0;
}
51 | P a g e
struct employee
{
char name[50];
float basic_pay;
float DA;
float gross_salary;
} e[100];
void readdata(struct
employee e[])
{
for (int i = 0; i < 3; i++)
{
printf("\nEmployee %d
details\n", i + 1);
printf("Enter employee
name: ");
scanf("%s", e[i].name);
printf("Enter basic pay:
");
scanf("%f",
&e[i].basic_pay);
// Calculate DA
e[i].DA = 0.52 *
e[i].basic_pay;
52 | P a g e
e[i].gross_salary =
e[i].basic_pay + e[i].DA;
}
}
void printdata(struct
employee e[])
{
printf("\nEmployee
Salary Details\n");
printf("------------------------\
n");
int main()
{
readdata(e);
printdata(e);
53 | P a g e
return 0;
}
struct book {
int book_id;
char title[50];
char author_name[100];
float price;
};
void
printBookDetails(struct
book b) {
printf("\nBook Details:\
n");
printf("Book ID: %d\n",
b.book_id);
printf("Title: %s\n",
b.title);
54 | P a g e
printf("Author: %s\n",
b.author_name);
printf("Price: %.2f\n",
b.price);
}
int main() {
printf("Enter author
name: ");
scanf("%s",
&bk.author_name);
55 | P a g e
printBookDetails(bk);
return 0;
}
56 | P a g e
char state[100];
int zip;
};
int main()
{
union address a1;
strcpy
(a1.hostel_address ,"cryst
al crown hostel\nupes
road\nbidholi\
ndehradun");
printf("hostel address:
%s\n", a1.hostel_address);
return 0;
}
57 | P a g e
char c = 'a';
// pointers declaration
int *pointer_a;
float *pointer_b;
char *pointer_c;
// adding address to
pointers
pointer_a = &a;
pointer_b = &b;
pointer_c = &c;
// printing address of
variable using pointers
printf("address of a :
%p\n", pointer_a);
printf("address of b :
%p\n", pointer_b);
printf("address of c :
%p\n", pointer_c);
// printing values of
variable using pointers
printf("value of a : %d\
n", *pointer_a);
printf("value of b : %f\
n", *pointer_b);
printf("value of c : %c\
n", *pointer_c);
58 | P a g e
return 0;
}
// pointers declaration
int *pointer_a;
float *pointer_b;
char *pointer_c;
// adding address to
pointers
pointer_a = &a;
pointer_b = &b;
pointer_c = &c;
// printing address of
variable using pointers
59 | P a g e
printf("address of a :
%p\n", pointer_a);
printf("address of b :
%p\n", pointer_b);
printf("address of c :
%p\n", pointer_c);
// increment
pointer_a++;
pointer_b++;
pointer_c++;
// printing address of
variavle after pointers
increment
printf("\nafter
increment\n");
printf("address of a :
%p\n", pointer_a);
printf("address of b :
%p\n", pointer_b);
printf("address of c :
%p\n", pointer_c);
// decrement
pointer_a--;
pointer_b--;
pointer_c--;
// printing address of
variable after pointers
60 | P a g e
decrement
printf("\nafter
decrement\n");
printf("address of a :
%p\n", pointer_a);
printf("address of b :
%p\n", pointer_b);
printf("address of c :
%p\n", pointer_c);
return 0;
}
// function call
pointer_function(&a,
&b);
return 0;
}
62 | P a g e
Lab Assignment 9 (File Structure)
Question 1: Write a program to create a new file and write text
into it.
Solution:
Coding Output
#include<stdio.h>
int main()
{
FILE *file;
// opening a file
file = fopen ("hello.txt",
"w");
if (file == NULL)
{
printf("error opening
63 | P a g e
the file\n");
return 1;
}
// closing file
fclose(file);
printf("text is been
entered in 'hello.txt' file\
n");
return 0;
}
int main()
{
FILE *file;
file = fopen("hello.txt",
64 | P a g e
"r");
char a; // to read
content of file
a = fgetc(file);
if (file == NULL)
{
printf("error in
opening file");
return 1;
}
printf("file content:\n");
while (a != EOF)
{
printf("%c", a);
a = fgetc(file);
}
fclose(file);
return 0;
}
Question 3: Open a file, read its content line by line, and display
each line on the console.
Solution:
Coding Output
#include<stdio.h>
65 | P a g e
int main()
{
FILE *file;
char li [200]; // to read
content of file
file = fopen("hello.txt",
"r");
if (file == NULL)
{
printf("error in
opening file");
return 1;
}
printf("file content:\n");
while (fgets(li, sizeof(li),
file))
{
printf("%s", li);
}
fclose(file);
return 0;
}
66 | P a g e
Lab Assignment 10 (Dynamic Memory
Allocation)
Question 1: Write a program to create a simple linked list in C
using pointer and structure.
Solution:
Coding Output
#include <stdio.h>
#include <stdlib.h>
67 | P a g e
struct str {
int data;
struct str *next;
};
int main() {
struct str *head = NULL,
*second = NULL, *third =
NULL;
second->data = 12;
second->next = third;
third->data = 18;
third->next = NULL;
68 | P a g e
>data);
temp = temp->next;
}
printf("NULL\n");
return 0;
}
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;
69 | P a g e
return newNode;
}
struct Node*
insertInMiddle(struct
Node* head, int x) {
struct Node* newNode =
createNode(x);
if (head == NULL) {
return newNode;
}
if (prev != NULL) {
prev->next =
70 | P a g e
newNode;
newNode->next =
slow;
} else {
newNode->next =
head;
return newNode;
}
return head;
}
int main() {
struct Node* head =
NULL;
71 | P a g e
head = createNode(1);
head->next =
createNode(2);
head->next->next =
createNode(4);
head->next->next-
>next = createNode(5);
int x = 3;
head =
insertInMiddle(head, x);
printf("Updated List
after inserting %d: ", x);
printList(head);
return 0;
}
72 | P a g e
Lab Assignment 11 (Bitwise Operator)
Question 1: Write a program to apply bitwise OR, AND and NOT
operators on bit level.
Solution:
Coding Output
#include<stdio.h>
void display_binary(int n)
{
for (int i=7; i >= 0; i--) //
where 7 to 0 reperesnt 8
bit display_binary
{
printf("%d", (n >> i) &
1);
}
}
int main()
{
int a = 36;
73 | P a g e
int b = 6;
printf("binary of a is :");
display_binary(a);
printf("\nbinary of b
is :");
display_binary(b);
// bitwize OR
int bit_OR = a|b;
printf("\nbitwize OR of
%d and %d is:" ,a, b);
display_binary(bit_OR);
// bitwize AND
int bit_AND = a&b;
printf("\nbitwize AND of
%d and %d is:", a, b);
display_binary(bit_AND);
// bitwize NOT
int bit_NOT_a = ~a;
printf("\nbitwize NOT of
%d is:", a);
display_binary(bit_NOT_a);
return 0;
}
return 0;
}
76 | P a g e
#include<stdio.h>
int main()
{
printf("message :%s\n",
print);
printf("minimum value :
%d\n", min_value);
return 0;
}
int main()
77 | P a g e
{
int num1 = 6;
int num2 = 3;
printf("square of %d is :
%d\n",num1,
square(num1));
printf("sum of %d and
%d is :%d\n", num1, num2,
sum (num1, num2));
return 0;
}
78 | P a g e
#include<stdio.h>
int main()
{
int num1 = 21;
int num2 = 14;
printf("sum of %d and
%d is :%d\n", num1, num2,
sum (num1, num2));
printf("subtraction of
%d and %d is :%d\n",
num1, num2, sub (num1,
num2));
printf("multiplication of
%d and %d is :%d\n",
num1, num2, multiply
(num1, num2));
if(num2 != 0)
{
printf("sum of %d and
79 | P a g e
%d is :%d\n", num1, num2,
divide (num1, num2));
}
return 0;
}
80 | P a g e
Lab Assignment 14 (Static Library in C)
Question 1: Write a program to create a static library for
performing arithmetic functions.
Solution:
Coding Output
Header File:
int add(int x, int y);
int sub(int x, int y);
int multiply(int x, int y);
Static Library:
#include<stdio.h>
#include "arithmetic.h"
int main()
{
int a = 7;
int b = 4;
printf("%d + %d = %d\
n",a, b, add(a,b));
printf("%d - %d = %d\n",a,
b, sub(a,b));
printf("%d * %d = %d\n",a,
b, multiply(a,b));
return 0;
}
Source File:
int add(int x, int y)
{
81 | P a g e
return x+y;
}
int sub(int x, int y)
{
return x-y;
}
int multiply(int x, int y)
{
return x * y;
}
#endif
Shared Library:
#include<stdio.h>
#include "arithmetic.h"
int main()
{
int a = 15;
int b = 10;
83 | P a g e
printf("using shared
library\n");
printf("addition : %d\n",
add(a, b));
printf("subtraction : %d\
n", sub(a, b));
printf("multiplicaton : %d\
n", multiply(a, b));
return 0;
}
Source File:
#include "arithemtic.h"
int add(int x, int y)
{
return x + y;
}
int sub(int x, int y)
{
return x - y;
}
int multiply(int x, int y)
{
return x * y;
}
85 | P a g e
Lab Assignment 16 (Multithreading in C)
Question 1: Write a program to print 1 – 10 numbers five time
using multithreading in C.
Solution:
Coding Output
#include <stdio.h>
#include <pthread.h>
void* print_numbers(void*
arg) {
for (int i = 1; i <= 10; i+
+) {
printf("%d ", i);
}
printf("\n");
return NULL;
}
86 | P a g e
int main() {
pthread_t arr[5];
for (int i = 0; i < 5; i++)
{
if
(pthread_create(&arr[i],
NULL, print_numbers,
NULL) != 0) {
perror("pthread_create
failed");
return 1;
}
}
for (int i = 0; i < 5; i++)
{
pthread_join(arr[i],
NULL);
}
return 0;
}
88 | P a g e
printf("\nConnection Failed \n");
return -1;
}
send(sock, hello, strlen(hello), 0);
printf("Hello message sent\n");
valread = read(sock, buffer, 1024);
printf("%s\n", buffer);
// closing the connected socket
close(client_fd);
return 0;
}
For Server:
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#define PORT 8080
int main(int argc, char const* argv[])
{
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = { 0 };
char* hello = "Hello from server";
89 | P a g e
// Creating socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}
// Forcefully attaching socket to port 8080
if (setsockopt(server_fd, SOL_SOCKET,SO_REUSEADDR |
SO_REUSEPORT, &opt,
sizeof(opt))) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
address.sin_family= AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
// Forcefully attaching socket to port 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");
exit(EXIT_FAILURE);
}
if ((new_socket = accept(server_fd, (struct
sockaddr*)&address,(socklen_t*)&addrlen))< 0) {
90 | P a g e
perror("accept");
exit(EXIT_FAILURE);
}
valread = read(new_socket, buffer, 1024);
printf("%s\n", buffer);
send(new_socket, hello, strlen(hello), 0);
printf("Hello message sent\n");
// closing the connected socket
close(new_socket);
// closing the listening socket
shutdown(server_fd, SHUT_RDWR);
return 0;
}
91 | P a g e
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
def prime_checker():
while True:
try:
num = int(input("Enter a number to check if it's
prime: "))
if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")
except ValueError:
print("Invalid input. Please enter a valid
integer.")
92 | P a g e
93 | P a g e