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

Harekam Bhatia (590014459) C Programming (1) (1)

Uploaded by

mananarora661
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 views113 pages

Harekam Bhatia (590014459) C Programming (1) (1)

Uploaded by

mananarora661
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/ 113

Programming in C

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

Lab ASSIGNMENT 1

1|Page
Question 1: Write a program to print “Hello World”
Solution:
Coding

#include<stdio.h> Output:

int main()

printf (“Hello World”);

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)+3
2;

7|Page
printf("Celsius to
fahrenheit is %.2f\
n",far);
}

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

8|Page
#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 || a == c)
{
9|Page
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
10 | P a g e
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

Solution:
Coding Output
#include<stdio.h>
int main ()
{
float a, w, h;
11 | P a g e
// 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)
{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)

12 | P a g e
{printf("Overweight");}
else if (a >= 30 && a <=
39.9)
{printf("Obese");}
else
{printf("Morbidity
Obese");}
return 0;
}

13 | 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
COLLINEAR");
}
return 0;
}

14 | P a g e
Question 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.
Solution:
Coding Output
#include<stdio.h>
int main()
{int
year,nyear,leapyr ,nonleapyr
,days;
printf("Plz Enter the
year between 2001 to 2024 \
n");
scanf("%d",&year);
nyear= year - 2000;
leapyr= nyear/4;
nonleapyr= nyear -
leapyr;

15 | P a g e
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
1ST january of %d ",year);
}
else if (days%7==3){
printf("It is a wednesday
on 1ST january of %d

16 | P a g e
",year);
}
else if (days%7==4){
printf("It is a thrusday on
1ST january of %d ",year);
}
return 0;
}

Question 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.
Solution:
Coding
#include <stdio.h>
int main() {
int l1, b1, l2, b2, l3, b3, perimeter1,
perimeter2, perimeter3, highest_perimeter;

printf("Enter length and breadth of


rectangle 1: ");
scanf("%d %d", &l1, &b1);

17 | P a g e
printf("Enter length and breadth of
rectangle 2: ");
scanf("%d %d", &l2, &b2);

printf("Enter length and breadth of


rectangle 3: ");
scanf("%d %d", &l3, &b3);

perimeter1 = 2 * (l1 + b1);


perimeter2 = 2 * (l2 + b2);
perimeter3 = 2 * (l3 + b3);

highest_perimeter = (perimeter1 >


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

printf("Rectangle with the highest


perimeter is:\n");
if (highest_perimeter == 2 * (l1 + b1)) {
printf("Rectangle 1\n");
} else if (highest_perimeter == 2 * (l2 +

18 | P a g e
b2)) {
printf("Rectangle 2\n");
} else {
printf("Rectangle 3\n");
}
return 0;
}

Experiment 3.2: Loops


Question 1: WAP to enter numbers till the user
wants. At the end, it should display the count of
positive, negative, and Zeroes entered.
Solution:
Coding Output
#include <stdio.h>
int main() {
int number;

19 | P a g e
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+
+;
}
printf("Do you
want to enter
another number?
(y/n): ");
scanf(" %c",
20 | P a g e
&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;
}

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
21 | P a g e
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 *
%d = %d\n", num,
i, num * i);
}
return 0;

22 | P a g e
}

Question 3: WAP to generate the following set of


output
a. 1
23
456

b. 1
11
121
1331
14641

Solution:
a.
Coding Output
#include <stdio.h>
int main() {
int rows = 3;
int number = 1;
for (int i = 1; i <=
rows; i++) {

23 | P a g e
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++) {
int num = 1;
for (int j = 0; j <=
i; j++) {
printf("%d ",
num);
24 | P a g e
num = num * (i -
j) / (j + 1);
}
printf("\n");
}
return 0;
}

Question 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.

Solution:

Coding Output
#include <stdio.h>
#include <math.h>
int main() {
int initial_population =
100000;
float growth_rate =

25 | P a g e
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;
}

Question 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.

Example of Ramanujan number: 1729

26 | P a g e
12^3 + 1^3 and 10^3 + 9^3. for a number
L=20(that is limit)

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;
for (int k = 1; k
<= limit; k++) {
for (int l = k; l
<= limit; l++) {
if (i == k &&
j == l) continue;
27 | P a g e
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);
}
}
}
}
}
if (!found) {
printf("No
Ramanujan numbers
found up to %d.\n",
28 | P a g e
limit);
}
return 0;
}

Experiment 4: Variable and Scope of Variable


Question 1: Declare a global variable outside all
functions and use it inside various functions to
understand its accessibility.
Solution:
Coding Output
#include <stdio.h>
int globalVar = 10;
void printGlobal() {
printf("Global

29 | P a g e
Variable in printGlobal:
%d\n", globalVar);
}
void modifyGlobal() {
globalVar += 5;
printf("Global
Variable modified in
modifyGlobal: %d\n",
globalVar);
}
void resetGlobal() {
globalVar = 10;
printf("Global
Variable reset in
resetGlobal: %d\n",
globalVar);
}
int main() {
printf("Initial Global
Variable: %d\n",
globalVar);
printGlobal();
modifyGlobal();
printGlobal();
resetGlobal();
30 | P a g e
printGlobal();
return 0;
}

Question 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.

Solution:

Coding Output
#include <stdio.h>

31 | P a g e
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;
}
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>

32 | P a g e
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);
return 0;
}
Question 4: Declare a static local variable inside a
function. Observe how its value persists across
function calls.
Solution:
33 | P a g e
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; }

