CP Lab Manual | PDF | Fahrenheit | Computer Programming
0% found this document useful (0 votes)
1K views

CP Lab Manual

The document provides information about a computer programming lab course for the B.Tech program at Tadipatri Engineering College. It includes 5 weekly objectives that involve getting familiar with writing simple C programs, algorithms, variables, operators, and conditional statements. For each week, it lists suggested experiments and activities along with examples of C code programs that demonstrate the relevant programming concepts.

Uploaded by

Bhagya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views

CP Lab Manual

The document provides information about a computer programming lab course for the B.Tech program at Tadipatri Engineering College. It includes 5 weekly objectives that involve getting familiar with writing simple C programs, algorithms, variables, operators, and conditional statements. For each week, it lists suggested experiments and activities along with examples of C code programs that demonstrate the relevant programming concepts.

Uploaded by

Bhagya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

TADIPATRI ENGINEERING COLLEGE

(APPROVED BY AICTE&AFFILIATED TO JNTUA)

KADAPA ROAD,NEAR SJK, TADIPATRI,ANANTAPUR-515411.

COMPUTER PROGRAMMING LAB


COURSE :- B.TECH

REGULATION :- R23

PREPARED BY

C.BALAJIM.TECH,

Prepared By C.BALAJI M.Tech Page 1


WEEK 1
Objective: Getting familiar with the programming environment on the computer and writing
the first program.
Suggested Experiments/Activities:
Tutorial 1: Problem-solving using Computers.
Lab1: Familiarization with programming environment
i) Writing simple programs using printf(), scanf()

Program

#include <stdio.h>

int main() {

int number1, number2, sum;

printf("Enter two integers: ");

scanf("%d %d", &number1, &number2);

// calculate the sum

sum = number1 + number2;

printf("%d + %d = %d", number1, number2, sum);

return 0;

Prepared By C.BALAJI M.Tech Page 2


WEEK 2
Objective: Getting familiar with how to formally describe a solution to a problem in a series
of finite steps both using textual notation and graphic notation.
Suggested Experiments
periments /Activities:
Tutorial 2: Problem-solving
solving using Algorithms and Flow charts.
Lab 1: Converting algorithms/flow charts into C Source code.
Developing the algorithms/flowcharts for the following sample programs
i) Sum and average of 3 numbers
ii) Conversion
version of Fahrenheit to Celsius and vice versa
iii) Simple interest calculation

i) Sum and average of 3 numbers

Flow chart

Prepared By C.BALAJI M.Tech Page 3


Algorithm

Step1:start
Step2: Declare a variable a,b,c and avg as int;
Step3:Read two numbers a,b and c;
Step4avg=(a+b+c)/3;
Step5:Print avg;
Step6:stop

Program:
#include<stdio.h>

int main() {

int a, b, c, avg; //Declaring the variables


printf("Enter three variables:\n");
printf("a:");
scanf("%d", & a); //Reading Variable a
printf("b:");
scanf("%d", & b); //Reading Variable b
printf("c:");
scanf("%d", & c); //Reading Variable c
avg = (a + b + c) / 3;

printf("\nAverage of %d,%d and %d is %d", a, b, c, avg);

}
Output:
Enter three variables:
a:10
b:20
c:25
average of 10,20 and 25 is 20

Prepared By C.BALAJI M.Tech Page 4


ii) Conversion of Fahrenheit to Celsius

Program:

#include<stdio.h>
#include<conio.h>
void main()
{
float celsius, fahrenheit;
clrscr();
printf("\n
n Enter Temp in Fahrenheit : ");
scanf("%f", &fahrenheit);
celsius = (fahrenheit-32)
32) / 1.8;
printf("\n
n Temperature in Celsius : %.2f ", celsius);
getch();
}

Prepared By C.BALAJI M.Tech Page 5


Conversion From Celsius to Fahrenheit C Program
#include<stdio.h>
#include<conio.h>
void main()
{
float celsius, fahrenheit;
clrscr();
printf("\n Enter Temp in Celsius : ");
scanf("%f", &celsius);
fahrenheit = (1.8 * celsius) + 32;
printf("\n Temperature in Fahrenheit : %.2f ", fahrenheit);
getch();
}

Prepared By C.BALAJI M.Tech Page 6


iii) Simple interest calculation

