0% found this document useful (0 votes)
4 views19 pages

CP Lab Programs

The document outlines the C Programming Lab Programs for the first semester of the B.E. course at SJB Institute of Technology for the academic year 2023-2024. It includes guidelines for writing lab records, various programming exercises, and their respective purposes, procedures, inputs, expected outputs, and sample codes. The exercises cover topics such as area calculation, arithmetic operations, electricity billing, array manipulation, prime number generation, sorting algorithms, and matrix multiplication.

Uploaded by

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

CP Lab Programs

The document outlines the C Programming Lab Programs for the first semester of the B.E. course at SJB Institute of Technology for the academic year 2023-2024. It includes guidelines for writing lab records, various programming exercises, and their respective purposes, procedures, inputs, expected outputs, and sample codes. The exercises cover topics such as area calculation, arithmetic operations, electricity billing, array manipulation, prime number generation, sorting algorithms, and matrix multiplication.

Uploaded by

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

||Jai Sri Gurudev ||

Sri Adichunchanagiri Shikshana Trust®

SJB INSTITUTE OF TECHNOLOGY


Accredited by NBA & NAAC with ‘A’ Grade
No. 67, BGS Health & Education City, Dr. Vishnuvardhan Road
Kengeri, Bangalore – 560 060

Department of Electronics & Communication


Engineering
C - Programming [23CPI15B]

C Programming Lab Programs


Notes (as per Autonomous Syllabus)

I SEMESTER – B. E

Academic Year: 2023 – 2024 (ODD)

Course Coordinator : Mrs. Uma S

Designation : Assistant Professor


C Programming 23CPI15B

Guidelines to write the record


1. Name, USN, sem, section every details to be filled.
2. Fill the content sheet with date, program title and page number.
3. On left hand side i.e on white sheet every program’s Algorithm and flow
chart to be written
4. On right hand side, program number example program-1, title of
program, purpose , procedure, input and expected output and then
program to be written
5. Next page , on left hand side i.e on blank sheet result to be tabulated.
6. Finally conclusion on right had side at the end of program

LHS RHS

Algorithm Flowchart Program - 1


Write a C program to find
Area,perimeter and Cost of
Rectangular plot of land.

purpose

Procedure

Input

expected output

Program

LHS RHS

Result: Program

Conclusion

Dept. of ECE, SJBIT Page 2


C Programming 23CPI15B

1. Write a C program to find Area,perimeter and Cost of Rectangular


plot of land.

Purpose: This program demonstrates simple equations, printf and scanf


statements.
Procedure: To read length , breadth of rectangular plot and to calculate
area, perimeter and cost.
Input: Length and Breadth’
Expected Output: This program performs the simple calculation and prints
the result.
#include<stdio.h>
int main()
{
int l, b; // length and breadth of rectangular plot
float area, perimeter,cost;
printf(“Enter the length , breadth and cost for rectangular plot\n”);
scanf(“%d %d %f”, &l,&b,&cost);
area= l*b;
perimeter= 2*(l+b);
cost = cost*area; // cost + = area;
printf(“The area of rectangular plot = %f\n The perimeter of rectangular
plot = %f\n The cost of rectangular plot = %f\n”, area,perimeter,cost) ;
return 0;
}

Output:

Sl.No. Input Parameters Expected result Obtained output Remarks


L= Area = Area =
1 B= Perimeter = Perimeter =
Cost= Cost = Cost =

Dept. of ECE, SJBIT Page 3


C Programming 23CPI15B

2. Develop a program to solve simple computational problems using


arithmetic expressions and use of each operator leading to simulation
of a commercial calculator. (No built-in math function)

Purpose: This program demonstrates SWITCH conditional statements.


Procedure: To read arithmetic operator from user to demonstrate simple
calculation
Input: Arithematic operators : ‘+’,’-‘, ‘*’,’/’
Expected Output: This program performs the simple calculation and prints
the result.

