SlideShare a Scribd company logo
Prepared By C.BALAJI M.Tech Page 1
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 2
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
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 /Activities:
Tutorial 2: Problem-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 of Fahrenheit to Celsius and vice versa
iii) Simple interest calculation
i) Sum and average of 3 numbers
Flow chart
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.
periments /Activities:
solving using Algorithms and Flow charts.
Converting algorithms/flow charts into C Source code.
Developing the algorithms/flowcharts for the following sample programs
i) Sum and average of 3 numbers
version of Fahrenheit to Celsius and vice versa
iii) Simple interest calculation
Sum and average of 3 numbers
Page 3
Getting familiar with how to formally describe a solution to a problem in a series
Prepared By C.BALAJI M.Tech Page 4
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
ii) Conversion of Fahrenheit to Celsius
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
float celsius, fahrenheit;
clrscr();
printf("n Enter Temp in Fahrenheit : ");
scanf("%f", &fahrenheit);
celsius = (fahrenheit-32) / 1.8;
printf("n Temperature in Celsius : %.2f ", celsius);
getch();
}
Conversion of Fahrenheit to Celsius
n Enter Temp in Fahrenheit : ");
32) / 1.8;
n Temperature in Celsius : %.2f ", celsius);
Page 5
Prepared By C.BALAJI M.Tech Page 6
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 7
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 8
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 9
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 10
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 trianglen");
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.4fn", 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
#include<stdio.h>
int main()
{
float u, a, d;
int t;
printf("nEnter the value of a : ");
scanf("%f", & a);
printf("nEnter the value of u : ");
scanf("%f", & u);
printf("nEnter the value of t : ");
scanf("%d", & t);
d = (u * t) + (a * t * t) / 2;
printf("n The Distance : %.2f", d);
return 0;
}
Output:
nEnter the value of a : ");
nEnter the value of u : ");
nEnter the value of t : ");
n The Distance : %.2f", d);
Page 11
Prepared By C.BALAJI M.Tech Page 12
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 13
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 = %.2fn", total);
printf("Average marks = %.2fn", average);
printf("Percentage = %.2f", percentage);
return 0;
}
Prepared By C.BALAJI M.Tech Page 14
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 15
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 16
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
4
5.6
root1 = -0.87+1.30i and root2 = -0.87-1.30i
Prepared By C.BALAJI M.Tech Page 17
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 18
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 19
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 20
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 Numbern", N);
}
else {
printf("The number %d is not a Prime Numbern", 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 21
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 22
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 23
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 24
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 25
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 26
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 27
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 28
if (j == c - 1) {
printf("nn");
}
}
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 29
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 30
printf("%dt",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=
1 1 1
2 2 2
3 3 3
enter the second matrix element=
1 1 1
2 2 2
3 3 3
multiply of the matrix=
6 6 6
12 12 12
18 18 18
Prepared By C.BALAJI M.Tech Page 31
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 32
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 33
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 34
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 35
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 arraysn");
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 Listn");
for (i = 0; i < n; i++)
{
scanf("%d", a + i);
}
printf("Enter Elements of Second Listn");
for (i = 0; i < n; i++)
{
scanf("%d", b + i);
}
for (i = 0; i < n; i++)
{
Prepared By C.BALAJI M.Tech Page 36
*(c + i) = *(a + i) + *(b + i);
}
printf("Resultant List isn");
for (i = 0; i < n; i++)
{
printf("%dn", *(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 37
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 38
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 39
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 40
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 41
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 42
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 43
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 44
{
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 45
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 46
}
The output
Prepared By C.BALAJI M.Tech Page 47
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 48
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 %cn", ptr2->a, ptr2->b);
some1 = *ptr;
printf("%d %cn", some1.a, some1.b);
*ptr3 = some1;
printf("%d %cn", ptr3->a, ptr3->b);
return 0;
}
Output
123 b
123 b
123 b

More Related Content

PDF
Chapter 4 : Balagurusamy Programming ANSI in C
PDF
The solution manual of programming in ansi by Robin
PDF
SPL 6.1 | Advanced problems on Operators and Math.h function in C
PDF
C programming Assignments and Questions.pdf
PDF
The solution manual of c by robin
PPTX
C programming BY Mazedur
PDF
C Programming Lab.pdf
PPT
The Basics of C - Math Functions and characters
Chapter 4 : Balagurusamy Programming ANSI in C
The solution manual of programming in ansi by Robin
SPL 6.1 | Advanced problems on Operators and Math.h function in C
C programming Assignments and Questions.pdf
The solution manual of c by robin
C programming BY Mazedur
C Programming Lab.pdf
The Basics of C - Math Functions and characters

Similar to Computer P-Lab-Manual acc to syllabus.pdf (20)

PDF
Functions
DOCX
Chapter 1 Programming Fundamentals Assignment.docx
PDF
Lec04-CS110 Computational Engineering
PDF
DOCX
C lab manaual
DOCX
Fatima Aliasgher Portfolio
PPTX
Conditional operators pgms with solns.pptx
PDF
C Programming lab
DOCX
programs of c www.eakanchha.com
PDF
Simple C programs
PDF
Numerical analysis
PDF
C Programming by Süleyman Kondakci
PDF
C SLIDES PREPARED BY M V B REDDY
PDF
Chapter 5
PDF
C and Data structure lab manual ECE (2).pdf
PPTX
C Programming Homework Help
DOCX
PDF
Control Flow Statements and Datatypes in C
Functions
Chapter 1 Programming Fundamentals Assignment.docx
Lec04-CS110 Computational Engineering
C lab manaual
Fatima Aliasgher Portfolio
Conditional operators pgms with solns.pptx
C Programming lab
programs of c www.eakanchha.com
Simple C programs
Numerical analysis
C Programming by Süleyman Kondakci
C SLIDES PREPARED BY M V B REDDY
Chapter 5
C and Data structure lab manual ECE (2).pdf
C Programming Homework Help
Control Flow Statements and Datatypes in C
Ad

Recently uploaded (20)

PPTX
Foundation to blockchain - A guide to Blockchain Tech
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PPTX
UNIT 4 Total Quality Management .pptx
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PDF
composite construction of structures.pdf
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PPT
Project quality management in manufacturing
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PDF
Well-logging-methods_new................
PPT
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PDF
Digital Logic Computer Design lecture notes
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PPTX
Lecture Notes Electrical Wiring System Components
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PPTX
Sustainable Sites - Green Building Construction
Foundation to blockchain - A guide to Blockchain Tech
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
CYBER-CRIMES AND SECURITY A guide to understanding
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
UNIT 4 Total Quality Management .pptx
UNIT-1 - COAL BASED THERMAL POWER PLANTS
composite construction of structures.pdf
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
Project quality management in manufacturing
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
Well-logging-methods_new................
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
Operating System & Kernel Study Guide-1 - converted.pdf
Digital Logic Computer Design lecture notes
R24 SURVEYING LAB MANUAL for civil enggi
Lecture Notes Electrical Wiring System Components
Embodied AI: Ushering in the Next Era of Intelligent Systems
Sustainable Sites - Green Building Construction
Ad

Computer P-Lab-Manual acc to syllabus.pdf

  • 1. Prepared By C.BALAJI M.Tech Page 1 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,
  • 2. Prepared By C.BALAJI M.Tech Page 2 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; }
  • 3. Prepared By C.BALAJI M.Tech 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 /Activities: Tutorial 2: Problem-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 of Fahrenheit to Celsius and vice versa iii) Simple interest calculation i) Sum and average of 3 numbers Flow chart 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. periments /Activities: solving using Algorithms and Flow charts. Converting algorithms/flow charts into C Source code. Developing the algorithms/flowcharts for the following sample programs i) Sum and average of 3 numbers version of Fahrenheit to Celsius and vice versa iii) Simple interest calculation Sum and average of 3 numbers Page 3 Getting familiar with how to formally describe a solution to a problem in a series
  • 4. Prepared By C.BALAJI M.Tech Page 4 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
  • 5. Prepared By C.BALAJI M.Tech ii) Conversion of Fahrenheit to Celsius Program: #include<stdio.h> #include<conio.h> void main() { float celsius, fahrenheit; clrscr(); printf("n Enter Temp in Fahrenheit : "); scanf("%f", &fahrenheit); celsius = (fahrenheit-32) / 1.8; printf("n Temperature in Celsius : %.2f ", celsius); getch(); } Conversion of Fahrenheit to Celsius n Enter Temp in Fahrenheit : "); 32) / 1.8; n Temperature in Celsius : %.2f ", celsius); Page 5
  • 6. Prepared By C.BALAJI M.Tech Page 6 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(); }
  • 7. Prepared By C.BALAJI M.Tech Page 7 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; }
  • 8. Prepared By C.BALAJI M.Tech Page 8 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
  • 9. Prepared By C.BALAJI M.Tech Page 9 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
  • 10. Prepared By C.BALAJI M.Tech Page 10 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 trianglen"); 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.4fn", area); return 0; } Output Enter the length of three sides of triangle 3 4 5 Area of triangle : 6.0000
  • 11. Prepared By C.BALAJI M.Tech #include<stdio.h> int main() { float u, a, d; int t; printf("nEnter the value of a : "); scanf("%f", & a); printf("nEnter the value of u : "); scanf("%f", & u); printf("nEnter the value of t : "); scanf("%d", & t); d = (u * t) + (a * t * t) / 2; printf("n The Distance : %.2f", d); return 0; } Output: nEnter the value of a : "); nEnter the value of u : "); nEnter the value of t : "); n The Distance : %.2f", d); Page 11
  • 12. Prepared By C.BALAJI M.Tech Page 12 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; }
  • 13. Prepared By C.BALAJI M.Tech Page 13 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 = %.2fn", total); printf("Average marks = %.2fn", average); printf("Percentage = %.2f", percentage); return 0; }
  • 14. Prepared By C.BALAJI M.Tech Page 14 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; }
  • 15. Prepared By C.BALAJI M.Tech Page 15 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; }
  • 16. Prepared By C.BALAJI M.Tech Page 16 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 4 5.6 root1 = -0.87+1.30i and root2 = -0.87-1.30i
  • 17. Prepared By C.BALAJI M.Tech Page 17 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; }
  • 18. Prepared By C.BALAJI M.Tech Page 18 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
  • 19. Prepared By C.BALAJI M.Tech Page 19 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
  • 20. Prepared By C.BALAJI M.Tech Page 20 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 Numbern", N); } else { printf("The number %d is not a Prime Numbern", 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
  • 21. Prepared By C.BALAJI M.Tech Page 21 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.
  • 22. Prepared By C.BALAJI M.Tech Page 22 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
  • 23. Prepared By C.BALAJI M.Tech Page 23 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
  • 24. Prepared By C.BALAJI M.Tech Page 24 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
  • 25. Prepared By C.BALAJI M.Tech Page 25 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; }
  • 26. Prepared By C.BALAJI M.Tech Page 26 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
  • 27. Prepared By C.BALAJI M.Tech Page 27 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]);
  • 28. Prepared By C.BALAJI M.Tech Page 28 if (j == c - 1) { printf("nn"); } } 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
  • 29. Prepared By C.BALAJI M.Tech Page 29 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++) {
  • 30. Prepared By C.BALAJI M.Tech Page 30 printf("%dt",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= 1 1 1 2 2 2 3 3 3 enter the second matrix element= 1 1 1 2 2 2 3 3 3 multiply of the matrix= 6 6 6 12 12 12 18 18 18
  • 31. Prepared By C.BALAJI M.Tech Page 31 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
  • 32. Prepared By C.BALAJI M.Tech Page 32 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
  • 33. Prepared By C.BALAJI M.Tech Page 33 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
  • 34. Prepared By C.BALAJI M.Tech Page 34 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
  • 35. Prepared By C.BALAJI M.Tech Page 35 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 arraysn"); 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 Listn"); for (i = 0; i < n; i++) { scanf("%d", a + i); } printf("Enter Elements of Second Listn"); for (i = 0; i < n; i++) { scanf("%d", b + i); } for (i = 0; i < n; i++) {
  • 36. Prepared By C.BALAJI M.Tech Page 36 *(c + i) = *(a + i) + *(b + i); } printf("Resultant List isn"); for (i = 0; i < n; i++) { printf("%dn", *(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
  • 37. Prepared By C.BALAJI M.Tech Page 37 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); }
  • 38. Prepared By C.BALAJI M.Tech Page 38 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
  • 39. Prepared By C.BALAJI M.Tech Page 39 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
  • 40. Prepared By C.BALAJI M.Tech Page 40 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 ;
  • 41. Prepared By C.BALAJI M.Tech Page 41 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 ) ;
  • 42. Prepared By C.BALAJI M.Tech Page 42 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 " ) ;
  • 43. Prepared By C.BALAJI M.Tech Page 43 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()
  • 44. Prepared By C.BALAJI M.Tech Page 44 { 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 " ) ;
  • 45. Prepared By C.BALAJI M.Tech Page 45 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 " ) ; } }
  • 46. Prepared By C.BALAJI M.Tech Page 46 } The output
  • 47. Prepared By C.BALAJI M.Tech Page 47 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
  • 48. Prepared By C.BALAJI M.Tech Page 48 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 %cn", ptr2->a, ptr2->b); some1 = *ptr; printf("%d %cn", some1.a, some1.b); *ptr3 = some1; printf("%d %cn", ptr3->a, ptr3->b); return 0; } Output 123 b 123 b 123 b