# include <stdio.h>
# include <stdlib.h>
int main(){
//Simple interset program
int P, R, T;
double SI;
printf("Enter the principal: ");
scanf("%d", &P);
printf("Enter the rate: ");
scanf("%d", &R);
printf("Enter the time: ");
scanf("%d", &T);
SI = (P * R * T) / 100;
printf("The Simple interest is %f", SI);
return 0;
}

Prepared By C.BALAJI M.Tech Page 7


WEEK 3
Objective: Learn how to define variables with the desired data-type, initialize them with
appropriate values and how arithmetic operators can be used with variables and constants.
Suggested Experiments/Activities:
Tutorial 3: Variable types and type conversions:
Lab 3: Simple computational problems using arithmetic expressions.
i) Finding the square root of a given number
ii) Finding compound interest
iii) Area of a triangle using heron’s formulae
iv) Distance travelled by an object

i) Finding the square root of a given number

#include <math.h>
#include <stdio.h>
int main() {
double number, squareRoot;
printf("Enter a number: ");
scanf("%lf", &number);
// computing the square root
squareRoot = sqrt(number);
printf("Square root of %.2lf = %.2lf", number, squareRoot);
return 0;
}

Enter a number: 23.4


Square root of 23.40 = 4.84

Prepared By C.BALAJI M.Tech Page 8


ii) Finding compound interest
#include <stdio.h>
#include<math.h>
int main()
{
double principal = 10000;
double rate = 5;
double time = 2;
double Amount = principal * ((pow((1 + rate / 100),time)));
double CI = Amount - principal;

printf("Compound Interest is : %lf",CI);

return 0;
}

Out put
Compound interest is 1025

Prepared By C.BALAJI M.Tech Page 9


iii) Area of a triangle using heron’s formulae
#include <stdio.h>
#include <math.h>

int main(){

float sideOne, sideTwo, sideThree, s, area;

printf("Enter the length of three sides of triangle\n");

scanf("%f %f %f", &sideOne, &sideTwo, &sideThree);

s = (sideOne + sideTwo + sideThree)/2;

area = sqrt(s*(s-sideOne)*(s-sideTwo)*(s-sideThree));
printf("Area of triangle : %0.4f\n", area);

return 0;

}
Output
Enter the length of three sides of triangle
3 4 5
Area of triangle : 6.0000

Prepared By C.BALAJI M.Tech Page 10


#include<stdio.h>

int main()

float u, a, d;

int t;

printf("\nEnter
nEnter the value of a : ");

scanf("%f", & a);

printf("\nEnter
nEnter the value of u : ");

scanf("%f", & u);

printf("\nEnter
nEnter the value of t : ");

scanf("%d", & t);

d = (u * t) + (a * t * t) / 2;

printf("\nn The Distance : %.2f", d);

return 0;

Output:

Prepared By C.BALAJI M.Tech Page 11


WEEK 4
Objective: Explore the full scope of expressions, type-compatibility of variables & constants
and operators used in the expression and how operator precedence works.
Suggested Experiments/Activities:
Tutorial4: Operators and the precedence and as associativity:
Lab4: Simple computational problems using the operator’ precedence and associativity
i) Evaluate the following expressions.
a. A+B*C+(D*E) + F*G
b. A/B*C-B+A*D/3
c. A+++B---A
d. J= (i++) + (++i)
ii) Find the maximum of three numbers using conditional operator
ii) Take marks of 5 subjects in integers, and find the total, average in float

ii) Find the maximum of three numbers using conditional operator

#include<stdio.h>

int main(){

int a,b,c,big;

printf("\nEnter 3 numbers:");

scanf("%d %d %d",&a,&b,&c);

big=(a>b&&a>c?a:b>c?b:c);

printf("\nThe biggest number is:%d",big);

return 0;

Prepared By C.BALAJI M.Tech Page 12


iii) Take marks of 5 subjects in integers, and find the total, average in float

#include <stdio.h>

int main()

float eng, phy, chem, math, comp;

float total, average, percentage;

printf("Enter marks of five subjects: :- ");

scanf("%f%f%f%f%f", &eng, &phy, &chem, &math, &comp);

total = eng + phy + chem + math + comp;

average = total / 5.0;

percentage = (total / 500.0) * 100;

printf("Total marks = %.2f\n", total);

printf("Average marks = %.2f\n", average);

printf("Percentage = %.2f", percentage);

return 0;

Prepared By C.BALAJI M.Tech Page 13


WEEK 5
Objective: Explore the full scope of different variants of “if construct” namely if-else, nullelse,
if-else if*-else, switch and nested-if including in what scenario each one of them can be
used and how to use them. Explore all relational and logical operators while writing
conditionals for “if construct”.
Suggested Experiments/Activities:
Tutorial 5: Branching and logical expressions:
Lab 5: Problems involving if-then-else structures.
i) Write a C program to find the max and min of four numbers using if-else.

#include<stdio.h>
int main()
{
int num1, num2, num3, num4;
printf("Enter 4 numbers here...\n");
scanf("%d %d %d %d", &num1, &num2, &num3, &num4);
if(num1>num2&&num1>num3&&num1>num4)
{
printf("%d (num1) is greatest",num1);
}
else if(num2>num3&&num2>num4)
{
printf("%d (num2) is greatest",num2);
}
else if(num3>num4)
{
printf("%d (num3) is greatest",num3);
}
else
{
printf("%d (num4) is greatest",num4);
}
return 0;

Prepared By C.BALAJI M.Tech Page 14


ii) Write a C program to generate electricity bill.

#include <stdio.h>

int main()
{
int unit;
float amt, total_amt, sur_charge;

/* Input unit consumed from user */


printf("Enter total units consumed: ");
scanf("%d", &unit);

if(unit <= 50)


{
amt = unit * 0.50;
}
else if(unit <= 150)
{
amt = 25 + ((unit-50) * 0.75);
}
else if(unit <= 250)
{
amt = 100 + ((unit-150) * 1.20);
}
else
{
amt = 220 + ((unit-250) * 1.50);
}

sur_charge = amt * 0.20;


total_amt = amt + sur_charge;

printf("Electricity Bill = Rs. %.2f", total_amt);

return 0;
}

Prepared By C.BALAJI M.Tech Page 15


iii) Find the roots of the quadratic equation.

#include <math.h>
#include <stdio.h>
int main() {
double a, b, c, discriminant, root1, root2, realPart, imagPart;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf", &a, &b, &c);

discriminant = b * b - 4 * a * c;

if (discriminant > 0)
{
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("root1 = %.2lf and root2 = %.2lf", root1, root2);
}

else if (discriminant == 0)
{
root1 = root2 = -b / (2 * a);
printf("root1 = root2 = %.2lf;", root1);
}

else
{
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart, imagPart, realPart,
imagPart);
}

return 0;
}
Output

Enter coefficients a, b and c: 2.3

5.6

root1 = -0.87+1.30i and root2 = -0.87-1.30i

Prepared By C.BALAJI M.Tech Page 16


iv) Write a C program to simulate a calculator using switch case.

#include <stdio.h>

int main() {

char op;
double first, second;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &op);
printf("Enter two operands: ");
scanf("%lf %lf", &first, &second);

switch (op) {
case '+':
printf("%.1lf + %.1lf = %.1lf", first, second, first + second);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf", first, second, first - second);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf", first, second, first * second);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf", first, second, first / second);
break;
// operator doesn't match any case constant
default:
printf("Error! operator is not correct");
}

return 0;
}

Prepared By C.BALAJI M.Tech Page 17


v) Write a C program to find the given year is a leap year or not.

#include<stdio.h>
#include<conio.h>
void main() {
int year;
printf("Enter a year: ");
scanf("%d", &year);
if(((year%4==0) && ((year%400==0) || (year%100!==0))
{
printf("%d is a leap year", &year);
} else {
printf("%d is not a leap year", &year);
}
getch();
}

Output
Enter a year: 2004
2004 is a leap year

Enter a year: 1700


1700 is not a leap year

Prepared By C.BALAJI M.Tech Page 18


WEEK 6
Objective: Explore the full scope of iterative constructs namely while loop, do-while loop and
for loop in addition to structured jump constructs like break and continue including when each
of these statements is more appropriate to use.
Suggested Experiments/Activities:
Tutorial 6: Loops, while and for loops
Lab 6: Iterative problems e.g., the sum of series
i) Find the factorial of given number using any loop.
#include<stdio.h>
int main()
{
int i,fact=1,number;
printf("Enter a number: ");
scanf("%d",&number);
for(i=1;i<=number;i++){
fact=fact*i;
}
printf("Factorial of %d is: %d",number,fact);
return 0;
}
Output
Enter a number: 5
Factorial of 5 is: 120

Prepared By C.BALAJI M.Tech Page 19


ii) Find the given number is a prime or not.
#include <stdio.h>
void checkPrime(int N)
{
int flag = 1;
for (int i = 2; i <= N / 2; i++)
{
if (N % i == 0) {
flag = 0;
break;
}
}
if (flag) {
printf("The number %d is a Prime Number\n", N);
}
else {
printf("The number %d is not a Prime Number\n", N);
}
return;
}
int main()
{
int N;
printf(“enter any number”);
scanf(“%d”,&N)
checkPrime(N);
return 0;
}

Output
Enter any number 6
The number 6 is not a Prime Number

Enter any number 546


The number 546 is a Prime Number

Prepared By C.BALAJI M.Tech Page 20


iv) Checking a number palindrome
#include <stdio.h>
int main() {
int n, reversed = 0, remainder, original;
printf("Enter an integer: ");
scanf("%d", &n);
original = n;
while (n != 0) {
remainder = n % 10;
reversed = reversed * 10 + remainder;
n /= 10;
}
if (original == reversed)
printf("%d is a palindrome.", original);
else
printf("%d is not a palindrome.", original);

return 0;
}

Output
Enter an integer: 1001
1001 is a palindrome.

Prepared By C.BALAJI M.Tech Page 21


v) Construct a pyramid of numbers.
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i) {
for (j = 1; j <= i; ++j) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}

Output
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Prepared By C.BALAJI M.Tech Page 22


WEEK 7:
Objective: Explore the full scope of Arrays construct namely defining and initializing 1-D
and 2-D and more generically n-D arrays and referencing individual array elements from the
defined array. Using integer 1-D arrays, explore search solution linear search.
Suggested Experiments/Activities:
Tutorial 7: 1 D Arrays: searching.
Lab 7:1D Array manipulation, linear search
i) Find the min and max of a 1-D integer array.

program
#include <stdio.h>
#include <conio.h>
int main()
{
int a[1000],i,n,min,max;
printf("Enter size of the array : ");
scanf("%d",&n);
printf("Enter elements in array : ");
for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
}
min=max=a[0];
for(i=1; i<n; i++)
{
if(min>a[i])
min=a[i];
if(max<a[i])
max=a[i];
}
printf("minimum of array is : %d",min);
printf("\nmaximum of array is : %d",max);

return 0;
}
S
output
Enter size of the array: 5
Enter elements in array: 1
2
3
4
5
minimum of an array is: 1
maximum of an array is: 5

Prepared By C.BALAJI M.Tech Page 23


ii) The reverse of a 1D integer array

program
// C Program to Reverse an Array by Printing it from The Last Element to the First Element

#include <stdio.h>
#define N 1000

int main() {
int arr[N];

int n;
printf("Enter the size of the array: ");
scanf("%d", &n);
printf("Enter an array: ");
for (int i = 0; i< n; i++){
scanf("%d", &arr[i]);
}
printf("Reversed array: ");
for (int i = n-1; i>=0; i--){
printf("%d ", arr[i]);
}

return 0;
}

output
Enter the size of the array: 5
Enter an array: 3 8 4 9 6
Reversed array: 6 9 4 8 3

Prepared By C.BALAJI M.Tech Page 24


iii) Eliminate duplicate elements in an array.
Program

#include <stdio.h>
int main()
{
int n, count = 0;
printf("Enter number of elements in the array: ");
scanf("%d", &n);
int arr[n], temp[n];
if(n==0)
{
printf("No element inside the array.");
exit(0);
}
printf("Enter elements in the array: ");
for (int i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
printf("\nArray Before Removing Duplicates: ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
for (int i = 0; i < n; i++)
{
int j;
for (j = 0; j < count; j++)
{
if (arr[i] == temp[j])
break;
}

Prepared By C.BALAJI M.Tech Page 25


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

printf("\nArray After Removing Duplicates: ");


for (int i = 0; i < count; i++)
printf("%d ", temp[i]);

return 0;
}

Output
Enter number of elements in the array: 8
Enter elements in the array: 9 3 6 9 5 4 0 5

Array Before Removing Duplicates: 9 3 6 9 5 4 0 5


Array After Removing Duplicates: 9 3 6 5 4 0

Prepared By C.BALAJI M.Tech Page 26


WEEK 8:
Objective: Explore the difference between other arrays and character arrays that can be used
as Strings by using null character and get comfortable with string by doing experiments that
will reverse a string and concatenate two strings. Explore sorting solution bubble sort using
integer arrays.
Suggested Experiments/Activities:
Tutorial 8: 2 D arrays, sorting and Strings.
Lab 8: Matrix problems, String operations, Bubble sort
i) Addition of two matrices

program

#include <stdio.h>
int main() {
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter the number of rows (between 1 and 100): ");
scanf("%d", &r);
printf("Enter the number of columns (between 1 and 100): ");
scanf("%d", &c);

printf("\nEnter elements of 1st matrix:\n");


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}

printf("Enter elements of 2nd matrix:\n");


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element b%d%d: ", i + 1, j + 1);
scanf("%d", &b[i][j]);
}

// adding two matrices


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
sum[i][j] = a[i][j] + b[i][j];
}

// printing the result


printf("\nSum of two matrices: \n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("%d ", sum[i][j]);

Prepared By C.BALAJI M.Tech Page 27


if (j == c - 1) {
printf("\n\n");
}
}

return 0;
}
Outpur
Enter the number of rows (between 1 and 100): 2
Enter the number of columns (between 1 and 100): 3

Enter elements of 1st matrix:


Enter element a11: 2
Enter element a12: 3
Enter element a13: 4
Enter element a21: 5
Enter element a22: 2
Enter element a23: 3
Enter elements of 2nd matrix:
Enter element b11: -4
Enter element b12: 5
Enter element b13: 3
Enter element b21: 5
Enter element b22: 6
Enter element b23: 3

Sum of two matrices:


-2 8 7

10 8 6

Prepared By C.BALAJI M.Tech Page 28


ii) Multiplication two matrices

program
#include<stdio.h>
#include<stdlib.h>
int main(){
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
system("cls");
printf("enter the number of row=");
scanf("%d",&r);
printf("enter the number of column=");
scanf("%d",&c);
printf("enter the first matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter the second matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
}
}

printf("multiply of the matrix=\n");


for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
mul[i][j]=0;
for(k=0;k<c;k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
}
}
//for printing result
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{

Prepared By C.BALAJI M.Tech Page 29


printf("%d\t",mul[i][j]);
}
printf("\n");
}
return 0;
}

Output

enter the number of row=3


enter the number of column=3
enter the first matrix element=
111
222
333
enter the second matrix element=
111
222
333
multiply of the matrix=
666
12 12 12
18 18 18

Prepared By C.BALAJI M.Tech Page 30


iii) Sort array elements using bubble sort

program

#include <stdio.h>
int main(){
int arr[50], num, x, y, temp;
printf("Please Enter the Number of Elements you want in the array: ");
scanf("%d", &num);
printf("Please Enter the Value of Elements: ");
for(x = 0; x < num; x++)
scanf("%d", &arr[x]);
for(x = 0; x < num - 1; x++){
for(y = 0; y < num - x - 1; y++){
if(arr[y] > arr[y + 1]){
temp = arr[y];
arr[y] = arr[y + 1];
arr[y + 1] = temp;
}
}
}
printf("Array after implementing bubble sort: ");
for(x = 0; x < num; x++){
printf("%d ", arr[x]);
}
return 0;
}

Output
Please Enter the Number of Elements you want in the array:5
Please Enter the Value of Elements: 9 5 -2 7 3
Array after implementing bubble sort: -2 3 5 7 9

Prepared By C.BALAJI M.Tech Page 31


iv) Concatenate two strings without built-in functions

program

void main(void)
{
char str1[25],str2[25];
int i=0,j=0;
printf("\n Enter First String:");
gets(str1);
printf("\nEnter Second String:");
gets(str2);
while(str1[i]!='\0')
i++;
while(str2[j]!='\0')
{
str1[i]=str2[j];
j++;
i++;
}
str1[i]='\0';
printf("\nConcatenated String is %s",str1);
}

Out put
Enter First String: tech
Enter Second String: college
Concatenated String is tech college

Prepared By C.BALAJI M.Tech Page 32


v) Reverse a string using built-in and without built-in string functions