34 | 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];
35 | P a g e
}
}
printf("The second
largest integer is: %d\n",
second_largest);
return 0;
}

Coding Output
#include<stdio.h>

struct complex{
float real;
float imag;
};

void complexsum
(struct complex n1,
struct complex n2,
struct complex sum)
{
sum.real = n1.real
+ n2.real;
sum.imag =

36 | P a g e
n1.imag + n2.imag;

printf("sum of real
part : %f\n",
sum.real);
printf("sum of
imaginary part : %f\
n", sum.imag);

int main()
{
struct complex n1
= {9, 7};
struct complex n2
= {5, 11};
struct complex
sum = {0};

complexsum(n1,
n2, sum);

return 0;
}

37 | P a g e
Question 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.
Solution:
Coding Output
#include <stdio.h>

int main() {
int n, i;
//pc is positive
count, nc is negative
count, oc is odd
count, ec is even
count
int pc = 0, nc = 0,
oc = 0, ec = 0;
38 | P a g e
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]);
}

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

if (arr[i] > 0)
{
pc++;
} else if (arr[i]
< 0)
{
39 | P a g e
nc++;
}

if (arr[i] % 2 ==
0)
{
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;
}
40 | P a g e
Question 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.
Solution:
Coding Output
#include<stdio.h>
int main()
{
int a, numfind,
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]);

41 | P a g e
}

//ask user which


number o find
printf("enter the
number whose
frequency you want
to find:");
scanf("%d",
&numfind);

for(int i=0; i<a; i+


+)
{
if(arr[i] ==
numfind)
{
frequency+
+;
}
}
printf("the
frequency of %d is:
%d\n ", numfind,
frequency);
return 0;
42 | P a g e
}

Question 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.
Solution:
Coding Output
#include <stdio.h>
int main()
{
int x, y, z, t, i, j, k;
// matrix a
printf("Enter the
number of rows and
columns for matrix
a: ");
scanf("%d %d", &x,
&y);
// matrix b
printf("Enter the
43 | P a g e
number of rows and
columns for matrix
b: ");
scanf("%d %d", &z,
&t);

if (y != z) {
printf("Matrix
multiplication not
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]);
44 | P a g e
}
}
// 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;
}
}
for (i = 0; i < x; i++)
{
for (j = 0; j < t; j++)
{
for (k = 0; k < y; k+
45 | P a g e
+) {
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]);

46 | P a g e
}
printf("\n");
}
printf("\nfinal Matrix
(a * b):\n");
for (i = 0; i < x; i++)
{
for (j = 0; j < t; j++)
{
printf("%d ", c[i][j]);
}
printf("\n");
}
return 0;
}