#include<stdio.h>
#include<stdlib.h>
void main()
{
float a,b,res;
char ch;

printf("enter the operator\n");


scanf("%c",&ch);
printf("enter two integers\n");
scanf("%f%f",&a,&b);

switch(ch)
{
case '+':res=a+b;
break;
case '-':res=a-b;
break; case '*':res=a*b;
break; case '/':if(b!=0)
{
res=a/b;
}
else

Dept. of ECE, SJBIT Page 4


C Programming 23CPI15B

{
printf("divide by zero error");
exit(0);
}
break;
default:printf("not a valid operator");
exit(0);
}
printf("result=%f",res);
}

Output:

Input Expected Obtained


Test No Remarks
Parameters Output Output

Operator= +
1 Res=19 Res=19 PASS
a=9,b=10

Dept. of ECE, SJBIT Page 5


C Programming 23CPI15B

3. An electricity board charges the following rates for the use of


electricity: for the first 200 units 80 paise per unit: for the next 100
units 90 paise per unit: beyond 300 units Rs 1 per unit. All users are
charged a minimum of Rs. 100 as meter charge. If the total amount is
more than Rs 400, then an additional surcharge of 15% of total amount
is charged. Write a program

Purpose: This program demonstrates if elseif conditional statements.


Procedure: To read the number of units consumed and to calculate the
amount to be paid .
Input: character string , no. of units consumed.
Expected Output: This program performs the calculation of amount for
different slabs of unit consumed and prints the result.

#include<stdio.h>
int main()
{
char name[20];
int n; float amount;

printf("Enter the consumer name\n");


scanf("%s", name);
printf("Enter no. of units consumed \n");
scanf("%d",&n);
if(n<=200)
{
amount=n*80;
}
else if(n>200 && n<=300)
{
amount=200*80;
amount=amount+(n-200)*90;
}
else

Dept. of ECE, SJBIT Page 6


C Programming 23CPI15B

{
amount=(n-300)*100;
amount=amount+100*90;
amount=amount+200*80;
}
amount=amount/100;
amount=amount+100;
if(amount>400)
{
amount=amount+15*amount/100;
}
printf("Total amount to be paid is %.2f Rs",amount);
}

Output:

Input
Test No Expected output Obtained output Remarks
Parameters

Total Amount to be Total Amount to be


1 N=100 PASS
paid=180Rs paid=180Rs

Dept. of ECE, SJBIT Page 7


C Programming 23CPI15B

4. Introduce 1D Array manipulation and implement Binary search.


Purpose: This program demonstrates the LOOPS and ARRAY.
Procedure: Input N array elements and to find whether element is present
or not
Input: Array elements Expected
Output: Successful search or unsuccessful search
Program

#include<stdio.h>
int main()
{
int a[30],i,num,key,low,mid,high;
printf("\n enter the no of elements");
scanf("%d",&num);
printf("\n enter the elements : ");
for(i=0;i<=high;i++)
{
scanf("%d",&a[i]);
}
printf("\nenter the key element to be searched\n");
scanf("%d",&key);
low=0;
high=num-1;
while(low<=high)
{
mid=(low+high)/2;
if(a[mid]==key)
{
printf("element %d is found at %d position :",key,mid+1);
exit(0);
}
else if(a[mid]>key)
high=mid-1;
else low=mid+1;
}
printf("UNSUCCESSFULL SEARCH\n");

Dept. of ECE, SJBIT Page 8


C Programming 23CPI15B

return 0;
}

Result :

Test no Input Expected Obtained Remarks


Parameters output output

1 N= Element Element Pass or Fail


A[0]= found at found at
position : position :
A[1]=
A[2]=
A[3]=
A[4]=
Key=

Dept. of ECE, SJBIT Page 9


C Programming 23CPI15B

5. Implement using functions to print the prime numbers within a range.


Purpose: This program demonstrates USER DEFINED FUNCTIONS.
Procedure: Input N array elements and to find whether element is present or not
Input: starting and ending value
Output: List of prime numbers within range
#include <stdio.h> // Include the standard input/output header file.
int main()
{
int num, i, ctr, stno, enno; // Declare variables for the number, loop counters, and
range.
printf("Input starting number of range: ");
scanf("%d", &stno); // Read the input from the user.

printf("Input ending number of range : ");


scanf("%d", &enno); // Read the input from the user.

printf("The prime numbers between %d and %d are: \n", stno, enno);

for (num = stno; num <= enno; num++)


{
ctr = 0; // Initialize the counter.

for (i = 2; i <= num / 2; i++) { // Loop through possible divisors.


if (num % i == 0) { // If a divisor is found...
ctr++; // ...increment the counter.
break; // Exit the loop.
}
}

if (ctr == 0 && num != 1) // If no divisors were found and the number is not 1...
printf("%d ", num); // ...print the prime number.
}

printf("\n"); // Move to the next line after printing all prime numbers.

return 0; // Return 0 to indicate successful execution.


}

Result:

Dept. of ECE/SJBIT Page 1


C Programming 23CPI15B

6. Develop a program to sort the given set of N numbers using Bubble sort
Purpose: This program demonstrates NESTED FOR loop.
Procedure: To read an array of elements a[ ] . While iterating, compare each pair of
adjacent items in every pass. If the former value is greater than the latter one, their
positions are swapped. Over a number of passes, at most equal to the number of
elements in the list, all of the values drift into their correct positions. Then print
sorted array elements.
Input: Number of Elements – n An array of unsorted elements – a[ ]
Output: An array of sorted elements – a[ ]

#include<stdio.h>
#include<conio.h>
int main()
{
int n,i,j,a[10],temp;

printf("Enter the no. of elements : \n");


scanf("%d",&n);
printf("Enter the array elements \n");
for(i = 0 ; i < n ; i++)
scanf("%d",&a[i]);

printf("The original elements are \n");


for(i = 0 ; i < n ; i++)
printf("%d ",a[i]);

for(i= 0 ; i < n-1 ; i++) // Number of Passes


{
for(j= 0 ; j< n-i+1; j++) // Comparisons
if(a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
printf("\n The Sorted elements are \n");

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


printf("%d ",a[i]);
return 0;
}
Result:

Dept. of ECE/SJBIT Page 1


C Programming 23CPI15B

7. Develop a Program to compute Sin(x) using Taylor series approximation


.Compare your result with the built- in Library function. Print both the
results with appropriate messages.
/* Program to calculate sine value of given angle */
#include<stdio.h>
#include<conio.h>
#include <math.h>
#define PI 3.142
int main()
{

int i, degree;
float x, sum=0,term,nume,deno;

printf("Enter the value of degree");


scanf("%d",&degree);

x = degree * (PI/180); //converting degree into radian


nume = x;
deno = 1;
i=2;
do
{ //calculating the sine value.
term = nume/deno;
nume = -nume*x*x;
deno = deno*i*(i+1);
sum=sum+term;
i=i+2;
}
while (fabs(term) >= 0.00001); // Accurate to 4 digits
printf("The sine of %d is %.3f\n", degree, sum);
printf("The sine function of %d is %.3f", degree, sin(x));
return 0;
}
Result:
Test Input Expected output Obtained output Remarks
No Parameters
1 Degree = 0 The sine of 0 is = The sine of 0 is=
Using inbuilt function sin(0)=

Dept. of ECE/SJBIT Page 1


C Programming 23CPI15B

8. C program that calculates IHP, BHP, and CR for a four-stroke gas engine:
/*Concepts:

Indicated Horsepower (IHP): The theoretical power produced within the


engine cylinders.
Brake Horsepower (BHP): The actual power available at the crankshaft,
accounting for frictional losses.
Compression Ratio (CR): The ratio of the volume of the cylinder when the
piston is at the bottom of its stroke (BDC) to the volume when the piston
is at the top of its stroke (TDC).
Formulas:

IHP = (LAN * V * N) / (60 * 1000)


LAN: Indicated mean effective pressure (kPa)
V: Engine displacement (liters)
N: Engine speed (RPM)
BHP = IHP * Mechanical Efficiency
Mechanical Efficiency: Typically around 85%
CR = (V + Vc) / Vc
Vc: Clearance volume (volume at TDC) */

Program
#include <stdio.h>

int main() {
float bp, ip, rpm, lan, d, sp, v, cr;

printf("Enter the Brake power (BHP) in kW: ");


scanf("%f", &bp);

printf("Enter the Engine speed (RPM): ");


scanf("%f", &rpm);

printf("Enter the Indicated mean effective pressure (LAN) in kPa: ");


scanf("%f", &lan);

printf("Enter the Bore diameter (D) in cm: ");


scanf("%f", &d);

printf("Enter the Stroke length (S) in cm: ");


scanf("%f", &sp);

// Calculations:
ip = bp / 0.85; // Assuming mechanical efficiency of 85%
v = 3.14159 * d * d * sp * 0.001 / 4; // Engine displacement in
liters

cr = (sp + v) / v; // Compression ratio

printf("\nIndicated Horsepower (IHP) = %.2f kW\n", ip);


printf("Brake Horsepower (BHP) = %.2f kW\n", bp);
printf("Compression Ratio (CR) = %.2f\n", cr);

return 0;
}

Dept. of ECE, SJBIT Page 2


C Programming 23CPI15B

9. Implement Matrix Multiplication and Validate the rules of multiplication

#include <stdio.h>

int main() {
int m, n, p, q, i, j, k;

printf("Enter the order of the first matrix (m x n): ");


scanf("%d %d", &m, &n);

printf("Enter the order of the second matrix (p x q): ");


scanf("%d %d", &p, &q);

// Validate multiplication rule:


if (n != p) {
printf("Matrix multiplication not possible! Number of columns of the first matrix must
equal the number of rows of the second matrix.\n");
return 1; // Indicate error
}

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

printf("Enter the elements of the first matrix:\n");


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

printf("Enter the elements of the second matrix:\n");


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

// Initialize the result matrix to zero:


for (i = 0; i < m; i++) {
for (j = 0; j < q; j++) {
C[i][j] = 0;
}
}

// Multiply the matrices:


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

Dept. of ECE, SJBIT Page 3


C Programming 23CPI15B

printf("The product of the matrices is:\n");


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

return 0;
}

10. Write functions to implement string operations such as copy, compare and
concatenate using user defined functions

#include<stdio.h>

int Length(char s1[]);


int compare(char s1[], char s2[]);
void concat(char s1[], char s2[]);

int main()
{
char s1[200], s2[100];
int len,res,count;
printf("\nEnter the String s1: ");
gets(s1);
printf("\nEnter String s2 :");
gets(s2);

len = Length(s1);
printf("\nLength of the String s1 is : %d", len);

res = compare(s1, s2);


if(res == 0)
{
printf("\nBoth the Strings are Equal\n");
}
else
{
printf("\nThe Strings are not Equivalent\n");
}
concat(s1, s2);
printf("\nConcated string is :%s", s1);
return(0);
}

int Length(char s1[])


{
int len = 0;
while (s1[len] != '\0')
len++;
return (len);
}
int compare(char s1[], char s2[])
{
int count = 0;
while(s1[count] == s2[count])

Dept. of ECE, SJBIT Page 4


C Programming 23CPI15B

{
if(s1[count] == '\0' || s2[count] == '\0')
break;
else count++;
}
if(s1[count] == '\0' && s2[count] == '\0')
return 0;
else
return -1;
}

void concat(char s1[], char s2[])


{ int i, j;
i = strlen(s1);
for (j = 0; s2[j] != '\0'; i++, j++)
{
s1[i] = s2[j];
}
s1[i] = '\0';
}

11. Write functions to implement string operations such as compare, reverse


and find string length. Use the parameter passing techniques.

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

int compare_strings(char str1[], char str2[]) {


int i = 0;
while (str1[i] == str2[i] && str1[i] != '\0' && str2[i] != '\0') {
i++;
}
return str1[i] - str2[i]; // Returns 0 for equal, negative for str1 < str2, positive for
str1 > str2
}

Void reverse_string(char str[])

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

int find_string_length(char str[]) {


int len = 0;
while (str[len] != '\0') {
len++;
}
Dept. of ECE, SJBIT Page 5
C Programming 23CPI15B

return len;
}

int main() {
char str1[50], str2[50];

printf("Enter the first string: ");


fgets(str1, 50, stdin); // Use fgets to handle spaces in input
str1[strcspn(str1, "\n")] = '\0'; // Remove trailing newline

printf("Enter the second string: ");


fgets(str2, 50, stdin);
str2[strcspn(str2, "\n")] = '\0';

int comparison = compare_strings(str1, str2);


if (comparison == 0) {
printf("The strings are equal.\n");
} else if (comparison < 0) {
printf("The first string is lexicographically smaller.\n");
} else {
printf("The second string is lexicographically smaller.\n");
}

reverse_string(str1);
printf("Reversed first string: %s\n", str1);

int length = find_string_length(str2);


printf("Length of second string: %d\n", length);

return 0;
}

12. Write a program to convert given binary to decimal using function.

#include <stdio.h>
int convert(int);
int main()
{
int dec, bin;
printf("Enter a binary number: ");
scanf("%d", &bin);
dec = convert(bin);
printf("The decimal equivalent of %d is %d.\n", bin,dec);
return 0;
}
int convert(int bin)
{
if (bin == 0)
{
Dept. of ECE, SJBIT Page 6
C Programming 23CPI15B

return 0;
}
else
{
return (bin % 10 + 2 * convert(bin / 10));
}

13. Implement structures to read, write and compute average marks of the
students, list the students scoring above and below the average marks for a
class of N students.

#include <stdio.h>
struct student
{
char usn[50];
char name[50];
int marks;
}
s[10];
void main()
{
int i,n,countav=0,countbv=0;
float sum,average;
printf("Enter number of Students\n");
scanf("%d",&n);
printf("Enter information of students:\n");

for(i=0; i<n;i++)
{
printf("Enter USN: ");
scanf("%s",s[i].usn);
printf("Enter name: ");
scanf("%s",s[i].name);
printf("Enter marks: ");
scanf("%d",&s[i].marks);
printf("\n");
}
for(i=0;i<n;i++)
{
sum=sum+s[i].marks;
}
average=sum/n;
printf("\nAverage marks: %f",average);
countav=0;
countbv=0;
for(i=0;i<n;i++)
{
if(s[i].marks>=average)
countav++;
else
countbv++;
}
printf("\nTotal No of students above average= %d",countav);
printf("\nTotal No of students below average= %d",countbv);
}

14. Develop a program using pointers to compute the sum mean and standard
deviation of all elements stored in an array of N real numbers.
Dept. of ECE, SJBIT Page 7
C Programming 23CPI15B

#include<stdio.h>
#include <conio.h>
#include <math.h>
int main()
{
float a[10], *ptr, mean, std, sum=0, sumstd=0;
int n,i;
printf("Enter the no of elements\n");
scanf("%d",&n);
printf("Enter the array elements\n");
for(i=0;i<n;i++)
{
scanf("%f",&a[i]);
}
ptr=a;
for(i=0;I <n;i++)
{
sum=sum+ *ptr;
ptr++;
}
mean=sum/n;
ptr=a;
for(i=0;I <n;i++)
{
sumstd=sumstd + pow((*ptr - mean),2);
ptr++;
}
std= sqrt(sumstd/n);
printf("Sum=%.3f\t",sum);
printf("Mean=%.3f\t",mean);
printf("Standard deviation=%.3f\t",std);
return 0;
}

15. Write a c program to copy a text file to another , reading both the input file
name and target file name.

Dept. of ECE, SJBIT Page 8

You might also like