Reverse a string using built-in

Program:
#include<stdio.h>
main ()
{
char a[50];
clrscr();
printf(“enter a string”);
gets(a);
strrev(a);
printf(“reversed string =%s,a);
getch();
}

Output
enter a string hello
reversed string =olleh

Prepared By C.BALAJI M.Tech Page 33


Reverse a string without built-in string functions

#include <stdio.h>
#include <conio.h>
#include <string.h>
void main(){
char string[20],temp;
int i,length;
printf("Enter String : ");
scanf("%s",string);
length=strlen(string)-1;
for(i=0;i<strlen(string)/2;i++){
temp=string[i];
string[i]=string[length];
string[length--]=temp;
}
printf("Reverse string :%s",string);
getch();
}
Output
enter a string hello
reversed string is olleh

Prepared By C.BALAJI M.Tech Page 34


UNIT IV
WEEK 9:
Objective: Explore pointers to manage a dynamic array of integers, including memory allocation
&amp; value initialization, resizing changing and reordering the contents of an array and
memory de-allocation using malloc (), calloc (), realloc () and free () functions. Gain experience
processing command-line arguments received by C
Suggested Experiments/Activities:
Tutorial 9: Pointers, structures and dynamic memory allocation
Lab 9: Pointers and structures, memory dereference.

i) Write a C program to find the sum of a 1D array using malloc()

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

void main()
{

int i, n;
int *a, *b, *c;

printf("Enter the size of the arrays\n");


scanf("%d", &n);

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


b = (int *)malloc(n * sizeof(int));
c = (int *)malloc(n * sizeof(int));

printf("Enter Elements of First List\n");

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


{
scanf("%d", a + i);
}

printf("Enter Elements of Second List\n");

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


{
scanf("%d", b + i);
}

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


{

Prepared By C.BALAJI M.Tech Page 35


*(c + i) = *(a + i) + *(b + i);
}

printf("Resultant List is\n");

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


{
printf("%d\n", *(c + i));
}
return 0;
}

OUTPUT

Enter the size of the arrays


5
Enter Elements of First List
23
45
67
12
90
Enter Elements of Second List
87
56
90
45
10
Resultant List is
110
101
157
57
100

Prepared By C.BALAJI M.Tech Page 36


ii) Write a C program to find the total, average of n students using structures

#include <stdio.h>
#include <conio.h>
struct student
{
int rollno,tot;
char name[25];
int mark[5];
};
void main()
{
struct student s[5];
int i,n,j;
clrscr();
printf(“Enter the number of students:”);
scanf(“%d”,&n);
printf(“\t*Students Records*\n”);
//take input from user
for(i=0;i<n;i++)
{
printf("\nEnter Student Roll Number: ");
scanf("%d",&s[i].rollno);
printf("\nEnter Student name: ");
scanf("%s",s[i].name);
printf("\nEnter Student 3 subject's marks: ");
for(j=0;j<3;j++)
scanf("%d",&s[i].mark[j]);
}
//calculation
for(i=0;i<n;i++)
{
s[i].tot=0;
for(j=0;j<3;j++)
s[i].tot = s[i].tot+ s[i].mark[j];
}
//Display result
for(i=0;i<n;i++)
{
printf("\t*Students Records*\n");
printf("\n==================================\n");
printf("\nStudent's Roll no. – %d", s[i].rollno);
printf("\nStudent's Name – %s", s[i].name);
printf("\nStudent's Total Marks – %d", s[i].tot);
}

Prepared By C.BALAJI M.Tech Page 37


getch();
}
OUTPUTEnter the number of students:2
*Students Records*
Enter Student Roll Number: 01
Enter Student name: rathi
Enter Student 3 subject’s marks:
12
67
89
Enter Student Roll Number: 02
Enter Student name: kishore
Enter Student 3 subject’s marks:
56
89
90
*Students Records*
==================================
Student’s Roll no. – 1
Student’s Name – rathi
Student’s Total Marks – 168 *Students Records*
==================================
Student’s Roll no. – 2
Student’s Name – kishore
Student’s Total Marks – 235

Prepared By C.BALAJI M.Tech Page 38


ii) Write a C program to implement realloc()

#include <stdio.h>

#include <stdlib.h>