47 | P a g e
Lab Assignment 6 (Function)
Question 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) = 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.
Solution:
Coding Output
#include <stdio.h>

int fact(int n)
{
if (n==0)
{return 1;}
int factnm1 = fact
(n-1);
int factn =
factnm1 * n;

48 | P a g e
}
int main()

{
printf("factorial
is: %d\n", fact(4));

return 0;
}

Question 2: 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.
Solution:
Coding Output
#include<stdio.h>

int GCD(int num1,


int num2)
{
if (num2 == 0)

49 | P a g e
{
return num1;
}
else
{
return (num2 ,
num1 % num2);
}

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, GCD(num2,
num1 % num2));
50 | P a g e
return 0;
}

Question 3: 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.
Solution:
Coding Output
#include <stdio.h>

int fib(int n)
{
if (n==0)
{return 0;}

if (n==1)
{return 1;}

int fibnm1 = fib(n-


1);
int fibnm2 = fib(n-
2);
int fibn = fibnm1
51 | P a g e
+ fibnm2;
return fibn;
}
int main()

{
printf("fibonachi
is: %d\n", fib(4));

return 0;
}

Question 4: Develop a C function ISPRIME (num)


that accepts an integer argument and returns 1 if
the argument is prime, 0 otherwise. Write a C
program that invokes this function to generate
prime numbers between the given ranges.
Solution:
Coding Output
#include <stdio.h>

//function definition
and declaration

52 | P a g e
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 s, e;// s stands
for start and e
stands for end

printf("Enter
starting range: ");
scanf("%d", &s);
printf("Enter ending
range: ");
53 | P a g e
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;
}

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.
54 | P a g e
Solution:
Coding Output
#include <stdio.h>
#include <string.h>

// function
definiation and
declaration
void reverse(char
str[])
{
int s = 0;//s stands
for start
int e = strlen(str) -
1;// e stands for end
char temp;

while (s < e)
{
temp = str[s];
str[s] = str[e];
str[e] = temp;
s++;
e--;
55 | 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;
}

56 | 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.
b. Writing a complex number.
c. Addition and subtraction of two complex
numbers
Solution:
Coding Output

57 | P a g e
#include<stdio.h>

struct complex{
float real;
float imag;
};

void complexsum
(struct complex n1,
struct complex n2,
struct complex sum)
{
sum.real = n1.real
+ n2.real;
sum.imag =
n1.imag + n2.imag;

printf("sum of real
part : %f\n",
sum.real);
printf("sum of
imaginary part : %f\
n", sum.imag);

58 | P a g e
int main()
{
struct complex n1
= {9, 7};
struct complex n2
= {5, 11};
struct complex
sum = {0};

complexsum(n1,
n2, sum);

return 0;
}

Question 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.
Solution:
Coding Output
#include <stdio.h>

59 | 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);
60 | P a g e
// Calculate DA
e[i].DA = 0.52 *
e[i].basic_pay;

// Calculate gross
salary
e[i].gross_salary =
e[i].basic_pay +
e[i].DA;
}
}

void printdata(struct
employee e[])
{
printf("\
nEmployee Salary
Details\n");

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

for (int i = 0; i < 3;


i++)
{

61 | P a g e
printf("\
nEmployee %d:\n", i
+ 1);
printf("Name: %s\
n", e[i].name);
printf("Gross
Salary: %.2f\n",
e[i].gross_salary);
}
}

int main()
{

readdata(e);
printdata(e);

return 0;
}

Question 3: Create a Book structure containing


book_id, title, author name and price. Write a C
62 | P a g e
program to pass a structure as a function argument
and print the book details.
Solution:
Coding Output
#include <stdio.h>

struct book {
int book_id;
char title[50];
char
author_name[100];
float price;
};

void
printBookDetails(str
uct book b) {
printf("\nBook
Details:\n");
printf("Book ID:
%d\n", b.book_id);
printf("Title: %s\
n", b.title);
printf("Author:
%s\n",
63 | P a g e
b.author_name);
printf("Price:
%.2f\n", b.price);
}

int main() {

struct book bk;

// Input details for


the book
printf("Enter book
ID: ");
scanf("%d",
&bk.book_id);

printf("Enter book
title: ");
scanf("%s",
&bk.title);

printf("Enter
author name: ");
scanf("%s",
&bk.author_name);
64 | P a g e
printf("Enter book
price: ");
scanf("%f",
&bk.price);

printBookDetails(bk)
;

return 0;
}

Question 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.

65 | P a g e
Solution:
Coding Output
#include<stdio.h>
#include<string.h>
union address {
char name[50];
char
home_address[100];
char
hostel_address[100];
char city[100];
char state[100];
int zip;
};

int main()
{
union address a1;
strcpy
(a1.hostel_address ,"
crystal crown hostel\
nupes road\nbidholi\
ndehradun");
printf("hostel
address:%s\n",
66 | P a g e
a1.hostel_address);
return 0;
}

Lab Assignment 8 (Pointers)


Question 1: declare different types of pointers (int,
float, char) and initialize them with the address of
variables. Print the values of both pointers and
variables they point to.
Solution:
Coding Output
#include<stdio.h>
int main()
{
int a = 4;
float b = 1.75;
char c = 'a';

// pointers
declaration
int *pointer_a;
float *pointer_b;
char *pointer_c;

67 | P a g e
// 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 :
68 | P a g e
%c\n", *pointer_c);

return 0;
}

Question 2: perform pointers arithmetic (increment


and decrement) on pointers of different types.
Observe how the memory address change and the
effects on data access.
Solution:
Coding Output
#include<stdio.h>
int main()
{
int a = 4;
float b = 1.75;
char c = 'a';

// pointers
declaration
int *pointer_a;
float *pointer_b;
char *pointer_c;

// adding address
69 | P a g e
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);

// increment
pointer_a++;
pointer_b++;
pointer_c++;

// printing address
of variavle after
pointers increment
printf("\nafter
70 | P a g e
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 decrement
printf("\nafter
decrement\n");
printf("address of
a : %p\n",
pointer_a);
printf("address of
b : %p\n",
pointer_b);

71 | P a g e
printf("address of
c : %p\n", pointer_c);

return 0;
}

Question 3: write a function that accepts pointers


as parameter. Pass variable by reference using
pointers and modify their values within the
function.
Solution:
Coding Output
#include<stdio.h>
void
pointer_function(int
*x, int *y) // function
defination
{
// function
declaration
*x = *x + 60;
*y = *y * 7;

72 | P a g e
}

int main()
{
// declare of two
variable
int a = 9;
int b = 10;

// printing value
before changes
printf("\nbefore
changes\n");
printf("a = %d
and b = %d", a, b);

// function call

pointer_function(&a,
&b);

// printing value
after changes
printf("\naftre
changes\n");
printf("a = %d
73 | P a g e
and b = %d", a, b);

return 0;
}

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>

74 | P a g e
int main()
{
FILE *file;

// opening a file
file = fopen
("hello.txt", "w");
if (file == NULL)
{
printf("error
opening the file\n");
return 1;
}

// taking inputs in
file
fprintf(file, "hello
world!!\n");
fprintf(file, "this
will show in the file
created\n");

// closing file
fclose(file);
75 | P a g e
printf("text is
been entered in
'hello.txt' file\n");
return 0;
}

Question 2: Open an existing file and read its


content character by character, and then close the
file.
Solution:
Coding Output
#include<stdio.h>

int main()
{
FILE *file;
file =
fopen("hello.txt",
"r");

char a; // to read
content of file
a = fgetc(file);

76 | P a g e
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>

77 | 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);
}

78 | P a g e
fclose(file);
return 0;
}

Lab Assignment 10 (Dynamic Memory Allocation)

79 | P a g e
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>

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

int main() {
struct str *head =
NULL, *second =
NULL, *third = NULL;

head = (struct str


*)
malloc(sizeof(struct
str));
second = (struct
str *)
malloc(sizeof(struct
80 | P a g e
str));
third = (struct str
*)
malloc(sizeof(struct
str));
head->data = 6;
head->next =
second;

second->data =
12;
second->next =
third;

third->data = 18;
third->next =
NULL;

printf("Linked list:
");
struct str *temp =
head;
while (temp !=
NULL) {
printf("%d -> ",
temp->data);
81 | P a g e
temp = temp-
>next;
}
printf("NULL\n");

return 0;
}

Question 2: Write a program to insert item in


middle of the linked list.
Solution:
Coding Output
#include <stdio.h>
#include <stdlib.h>

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

struct Node*
createNode(int data)
{
struct Node*
82 | P a g e
newNode = (struct
Node*)malloc(sizeof(
struct Node));
newNode->data =
data;
newNode->next =
NULL;
return newNode;
}

struct Node*
insertInMiddle(struc
t Node* head, int x)
{
struct Node*
newNode =
createNode(x);

if (head == NULL)
{
return
newNode;
}

struct Node* slow


= head;
83 | P a g e
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;
return
newNode;
84 | P a g e
}

return head;
}

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

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

head =
85 | P a g e
createNode(1);
head->next =
createNode(2);
head->next->next
= createNode(4);
head->next-
>next->next =
createNode(5);

printf("Original
List: ");
printList(head);

int x = 3;
head =
insertInMiddle(head,
x);

printf("Updated
List after inserting
%d: ", x);
printList(head);

return 0;
}
86 | 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
87 | P a g e
reperesnt 8 bit
display_binary
{
printf("%d", (n >>
i) & 1);
}
}

int main()
{
int a = 36;
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

88 | P a g e
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_AN
D);

// bitwize NOT
int bit_NOT_a = ~a;
printf("\nbitwize
NOT of %d is:", a);

display_binary(bit_NO
T_a);

int bit_NOT_b = ~b;


printf("\nbitwize
NOT of %d is:", b);

display_binary(bit_NO
T_b);
89 | P a g e
return 0;
}

Question 2: Write a program to apply left shift and


right shift operator.
Solution:
Coding Output
#include <stdio.h>
int main()
{
int n = 4;
printf("Original
number: %d", n );
printf("\nBinary
representation of
%d: ", n ); // binary
of 4
for (int i = 5; i >=
0; i--) {
printf("%d", (n
>> i) & 1);
}

int leftside = n <<


90 | P a g e
3; //left shift
printf("\nLeft shift
of %d by 3 positions:
%d", n, leftside);
printf("\nafter left
shift: ", leftside);
for (int i = 5; i >=
0; i--) {
printf("%d",
(leftside >> i) & 1);
}

int rightside = n
>> 1; //right shift
printf("\nRight
shift of %d by 1
positions: %d", n,
rightside);
printf("\nafter
right shift: ",
rightside);
for (int i = 5; i >=
0; i--) {
printf("%d",
(rightside >> i) & 1);
}
91 | P a g e
return 0;
}

Lab Assignment 12 (Preprocessor and Directives in


C)
Question 1: Write a program to define some
constant variable in preprocessor.
Solution:
Coding Output
#include<stdio.h>

//defining some
constant variable in
preprocessor
#define print "hello
world"
#define min_value
10

int main()
{
printf("message :
%s\n", print);
printf("minimum
92 | P a g e
value :%d\n",
min_value);
return 0;
}

Question 2: Write a program to define a function in


directives.
Solution:
Coding Output
#include<stdio.h>

//defining some
constant variable in
preprocessor
#define sum(a,b)
((a) + (b))
#define square(t)
((t) * (t))

int main()
{
int num1 = 6;
int num2 = 3;
printf("square of
%d is : %d\n",num1,
93 | P a g e
square(num1));
printf("sum of %d
and %d is :%d\n",
num1, num2, sum
(num1, num2));
return 0;
}

Lab Assignment 13 (Macros in C)


Question 1: Write a program to define multiple
macro to perform arithmetic functions.
Solution:
Coding Output

94 | P a g e
#include<stdio.h>

//defining some
constant variable in
preprocessor
#define sum(a,b)
((a) + (b))
#define sub(a,b) ((a)
- (b))
#define
multiply(a,b) ((a) *
(b))
#define divide(a,b)
((a) / (b))

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\
95 | P a g e
n", num1, num2, sub
(num1, num2));

printf("multiplicatio
n of %d and %d is :
%d\n", num1, num2,
multiply (num1,
num2));

if(num2 != 0)
{
printf("sum of
%d and %d is :%d\
n", num1, num2,
divide (num1,
num2));
}

return 0;
}

96 | P a g e
97 | 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));
98 | P a g e
printf("%d * %d =
%d\n",a, b,
multiply(a,b));
return 0;
}
Source File:
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;
}

Question 2: Write a program to use static library in


other program.
Solution:
Coding Output
99 | P a g e
Main Program:
#include <stdio.h>
#include
"arithmetic.h" //
Include the library's
header file
int main() {
int a = 7;
int b = 4;
printf("Using Static
Library:\n");
printf("Addition: %d\
n", add(a, b));
printf("Subtraction:
%d\n", subtract(a,
b));
printf("Multiplication
: %d\n", multiply(a,
b));
return 0;
}

Lab Assignment 15 (Shared Library in C)


Question 1: write a program to create a shared
library for performing arithmetic function.
100 | P a g e
Solution:
Coding Output
Header File:
#ifndef
ARITHMETIC_H
#define
ARITHMETIC_H

int add (int x, int y);


int sub (int x, int y);
int multipy (int x, int
y);

#endif
Shared Library:
#include<stdio.h>
#include
"arithmetic.h"

int main()
{
int a = 15;
int b = 10;
printf("using shared
101 | P a g e
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)
{

102 | P a g e
return x * y;
}

Question 2: Write a program to use shared library


in other program.
Solution:
Coding Output
Source File:
#include <stdio.h>
#include
"arithmetic.h" //
Include the library's
header file
int main() {
int a = 15, b = 10;
printf("Using Shared
Library:\n");
printf("Addition: %d\
n", add(a, b));
printf("Subtraction:
%d\n", subtract(a,
b));
printf("Multiplication
: %d\n", multiply(a,
b));
printf("Division:
103 | P a g e
%.2f\n", divide(a,
b));
return 0;
}

104 | 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;
}
int main() {
pthread_t arr[5];
for (int i = 0; i <
105 | P a g e
5; i++) {
if
(pthread_create(&ar
r[i], NULL,
print_numbers,
NULL) != 0) {

perror("pthread_cre
ate failed");
return 1;
}
}
for (int i = 0; i <
5; i++) {

pthread_join(arr[i],
NULL);
}

return 0;
}

Lab Assignment 17 (Socket Programming in C)


Question 1: write a program to implement socket
programming using C.
Solution:
106 | P a g e
Coding
For Client:
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#define PORT 8080
int main(int argc, char const* argv[])
{
int sock = 0, valread, client_fd;
struct sockaddr_in serv_addr;
char* hello = "Hello from client";
char buffer[1024] = { 0 };
if ((sock = socket(AF_INET, SOCK_STREAM,
0)) < 0) {
printf("\n Socket creation error \n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// Convert IPv4 and IPv6 addresses from
text to binary form

107 | P a g e
if (inet_pton(AF_INET, "127.0.0.1",
&serv_addr.sin_addr)<= 0) {
printf("\nInvalid address/ Address not
supported \n");
return -1;
}
if ((client_fd= connect(sock, (struct
sockaddr*)&serv_addr,sizeof(serv_addr)))<
0) {
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>

108 | P a g e
#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";
// 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,

109 | P a g e
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) {
perror("accept");
exit(EXIT_FAILURE);
}

110 | P a g e
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;
}

Lab Assignment 18 (Testing and Debugging)


Question 1: write a program and perform testing
and debugging on some implementation
Solution:
Coding
def is_prime(num):

111 | P a g e
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.")

next_check = input("Do you want to


check another number? (yes/no): ")
112 | P a g e
if next_check.lower() != 'yes':
break

# Run the prime number checker program


prime_checker()

113 | P a g e

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy