0% found this document useful (0 votes)
95 views

Lab Record Download

Uploaded by

pthrinesh42
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)
95 views

Lab Record Download

Uploaded by

pthrinesh42
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/ 120

Exp.

Name: Display hello world message Date:

Aim:
Write a C program to display hello world message

Page No: 1
Source Code:

hello.c

#include<stdio.h>

ID:
void main()
{
printf("Hello World\n");
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output

2024-2028-EEE
Hello World

Narayana Engineering College - Gudur


Exp. Name: Scan all data type variables and display
Date:
them

Aim:

Page No: 2
Write a C program to scan all data type variables(int, float, char, double) as input and print them as output.

Input Format:
• First Line: An integer, entered after the prompt "integer: ".
• Second Line: A floating-point number, entered after the prompt "floating-point number: ".

ID:
• Third Line: A character, entered after the prompt "character: ".
• Fourth Line: A double-precision floating-point number, entered after the prompt "double: ".

Output Format:
• First Line: A message "You entered:".
• Second Line: The integer entered, in the format "Integer: [integerVar]".
• Third Line: The floating-point number entered, formatted to six decimal places, in the format "Float:
[floatVar]".
• Fourth Line: The character entered, in the format "Character: [charVar]".
• Fifth Line: The double-precision floating-point number entered, formatted to six decimal places, in the
format "Double: [doubleVariable]".

2024-2028-EEE
Note: Please add Space before %c which removes any white space (blanks, tabs, or newlines).
Source Code:

scan.c

#include<stdio.h>

Narayana Engineering College - Gudur


void main()
{
int intVal;
float floatVal;
char charVal;
double doubleVal;
printf("integer: ");
scanf("%d",&intVal);
printf("floating-point number: ");
scanf("%f",&floatVal);
printf("character: ");
scanf(" %c",&charVal);
printf("double: ");
scanf("%lf",&doubleVal);
printf("You entered:\n");
printf("Integer: %d\n",intVal);
printf("Float: %f\n",floatVal);
printf("Character: %c\n",charVal);
printf("Double: %lf\n", doubleVal);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
integer:
9
floating-point number:
12.0254
character:

Page No: 3
C
double:
12.02543124
You entered:

ID:
Integer: 9
Float: 12.025400
Character: C
Double: 12.025431

Test Case - 2

User Output
integer:
-10

2024-2028-EEE
floating-point number:
12.2546
character:
T
double:
12.6789678

Narayana Engineering College - Gudur


You entered:
Integer: -10
Float: 12.254600
Character: T
Double: 12.678968
Exp. Name: Arithmetic operations Date:

Aim:
Write a C program to perform arithmetic operations like +,-,*,/,% on two input variables.

Page No: 4
Input Format:
• The first line of input should be the value for first number
• The second line of input should be the value of second number

ID:
Output Format:
• The program prints the results of addition, subtraction, multiplication, division, and modulus

Note : For Division and Modulo operation, the value of num2 must be greater than 0
Source Code:

arithmeticOperations.c
#include<stdio.h>
void main()
{
int num1,num2;

2024-2028-EEE
printf("num1: ");
scanf("%d",&num1);
printf("num2: ");
scanf("%d",&num2);
printf("Sum: %d\n",num1+num2);
printf("Difference: %d\n",num1-num2);
printf("Product: %d\n",num1*num2);

Narayana Engineering College - Gudur


printf("Division: %d\n",num1/num2);
printf("Modulus: %d\n",num1%num2);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
num1:
9
num2:
8
Sum: 17
Difference: 1
Product: 72
Division: 1
Modulus: 1

Test Case - 2

User Output
num1:
1000
num2:
2
Sum: 1002
Difference: 998

Page No: 5
Product: 2000
Division: 500
Modulus: 0

ID:
2024-2028-EEE
Narayana Engineering College - Gudur
Exp. Name: Write a C program to find Sum and
Date:
Average of three numbers

Aim:

Page No: 6
Write a program to find the sum and average of the three given integers.

Note: Use the printf() function with a newline character ( \n ) at the end.
Source Code:

ID:
Program314.c

#include<stdio.h>
void main()
{
int x,y,z,sum;
float avg;
printf("Enter three integers : ");
scanf("%d%d%d",&x,&y,&z);
sum=x+y+z;
avg= (float)sum/3;
printf("Sum of %d, %d and %d : %d\n",x,y,z,sum);

2024-2028-EEE
printf("Average of %d, %d and %d : %f\n",x,y,z,avg);
}

Execution Results - All test cases have succeeded!

Narayana Engineering College - Gudur


Test Case - 1

User Output
Enter three integers :
121 34 56
Sum of 121, 34 and 56 : 211
Average of 121, 34 and 56 : 70.333336

Test Case - 2

User Output
Enter three integers :
583
Sum of 5, 8 and 3 : 16
Average of 5, 8 and 3 : 5.333333

Test Case - 3

User Output
Enter three integers :
-1 5 -6
Sum of -1, 5 and -6 : -2
Average of -1, 5 and -6 : -0.666667
Exp. Name: Temperature conversions from
Date:
Centigrade to Fahrenheit and vice versa.

Aim:

Page No: 7
Write a C program to perform temperature conversions from Centigrade to Fahrenheit

Note : Refer to sample test cases for input and output format
Source Code:

ID:
temperature.c

#include<stdio.h>
void main()
{
float centigrade, fahrenheit;
scanf("%f",&centigrade);
fahrenheit = (centigrade* 9/ 5) + 32;
printf("%.2f Celsius = %.2f Fahrenheit\n", centigrade, fahrenheit);
}

2024-2028-EEE
Execution Results - All test cases have succeeded!
Test Case - 1

User Output

Narayana Engineering College - Gudur


37.5
37.50 Celsius = 99.50 Fahrenheit

Test Case - 2

User Output
-20
-20.00 Celsius = -4.00 Fahrenheit
Exp. Name: Problem Solving Date:

Aim:
Write a program to calculate the simple interest by reading principle amount, rate of interest and time.

Page No: 8
At the time of execution, the program should print the message on the console as:

Enter principle amount, rate of interest, time of loan :

ID:
For example, if the user gives the input as:

Enter principle amount, rate of interest, time of loan : 23456.78 3.5 2.5

then the program should print the result as:

Simple Interest = 2052.468018

Note: Do use the printf() function and ensure that there is a '\n' at the end after print the result.
Source Code:

Program3.c

2024-2028-EEE
#include<stdio.h>
void main()
{
double p,t,r,si;
printf("Enter principle amount, rate of interest, time of loan : ");

Narayana Engineering College - Gudur


scanf("%lf %lf %lf", &p, &t, &r);
si = (p * t *r) / 100;
printf("Simple Interest = %lf\n", si);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter principle amount, rate of interest, time of loan :
2500 5 2
Simple Interest = 250.000000
Exp. Name: Calculate the square root of an integer Date:

Aim:
Write a program that prompts the user to enter an integer and calculates its square root.

Page No: 9
Note:Print the result up to 3 decimal places.

Input format:
The program takes an integer as input with the print statement "Enter an integer: " followed by the integer.

ID:
Output format:
The output is the floating point value formatted to three decimals that represents the square root value of the
user-given integer.

Hint: You can use math library to perform mathematical operations.

Instruction: During writing your code, please follow the input and output layout as mentioned in the
sample test case.
Source Code:

squareRoot.c

2024-2028-EEE
#include<stdio.h>
#include<math.h>
int main()
{
double n,sr;

Narayana Engineering College - Gudur


printf("Enter an integer: ");
scanf("%lf",&n);
sr=sqrt(n);
printf("Square root: %.3lf\n",sr);
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter an integer:
2
Square root: 1.414

Test Case - 2

User Output
Enter an integer:
4
Square root: 2.000
Exp. Name: Calculate simple interest and
Date:
compound interest

Aim:

Page No: 10
Write a program to calculate the simple interest and compound interest by reading principal amount, rate
of interest and time.

Note: Use the printf() function and ensure that the character '\n' is printed at the end of the result.

ID:
The formula to find simple interest is simpleInterest = (principal * rate * time) / 100 .

The formula to find compound interest is


compoundInterest = principal * pow(1 + (rate / 100), time) - principal .

Note: Use float data type for all the involved variables.
Source Code:

Program315.c
#include<stdio.h>

2024-2028-EEE
#include<math.h>
int main()
{
float p, r, t, si, ci;
printf("Enter P,R,T: ");
scanf("%f%f%f",&p, &r, &t);

Narayana Engineering College - Gudur


si =(p*r*t)/100;
ci =p*pow(1+(r/100),t)-p;
printf("SI= %f\n", si);
printf("CI= %f\n", ci);
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter P,R,T:
5000 7 5
SI= 1750.000000
CI= 2012.760376

Test Case - 2

User Output
Enter P,R,T:
1000 6 4
SI= 240.000000
CI= 262.476685

Narayana Engineering College - Gudur 2024-2028-EEE ID: Page No: 11


Exp. Name: Area of a triangle using heron's formula Date:

Aim:
Write a program to find the area of a triangle using Heron's formula.

Page No: 12
During execution, the program should print the following message on the console:

sides:

ID:
For example, if the user gives the following as input (input is positive floating decimal point numbers):

sides: 2.3 2.4 2.5

Then the program should print the result round off upto 2 decimal places as:

area: 2.49

Instruction: Your input and output layout must match with the sample test cases (values as well as text strings).

The area of a triangle is given by Area = √ p(p − a)(p − b)(p − c) , where p is half of the perimeter, or
(a + b + c) / 2 . Let a,b,c be the lengths of the sides of the given triangle.

2024-2028-EEE
Hint: Use sqrt function defined in math.h header file
Source Code:

Program313.c

Narayana Engineering College - Gudur


#include<stdio.h>
#include<math.h>
int main()
{
double a, b, c, s,area;
printf("sides: ");
scanf("%lf%lf%lf", &a, &b, &c);
s = (a+b+c)/2;
area = sqrt(s*(s-a)*(s-b)*(s-c));
printf("area: %.2lf\n", area);
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
sides:
2.3 2.4 2.5
area: 2.49

Test Case - 2
sides:
2.6 2.7 2.8
area: 3.15
User Output

Narayana Engineering College - Gudur 2024-2028-EEE ID: Page No: 13


Exp. Name: Distance travelled by an object Date:

Aim:
Write a program to find the distance travelled by an object.

Page No: 14
Sample Input and Output:

Enter the acceleration value : 2.5


Enter the initial velocity : 5.7

ID:
Enter the time taken : 20
Distance travelled : 614.000000

Note - 1: Use the formula to find distance, distance = ut + (1/2) at2 .

Note: Use the printf() function with a newline character ( \n ) at the end.

Source Code:

DistanceTravelled.c

#include<stdio.h>

2024-2028-EEE
#include<math.h>
int main()
{
float accVal, ivVal, ttVal, dtVal;
printf("Enter the acceleration value : ");
scanf("%f", &accVal);

Narayana Engineering College - Gudur


printf("Enter the initial velocity : ");
scanf("%f", &ivVal);
printf("Enter the time taken : ");
scanf("%f", &ttVal);
dtVal = ivVal*ttVal+(0.5)*accVal*ttVal*ttVal;
printf("Distance travelled : %6f\n",dtVal);
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter the acceleration value :
4
Enter the initial velocity :
5
Enter the time taken :
6
Distance travelled : 102.000000

Test Case - 2
User Output
Enter the acceleration value :
5
Enter the initial velocity :
0

Page No: 15
Enter the time taken :
10
Distance travelled : 250.000000

ID:
Test Case - 3

User Output
Enter the acceleration value :
2.5
Enter the initial velocity :
5.7
Enter the time taken :
20
Distance travelled : 614.000000

2024-2028-EEE
Test Case - 4

User Output

Narayana Engineering College - Gudur


Enter the acceleration value :
50
Enter the initial velocity :
34.67
Enter the time taken :
6
Distance travelled : 1108.020020

Test Case - 5

User Output
Enter the acceleration value :
125.6
Enter the initial velocity :
45.8
Enter the time taken :
4
Distance travelled : 1188.000000
Exp. Name: Evaluate the expressions Date:

Aim:
Write a C program to evaluate the following expressions.

Page No: 16
a. A+B*C+(D*E) + F*G
b. A/B*C-B+A*D/3
c. A+++B---A
d. J= (i++) + (++i)

ID:
Note: consider expression as A++ + ++B - --A
Source Code:

evaluate.c
#include<stdio.h>
void main()
{
int A, B, C, D, E, F, G ,i;
printf("Enter values for A, B, C, D, E, F, G, i: ");
scanf("%d%d%d%d%d%d%d%d",&A, &B, &C, &D, &E, &F, &G,&i);
printf("a.A+B*C+(D*E) + F*G = %d\n", A+B*C+(D*E)+F*G);

2024-2028-EEE
printf("b.A/B*C-B+A*D/3 = %d\n",A/B*C-B+A*D/3);
printf("c.A+++B---A = %d\n", A+(++B)-(A));
printf("d.J = (i++) + (++i) = %d\n", (i++) + (++i));
}

Narayana Engineering College - Gudur


Execution Results - All test cases have succeeded!
Test Case - 1

User Output
Enter values for A, B, C, D, E, F, G, i:
12345678
a.A+B*C+(D*E) + F*G = 69
b.A/B*C-B+A*D/3 = -1
c.A+++B---A = 3
d.J = (i++) + (++i) = 18

Test Case - 2

User Output
Enter values for A, B, C, D, E, F, G, i:
10 20 60 30 40 4 6 1
a.A+B*C+(D*E) + F*G = 2434
b.A/B*C-B+A*D/3 = 80
c.A+++B---A = 21
d.J = (i++) + (++i) = 4
Exp. Name: Greatest of three numbers using a
Date:
conditional operator

Aim:

Page No: 17
Write a C program to display the greatest of three numbers using a conditional operator (ternary operator).

Input Format
The program prompts the user to enter three integers.

ID:
Output Format
The program prints the greatest of the three integers.

Source Code:

greatest.c

#include <stdio.h>
int main() {
int num1, num2, num3, greatest;
// Take input from user
printf("num1: ");

2024-2028-EEE
scanf("%d", &num1);
printf("num2: ");
scanf("%d", &num2);
printf("num3: ");
scanf("%d", &num3);
// Find the greatest number using the conditional operator

Narayana Engineering College - Gudur


greatest = 0;
if(num1 >= num2 && num3 <= num1) {
greatest = num1;
} else if ( num2 >= num3 && num1 <= num2){
greatest = num2;
}
else {
greatest = num3;
}
// Display the greatest number
printf("Greatest number: %d\n",greatest);
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
num1:
8
num2:
9
num3:
90
Greatest number: 90

Test Case - 2

User Output

Page No: 18
num1:
5
num2:
45

ID:
num3:
6
Greatest number: 45

2024-2028-EEE
Narayana Engineering College - Gudur
Exp. Name: Write a C program to Total and Average
Date:
of 5 subjects marks

Aim:

Page No: 19
Write a program to take marks of 5 subjects in integers, and find the total , average in float.

Sample Input and Output:

Enter 5 subjects marks : 55 56 57 54 55

ID:
Total marks : 277.000000
Average marks : 55.400002

Note: Use the printf() function with a newline character ( \n ) to print the output at the end.

Source Code:

TotalAndAvg.c

#include<stdio.h>
int main(){
int s1, s2,s3, s4, s5;

2024-2028-EEE
float tot, avg;
printf("Enter 5 subjects marks : ");
scanf("%d %d %d %d %d", &s1, &s2, &s3, &s4, &s5);
tot = s1 + s2 + s3 + s4 +s5;
avg = tot/5;
printf("Total marks : %f\n", tot);

Narayana Engineering College - Gudur


printf("Average marks : %f\n", avg);
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter 5 subjects marks :
45 67 89 57 49
Total marks : 307.000000
Average marks : 61.400002

Test Case - 2

User Output
Enter 5 subjects marks :
55 56 57 54 55
Total marks : 277.000000
Average marks : 55.400002
Test Case - 3

User Output
Enter 5 subjects marks :
90 97 95 92 91

Page No: 20
Total marks : 465.000000
Average marks : 93.000000

Test Case - 4

ID:
User Output
Enter 5 subjects marks :
20 30 66 77 44
Total marks : 237.000000
Average marks : 47.400002

Test Case - 5

User Output

2024-2028-EEE
Enter 5 subjects marks :
56 78 88 79 64
Total marks : 365.000000
Average marks : 73.000000

Narayana Engineering College - Gudur


Test Case - 6

User Output
Enter 5 subjects marks :
44 35 67 49 51
Total marks : 246.000000
Average marks : 49.200001
Exp. Name: Write a Program to find the Max and
Date:
Min of Four numbers

Aim:

Page No: 21
Write a program to find the max and min of four numbers.

Sample Input and Output :

Enter 4 numbers : 9 8 5 2

ID:
Max value : 9
Min value : 2

Note: Use the printf() function with a newline character ( \n ) to print the output at the end.

Source Code:

MinandMaxOf4.c

#include<stdio.h>
void main() {
int a[4], min, max;

2024-2028-EEE
printf("Enter 4 numbers : ");
for ( int i = 0; i < 4; i++) {
scanf("%d",&a[i]);
}

min = a[0];

Narayana Engineering College - Gudur


for ( int i = 0; i < 4; i++ ) {
if(a[i] < min )
min = a [i];
}

max = a[0];
for ( int i = 0; i < 4; i++){
if ( a[i] > max )
max = a[i];
}
printf("Max value : %d\n", max);
printf("Min value : %d\n", min);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter 4 numbers :
9852
Max value : 9
Min value : 2
Test Case - 2

User Output
Enter 4 numbers :
112 245 167 321

Page No: 22
Max value : 321
Min value : 112

Test Case - 3

ID:
User Output
Enter 4 numbers :
110 103 113 109
Max value : 113
Min value : 103

Test Case - 4

User Output

2024-2028-EEE
Enter 4 numbers :
-34 -35 -24 -67
Max value : -24
Min value : -67

Narayana Engineering College - Gudur


Test Case - 5

User Output
Enter 4 numbers :
24 28 34 16
Max value : 34
Min value : 16

Test Case - 6

User Output
Enter 4 numbers :
564 547 574 563
Max value : 574
Min value : 547
Exp. Name: Find out the electricity bill charges Date:

Aim:
An electricity board charges the following rates for the use of electricity:

Page No: 23
• If units are less than or equal to 200, then the charge is calculated as 80 paise per unit.
• If units are less than or equal to 300, then the charge is calculated as 90 paise per unit.
• If units are beyond 300, then the charge is calculated as 1 Rupee per unit.

ID:
All users are charged a minimum of Rs. 100 as a meter charge even though the amount calculated is less than Rs.
100.

If the total amount charged is greater than Rs. 400, then an additional surcharge of 15% of the total amount is
charged.

Write a C program to read the name of the user, and the number of units consumed and print out the charges as
shown in the sample test cases.

Note: Print the amount charged up to 2 decimal places (actual amount, surcharges, amount to be paid).
Source Code:

2024-2028-EEE
electricityBillCharges.c

#include<stdio.h>
void main(){
char name[50];
int units;

Narayana Engineering College - Gudur


float amountcharged,surcharge,amounttobepaid;
printf("Enter customer name: ");
scanf("%s",name);
printf("Units consumed: ");
scanf("%d",&units);
printf("Customer name: %s\n",name);
printf("Units consumed: %d\n",units);
if(units<=200){
amountcharged=units*0.8;
}else if(units<=300&&units>=200){
amountcharged=units*0.9;
}else {
amountcharged=units*1;
}
printf("Amount charged: %.2f\n",amountcharged);
if(amountcharged>400){
surcharge=amountcharged*0.15;
}else{
surcharge=0.00;
}if(amountcharged<100){
amounttobepaid=100;
}else{
amounttobepaid=surcharge+amountcharged;
}printf("Surcharges: %.2f\n",surcharge);
printf("Amount to be paid: %.2f\n",amounttobepaid);
}
Execution Results - All test cases have succeeded!
Test Case - 1

User Output

Page No: 24
Enter customer name:
John
Units consumed:
78

ID:
Customer name: John
Units consumed: 78
Amount charged: 62.40
Surcharges: 0.00
Amount to be paid: 100.00

Test Case - 2

User Output
Enter customer name:
Rosy

2024-2028-EEE
Units consumed:
325
Customer name: Rosy
Units consumed: 325
Amount charged: 325.00

Narayana Engineering College - Gudur


Surcharges: 0.00
Amount to be paid: 325.00

Test Case - 3

User Output
Enter customer name:
Amar
Units consumed:
801
Customer name: Amar
Units consumed: 801
Amount charged: 801.00
Surcharges: 120.15
Amount to be paid: 921.15

Test Case - 4

User Output
Enter customer name:
Raman
Units consumed:
300
Customer name: Raman
Units consumed: 300
Amount charged: 270.00
Surcharges: 0.00
Amount to be paid: 270.00

Page No: 25
ID:
2024-2028-EEE
Narayana Engineering College - Gudur
Exp. Name: C program to find roots and nature of
Date:
quadratic equation.

Aim:

Page No: 26
Write a C program to find the roots of a quadratic equation, given its coefficients.
Source Code:

quad.c

ID:
#include<stdio.h>
#include<math.h>
void main() {
float a, b, c,real,imag, disc;
printf("Enter coefficients a, b and c: ");
scanf("%f %f %f", &a, &b, &c);
disc = b * b - 4 * a *c;

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

2024-2028-EEE
} else if ( disc ==0 ) {
double root1 = -b / ( 2 * a );
printf("root1 = %.2lf and root2 = %.2lf\n", root1, root1);
} else {
real = - b / ( 2 * a );
imag = sqrt (-disc ) / ( 2 *a );

Narayana Engineering College - Gudur


printf("root1 = %.2lf+%.2lfi and root2 = %.2lf-%.2lfi\n", real, imag, real,
imag);
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter coefficients a, b and c:
379
root1 = -1.17+1.28i and root2 = -1.17-1.28i

Test Case - 2

User Output
Enter coefficients a, b and c:
886
root1 = -0.50+0.71i and root2 = -0.50-0.71i
Exp. Name: Simulate a basic calculator Date:

Aim:
Write a program to perform basic calculator operations [+, -, *, /] of two integers a and b using switch statement.

Page No: 27
Constraints:
• 10-4 <= a,b = 104
• operations allowed are +, -, *, /
• "/" divisibility will perform integer division operation.

ID:
Input Format: The first line of the input consists of an integer which corresponds to a, character which
corresponds to the operator and an integer which corresponds to b.

Output format: Output consists of result after performing mentioned operation (a operation b).

Instruction: To run your custom test cases strictly map your input and output layout with the visible test cases.
Source Code:

calculator.c
#include<stdio.h>

2024-2028-EEE
void main()
{
int a,b,result;
char op;
scanf("%d %c %d", &a, &op, &b);
switch(op)

Narayana Engineering College - Gudur


{
case '+':

result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
}
printf("%d", result);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
36-31
5
Test Case - 2

User Output
89/45
1

Page No: 28
Test Case - 3

User Output

ID:
10000/10000
1

2024-2028-EEE
Narayana Engineering College - Gudur
Exp. Name: Write a program to find leap year or
Date:
not

Aim:

Page No: 29
Lucy is celebrating her 15th birthday. Her father promised her that he will buy her a new computer on her
birthday if she solves the question asked by him.

He asks Lucy to find whether the year on which she had born is leap year or not.

ID:
Help her to solve this puzzle so that she celebrates her birthday happily. If her birth year is 2016 and it is a leap
year display 2016 is a leap year.? Else display 2016 is not a leap year and check with other leap year conditions.
Source Code:

leapYear.c
#include<stdio.h>
void main()
{
int year;
scanf("%d",&year);
if((year %4 == 0 && year %100 != 0) || (year %400 == 0))

2024-2028-EEE
{
printf("%d is a leap year",year);
}
else
{
printf("%d is not a leap year",year);

Narayana Engineering College - Gudur


}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
1900
1900 is not a leap year

Test Case - 2

User Output
2004
2004 is a leap year

Test Case - 3

User Output
1995
1995 is not a leap year
Exp. Name: Factorial of a given number Date:

Aim:
Write a C program to find the factorial of a given number

Page No: 30
Source Code:

factorialOfInt.c
#include<stdio.h>

ID:
void main()
{
int num, fact = 1;
printf("Integer: ");
scanf("%d",&num);
for(int i = 1; i <= num; i++)
{
fact *=i;
}
printf("Factorial: %d\n",fact);
}

2024-2028-EEE
Execution Results - All test cases have succeeded!
Test Case - 1

Narayana Engineering College - Gudur


User Output
Integer:
5
Factorial: 120

Test Case - 2

User Output
Integer:
4
Factorial: 24
Exp. Name: C program to determine whether a
Date:
given number is prime or not.

Aim:

Page No: 31
Write the C program to determine whether a given number is prime or not.
Source Code:

Prime.c

ID:
#include<stdio.h>
void main()
{
int num, i, flag = 0;
printf("Enter a number: ");
scanf("%d",&num);

for(i = 2; i <= num / 2; i++)


{
if(num % i == 0)
{
flag = 1;

2024-2028-EEE
break;
}
}
if(flag == 0)
{
printf("%d is a prime number\n",num);

Narayana Engineering College - Gudur


}
else
{
printf("%d is not a prime number\n",num);
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter a number:
9
9 is not a prime number

Test Case - 2

User Output
Enter a number:
11
11 is a prime number
Exp. Name: Compute sine and cos series using
Date:
taylor series

Aim:

Page No: 32
Write a C program to compute the sine and cosine series using the Taylor series.

Taylor series:

sin x = x - (x3/3!) + (x5/5!) - (x7/7!) + .....

ID:
cos x = 1 - (x2/2!) + (x4/4!) - (x6/6!) + ....

Note: Print the result up to 4 decimal places. Use the double data type for all variables except for the number of
terms in the series, which should be an integer. Additionally, initialize the variables that will store the results of the
sine and cosine series to 0.0 at the beginning.
Source Code:

taylor.c

2024-2028-EEE
Narayana Engineering College - Gudur
#include<stdio.h>
#include<math.h>

double factorial (int n) {


if (n == 0 || n == 1) {

Page No: 33
return 1.0;
} else {
return n * factorial(n-1);
}
}

ID:
double computeSine(double x, int terms) {
double result = 0.0;
int sign = 1;
for (int n = 0; n < terms; n++) {
result += sign * pow(x, 2*n+1) / factorial(2*n+1);
sign *= -1;
}
return result;
}

double computeConsine(double x, int terms) {

2024-2028-EEE
double result = 0.0;
int sign = 1;
for (int n = 0; n < terms; n++) {
result += sign * pow(x,2*n) / factorial(2*n);
sign *= -1;
}

Narayana Engineering College - Gudur


return result;
}

int main() {
double angle;
int terms;
printf("angle in radians: ");
scanf("%lf", &angle);
printf("number of terms in the series: ");
scanf("%d", &terms);
printf("Sine = %.4lf\n", computeSine(angle, terms));
printf("Cosine = %.4lf\n", computeConsine(angle,terms));
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
angle in radians:
0.5
number of terms in the series:
3
Sine = 0.4794
Cosine = 0.8776

Test Case - 2

User Output

Page No: 34
angle in radians:
0.6
number of terms in the series:
5

ID:
Sine = 0.5646
Cosine = 0.8253

2024-2028-EEE
Narayana Engineering College - Gudur
Exp. Name: Check given number is palindrome or
Date:
not

Aim:

Page No: 35
Write an C program to check given number is palindrome or not

Input Format:
• Single Line: An integer value representing the number to be checked for palindrome status.

ID:
Output Format:
• Single Line: A message indicating whether the number is a palindrome or not. The format of the message
will be:
• "[number] is a palindrome." if the number is a palindrome.
• "[number] is not a palindrome." if the number is not a palindrome.
Source Code:

palindrome.c

#include<stdio.h>
void main() {
int num, oriNum, rev = 0;

2024-2028-EEE
scanf("%d", &num);
oriNum = num;
while ( num > 0 ) {
int digit = num % 10;
rev = rev * 10 + digit;
num /= 10;

Narayana Engineering College - Gudur


}

if ( oriNum == rev )
printf("%d is a palindrome.\n", oriNum);
else
printf("%d is not a palindrome.\n", oriNum);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
121
121 is a palindrome.

Test Case - 2

User Output
143
143 is not a palindrome.
Exp. Name: Pyramid with numbers Date:

Aim:
Write a program to print a pyramid of numbers separated by spaces for the given number of rows.

Page No: 36
At the time of execution, the program should print the message on the console as:

Enter number of rows :

ID:
For example, if the user gives the input as :

Enter number of rows : 3

then the program should print the result as:

1
1 2
1 2 3

Source Code:

2024-2028-EEE
PyramidDemo15.c

#include <stdio.h>
void main() {
int n, i, j, s;
printf("Enter number of rows : ");
scanf("%d", &n);

Narayana Engineering College - Gudur


// Fill the missing code
for ( i = 1; i <= n; i++ ) {
int space = n -i;
for ( j = 0; j < space; j++ ) {
printf(" ");
}
for ( s = 1; s <= i; s++ ) {
printf("%d ",s);
}
printf("\n");
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter number of rows :
3
1
1 2
1 2 3
Test Case - 2

User Output
Enter number of rows :
6

Page No: 37
1
1 2
1 2 3
1 2 3 4

ID:
1 2 3 4 5
1 2 3 4 5 6

Test Case - 3

User Output
Enter number of rows :
8
1
1 2

2024-2028-EEE
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8

Narayana Engineering College - Gudur


Exp. Name: Minimum and maximum in an array of
Date:
integers.

Aim:

Page No: 38
Write a C program to find the minimum and maximum in an array of integers.
Source Code:

ArrayElements.c

ID:
#include <stdio.h>
void main() {
int arr[20], number, min = 0, max = 0;
scanf("%d", &number);
printf("Elements: ");
for (int i = 0; i < number; i++) {
scanf("%d", &arr[i]);
}
/* Write your logic here to find the maximum and minimum in the given integer
array*/
min = arr[0];
for ( int i = 0; i < number; i++ ) {

2024-2028-EEE
if (min > arr[i]) {
min = arr[i];
}
if( max < arr[i]) {
max = arr[i];
}

Narayana Engineering College - Gudur


}
printf("Min an Max: %d and %d", min, max);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
5
Elements:
49682
Min an Max: 2 and 9

Test Case - 2

User Output
1
Elements:
216
Min an Max: 216 and 216
Exp. Name: Search for an element using Linear
Date:
search

Aim:

Page No: 39
Write a C program to check whether the given element is present or not in the array of elements using linear
search.
Source Code:

SearchEle.c

ID:
#include <stdio.h>
#include <stdlib.h>
void main()
{
int arr[20], n, key, found = 0, i;
printf("Enter size: ");
scanf("%d", &n);
printf("Enter %d element: ", n);
for (i = 0; i < n; i++)
scanf("%d", &arr[i]);
printf("Enter search element: ");

2024-2028-EEE
scanf("%d", &key);
for (i = 0; i < n; i++)
{
if (key == arr[i])
{
found = 1;

Narayana Engineering College - Gudur


printf("Found at position %d\n", i);
exit(0);
}
}
if (found == 0)
printf("%d is not found\n", key);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter size:
6
Enter 6 element:
248135
Enter search element:
6
6 is not found

Test Case - 2

User Output
Enter size:
6
Enter 6 element:
248135
Enter search element:

Page No: 40
2
Found at position 0

Test Case - 3

ID:
User Output
Enter size:
6
Enter 6 element:
248135
Enter search element:
9
9 is not found

2024-2028-EEE
Narayana Engineering College - Gudur
Exp. Name: C program to reverse an array. Date:

Aim:
Write a C program to reverse the elements an array of integers.

Page No: 41
Source Code:

reverseArray.c

#include <stdio.h>

ID:
void main()
{
int arr[20], n, i;
printf("Enter no of elements: ");
scanf("%d", &n);
printf("Enter elements: ");
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
printf("The reversed array: ");
for (i = n - 1; i >= 0; i--)

2024-2028-EEE
printf("%d ", arr[i]);
}

Execution Results - All test cases have succeeded!

Narayana Engineering College - Gudur


Test Case - 1

User Output
Enter no of elements:
5
Enter elements:
34124
The reversed array: 4 2 1 4 3

Test Case - 2

User Output
Enter no of elements:
8
Enter elements:
2 5 1 77 33 88 2 9
The reversed array: 9 2 88 33 77 1 5 2
Exp. Name: 2’s complement of a given Binary
Date:
number

Aim:

Page No: 42
Write a C program to find 2’s complement of a given binary number.

Note: The binary input should be separated by a space.


Source Code:

ID:
twosComplement.c
#include<stdio.h>
void onesComplement(int binary[], int n) {
for (int i =0; i < n; i++) {
if (binary[i] == 0) {
binary[i] =1;
} else if (binary[i] == 1) {
binary[i] = 0;
}
}
}

2024-2028-EEE
void addOne(int binary[], int n) {
int carry =1;
for (int i= n - 1; i > 0; i--) {
if (binary[i] ==0 && carry == 1) {
binary[i] =1;
carry = 0;

Narayana Engineering College - Gudur


} else if (binary[i] == 1 && carry ==1) {
binary[i] = 0;
carry = 1;
} else if (binary[i] == 1 && carry == 0) {
binary[i] = 1;
carry = 0;
} else if (binary[i] == 0 && carry == 0) {
binary[i] = 0;
carry = 0;
}
}
}
int main() {
int n, binary[32];
printf("Enter size: ");
scanf("%d",&n);
printf("Enter %d bit binary number: ", n);
for (int i = 0; i < n; i++)
scanf("%d", &binary[i]);
onesComplement (binary, n);
addOne (binary, n);
printf("2's complement: ");
for(int i=0;i<n;i++)
printf("%d ",binary[i]);
printf("\n");
return 0;
}
Execution Results - All test cases have succeeded!
Test Case - 1

User Output

Page No: 43
Enter size:
5
Enter 5 bit binary number:
10010

ID:
2's complement: 0 1 1 1 0

Test Case - 2

User Output
Enter size:
6
Enter 6 bit binary number:
100011
2's complement: 0 1 1 1 0 1

2024-2028-EEE
Narayana Engineering College - Gudur
Exp. Name: Eliminate duplicate elements in an
Date:
array

Aim:

Page No: 44
Write a C program to eliminate duplicate elements of an array.

Input Format:
• First Line: An integer n representing the size of the array.
• Second Line: n integers representing the elements of the array.

ID:
Output Format:
• Single Line: A space-separated list of the unique elements of the array after duplicates have been removed.
Source Code:

eliminateDuplicates.c
#include <stdio.h>
void main()
{
int a[10], i, j, k, cout = 0, number;
printf("Enter size: ");

2024-2028-EEE
scanf("%d", &number);
printf("Enter %d elements: ", number);
for (i = 0; i < number; i++)
{
scanf("%d", &a[i]);
}

Narayana Engineering College - Gudur


for (i = 0; i < number; i++)
{
for (j = i + 1; j < number; j++)
{
if (a[i] == a[j])
{
for (k = j; k < number; k++)
{
a[k] = a[k + 1];
}
j--;
number--;
}
}
}
printf("After eliminating duplicates: ");
for (i = 0; i < number; i++)
{
printf("%d ", a[i]);
}
printf("\n");
}

Execution Results - All test cases have succeeded!


Test Case - 1
User Output
Enter size:
5
Enter 5 elements:
12123

Page No: 45
After eliminating duplicates: 1 2 3

Test Case - 2

ID:
User Output
Enter size:
5
Enter 5 elements:
11 13 11 12 13
After eliminating duplicates: 11 13 12

2024-2028-EEE
Narayana Engineering College - Gudur
Exp. Name: Addition of Two Matrices Date:

Aim:
Write a C program to perform the addition of two matrices.

Page No: 46
Input Format:
The first line contains two space separated integers, row & col, representing the number of rows and columns of
each matrix
The second line contains row * col number of space separated integers representing the elements of matrix 1

ID:
The last line contains row * col number of space separated integers representing the elements of matrix 2

Output Format:
row number of lines with col number of space separated elements representing the elements of sum matrix

Note: Addition of two matrices can only be done when the dimensions of both matrices are same, so we are
taking the same dimensions for both matrices.
Source Code:

addTwoMatrices.c
#include <stdio.h>

2024-2028-EEE
void main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
printf("Enter no of rows, columns: ");
scanf("%d%d", &m, &n);
printf("Elements of matrix 1: ");

Narayana Engineering College - Gudur


for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Elements of matrix 2: ");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &second[c][d]);
printf("Addition of matrices:\n");
for (c = 0; c < m; c++)
{
for (d = 0; d < n; d++)
{
sum[c][d] = first[c][d] + second[c][d];
printf("%d ", sum[c][d]);
}
printf("\n");
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter no of rows, columns:
12
Elements of matrix 1:
12
Elements of matrix 2:
98
Addition of matrices:

Page No: 47
10 10

Test Case - 2

ID:
User Output
Enter no of rows, columns:
23
Elements of matrix 1:
123456
Elements of matrix 2:
987654
Addition of matrices:
10 10 10
10 10 10

2024-2028-EEE
Narayana Engineering College - Gudur
Exp. Name: Multiplication of two matrices Date:

Aim:
Write a C program to find the multiplication of two matrices

Page No: 48
Input Format:
• First line contains an integer r and an integer c, representing the number of rows and columns
• Next r rows contains c number of integers representing the elements of the matrix1
• Repeat the Same for matrix2

ID:
Output Format:
• Prints the matrix1 and matrix2 and finally the result of multiplication of both the matrices

Note: For more clarification refer to the shown test cases


Source Code:

matrixMul.c

2024-2028-EEE
Narayana Engineering College - Gudur
#include<stdio.h>
#include<stdlib.h>
int main()
{
int r1,r2,c1,c2,m1[10][10],m2[10][10],i,j,k;

Page No: 49
printf("no of rows, columns of matrix1: ");
scanf("%d%d",&r1,&c1);
printf("matrix1 elements:\n");
for (i = 0;i < r1; i++) {

ID:
for(j = 0; j < c1; j++) {
scanf("%d",&m1[i][j]);
}
}

printf("no of rows, columns of matrix2: ");


scanf("%d%d",&r2,&c2);
printf("matrix2 elements:\n");
for (i = 0;i < r2; i++) {
for (j = 0; j < c2; j++) {
scanf("%d", &m2[i][j]);
}

2024-2028-EEE
}
printf("Given matrix1:\n");
for (i = 0;i <r1; i++) {
for (j = 0;j <c1; j++) {
printf("%d ", m1[i][j]);
}

Narayana Engineering College - Gudur


printf("\n");
}
printf("Given matrix2:\n");
for (i = 0;i < r2; i++) {
for (j = 0;j < c2; j++){
printf("%d ",m2[i][j]);
}
printf("\n");
}
if(c1 != r2) {
printf("Multiplication not possible\n");
exit(-1);
}
int mul[r1][c2];
for (i =0; i < r1; i++) {
for (j =0; j< c2; j++) {
mul[i][j] = 0;
for ( k = 0; k < c1; k++) {
mul[i][j] += m1[i][k] * m2[k][j];
}
}
}
printf("Multiplication of two matrices:\n");

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


for (j = 0; j < c2; j++) {
printf("%d ",mul[i][j]);
}

return 0;
}

Page No: 50
Execution Results - All test cases have succeeded!
Test Case - 1

ID:
User Output
no of rows, columns of matrix1:
22
matrix1 elements:
11 22
33 44
no of rows, columns of matrix2:
22
matrix2 elements:

2024-2028-EEE
11 22
33 44
Given matrix1:
11 22
33 44

Narayana Engineering College - Gudur


Given matrix2:
11 22
33 44
Multiplication of two matrices:
847 1210
1815 2662

Test Case - 2

User Output
no of rows, columns of matrix1:
33
matrix1 elements:
123
456
789
no of rows, columns of matrix2:
23
matrix2 elements:
123
456
Given matrix1:
1 2 3
4 5 6
4 5 6
1 2 3
7 8 9
Given matrix2:

Multiplication not possible

Narayana Engineering College - Gudur 2024-2028-EEE ID: Page No: 51


Exp. Name: Write a C program to Sort given
Date:
elements using Bubble sort

Aim:

Page No: 52
Develop an algorithm, implement and execute a C program that reads n integer numbers and arrange them in
ascending order using Bubble Sort.
Source Code:

Lab7.c

ID:
#include <stdio.h>
void main()
{
int a[10];
int i, j, num, temp;
scanf("%d", &num);
printf("Elements: ");
for (i = 0; i < num; i++)
{
scanf("%d", &a[i]);
}

2024-2028-EEE
printf("Before sorting: ");
for (i = 0; i < num; i++)
{
printf("%d ", a[i]);
}
/* Bubble sorting begins */

Narayana Engineering College - Gudur


for (i = 0; i < num; i++)
{
for (j = 0; j < (num - i - 1); j++)
{
if (a[j] > a[j + 1])
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
printf("\nAfter sorting: ");
for (i = 0; i < num; i++)
{
printf("%d ", a[i]);
}
printf("\n");
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
4
Elements:
44 22 66 11
Before sorting: 44 22 66 11
After sorting: 11 22 44 66

Page No: 53
Test Case - 2

User Output
5

ID:
Elements:
92716
Before sorting: 9 2 7 1 6
After sorting: 1 2 6 7 9

2024-2028-EEE
Narayana Engineering College - Gudur
Exp. Name: Concatenate two given strings without
Date:
using string library functions

Aim:

Page No: 54
Write a program to concatenate two given strings without using string library functions.

At the time of execution, the program should print the message on the console as:

string1 :

ID:
For example, if the user gives the input as:

string1 : ILove

Next, the program should print the message on the console as:

string2 :

For example, if the user gives the input as:

string2 : Coding

2024-2028-EEE
then the program should print the result as:

concatenated string = ILoveCoding

Note: Do use the printf() function with a newline character ( \n ) at the end.

Narayana Engineering College - Gudur


Source Code:

Program605.c
#include <stdio.h>
int main() {
char string1[100], string2[100];
int i, j;
printf("string1 : ");
scanf("%s", string1);
printf("string2 : ");
scanf("%s", string2);
for (i = 0; string1[i] != '\0'; ++i);
for (j = 0; string2[j] != '\0'; ++j, ++i) {
string1[i] = string2[j];
}
string1[i] = '\0';
printf("concatenated string = %s\n", string1);
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
string1 :
ILove
string2 :
Coding
concatenated string = ILoveCoding

Page No: 55
Test Case - 2

User Output

ID:
string1 :
1234
string2 :
567
concatenated string = 1234567

2024-2028-EEE
Narayana Engineering College - Gudur
Exp. Name: Reverse the given string without using
Date:
the library functions

Aim:

Page No: 56
Write a program to reverse the given string without using the library functions.

At the time of execution, the program should print the message on the console as:

Enter a string :

ID:
For example, if the user gives the input as:

Enter a string : Dallas

then the program should print the result as:

Reverse string : sallaD

Note: Do use the printf() function with a newline character ( \n ) at the end.
Source Code:

2024-2028-EEE
Program609.c
#include<stdio.h>
void reverseString(char *str){
int length = 0;
while (str[length] != '\0') {

Narayana Engineering College - Gudur


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

int main(){
char str[100];
printf("Enter a string : ");
scanf("%[^\n]s", str);
reverseString(str);
printf("Reverse string : %s\n", str);
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter a string :
Dallas
Reverse string : sallaD

Narayana Engineering College - Gudur 2024-2028-EEE ID: Page No: 57


Exp. Name: Write a C program to find Sum of array
elements by allocating memory using malloc() Date:
function

Page No: 58
Aim:
Write a program to find the sum of n elements by allocating memory by using malloc() function.

Note: Write the functions allocateMemory(), read1() and sum() in UsingMalloc.c

ID:
Source Code:

SumOfArray1.c

#include <stdio.h>
#include <stdlib.h>
#include "UsingMalloc.c"
void main() {
int *p, n, i;
printf("Enter n value : ");
scanf("%d", &n);
p = allocateMemory(n);
printf("Enter %d values : ", n);

2024-2028-EEE
read1(p, n);
printf("The sum of given array elements : %d\n", sum(p, n));
}

Narayana Engineering College - Gudur


UsingMalloc.c
#include <stdio.h>
#include <stdlib.h>
int *allocateMemory(int n) {
int *arr = (int *)malloc(n * sizeof(int));
return arr;
}
void read1(int *arr, int n) {
for (int i = 0; i < n; i++) {
scanf("%d",&arr[i]);
}
}
int sum(int *arr, int n) {
int total = 0;
for (int i = 0; i < n; i++) {
total += arr[i];
}
return total;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter n value :
3
Enter 3 values :
10 20 30
The sum of given array elements : 60

Page No: 59
Test Case - 2

User Output

ID:
Enter n value :
4
Enter 4 values :
-5 -6 -4 -2
The sum of given array elements : -17

2024-2028-EEE
Narayana Engineering College - Gudur
Exp. Name: Write a program to find Total and
Average gained by Students in a Section using Date:
Array of Structures

Page No: 60
Aim:
Write a C program to find out the total and average marks gained by the students in a section using array of
structures.

ID:
Note: Consider that regdno, marks of 3 subjects, total and average are the members of a structure and make sure
to provide the int value for number of students which are lessthan 60

Sample Input and Output:

Enter number of students : 3


Enter regdno, three subjects marks of student-0: 101 56 78 76
Enter regdno, three subjects marks of student-1: 201 76 89 91
Enter regdno, three subjects marks of student-2: 301 46 57 61
Student-0 Regdno = 101 Total marks = 210 Average marks = 70.000000
Student-1 Regdno = 201 Total marks = 256 Average marks = 85.333336
Student-2 Regdno = 301 Total marks = 164 Average marks = 54.666668

2024-2028-EEE
Source Code:

ArrayOfStructures2.c

Narayana Engineering College - Gudur


#include <stdio.h>
struct student
{
// Write the members of structure
int rollno,tot;

Page No: 61
char name[25];
int mark[5];
float avg;
};

ID:
void main()
{
struct student s[60];
int i,j, n;
printf("Enter number of students : ");
scanf("%d", &n);
for (i=0;i<n;i++ )
{ // Complete the code in for
printf("Enter regdno, three subjects marks of student-%d: ", i);
scanf("%d",&s[i].rollno);
for(j=0;j<3;j++)
scanf("%d",&s[i].mark[j]);

2024-2028-EEE
}
for (i=0;i<n;i++)
{ // Complete the code in for
// Find Total and Average
s[i].tot=0;
for(j=0;j<3;j++)

Narayana Engineering College - Gudur


s[i].tot = s[i].tot+ s[i].mark[j];
s[i].avg=(float)s[i].tot/3;
printf("Student-%d Regdno = %d\tTotal marks = %d\tAverage marks =
%f\n",i,s[i].rollno,s[i].tot,s[i].avg ); // Fill the code in printf()
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter number of students :
3
Enter regdno, three subjects marks of student-0:
101 56 78 76
Enter regdno, three subjects marks of student-1:
201 76 89 91
Enter regdno, three subjects marks of student-2:
301 46 57 61
Student-0 Regdno = 101 Total marks = 210 Average marks = 70.000000
Student-1 Regdno = 201 Total marks = 256 Average marks = 85.333336
Student-2 Regdno = 301 Total marks = 164 Average marks = 54.666668
Test Case - 2

User Output
Enter number of students :
10

Page No: 62
Enter regdno, three subjects marks of student-0:
501 23 45 67
Enter regdno, three subjects marks of student-1:
502 78 65 76

ID:
Enter regdno, three subjects marks of student-2:
503 99 87 67
Enter regdno, three subjects marks of student-3:
504 89 78 82
Enter regdno, three subjects marks of student-4:
505 37 59 76
Enter regdno, three subjects marks of student-5:
506 78 59 67
Enter regdno, three subjects marks of student-6:
507 92 72 82

2024-2028-EEE
Enter regdno, three subjects marks of student-7:
508 45 47 48
Enter regdno, three subjects marks of student-8:
509 55 52 59
Enter regdno, three subjects marks of student-9:

Narayana Engineering College - Gudur


510 62 61 66
Student-0 Regdno = 501 Total marks = 135 Average marks = 45.000000
Student-1 Regdno = 502 Total marks = 219 Average marks = 73.000000
Student-2 Regdno = 503 Total marks = 253 Average marks = 84.333336
Student-3 Regdno = 504 Total marks = 249 Average marks = 83.000000
Student-4 Regdno = 505 Total marks = 172 Average marks = 57.333332
Student-5 Regdno = 506 Total marks = 204 Average marks = 68.000000
Student-6 Regdno = 507 Total marks = 246 Average marks = 82.000000
Student-7 Regdno = 508 Total marks = 140 Average marks = 46.666668
Student-8 Regdno = 509 Total marks = 166 Average marks = 55.333332
Student-9 Regdno = 510 Total marks = 189 Average marks = 63.000000

Test Case - 3

User Output
Enter number of students :
5
Enter regdno, three subjects marks of student-0:
101 76 78 73
Enter regdno, three subjects marks of student-1:
102 89 57 68
Enter regdno, three subjects marks of student-2:
103 77 67 59
Enter regdno, three subjects marks of student-3:
104 37 47 52
Enter regdno, three subjects marks of student-4:
105 88 47 69
Student-0 Regdno = 101 Total marks = 227 Average marks = 75.666664
Student-1 Regdno = 102 Total marks = 214 Average marks = 71.333336

Page No: 63
Student-2 Regdno = 103 Total marks = 203 Average marks = 67.666664
Student-3 Regdno = 104 Total marks = 136 Average marks = 45.333332
Student-4 Regdno = 105 Total marks = 204 Average marks = 68.000000

ID:
2024-2028-EEE
Narayana Engineering College - Gudur
Exp. Name: Write a Program to enter n students
Date:
data using calloc() and display Failed Students List

Aim:

Page No: 64
Write a C program to enter n students' data using calloc() and display the students list.

Note: If marks are less than 35 in any subject, the student will fail
Source Code:

ID:
FailedList.c

#include <stdio.h>
#include <stdlib.h>
struct student {
int roll;
int marks[6], sum;
float avg;
};
#include "FailedList1.c"
void main() {
struct student *s;

2024-2028-EEE
int i, n;
printf("Enter the number of students : ");
scanf("%d", &n);
s = allocateMemory(s, n);
read1(s, n);
calculateMarks(s, n);

Narayana Engineering College - Gudur


displayFailedList(s, n);
}

FailedList1.c
struct student* allocateMemory(struct student *s, int n) {
// Write the code
s = (struct student*)calloc(n, sizeof(struct student));
if (s == NULL) {
printf("Memory allocation failed\n");

Page No: 65
exit(1);
}
return s;
}
void read1(struct student *s, int n) {

ID:
// write the code
int i, j;
for (i = 0; i < n; i++) {
printf("Enter the details of student - %d\n", i + 1);
printf("Enter the roll number : ");
scanf("%d", &s[i].roll);
printf("Enter 6 subjects marks : ");
for (j = 0; j < 6; j++) {
scanf("%d", &s[i].marks[j]);
}
}
}

2024-2028-EEE
void calculateMarks(struct student *s, int n) {
// write the code
int i, j;
for (i = 0; i < n; i++) {
s[i].sum = 0;
for (j = 0; j < 6; j++) {

Narayana Engineering College - Gudur


s[i].sum += s[i].marks[j];
}
s[i].avg = (float)s[i].sum / 6;
}
}
void displayFailedList(struct student *s, int n) {
int i,j;
printf("RollNo\tTotalMarks\tAverageMarks\tStatus\n");
for (i = 0; i < n; i++) {
printf("%d\t", s[i].roll); // Fill the missing code
printf("%d\t", s[i].sum); // Fill the missing code
printf("%f\t", s[i].avg); // Fill the missing code
for (j = 0; j < 6;j++) {
if (s[i].marks[j] < 35) {
printf("Fail\n");
break;
}
}
if (j == 6) {
printf("Pass\n");
}
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter the number of students :
3

Page No: 66
Enter the details of student - 1
Enter the roll number :
101
Enter 6 subjects marks :

ID:
45 67 58 36 59 63
Enter the details of student - 2
Enter the roll number :
102
Enter 6 subjects marks :
34 56 98 39 78 89
Enter the details of student - 3
Enter the roll number :
103
Enter 6 subjects marks :

2024-2028-EEE
35 67 89 98 76 56
RollNo TotalMarks AverageMarks Status
101 328 54.666668 Pass
102 394 65.666664 Fail
103 421 70.166664 Pass

Narayana Engineering College - Gudur


Test Case - 2

User Output
Enter the number of students :
2
Enter the details of student - 1
Enter the roll number :
1001
Enter 6 subjects marks :
26 57 68 67 67 65
Enter the details of student - 2
Enter the roll number :
1002
Enter 6 subjects marks :
58 67 58 89 87 76
RollNo TotalMarks AverageMarks Status
1001 350 58.333332 Fail
1002 435 72.500000 Pass
Exp. Name: Write a C program to find Total Marks
Date:
of a Student using Command-line arguments

Aim:

Page No: 67
Write a C program to read student name and 3 subjects marks from the command line and display the student
details along with total.

Sample Input and Output - 1:

ID:
If the arguments passed as $./TotalMarksArgs.c Sachin 67 89 58 , then the program should
print the output as:
Cmd Args : Sachin 67 89 58
Student name : Sachin
Subject-1 marks : 67
Subject-1 marks : 89
Subject-1 marks : 58
Total marks : 214

Sample Input and Output - 2:

If the arguments passed as $./TotalMarksArgs.c Johny 45 86 57 48 , then the program should

2024-2028-EEE
print the output as:
Cmd Args : Johny 45 86 57 48
Arguments passed through command line are not equal to 4

Hint : atoi() is a library function that converts string to integer. When program gets the input from command
line, string values transfer in the program, we have to convert them to integers. atoi() is used to return the

Narayana Engineering College - Gudur


integer of the string arguments.
Source Code:

TotalMarksArgs.c
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc != 5) {
printf("Arguments passed through command line are not equal to 4\n");

Page No: 68
return 1;

}
char *name = argv[1];
int marks1 = atoi(argv[2]);

ID:
int marks2 = atoi(argv[3]);
int marks3 = atoi(argv[4]);

// Print student name and marks for each subject


printf("Student name : %s\n", name);
printf("Subject-1 marks : %d\n", marks1);
printf("Subject-2 marks : %d\n", marks2);
printf("Subject-3 marks : %d\n", marks3);

// Calculate total marks


int totalMarks = marks1 + marks2 +marks3;
printf("Total marks : %d\n", totalMarks);

2024-2028-EEE
return 0;
}

Execution Results - All test cases have succeeded!

Narayana Engineering College - Gudur


Test Case - 1

User Output
Student name : Sachin
Subject-1 marks : 67
Subject-2 marks : 89
Subject-3 marks : 58
Total marks : 214

Test Case - 2

User Output
Arguments passed through command line are not equal to 4
Exp. Name: Write a C program to implement
Date:
realloc()

Aim:

Page No: 69
Write a C program to implement realloc() .

The process is
1. Allocate memory of an array with size 2 by using malloc()
2. Assign the values 10 and 20 to the array

ID:
3. Reallocate the size of the array to 3 by using realloc()
4. Assign the value 30 to the newly allocated block
5. Display all the 3 values
Source Code:

ProgramOnRealloc.c

#include <stdio.h>
#include <stdlib.h> /*
int main() {
int *ptr = (int *)malloc(sizeof(int) * 2);
int i;

2024-2028-EEE
int *ptr_new;
*ptr = 10;
*(ptr + 1) = 20;
// Reallocate the *ptr size to 3
//Assign the value 30 to newly allocated memory
for (i = 0; i < 3; i++)

Narayana Engineering College - Gudur


printf("%d ", *(ptr_new + i));
} */
int main()
{
int *ptr=malloc(sizeof(int)*2);
if(!ptr)
{

printf("Memory allocation failed.\n");


return 1;
}ptr[0]=10,ptr[1]=20;
ptr=realloc(ptr,sizeof(int)*3);if(!ptr)
{
printf("Memory reallocation failed.\n");
return 1;
}
ptr[2]=30;
printf("%d %d %d ",ptr[0],ptr[1],ptr[2]);
free(ptr);
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1
10 20 30
User Output

Narayana Engineering College - Gudur 2024-2028-EEE ID: Page No: 70


Exp. Name: Write a C Program to store information
Date:
using Structures with DMA

Aim:

Page No: 71
Write a program to create a list of nodes using self-referential structure and print that data.

At the time of execution, the program should print the message on the console as:

Enter an integer value :

ID:
For example, if the user gives the input as:

Enter an integer value : 10

Next, the program should print the message on the console as:

Do u want another list (y|n) :

if the user gives the input as:

Do u want another list (y|n) : y

2024-2028-EEE
The input to the list is continued up to the user says n (No)

For example, if the user gives the input as:

Enter an integer value : 20

Narayana Engineering College - Gudur


Do u want another list (y|n) : y
Enter an integer value : 30
Do u want another list (y|n) : n

Finally, the program should print the result on the console as:

The elements in the single linked lists are : 10-->20-->30-->NULL

Note: Write the functions create() and display() in CreateNodes.c .


Source Code:

StructuresWithDma.c
#include <stdio.h>
#include <stdlib.h>
struct list {
int data;
struct list *next;
};
#include "CreateNodes.c"
void main() {
struct list *first = NULL;
first = create(first);
printf("The elements in the single linked lists are : ");
display(first);
}
CreateNodes.c
struct list* create(struct list *first) {
char op;
struct list *q, *temp;
do {

Page No: 72
temp = (struct list*)malloc(sizeof(struct list)) ; // Allocate memory
printf("Enter an integer value : ");
scanf("%d", &temp->data); // Read data
temp -> next = NULL; // Place NULL
if (first == NULL) {

ID:
first = temp; // Assign temp to the first node
} else {
q -> next = temp; // Create a link from the last node to new node
temp
}
q = temp;
printf("Do u want another list (y|n) : ");
scanf(" %c", &op);
} while(op == 'y' || op == 'Y');
return first;
}
void display(struct list *first) {

2024-2028-EEE
struct list *temp = first;
while ( temp != NULL ) { // Stop the loop where temp is NULL
printf("%d-->", temp->data);
temp = temp -> next; // Assign next of temp to temp
}
printf("NULL\n");

Narayana Engineering College - Gudur


}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter an integer value :
10
Do u want another list (y|n) :
y
Enter an integer value :
20
Do u want another list (y|n) :
y
Enter an integer value :
30
Do u want another list (y|n) :
n
The elements in the single linked lists are : 10-->20-->30-->NULL
Exp. Name: Write a C program to demonstrate the
Date:
differences between Structures and Unions

Aim:

Page No: 73
Write a C program to demonstrate the differences between structures and unions .

The process is
6. Create a structure student-1 with members rollno, m1, m2, m3, total of int type and avg of float type
7. Read rollno, m1, m2 and m3 of student-1

ID:
8. Find and display total and average marks of student-1
9. Display the size of struct student-1
10. Create a union student-2 with members rollno, m1, m2, m3, total of int type and avg of float type
11. Read rollno, m1, m2 and m3 of student-2
12. Find and display total and average marks of student-2
13. Display the size of union student-2
Sample Input and Output:

Enter rollno and 3 subjects marks of student - 1 : 101 76 58 67


Total and average marks of student - 1 : 201 67.000000
Size of struct student - 1 : 24
Enter rollno of student - 2 : 102

2024-2028-EEE
Enter first subject marks of student - 2 : 76
Enter second subject marks of student - 2 : 87
Enter third subject marks of student - 2 : 69
Total marks of student - 2 : 232
Average marks of student - 2 : 77.333336
Size of union student - 2 : 4

Narayana Engineering College - Gudur


Source Code:

StructureAndUnion.c
#include <stdio.h>
struct student1 {
int rollno;
int m1, m2, m3, total;
float avg;

Page No: 74
};
union student2 {
int rollno;
int m1, m2, m3, total;
float avg;

ID:
};
void main() {
union student2 u;
struct student1 s;
int sum = 0;
printf("Enter rollno and 3 subjects marks of student - 1 : ");
scanf("%d%d%d%d", &s.rollno, &s.m1, &s.m2, &s.m3);
s.total = s.m1 + s.m2 + s.m3;
s.avg = s.total/3.0;
printf("Total and average marks of student - 1 : %d %f\n", s.total, s.avg);
printf("Size of struct student - 1 : %zu\n", sizeof(struct student1));

2024-2028-EEE
printf("Enter rollno of student - 2 : ");
scanf("%d", &u.rollno);
printf("Enter first subject marks of student - 2 : ");
scanf("%d", &u.m1);
sum = u.m1;
printf("Enter second subject marks of student - 2 : ");

Narayana Engineering College - Gudur


scanf("%d", &u.m2);
sum = sum + u.m2;
printf("Enter third subject marks of student - 2 : ");
scanf("%d", &u.m3);
sum = sum + u.m3;
u.total = sum;
printf("Total marks of student - 2 : %d\n", u.total);
u.avg = u.total/3.0;
printf("Average marks of student - 2 : %f\n", u.avg);
printf("Size of union student - 2 : %zu\n", sizeof(union student2));
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter rollno and 3 subjects marks of student - 1 :
101 76 58 67
Total and average marks of student - 1 : 201 67.000000
Size of struct student - 1 : 24
Enter rollno of student - 2 :
102
Enter first subject marks of student - 2 :
76
Enter second subject marks of student - 2 :
87
Enter third subject marks of student - 2 :
69
Total marks of student - 2 : 232

Page No: 75
Average marks of student - 2 : 77.333336
Size of union student - 2 : 4

Test Case - 2

ID:
User Output
Enter rollno and 3 subjects marks of student - 1 :
105 66 65 68
Total and average marks of student - 1 : 199 66.333336
Size of struct student - 1 : 24
Enter rollno of student - 2 :
106
Enter first subject marks of student - 2 :
88

2024-2028-EEE
Enter second subject marks of student - 2 :
89
Enter third subject marks of student - 2 :
79
Total marks of student - 2 : 256

Narayana Engineering College - Gudur


Average marks of student - 2 : 85.333336
Size of union student - 2 : 4

Test Case - 3

User Output
Enter rollno and 3 subjects marks of student - 1 :
501 76 85 84
Total and average marks of student - 1 : 245 81.666664
Size of struct student - 1 : 24
Enter rollno of student - 2 :
502
Enter first subject marks of student - 2 :
99
Enter second subject marks of student - 2 :
57
Enter third subject marks of student - 2 :
69
Total marks of student - 2 : 225
Average marks of student - 2 : 75.000000
Size of union student - 2 : 4

Test Case - 4
User Output
Enter rollno and 3 subjects marks of student - 1 :
201 75 46 59
Total and average marks of student - 1 : 180 60.000000
Size of struct student - 1 : 24

Page No: 76
Enter rollno of student - 2 :
201
Enter first subject marks of student - 2 :
66

ID:
Enter second subject marks of student - 2 :
57
Enter third subject marks of student - 2 :
61
Total marks of student - 2 : 184
Average marks of student - 2 : 61.333332
Size of union student - 2 : 4

2024-2028-EEE
Narayana Engineering College - Gudur
Exp. Name: Demonstrate left shift operation Date:

Aim:
Write a C program to demonstrate left shift operation

Page No: 77
Source Code:

shift.c
#include <stdio.h>

ID:
void printBinary(int num) {
if (num == 0) {
printf("0");
return;

}
int binary[32];
int i = 0;
while (num > 0) {
binary[i] = num %2;
num = num / 2;
i++;

2024-2028-EEE
}
for (int j = i - 1; j >= 0; j--) {
printf("%d", binary[j]);
}
}

int main() {

Narayana Engineering College - Gudur


int number, shift;
printf("Enter an integer: ");
scanf("%d",&number);
printf("Original value: ");
printBinary(number);
printf("\n");
printf("number of bits to left shift: ");
scanf("%d", &shift);
int result = number << shift;
printf("After left shift: %d\n", result);
printf("Binary representation:");
printBinary(result);
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter an integer:
12
Original value: 1100
number of bits to left shift:
2
After left shift: 48
Binary representation:110000

Test Case - 2

Page No: 78
User Output
Enter an integer:
5

ID:
Original value: 101
number of bits to left shift:
3
After left shift: 40
Binary representation:101000

2024-2028-EEE
Narayana Engineering College - Gudur
Exp. Name: Copy the contents of one structure
Date:
variable to another structure variable

Aim:

Page No: 79
Write a C program to Copy the contents of one structure variable to another structure variable.

Let us consider a structure student, containing name, age and height fields.

Declare two structure variables to the structure student, read the contents of one structure variable and copy the

ID:
same to another structure variable, finally display the copied data.

Note: Driver code is provided to you in the CopyStructureMain.c file. You need to fill the missing code in
CopyStructureFunctions.c
Source Code:

CopyStructureMain.c
#include <stdio.h>
#include "CopyStructureFunctions.c"

int main() {

2024-2028-EEE
struct student s1, s2;
read1(&s1);
s2 = copyStructureVariable(s1, s2);
display1(s2);
}

Narayana Engineering College - Gudur


CopyStructureFunctions.c
struct student {
//write the code
char name[20];
int age;
float height;

Page No: 80
}s;

void read1(struct student *p) {


printf("Enter student name, age and height: ");
// Write the code to take inputs to structure

ID:
scanf("%s %d %f", p->name, &p->age, &p->height);

struct student copyStructureVariable(struct student s1, struct student s2) {


//write your code here to copy the structure
s2 = s1;
return s2;

void display1(struct student s) {

2024-2028-EEE
//write your code here to display the structure data
printf("Student name: %s\n", s.name);
printf("Age: %d\n", s.age);
printf("Height: %f\n", s.height);
}

Narayana Engineering College - Gudur


Execution Results - All test cases have succeeded!
Test Case - 1

User Output
Enter student name, age and height:
Yamuna 19 5.2
Student name: Yamuna
Age: 19
Height: 5.200000

Test Case - 2

User Output
Enter student name, age and height:
Kohli 21 5.11
Student name: Kohli
Age: 21
Height: 5.110000
Exp. Name: Write a C Program to find nCr using
Date:
Factorial recursive function

Aim:

Page No: 81
Draw the flowchart and write a recursive C function to find the factorial of a number, n! , defined by fact(n) = 1,
if n = 0. Otherwise fact(n) = n * fact(n-1).

Using this function, write a C program to compute the binomial coefficient ncr . Tabulate the results for different

ID:
values of n and r with suitable messages.

At the time of execution, the program should print the message on the console as:

Enter the values of n and r :

For example, if the user gives the input as:

Enter the values of n and r : 4 2

then the program should print the result as:

The value of 4c2 = 6

2024-2028-EEE
If the input is given as 2 and 5 then the program should print the result as:

Enter valid input data

Note: Write the recursive function factorial() in Lab14a.c .

Narayana Engineering College - Gudur


Source Code:

Lab14a.c
int factorial(int n)
{
if(n)
return(n * factorial(n-1));
else
return 1;
}

Lab14.c
#include <stdio.h>
#include "Lab14a.c"
void main() {
int n, r;
printf("Enter the values of n and r : ");
scanf("%d %d", &n, &r);
if (n >= r)
printf("The value of %dc%d = %d\n", n, r, factorial(n) / (factorial(r) *
factorial(n - r)));
else
printf("Enter valid input data\n");
}
Execution Results - All test cases have succeeded!
Test Case - 1

User Output

Page No: 82
Enter the values of n and r :
10 4
The value of 10c4 = 210

ID:
Test Case - 2

User Output
Enter the values of n and r :
79
Enter valid input data

Test Case - 3

User Output

2024-2028-EEE
Enter the values of n and r :
52
The value of 5c2 = 10

Narayana Engineering College - Gudur


Exp. Name: Write a Program to find the Length of a
Date:
String

Aim:

Page No: 83
Write a C program to find the length of a given string.

Sample Input and Output - 1:

Enter the string : CodeTantra

ID:
Length of CodeTantra : 10

Source Code:

StrLength.c
#include <stdio.h>
#include "StrLength1.c"
void main() {
char str[30];
printf("Enter the string : ");
scanf("%s", str);

2024-2028-EEE
printf("Length of %s : %d\n", str, myStrLen(str));
}

StrLength1.c

Narayana Engineering College - Gudur


unsigned int myStrLen(const char *s)
{
unsigned int count = 0;
while(*s!='\0')
{
count++;
s++;
}
return count;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter the string :
CodeTantra
Length of CodeTantra : 10

Test Case - 2

User Output
Enter the string :
IndoUsUk
Length of IndoUsUk : 8

Test Case - 3

Page No: 84
User Output
Enter the string :
MalayalaM
Length of MalayalaM : 9

ID:
Test Case - 4

User Output
Enter the string :
Oh!MyGod
Length of Oh!MyGod : 8

2024-2028-EEE
Narayana Engineering College - Gudur
Exp. Name: Transpose using functions. Date:

Aim:
Write a C program to print the transpose of a matrix using functions.

Page No: 85
Input Format
• First Line: The user will input the number of rows for the matrix.
• Second Line: The user will input the number of columns for the matrix.
• Subsequent Lines: The user will input the matrix elements row by row.

ID:
Output Format
• First Line: The program will print the matrix in its original form.
• Second Line: The program will print the transpose of the matrix.
Source Code:

transpose.c

2024-2028-EEE
Narayana Engineering College - Gudur
#include <stdio.h>
int rows=5, cols=5;
//write your code..
void readMatrix(int matrix[100] [100])
{

Page No: 86
printf("Elements:\n");
for (int i =0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{

ID:
scanf("%d", &matrix[i][j]);
}
}
}

void printMatrix(int matrix[100][100])


{
printf("Matrix:\n");
for (int i =0; i <rows; i++) {
for (int j = 0; j <cols; j++) {
printf("%d ", matrix[i][j]);
}

2024-2028-EEE
printf("\n");
}
}

void transposeMatrix(int matrix[100][100])


{

Narayana Engineering College - Gudur


printf("Transpose:\n");
for (int i = 0; i < cols; i++) {
for (int j =0; j < rows; j++) {
printf("%d ", matrix[j][i]);
}
printf("\n");
}
}
int main() {
printf("rows: ");
scanf("%d", &rows);
printf("columns: ");
scanf("%d", &cols);
int matrix[rows][cols];

// Input: Read the matrix elements


readMatrix(matrix);

// Print the original matrix


printMatrix(matrix);

// Print the transpose of the matrix


transposeMatrix(matrix);

return 0;
}
Execution Results - All test cases have succeeded!
Test Case - 1

User Output

Page No: 87
rows:
2
columns:
2

ID:
Elements:
89
65
Matrix:
8 9
6 5
Transpose:
8 6
9 5

2024-2028-EEE
Test Case - 2

User Output
rows:
1
columns:

Narayana Engineering College - Gudur


2
Elements:
69
Matrix:
6 9
Transpose:
6
9
Exp. Name: Demonstrate numerical integration of
Date:
differential equations using Euler’s method

Aim:

Page No: 88
Write a C function to demonstrate the numerical integration of differential equations using Euler’s method.

Your program should prompt the user to input the initial value of y (yo)the initial value of t (to) the step size
(h).and the end value fort. Implement the Euler's method in a function, and print the values oft andy at each step.

ID:
The formula for Euler's Method:

ynext= y + h * f(y ,t)


wheref(y, t) is the derivative function representing dy/dtin the given Ordinary differential equation.

Note: print the values of t and y up to 2 decimal places.

Source Code:

euler.c

2024-2028-EEE
Narayana Engineering College - Gudur
#include <stdio.h>
//write your code...
// Define the differential equation function f(y, t)
double f(double y, double t) {
return t * y;

Page No: 89
// Example: dy/dt = t*y
}
// Euler's method for numerical integration
void eulerIntegration( double y0, double t0, double h, double endValue ) {
double y = y0;

ID:
double t = t0;
while (t < endValue)
{
printf("t = %.2lf y = %.2lf\n", t, y);
double y_next= y + h * f(y, t);
t += h;
y = y_next;
if (t + h > endValue) {
h = endValue - t;
}
}
}

2024-2028-EEE
int main() {
double y0, t0, h, endValue;
printf("initial value of y (y0): ");
scanf("%lf", &y0);
printf("initial value of t (t0): ");
scanf("%lf", &t0);

Narayana Engineering College - Gudur


printf("step size (h): ");
scanf("%lf", &h);
printf("end value for t: ");
scanf("%lf", &endValue);
eulerIntegration(y0, t0, h, endValue);
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
initial value of y (y0):
1
initial value of t (t0):
1
step size (h):
3
end value for t:
10
t = 1.00 y = 1.00
t = 4.00 y = 4.00
t = 7.00 y = 52.00
Test Case - 2

User Output
initial value of y (y0):
1

Page No: 90
initial value of t (t0):
1
step size (h):
3

ID:
end value for t:
3
t = 1.00 y = 1.00

2024-2028-EEE
Narayana Engineering College - Gudur
Exp. Name: Fibonacci series up to the given number
Date:
of terms using Recursion

Aim:

Page No: 91
Write a program to display the fibonacci series up to the given number of terms using recursion process.
Source Code:

fibonacciSeries.c

ID:
#include <stdio.h>
#include "fibonacciSeriesa.c"
void main() {
int n, i;
printf("n: ");
scanf("%d", &n);
printf("%d terms: ", n);
for (i = 0; i < n; i++) {
printf("%d ", fib(i));
}
}

2024-2028-EEE
fibonacciSeriesa.c
int fib(int i)
{
if (i == 0)

Narayana Engineering College - Gudur


return 0;
else if (i == 1)
return 1;
else
return ( fib(i-1) + fib(i-2));
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
n:
4
4 terms: 0 1 1 2

Test Case - 2

User Output
n:
10
10 terms: 0 1 1 2 3 5 8 13 21 34
Exp. Name: LCM of two numbers using recursion Date:

Aim:
Write a program to find the lcm (Least Common Multiple) of a given two numbers using recursion process.

Page No: 92
The least common multiple ( lcm ) of two or more integers, is the smallest positive integer that is divisible by both
a and b.

ID:
At the time of execution, the program should print the message on the console as:

Enter two integer values :

For example, if the user gives the input as:

Enter two integer values : 25 15

then the program should print the result as:

The lcm of two numbers 25 and 15 = 75

Note: Write the function lcm() and recursive function gcd() in Program907a.c .

2024-2028-EEE
Source Code:

Program907.c
#include <stdio.h>
#include "Program907a.c"

Narayana Engineering College - Gudur


void main() {
int a, b;
printf("Enter two integer values : ");
scanf("%d %d", &a, &b);
printf("The lcm of two numbers %d and %d = %d\n", a, b, lcm(a, b));
}

Program907a.c
int lcm(int a, int b)
{
static int multiple = 0;
multiple =multiple+b;
if((multiple %a == 0)&&(multiple %b == 0))
{
return multiple;
}
else
{
return lcm(a,b);
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter two integer values :
34 24

Page No: 93
The lcm of two numbers 34 and 24 = 408

Test Case - 2

ID:
User Output
Enter two integer values :
69
The lcm of two numbers 6 and 9 = 18

Test Case - 3

User Output
Enter two integer values :
345 467

2024-2028-EEE
The lcm of two numbers 345 and 467 = 161115

Test Case - 4

User Output

Narayana Engineering College - Gudur


Enter two integer values :
100 88
The lcm of two numbers 100 and 88 = 2200

Test Case - 5

User Output
Enter two integer values :
123 420
The lcm of two numbers 123 and 420 = 17220
Exp. Name: Write a C program to find the Factorial
Date:
of a given number using Recursion

Aim:

Page No: 94
Write a program to find the factorial of a given number using recursion process.

Note: Write the recursive function factorial() in Program901a.c .


Source Code:

ID:
Program901.c

#include <stdio.h>
#include "Program901a.c"
void main() {
long int n;
printf("Enter an integer : ");
scanf("%ld", &n);
printf("Factorial of %ld is : %ld\n", n ,factorial(n));
}

2024-2028-EEE
Program901a.c
long int factorial(int n)
{
if(n)
return(n * factorial(n - 1));

Narayana Engineering College - Gudur


else
return 1;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter an integer :
5
Factorial of 5 is : 120

Test Case - 2

User Output
Enter an integer :
4
Factorial of 4 is : 24

Test Case - 3
User Output
Enter an integer :
8
Factorial of 8 is : 40320

Page No: 95
Test Case - 4

User Output

ID:
Enter an integer :
0
Factorial of 0 is : 1

2024-2028-EEE
Narayana Engineering College - Gudur
Exp. Name: Ackermann function using Recursion Date:

Aim:
Write a program to implement Ackermann function using recursion process.

Page No: 96
At the time of execution, the program should print the message on the console as:

Enter two numbers :

ID:
For example, if the user gives the input as:

Enter two numbers : 2 1

then the program should print the result as:

A(2, 1) = 5

Source Code:

AckermannFunction.c

2024-2028-EEE
#include <stdio.h>
#include "AckermannFunction1.c"
void main() {
long long int m, n;
printf("Enter two numbers : ");
scanf("%lli %lli", &m, &n);

Narayana Engineering College - Gudur


printf("A(%lli, %lli) = %lli\n", m, n, ackermannFun(m, n));
}

AckermannFunction1.c
long long int ackermannFun(int m, int n)
{
if(m==0)
return n+1;
else if(n==0)
return ackermannFun(m-1,1);
else
return ackermannFun(m-1,ackermannFun(m,n-1));
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter two numbers :
01
A(0, 1) = 2
Test Case - 2

User Output
Enter two numbers :
22

Page No: 97
A(2, 2) = 7

Test Case - 3

ID:
User Output
Enter two numbers :
21
A(2, 1) = 5

Test Case - 4

User Output
Enter two numbers :
11

2024-2028-EEE
A(1, 1) = 3

Test Case - 5

User Output

Narayana Engineering College - Gudur


Enter two numbers :
10
A(1, 0) = 2

Test Case - 6

User Output
Enter two numbers :
23
A(2, 3) = 9
Exp. Name: Problem solving Date:

Aim:
Write a program to find the sum of n natural numbers using recursion process.

Page No: 98
At the time of execution, the program should print the message on the console as:

Enter value of n :

ID:
For example, if the user gives the input as:

Enter value of n : 6

then the program should print the result as:

Sum of 6 natural numbers = 21

Note: Write the recursive function sum() in Program903a.c .


Source Code:

Program903.c

2024-2028-EEE
#include <stdio.h>
#include "Program903a.c"
void main() {
int n;
printf("Enter value of n : ");

Narayana Engineering College - Gudur


scanf("%d", &n);
printf("Sum of %d natural numbers = %d\n", n, sum(n));
}

Program903a.c
int sum(int n)
{
if (n != 0)
return n + sum(n - 1);
else
return n;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter value of n :
5
Sum of 5 natural numbers = 15
Test Case - 2

User Output
Enter value of n :
9

Page No: 99
Sum of 9 natural numbers = 45

ID:
2024-2028-EEE
Narayana Engineering College - Gudur
Exp. Name: Write a C program to Swap two values
Date:
by using Call-by-Address method

Aim:

Page No: 100


Write a program to swap two values by using call by address method.

At the time of execution, the program should print the message on the console as:

Enter two integer values :

ID:
For example, if the user gives the input as:

Enter two integer values : 12 13

then the program should print the result as:

Before swapping in main : a = 12 b = 13


After swapping in swap : *p = 13 *q = 12
After swapping in main : a = 13 b = 12

Note: Write the function swap() in Program1002a.c and do use the printf() function with a newline character

2024-2028-EEE
( \n ).
Source Code:

Program1002.c
#include <stdio.h>

Narayana Engineering College - Gudur


#include "Program1002a.c"
void main() {
int a, b;
printf("Enter two integer values : ");
scanf("%d %d", &a, &b);
printf("Before swapping in main : a = %d b = %d\n", a, b);
swap(&a, &b);
printf("After swapping in main : a = %d b = %d\n", a, b);
}

Program1002a.c
void swap(int *p, int *q){
int temp = *p;
*p =*q;
*q = temp;
printf("After swapping in swap : *p = %d *q = %d\n", *p, *q);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter two integer values :
121 131
Before swapping in main : a = 121 b = 131
After swapping in swap : *p = 131 *q = 121
After swapping in main : a = 131 b = 121

Page No: 101


Test Case - 2

User Output
Enter two integer values :

ID:
555 999
Before swapping in main : a = 555 b = 999
After swapping in swap : *p = 999 *q = 555
After swapping in main : a = 999 b = 555

Test Case - 3

User Output
Enter two integer values :
1001 101

2024-2028-EEE
Before swapping in main : a = 1001 b = 101
After swapping in swap : *p = 101 *q = 1001
After swapping in main : a = 101 b = 1001

Test Case - 4

Narayana Engineering College - Gudur


User Output
Enter two integer values :
9999 2999
Before swapping in main : a = 9999 b = 2999
After swapping in swap : *p = 2999 *q = 9999
After swapping in main : a = 2999 b = 9999

Test Case - 5

User Output
Enter two integer values :
10101 11010
Before swapping in main : a = 10101 b = 11010
After swapping in swap : *p = 11010 *q = 10101
After swapping in main : a = 11010 b = 10101
Exp. Name: Dangling Pointers Date:

Aim:
Demonstrate Dangling pointer problem using a C program.

Page No: 102


Note: The dangling pointers are set to NULL at the end of the program to avoid undefined behavior on the code.
Source Code:

danglingPointer.c

ID:
#include <stdio.h>
#include <stdlib.h>

int main() {
int *ptr1 = NULL;
int *ptr2 = NULL;
int value;

// Allocate memory for an integer


ptr1 = (int *)malloc(sizeof(int));

2024-2028-EEE
if (ptr1 == NULL) {
printf("Memory allocation failed.\n");
return 1;
}

// Input the integer value

Narayana Engineering College - Gudur


printf("Enter an integer value: ");
scanf("%d", &value);
// Assign the input value to the allocated memory
*ptr1 = value;
// Point ptr2 to the same memory location as ptr1
ptr2 = ptr1;
// Check if ptr2 is a valid pointer before accessing
if ( ptr2 != NULL ) {
printf("Value through ptr2: %d\n", *ptr2);
} else {
printf("ptr2 is a dangling pointer (invalid)\n");
}

// Deallocate the memory pointed to by ptr1


free(ptr1);
// Set ptr1 and ptr2 to NULL to avoid dangling pointers
ptr1 = NULL;
ptr2 = NULL;

return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter an integer value:
54

Page No: 103


Value through ptr2: 54

Test Case - 2

ID:
User Output
Enter an integer value:
10
Value through ptr2: 10

2024-2028-EEE
Narayana Engineering College - Gudur
Exp. Name: Write a C program to Copy one String
Date:
into another using Pointers

Aim:

Page No: 104


Write a C program to copy one string into another using pointers.

Sample Input and Output:


Enter source string : Robotic Tool
Target string : Robotic Tool

ID:
Source Code:

CopyStringPointers.c
#include <stdio.h>
#include "CopyStringPointers1.c"
void main() {
char source[100], target[100];
printf("Enter source string : ");
fgets(source, sizeof(source), stdin);
copyString(target, source);
printf("Target string : %s\n", target);

2024-2028-EEE
}

CopyStringPointers1.c
void copyString(char *target, const char *source) {
while (*source) {

Narayana Engineering College - Gudur


*target = * source;
source++;
target++;
}
*target = '\0';
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter source string :
CodeTantra
Target string : CodeTantra

Test Case - 2

User Output
Enter source string :
Robotic Tool
Target string : Robotic Tool
Exp. Name: Write a C program to Count number of
Lowercase, Uppercase, digits and Other Characters Date:
using Pointers

Page No: 105


Aim:
Write a C program to find number of lowercase , uppercase , digits and other characters using pointers.

Sample Input and Output:

ID:
Enter a string : Indo Pak 125 143 *.$
Number of uppercase letters = 2
Number of lowercase letters = 5
Number of digits = 6
Number of other characters = 7

Source Code:

CountCharDigitOthers.c
#include <stdio.h>
#include "CountCharDigitOthers1.c"

2024-2028-EEE
void main() {
char str[80];
int upperCount = 0, lowerCount = 0, digitCount = 0, otherCount = 0;
printf("Enter a string : ");
gets(str);
countCharDigitOthers(str, &upperCount, &lowerCount, &digitCount, &otherCount);

Narayana Engineering College - Gudur


printf("Number of uppercase letters = %d\n", upperCount);
printf("Number of lowercase letters = %d\n", lowerCount);
printf("Number of digits = %d\n", digitCount);
printf("Number of other characters = %d\n", otherCount);
}

CountCharDigitOthers1.c
void countCharDigitOthers(char *str, int *upperCount, int *lowerCount, int *digitCount, int
*otherCount) {
while (*str) {
if (*str >= 'A' && *str <= 'Z')
(*upperCount)++;
else if (*str >= 'a' && *str <= 'z')
(*lowerCount)++;
else if (*str >= '0' && *str <= '9')
(*digitCount)++;
else
(*otherCount)++;
str++;
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter a string :
CodeTantra123&*@987.

Page No: 106


Number of uppercase letters = 2
Number of lowercase letters = 8
Number of digits = 6
Number of other characters = 4

ID:
Test Case - 2

User Output
Enter a string :
Indo Pak 125 143 *.$
Number of uppercase letters = 2
Number of lowercase letters = 5
Number of digits = 6
Number of other characters = 7

2024-2028-EEE
Test Case - 3

User Output
Enter a string :

Narayana Engineering College - Gudur


12345
Number of uppercase letters = 0
Number of lowercase letters = 0
Number of digits = 5
Number of other characters = 0
Exp. Name: Write the code Date:

Aim:
Write a program to read a text content from a file and display on the monitor with the help of C program.

Page No: 107


Source Code:

readFilePrint.c
#include <stdio.h>
int main()

ID:
{
char filename[100], c;
char line[1000];
FILE *fp;
printf("Enter the name of the file to read: ");
scanf("%s", filename);
fp=fopen(filename,"r");

if (fp == NULL) {
printf("Unable to open the file.\n");

2024-2028-EEE
return 1;
}
printf("Content of the file %s:\n", filename);
while (fgets(line, sizeof(line), fp) != NULL) {

printf("%s", line);

Narayana Engineering College - Gudur


}
fclose(fp);
return 0;
}

file1.txt

A man was very upset with his old parents. He sometimes beat them in anger.
One day he threw them out of his house.
They both left the house sadly and never came back.
Now, the man lived happily with his wife and children.
Twenty years later, now his children had grown up, and all of them had gotten married.
They were doing the same with the man as he used to with his old parents.

file2.txt
There were two very close friends. One friend was rich and the other was poor.
The rich friend would often ask the other to tell him whenever he needed money so that he
could help him.
But, the poor friend never got such a chance.
One day the poor friend really needed money, and he thought that he would ask his friend.

file3.txt
A couple was living their life happily. The womans husband had a clothing business.
One day suddenly his health deteriorated very much and he died.
Now calamity had arisen in front of the woman.
She was very depressed about how she would take care of herself and her children.
Her husbands shop was closed. She had no idea what to do.

Page No: 108


Execution Results - All test cases have succeeded!

ID:
Test Case - 1

User Output
Enter the name of the file to read:
file1.txt
Content of the file file1.txt:
A man was very upset with his old parents. He sometimes beat them in anger.
One day he threw them out of his house.
They both left the house sadly and never came back.
Now, the man lived happily with his wife and children.
Twenty years later, now his children had grown up, and all of them had gotten married.

2024-2028-EEE
They were doing the same with the man as he used to with his old parents.

Test Case - 2

User Output

Narayana Engineering College - Gudur


Enter the name of the file to read:
file2.txt
Content of the file file2.txt:
There were two very close friends. One friend was rich and the other was poor.
The rich friend would often ask the other to tell him whenever he needed money so that he
could help him.
But, the poor friend never got such a chance.
One day the poor friend really needed money, and he thought that he would ask his friend.
Exp. Name: C program to write and read text into a
Date:
binary file using fread() and fwrite()

Aim:

Page No: 109


Write a C program to write and read text into a binary file using fread() and fwrite().

The program is to write a structure containing student roll number, name, marks into a file and read them to print
on the standard output device.
Source Code:

ID:
FilesStructureDemo1.c
#include<stdio.h>
struct student {
int roll;
char name[25];
float marks;
}s;
void main() {
FILE *fp;
char ch;

2024-2028-EEE
struct student s;
fp = fopen("student-information.txt", "w"); // Complete the statement
do {
printf("Roll no: ");
scanf("%d", &s.roll); // Complete the statement
printf("Name: ");

Narayana Engineering College - Gudur


scanf("%s", s.name); // Complete the statement
printf("Marks: ");
scanf("%f", &s.marks); // Complete the statement
fwrite(&s, sizeof(s), 1, fp); // Complete the statement
printf("Want to add another data (y/n): ");
scanf(" %c", &ch);
}while (ch =='y' || ch == 'Y'); // Complete the condition
printf("Data written successfully\n");
fclose(fp);
fp = fopen("student-information.txt","r"); // Complete the statement
printf("Roll\tName\tMarks\n");
while (fread(&s, sizeof(s), 1, fp) > 0) { // Complete the condition
printf("%d\t%s\t%f\n", s.roll, s.name, s.marks); // complete the statement
}
fclose(fp);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Roll no:
501
Name:
Ganga
Marks:
92
Want to add another data (y/n):
y

Page No: 110


Roll no:
502
Name:
Smith

ID:
Marks:
65
Want to add another data (y/n):
n
Data written successfully
Roll Name Marks
501 Ganga 92.000000
502 Smith 65.000000

2024-2028-EEE
Narayana Engineering College - Gudur
Exp. Name: Copy contents of one file into another
Date:
file.

Aim:

Page No: 111


Write a C program that creates a file (eg: SampleTextFile1.txt) and allows a user to input text until they enter '@'
into the file. The program then creates another file (eg: SampleTextFile2.txt) and copies the contents of the first
file to the second file. Finally, it should display the contents of the second file.

Input Format:

ID:
The program prompts the user to enter text, which can include any characters. The input ends when the user
types the character @.

Output Format:
The program outputs the copied text from the second file in the following format: "Copied text is : [text]" where
[text] is the content copied from the first text file.

Source Code:

copy.c
#include <stdio.h>

2024-2028-EEE
void main() {
FILE *fp, *fp1, *fp2;
char ch;

fp = fopen("SampleTextFile1.txt", "w"); // write the missing code

Narayana Engineering College - Gudur


printf("Enter the text with @ at end : ");
while ((ch = getchar()) != '@') {
putc(ch, fp);
}
putc(ch, fp);
fclose(fp);

// write the missing code...


fp1 = fopen("SampleTextFile1.txt", "r");
fp2 = fopen("SampleTextFile2.txt", "w");

while ((ch = getc(fp1)) != '@')


{
putc(ch, fp2);
}
putc(ch, fp2);
fclose(fp1);
fclose(fp2);
fp2 = fopen("SampleTextFile2.txt", "r");
printf("Copied text is : ");
while ((ch = getc(fp2)) != '@')
{
putchar(ch);
}
printf("\n");
fclose(fp2);
}
Execution Results - All test cases have succeeded!
Test Case - 1

User Output

Page No: 112


Enter the text with @ at end :
CodeTantra received
best Startup award from Hysea in 2016@
Copied text is : CodeTantra received
best Startup award from Hysea in 2016

ID:
2024-2028-EEE
Narayana Engineering College - Gudur
Exp. Name: Merge two files and store their contents
Date:
in another file using command-line arguments

Aim:

Page No: 113


Write a program to merge two files and stores their contents in another file using command-line arguments.
• Open a new file specified in argv[1] in write mode
• Write the content onto the file
• Close the file
• Open another new file specified in argv[2] in write mode

ID:
• Write the content onto the file
• Close the file
• Open first existing file specified in argv[1] in read mode
• Open a new file specified in argv[3] in write mode
• Copy the content from first existing file to new file
• Close the first existing file
• Open another existing file specified in argv[2] in read mode
• Copy its content from existing file to new file
• Close that existing file
• Close the merged file
Source Code:

2024-2028-EEE
MergeFilesArgs.c

Narayana Engineering College - Gudur


#include <stdio.h>
void main(int argc,char*argv[]) {// fill argument parameters
FILE *fp1, *fp2, *fp3;
char ch;
fp1 = fopen(argv[1], "w"); // Open file in corresponding mode

Page No: 114


printf("Enter the text with @ at end for file-1 :\n");
while ((ch=getchar())!='@') { // Write the condition
putc(ch, fp1);
}
putc(ch, fp1);
fclose(fp1);

ID:
fp2 = fopen(argv[2], "w"); // Open file in corresponding mode
printf("Enter the text with @ at end for file-2 :\n");
while ((ch=getchar())!='@') { // Write the condition
putc(ch, fp2);
}
putc(ch, fp2);
fclose(fp2);
fp1 = fopen(argv[1], "r"); // Open a first existed file in read mode
fp3 = fopen(argv[3], "w"); // Open a new file in write mode
while ((ch=getc(fp1))!='@') { // Repeat loop till get @ at the end of existed file
putc(ch, fp3);

2024-2028-EEE
}
fclose(fp1); // Close the first existed file
fp2 = fopen(argv[2], "r"); // Open a secong existed file in read mode
while ((ch=getc(fp2))!='@') { // Repeat loop till get @ at the end of existed file
putc(ch, fp3);
}

Narayana Engineering College - Gudur


putc(ch, fp3);
fclose(fp2);
fclose(fp3);
fp3 = fopen(argv[3], "r"); // Open the merged file in read mode
printf("Merged text is : ");
while ((ch=getc(fp3))!='@') { // Repeat loop till get @ at the end of merged file
putchar(ch);
}
printf("\n");
fclose(fp3); // Close the merged file
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter the text with @ at end for file-1 :
This is CodeTantra
They implemented automatic robotic tool@
Enter the text with @ at end for file-2 :
Started the company in
2014@
Merged text is : This is CodeTantra
They implemented automatic robotic tool
Started the company in
2014

Test Case - 2

Page No: 115


User Output
Enter the text with @ at end for file-1 :
Best

ID:
Fair
Awesome@
Enter the text with @ at end for file-2 :
False@
Merged text is : Best
Fair
Awesome
False

2024-2028-EEE
Narayana Engineering College - Gudur
Exp. Name: Write a C program to Count number of
Date:
Characters, Words and Lines of a given File

Aim:

Page No: 116


Write a program to count number of characters, words and lines of given text file.
• open a new file " DemoTextFile2.txt " in write mode
• write the content onto the file
• close the file
• open the same file in read mode

ID:
• read the text from file and find the characters, words and lines count
• print the counts of characters, words and lines
• close the file
Source Code:

Program1508.c

#include <stdio.h>
void main() {
FILE *fp;
char ch;
int charCount = 0, wordCount = 0, lineCount = 0;

2024-2028-EEE
fp = fopen("DemoTextFile2.txt", "w"); // Open a new file in write mode
printf("Enter the text with @ at end : ");
while ((ch=getchar())!='@') { // Repeat loop till read @ at the end
putc(ch,fp); // Put read character onto the file
}
putc(ch,fp); // Put delimiter @ at the end on the file

Narayana Engineering College - Gudur


fclose(fp); // Close the file
fp = fopen("DemoTextFile2.txt", "r"); // Open the existing file in read mode
do {
if ((ch=='\n'||ch=='@'||ch==' ')) // Write the condition to count words
wordCount++;
else
charCount++;
if ((ch=='\n'||ch=='@')) // Write the condition to count lines
lineCount++;
} while ((ch=getc(fp))!='@'); // Repeat loop till read @ at the end
fclose(fp);
printf("Total characters : %d\n", charCount);
printf("Total words : %d\n", wordCount);
printf("Total lines : %d\n", lineCount);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter the text with @ at end :
Arise! Awake!
and stop not until
the goal is reached@
Total characters : 43
Total words : 10
Total lines : 3

Test Case - 2

Page No: 117


User Output
Enter the text with @ at end :
Believe in your self

ID:
and the world will be
at your feet@
Total characters : 44
Total words : 12
Total lines : 3

2024-2028-EEE
Narayana Engineering College - Gudur
Exp. Name: Print the last n characters of a file by
Date:
reading the file

Aim:

Page No: 118


Write a C program to print the last n characters of a file by reading the file name and n value from the command
line.
Source Code:

file.c

ID:
#include<stdio.h>
#include<stdlib.h>
int main(int argc,char*argv[]) {
if(argc != 3) {
printf("Usage:%s <filename> <n>\n",argv[0]);
return 1;
}
char *filename = argv[1];
int n = atoi(argv[2]);
if(n <= 0) {
printf("Invalid value of n. please enter a positive integer.\n");

2024-2028-EEE
return 1;
}
FILE *file = fopen(filename,"r");
if (file == NULL) {
printf("Failed to open the file.\n");
return 1;

Narayana Engineering College - Gudur


}
fseek(file, 0, SEEK_END);
long fileSize = ftell(file);
if (n > fileSize) {
printf("n is greater than the file size. printing
the entire file:\n");
fseek(file,0,SEEK_SET);
}
else{
fseek(file, -n, SEEK_END);
}
int ch;
while((ch = fgetc(file)) != EOF) {
putchar(ch);
}
fclose(file);
return 0;
}

input1.txt
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
Now is better than never.

Page No: 119


If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.

input2.txt

ID:
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Everything matters.

test1.txt

2024-2028-EEE
CodeTantra
Start coding in 60 mins

test2.txt

Narayana Engineering College - Gudur


Hydrofoil is an underwater fin with a falt or curved wing-like
surface that is designed to lift a moving boat or ship
by means of the reaction upon its surface

test3.txt
Count the sentences in the file.
Count the words in the file.
Count the characters in the file.

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
good idea.

Test Case - 2

User Output
verything matters.

You might also like