int main() {

int *ptr = (int*) malloc(3 * sizeof(int));

ptr[0] = 1;

ptr[1] = 2;

ptr[2] = 3;

// resize the memory block to hold 5 integers

ptr = (int*) realloc(ptr, 5 * sizeof(int));

ptr[3] = 4;

ptr[4] = 5;

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

printf("%d ", ptr[i]);

// free the memory block

free(ptr);

return 0;

Output

1 2 3 4 5

Prepared By C.BALAJI M.Tech Page 39


WEEK 10:
Objective: Experiment with C Structures, Unions, bit fields and self-referential structures
(Singly linked lists) and nested structures
Suggested Experiments/Activities:
Tutorial 10: Bitfields, Self-Referential Structures, Linked lists
Lab10 : Bitfields, linked lists
Read and print a date using dd/mm/yyyy format using bit-fields and differentiate the same
without using bit- fields
i) Create and display a singly linked list using self-referential structure.

ii) Demonstrate the differences between structures and unions using a C program.

#include<stdio.h>
#include<stdlib.h>
struct node
{
int info ;
struct node *link ; // Self-referential structure link is pointing the same
// structure of the type node
};

struct node *START = NULL ; // start pointer to control the linked list //
struct node* createnode() ;
void insertatlast() ; // insert node at last //
void deleteatfirst() ; // delete node at first //
void viewlist() ;
void insertatfirst() ;
int getlength() ;
int menu() ;
void insertafteranynode() ;
void deleteatlast() ;
void deleteatposition() ;

struct node* createnode() // create node dynamically //


{
struct node *n ;
n = malloc( sizeof(struct node) ) ;
return ( n ) ;
}
void insertatlast()
{
struct node *temp ,*t ;
temp = createnode() ;
printf( "Enter the data in node \n " ) ;
scanf( " %d" , &temp->info ) ;
temp->link = NULL ;

Prepared By C.BALAJI M.Tech Page 40


if ( START == NULL )
START = temp ;
else
{
t = START ;
while ( t->link != NULL )
{
t = t->link ;
}
t->link = temp ;
}
}
void deleteatfirst() // delete node at first //
{
if ( START == NULL )
printf ( "List is empty \n " ) ;
else
{
struct node *q ;
q = START ;
START = START->link ;
free( q ) ;
}
}
void viewlist()
{ struct node* t ;
if ( START == NULL )
{
printf ( "No List \n " ) ;
}
else
{
t = START ;
while ( t != NULL )
{
printf ( " %d" , t->info ) ;
t = t->link ;
}
}
}
void insertatfirst()
{ struct node*New ;
New = createnode() ;
printf ( "Enter the data in node \n " ) ;
scanf ( " %d" , &New->info ) ;

Prepared By C.BALAJI M.Tech Page 41


if ( START == NULL )
START = New ;
else
{
New->link = START ;
START = New ;
}
}
int getlength()
{
int count = 0 ;
struct node* t ;
if ( START == NULL )
printf ( "List is empty \n " ) ;
else
{
t =START ;
while ( t != NULL )
{
count = count + 1 ;
t = t->link ;
}
}
return count ;
}
void insertafteranynode()
{
int position ;
struct node* newnode ,*t ;
if ( START == NULL )
printf ( "List is empty \n " ) ;
else
{
printf ( "Enter position after which you want to add: \n " ) ;
scanf ( " %d" , &position ) ;
if ( position > getlength() )
{
printf ( "Wrong position \n " ) ;
insertafteranynode() ; // recursion //

}
else
{
int i = 1 ;
newnode = createnode() ;
printf ( "Enter Data \n " ) ;

Prepared By C.BALAJI M.Tech Page 42


scanf ( " %d" , &newnode->info ) ;
newnode->link = NULL ;
if ( START == NULL )
START = newnode ;
else
{
t = START ;
while ( i < position )
{
t = t->link ;
i++ ;
}
newnode->link = t->link ;
t->link = newnode ;
}
}
}
}
void deleteatlast()
{
struct node* t , *q ;
if ( START == NULL )
{
printf ( "List is empty \n " ) ;
}
else
{
t = START ;
q = START ;
while ( t->link != NULL )
{
q=t;
t = t->link ;
}
if ( t == START )
{
START == NULL ;
}
else
{
q->link = NULL ;
free( t ) ;
}
}
}
void deleteatposition()

Prepared By C.BALAJI M.Tech Page 43


{
struct node *t , *q ;
int position , i = 1 ;
t = START ;
if ( START == NULL)
{
printf ( "List is empty \n " ) ;
}
else
{
printf ( "Enter position after which you want to delete: \n " ) ;
scanf ( " %d" , &position ) ;
if ( position > getlength() )
{
printf ( "Wrong position \n " ) ;
deleteatposition() ; // recursion //

}
else
{
while ( i < position )
{
q=t;
t = t->link ;
i++ ;
}
if ( t == START )
{
START == NULL ;
}
else
{
q->link = t->link ;
free( t ) ;
}
}
}
}
int menu()
{
int ch ;
printf ( " \t \t \t 1.ADD NODE LAST IN LINK \n " ) ;
printf ( " \t \t \t 2.ADD NODE AT FIRST IN LINK \n " ) ;
printf ( " \t \t \t 3.VIEW LIST IN LINK \n " ) ;
printf ( " \t \t \t 4.DELETE NODE AT FIRST IN LINK \n " ) ;
printf( " \t \t \t 5. TO SEE THE LENGTH OF LIST \n " ) ;

Prepared By C.BALAJI M.Tech Page 44


printf ( " \t \t \t 6. INSERT NODE IN BETWEEN \n " ) ;
printf ( " \t \t \t 7.DELETE NODE AT LAST IN LINK \n " ) ;
printf ( " \t \t \t 8.DELETE NODE AT SPECIFIC POSITION IN LINK \n " ) ;
printf ( " \t \t \t 9.EXIT \n " ) ;
printf ( "ENTER THE CHOICE \n " ) ;
scanf ( " %d" , &ch ) ;
return( ch ) ;
}
void main()
{ int k ;
while ( 1 )
{
switch ( menu() )
{
case 1 :
insertatlast() ;
break ;
case 2 :
insertatfirst() ;
break ;
case 3 :
viewlist() ;
break ;
case 4 :
deleteatfirst() ;
break ;
case 5 :
k = getlength() ;
printf ( "THE LENGTH OF THE LIST IS %d \n " , k ) ;
break ;
case 6 :
insertafteranynode() ;
break ;
case 7 :
deleteatlast() ;
break ;
case 8 :
deleteatposition() ;
break ;
case 9 :
exit( 0 ) ;
break ;
default :
printf ( " Not available \n " ) ;
}
}

Prepared By C.BALAJI M.Tech Page 45


}
The output

Prepared By C.BALAJI M.Tech Page 46


iii) Write a C program to shift/rotate using bitfields.

#include <stdio.h>
#define INT_BITS 32

/*Function to left rotate n by d bits*/


int leftRotate(int n, unsigned int d)
{
/* In n<<d, last d bits are 0. To put first 3 bits of n
at last, do bitwise or of n<<d with n >>(INT_BITS -
d) */
return (n << d) | (n >> (INT_BITS - d));
}

/*Function to right rotate n by d bits*/


int rightRotate(int n, unsigned int d)
{
return (n >> d) | (n << (INT_BITS - d));
}
void main()
{
int n = 16;
int d = 2;
printf("Left Rotation of %d by %d is ", n, d);
printf("%d", leftRotate(n, d));
printf(" Right Rotation of %d by %d is ", n, d);
printf("%d", rightRotate(n, d));
}
Out put:

Left Rotation of 16 by 2 is 64 Right Rotation of 16 by 2 is 4

Prepared By C.BALAJI M.Tech Page 47


iv) Write a C program to copy one structure variable to another structure of the same
type.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct some {
int a;
char b;
};

int main(void)
{
struct some some1;
struct some *ptr = malloc(sizeof(struct some));
struct some *ptr2 = malloc(sizeof(struct some));
struct some *ptr3 = malloc(sizeof(struct some));
memset(ptr, 0, sizeof(struct some));
memset(ptr2, 0, sizeof(struct some));

ptr->a = 123;
ptr->b = 'b';

*ptr2 = *ptr;
printf("%d %c\n", ptr2->a, ptr2->b);

some1 = *ptr;
printf("%d %c\n", some1.a, some1.b);

*ptr3 = some1;
printf("%d %c\n", ptr3->a, ptr3->b);

return 0;
}

Output
123 b
123 b
123 b

Prepared By C.BALAJI M.Tech Page 48

You might also like