0% found this document useful (0 votes)
46 views85 pages

CP Lab (R23)

The document provides an overview of a programming lab focused on familiarization with the Linux environment, text editors (Vi, Vim, Emacs), and basic C programming concepts. It includes instructions on using different editors, writing and compiling simple C programs, and converting algorithms into C source code for various computational problems. Additionally, it covers practical examples such as calculating sums, averages, temperature conversions, and simple interest.

Uploaded by

radha
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)
46 views85 pages

CP Lab (R23)

The document provides an overview of a programming lab focused on familiarization with the Linux environment, text editors (Vi, Vim, Emacs), and basic C programming concepts. It includes instructions on using different editors, writing and compiling simple C programs, and converting algorithms into C source code for various computational problems. Additionally, it covers practical examples such as calculating sums, averages, temperature conversions, and simple interest.

Uploaded by

radha
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/ 85

Lab1: Familiarization with programming environment

i) Basic Linux environment and its editors like Vi, Vim & Emacs etc.
ii) Exposure to Turbo C, gcc
iii) Writing simple programs using printf(), scanf()

i) Basic Linux environment and its editors like Vi, Vim & Emacs etc.

LINUX ENVIRONMENT

A Linux System has the following layers:

1. Hardware: This includes peripheral devices like RAM, HDD, and CPU.
2. Kernel: Interacts with the hardware directly and provides low level services to upper layer
components.
3. Shell: This hides the complexity of the functions of a kernel and acts as an interface to it. It
takes commands from users and executes kernel functions.
4. Utilities: Utility programs provide the user with OS functionalities.

VI - EDITOR :-

The default editor that comes with the UNIX operating system is called vi (visual editor).
Using vi editor, we can edit an existing file or create a new file from scratch. we can also use
this editor to just read a text file. The advanced version of the vi editor is the vim editor.

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 1


How to open VI editor?
To open vi editors, we just need to type the command mentioned below.

vi [file_name]

Here, [file_name] = this is the file name we want to create or to open the pre-existing file.

1) Creating a new file


To create a new file use the following syntax
vi <file_name>
Example:-
vi cse

2) Opening a pre-existing file .


To open an existing file, the syntax is
vi <file_name>
Example:-
$vi cse
Where cse is already existing file

MODES OF OPERATIONS

There are three modes of operations in vi:

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 2


Command Mode:
When vi starts up, it is in Command Mode. This mode is where vi interprets any characters
we type as commands and thus does not display them in the window. This mode allows us to
move through a file, and delete, copy, or paste a piece of text. Enter into Command Mode
from any other mode, requires pressing the [Esc] key.

Insert mode:
This mode enables you to insert text into the file. The vi always starts in command mode. To
enter text, you must be in insert mode. To come in insert mode, you simply type i. To get out
of insert mode, press the Esc key, which will put you back into command mode.

Last Line Mode (Escape Mode):


Last Line Mode is invoked by typing a colon [:], while vi is in Command Mode. The cursor
will jump to the last line of the screen and vi will wait for a command. This mode enables you
to perform tasks such as saving files and executing commands.

Common vi Editor Commands for Inserting and Replacing text:

To edit the file, we need to be in the insert mode. There are many ways to enter insert mode
from the command mode.

Save and Exit Commands in Vi Editor in Linux:


Need to press [Esc] key followed by the colon (:) before typing the following commands:

Commands Description

q Quit

q! Quit without saving changes i.e. discard changes.

wq Write and quit (save and exit).

w Write to file called [file_name] (save as).

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 3


VIM editor:-

vim is an advanced and highly configurable text editor built to enable efficient text editing.
vim text editor is developed by Bram Moolenaar. It supports most file types and vim editor is
also known as a programmer‟s editor. We can use its plugin based on our needs

Installation and Configure vim in Our Linux System


To install vim on Debian based Linux like ubuntu run the command:

sudo apt-get install vim

To install vim on an arch-based distro run the following command:

sudo pacman -S vim

Now vim will be installed on your system.

You can open vim by running vim command on the terminal.


$vim

There are some commands given to use the vim editor. You can see all commands, and it‟s
documentation by help command as follows:

:help

Now to exit type this command

:q!

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 4


Now, Let’s Start to use vim
To open a file in vim editor just write the file name after the vim command in the terminal as
follows:

vim filename.txt

Write into file


In the previous step we have opened the file now, Let‟s write some content in to write data we
need to go in insert mode. To go into insert /write mode type i. As follows:

After going into insert mode you will see INSERT in the status bar. After that, we can write
any data in it.

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 5


Save and Exit:
We have written the data into a file now the task is to save and close the file to do that first
exit from insert mode by pressing the Esc key. To write a command first type semicolon ( :
) and then type the command wq! or x! (both do the same thing) And then hit ENTER.
:wq!

Exit without saving the file:


To exit from the file without saving the file just use the command q! As follows
:q!
Exiting vim:
To exit without doing anything go into command mode by pressing the Esc key and type the
following command.

:q

To exit from vim without saving changes type the following command in vim

:q!

To quit and save changes type the following command

:wq

EMACS

emacs is one of the oldest and most versatile text editors. The GNU emacs version was originally
written in 1984 and is well known for its powerful and rich editing features.

Using the Interface


Start emacs by issuing the command emacs in your terminal:

$emacs

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 6


When emacs is started without a specified file, the program displays a welcome message:

To start a new file, move the cursor over to the link “Visit New File” by pressing the TAB key
and then press ENTER. A prompt appears at the end of your terminal requesting a file name:

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 7


Enter a filename to get started with text editing. In the following example, myfile.txt is used.
You can name this file whatever you like. Once you enter your file name, press ENTER to
proceed.

An empty file will be ready for text entry:

At the top of the screen there is a menu. After the menu, there is a large editing space. This is
called the main buffer where you type your text or view the contents of a file.

Saving and Quitting


Once you have made some changes to your document or written some text, you can save it by
pressing CTRL+X, followed by CTRL+S. The mini buffer will output the following message:

Output
Wrote /home/sammy/myfile.txt

You can exit out of emacs by pressing CTRL+X, then CTRL+C.

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 8


ii) Exposure to Turbo C, gcc

Using an IDE - Turbo C

We will recommend you to use Turbo C or Turbo C++ IDE, which is the oldest IDE for C
programming. It is freely available over the Internet .

Step 1: Open turbo C IDE(Integrated Development Environment), click on File, and then click
on New

Step 2: After clicking NEW button , A blank screen will be seen in which you can write C
program. Then you can save the file by selecting save option from FILE menu or F2 functional
key

Step 3: Click on Compile menu and then on Compile option, or press the keys and press Alt +
F9 to compile the code.
C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 9
Step 4: Click on Run or press Ctrl + F9 to run the code. Yes, C programs are first compiled to
generate the object code and then that object code is Run.

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 10


Step 5: To see the Output the program press Alt+F5.

Run C Program Linux Environment:

Step 1: Writing C program


To write a C program go to terminal and to write a C program use vi editor or open any text
editor to write C program and save the file with .c extension.

Step2: Compiling C program


To compile a C program go to terminal and type the following.
$ gcc <file_name>.c

Step 3: Run C program


To see the output of the C program
$ ./a.out

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 11


iii) Writing simple programs using printf(), scanf()

#include<stdio.h>
int main()
{
//Declaring Three Variables
int x;
printf("Enter The Number : \n");
scanf("%d", &x); //Input Numbers
printf("The Given number is : %d", x);
return 0;
}
OUT PUT:-
Enter The Number: 15

The Given number is: 15

Lab 2: Converting algorithms/flow charts into C Source code.


Developing the algorithms/flowcharts for the following sample programs
i) Sum and average of 3 numbers
ii)Conversion of Fahrenheit to Celsius and vice versa
iii) Simple interest calculation

i) Sum and average of 3 numbers

Algorithm :-

Step1: start
Step 2: define x,y,x, sum and avg
Step 3: read x,y,z from keyboard
Step 4: calculate sum and average
Step 5: write sun and average
Step 6: stop

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 12


Flow chart:-

Program:-

#include<stdio.h>
int main()
{
//Declaring Three Variables
int x, y, z, sum;
float avg;
printf("Enter Three Numbers : \n");
scanf("%d %d %d",&x, &y, &z); //Input Numbers
//Calculating Sum of three numbers
sum = x + y +z;
printf("Sum of Three Numbers is : %d", sum);
//Calculating Average of three numbers
avg=sum/3;
printf("\n Average of Three Numbers is : %f", avg);
return 0;
}

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 13


OUT PUT:-
Enter Three Numbers:
3
4
5
Sum of Three Numbers is: 12
Average of Three Numbers is: 4.000000

ii)Conversion of Fahrenheit to Celsius and vice versa

a) Conversion of Fahrenheit to Celsius


Algorithm:-
Step 1: start
Step 2: Define Celsius, fahrenheit
Step 3: read fahrenheit
Step 4: celsius = ((Fahrenheit-32)*5)/9
Step 5: write celsius
Step 6: stop

Flowchart:-

Program:-

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 14


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

Output:-
Enter Temp in Fahrenheit: 104
Temperature in Celsius: 40

b) Conversion of Celsius to Fahrenheit


Algorithm:-
Step 1: start
Step 2: Define Celsius, fahrenheit
Step 3: read Celsius
Step 4: fahrenheit = ((celsius*9)/5) + 32;
Step 5: write fahrenheit
Step 6: stop

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 15


Program :-
#include<stdio.h>
void main()
{
float celsius, fahrenheit;
printf("\n Enter Temp in Celsius : ");
scanf("%f", &celsius);
fahrenheit = ((celsius*9)/5) + 32;
printf("\n Temperature in Fahrenheit : %.2f ", fahrenheit);

Output :-
Enter Temp in Celsius: 40
Temperature in Fahrenheit: 104

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 16


iii) Simple interest calculation
Algorithm
Step 1: Start
Step 2: declare principal, rate, time, interest
Step 3: read the values of principal, rate, time
Step 4: Calculate Interest using formula SI= ((amount*rate*time)/100)
Step 5: print interest
Step 1: stop
Flowchart:-

program :-
# include <stdio.h>
int main(){
//Simple interset program
int principal, rate, time, interest;
printf("Enter the principal: ");
scanf("%d", &principal);
printf("Enter the rate: ");
scanf("%d", &rate);

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 17


printf("Enter the time: ");
scanf("%d", &time);
interest = (principal * rate * time) / 100;
printf("The Simple interest is %d", interest);
return 0;
}

Output:-
Enter the principal: 1000
Enter the rate: 2
Enter the time: 23
The Simple interest is 460

Lab 3: Simple computational problems using arithmetic expressions.


i) Finding the square root of a given number
ii) Finding compound interest
iii) Area of a triangle using heron’s formulae
iv) Distance travelled by an object

i) Finding the square root of a given number


Algorithm:-
1. Declare an integer variable, as num.
2. Use the sqrt() function to pass the num variable as an argument to find the square root.
3. Print the result.
4. Exit or terminate the program.

program:-
#include <stdio.h>
#include <conio.h>
#include <math.h>

int main ()
{
// declaration of the int, float and double variables
int x, res;

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 18


float y, res1;
double z, res2;
x = 289;
// use the sqrt() function to return integer values
res = sqrt(x);
printf (" The square root of %d is: %d", x, res);
// square root of float variable
y = 12.25;
// use the sqrt() function to return float values
res1 = sqrt(y);
printf (" \n The square root of %.2f is: %.2f", y, res1);

// square root of double variable


z = 144.00;
// use the sqrt() function to return double values
res2 = sqrt(z);
printf (" \n The square root of %.2lf is: %.2lf", z, res2);

return 0;
}
Output:-
The square root of 289 is: 17
The square root of 12.25 is: 3.50
The square root of 144.00 is: 12.00

ii) Finding compound interest

Compound Interest formula


Formula to calculate compound interest annually is given by.

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 19


Algorithm:-

1. Input principle amount. Store it in some variable say principle.


2. Input time in some variable say time.
3. Input rate in some variable say rate.
4. Calculate compound interest using formula, CI = principle * pow((1 + rate / 100), time).
5. Finally, print the resultant value of CI.

program:-
#include <stdio.h>
#include <math.h>
int main()
{
float principle, rate, time, CI;
/* Input principle, time and rate */
printf("Enter principle (amount): ");
scanf("%f", &principle);
printf("Enter time: ");
scanf("%f", &time);
printf("Enter rate: ");
scanf("%f", &rate);
/* Calculate compound interest */
CI = principle* (pow((1 + rate / 100), time));
/* Print the resultant CI */
printf("Compound Interest = %f", CI);
return 0;
}

Output :-
Enter principle (amount): 1200
Enter time: 2
Enter rate: 5.4
Compound Interest = 1333.099243

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 20


iii) Area of a triangle using heron’s formulae

program:-
#include<stdio.h>
#include<math.h>
int main()
{
float a, b, c, Perimeter, s, Area;
printf("\nPlease Enter three sides of triangle\n");
scanf("%f%f%f",&a,&b,&c);
Perimeter = a+b+c;
s = (a+b+c)/2;
Area = sqrt(s*(s-a)*(s-b)*(s-c));
printf("\n Perimeter of Traiangle = %.2f\n", Perimeter);
printf("\n Semi Perimeter of Traiangle = %.2f\n", s);
printf("\n Area of triangle = %.2f\n",Area);
return 0;
}

Output:-

Please enter three sides of triangle


3
4
5
Perimeter of Traiangle = 12.00
Semi Perimeter of Traiangle = 6.00
Area of triangle = 6.00

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 21


iv) Distance travelled by an object
program:-

#include<stdio.h>
void main()
{
float u,a,t,v,s;
printf("\n Enter initial velocity: ");
scanf("%f",&u);
printf("\n Enter acceleration: ");
scanf("%f",&a);
printf("\n Enter time required: ");
scanf("%f",&t);
s=(u*t)+(a*t*t)/2;
printf("\n \n The distance traveled is : %f \n \n",s);
}
OUTPUT

Enter initial velocity: 12

Enter acceleration: 12

Enter time required: 12

The distance traveled is : 1008.000000

Lab4: Simple computational problems using the operator‟ precedence and associativity
i) Evaluate the following expressions.
a. A+B*C+(D*E) + F*G
b. A/B*C-B+A*D/3
c. A+++B---A
d. J= (i++) + (++i)
ii) Find the maximum of three numbers using conditional operator
iii) Take marks of 5 subjects in integers, and find the total, average in float

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 22


i) Evaluate the following expressions.
a. A+B*C+(D*E) + F*G

#include <stdio.h>
int main()
{
int A,B,C,D,E,F,G,sum;
printf("enter the values of A,B,C,D,E,F,G:");
scanf("%d%d%d%d%d%d%d",&A,&B,&C,&D,&E,&F,&G);
sum=A+B*C+(D*E) + F*G;
printf("value of A+B*C+(D*E) + F*G is =%d",sum);
return 0;
}

Output:-
enter the values of A,B,C,D,E,F,G:1 2 3 4 5 6 7
value of A+B*C+(D*E) + F*G is =69

b. A/B*C-B+A*D/3
#include <stdio.h>
int main()
{
int A,B,C,D,sum;
printf("enter the values of A,B,C,D:");
scanf("%d%d%d%d",&A,&B,&C,&D);
sum=A/B*C-B+A*D/3;
printf("value of A/B*C-B+A*D/3 is =%d",sum);
return 0;
}
output:-
enter the values of A,B,C,D:20 5 4 8
value of A/B*C-B+A*D/3 is =64
c. A+++B---A
The expression A+++B---A is evaluated in the following form
A+++B---A = (A++)+(B--)-A
IF a=10 AND B=20 then
(10++)+(20--)-10
10+20-11
19

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 23


program:-
#include <stdio.h>
int main()
{
int A,B,sum;
printf("enter the values of A,B:");
scanf("%d%d",&A,&B);
sum=A+++B---A ;
printf("value of A+++B---A is =%d",sum);
return 0;
}
output:-
enter the values of A,B:10 20
value of A+++B---A is =19

d. J= (i++) + (++i)

#include <stdio.h>
int main()
{
int i,j;
printf("enter the value of i:");
scanf("%d",&i);
j= (i++) + (++i) ;
printf("value of (i++) + (++i) is =%d",j);
return 0;
}

Output:-
enter the value of i:10
value of (i++) + (++i) is =22

ii) Find the maximum of three numbers using conditional operator

# include <stdio.h>
int main()
{
int a, b, c, big ;
printf("Enter three numbers : ") ;

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 24


scanf("%d %d %d", &a, &b, &c) ;
big = a > b ? (a > c ? a : c) : (b > c ? b : c) ;
printf("\nThe biggest number is : %d", big) ;
return 0;
}

Output :-
Enter three numbers: 44 55 22

The biggest number is: 55

iii) Take marks of 5 subjects in integers, and find the total, average in float
#include <stdio.h>
int main()
{
int eng, phy, chem, math, comp;
float total, average;
/* Input marks of all five subjects */
printf("Enter English marks :");
scanf("%d", &eng);
printf("\nEnter physics marks : ");
scanf("%d", &phy);
printf("\nEnter chemistry marks : ");
scanf("%d", &chem);
printf("\nEnter maths marks : ");
scanf("%d", &math);
printf("\nEnter computer marks : ");
scanf("%d", &comp);
/* Calculate total, average and percentage */
total = eng + phy + chem + math + comp;
average = total / 5.0;
/* Print all results */
printf("\n Total marks = %.2f", total);
printf("\n Average marks = %.2f", average);

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 25


return 0;
}
Output:-

Enter English marks :65

Enter physics marks : 62

Enter chemistry marks : 63

Enter maths marks : 68

Enter computer marks : 58

Total marks = 316.00


Average marks = 63.20

Lab 5: Problems involving if-then-else structures.


i) Write a C program to find the max and min of four numbers using if-else.
ii) Write a C program to generate electricity bill.
iii) Find the roots of the quadratic equation.
iv) Write a C program to simulate a calculator using switch case.
v) Write a C program to find the given year is a leap year or not.

i) Write a C program to find the max and min of four numbers using if-else.
#include<stdio.h>
int main()
{
int a,b,c,d;

printf("Enter the Four Numbers :");


scanf("%d %d %d %d",&a,&b,&c,&d);
if(a>b)
{
if(a>c)
{
if(a>d)
{
printf("%d is big",a);
}
else

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 26


{
printf("%d is big",d);
}
}
}
else if(b>c)
{
if(b>d)
{
printf("%d is big",b);
}
else
{
printf("%d is big",d);
}
}
else if(c>d)
{
printf("%d is big",c);
}
else
{
printf("%d is big",d);
}
return 0;
}

Output:-
Enter the Four Numbers :1
2
3
4

4 is big
Enter the Four Numbers :10
15
2
1

15 is big

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 27


ii) Write a C program to generate electricity bill.
The total electricity bill according to the given condition:
For first 50 units Rs. 0.50/unit
For next 100 units Rs. 0.75/unit
For next 100 units Rs. 1.20/unit
For unit above 250 Rs. 1.50/unit
An additional surcharge of 20% is added to the bill.

Program:-

#include <stdio.h>
int main()
{
int unit;
float amt, total_amt, sur_charge;
/* Input unit consumed from user */
printf("Enter total units consumed: ");
scanf("%d", &unit);
/* Calculate electricity bill according to given conditions */
if(unit <= 50)
{
amt = unit * 0.50;
}
else if(unit <= 150)
{
amt = 25 + ((unit-50) * 0.75);
}
else if(unit <= 250)
{
amt = 100 + ((unit-150) * 1.20);
}
else
{
amt = 220 + ((unit-250) * 1.50);
}

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 28


/* Calculate total electricity bill after adding surcharge */
sur_charge = amt * 0.20;
total_amt = amt + sur_charge;
printf("Electricity Bill = Rs. %.2f", total_amt);
return 0;
}

Output:-
Enter total units consumed: 220
Electricity Bill = Rs. 220.80

iii) Find the roots of the quadratic equation.

The term b2 - 4ac is known as the discriminant of a quadratic equation. It tells the nature of the

roots.

 If the discriminant is greater than 0, the roots are real and different.

 If the discriminant is equal to 0, the roots are real and equal.

 If the discriminant is less than 0, the roots are complex and different .

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 29


Program :-

#include <math.h>
#include <stdio.h>
int main()
{
double a, b, c, discriminant, root1, root2, realPart, imagPart;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf", &a, &b, &c);
discriminant = b * b - 4 * a * c;
// condition for real and different roots
if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("root1 = %.2lf and root2 = %.2lf", root1, root2);
}
// condition for real and equal roots
else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
printf("root1 = root2 = %.2lf;", root1);
}
// if roots are not real
else {
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart, imagPart, realPart,
imagPart);

}
return 0;
}
Output:-
Enter coefficients a, b and c: 2 5 6
root1 = -1.25+1.20i and root2 = -1.25-1.20i

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


#include <stdio.h>
int main()
{
int num1,num2;
float result;

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 30


char ch; //to store operator choice
printf("Enter first number: ");
scanf("%d",&num1);
printf("Enter second number: ");
scanf("%d",&num2);
printf("Choose operation to perform (+,-,*,/): ");
scanf(" %c",&ch);
result=0;
switch(ch)
{
case '+':
result=num1+num2;
printf("Result: %d %c %d = %f\n",num1,ch,num2,result);
break;
case '-':
result=num1-num2;
printf("Result: %d %c %d = %f\n",num1,ch,num2,result);
break;
case '*':
result=num1*num2;
printf("Result: %d %c %d = %f\n",num1,ch,num2,result);
break;
case '/':
result=(float)num1/(float)num2;
printf("Result: %d %c %d = %f\n",num1,ch,num2,result);
break;
default:
printf("Invalid operation.\n");
}
return 0;
}
Output:-
Enter first number: 10
Enter second number: 5
Choose operation to perform (+,-,*,/): +
Result: 10 + 5 = 15.000000

Enter first number: 12


Enter second number: 15
Choose operation to perform (+,-,*,/): 0

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 31


Invalid operation.

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

#include <stdio.h>
int main()
{
int y;
printf("Enter the year to check: ");
scanf("%d",&y);
if (((y % 4 == 0) && (y % 100!= 0)) || (y%400 == 0))
printf("It is a leap year");
else
printf("It is not a leap year");
return 0;
}
Output:-
Enter the year to check: 2000
It is a leap year

Lab 6: Iterative problems e.g., the sum of series


i) Find the factorial of given number using any loop.
ii) Find the given number is a prime or not.
iii) Compute sine and cos series
iv) Checking a number palindrome
v) Construct a pyramid of numbers.

i) Find the factorial of given number using any loop.


#include<stdio.h>
int main()
{
int n,i=1,f=1;
printf("\n Enter The Number:");
scanf("%d",&n);

//LOOP TO CALCULATE FACTORIAL OF A NUMBER


while(i<=n)

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 32


{
f=f*i;
i++;
}

printf("\n The Factorial of %d is %d",n,f);


return 0;
}

Output:-
Enter The Number: 5
The Factorial of 5 is: 120

ii) Find the given number is a prime or not.


#include <stdio.h>
int main()
{
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);

// 0 and 1 are not prime numbers


// change flag to 1 for non-prime number
if (n == 0 || n == 1)
flag = 1;

for (i = 2; i <= n / 2; ++i) {

// if n is divisible by i, then n is not prime


// change flag to 1 for non-prime number
if (n % i == 0) {
flag = 1;
break;
}
}
// flag is 0 for prime numbers
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 33


return 0;
}
Output:-
Enter a positive integer: 7
7 is a prime number.

Enter a positive integer: 10


10 is not a prime number.

iii) Compute sine and cos series


Cosine Series:
Cosine Series is a series which is used to find the value of Cos(x). where, x is the angle
in degree which is converted to Radian. The formula used to express the Cos(x) as Cosine
Series is

Expanding the above notation, the formula of Cosine Series is

For example,

Let the value of x be 30.

So, Radian value for 30 degree is 0.52359.

So, the value of Cos(30) is 0.8660.

Sine Series:
Sine Series is a series which is used to find the value of Sin(x). where, x is the angle
in degree which is converted to Radian. The formula used to express the Sin(x) as Sine Series is

Expanding the above notation, the formula of Sine Series is

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 34


For example,

Let the value of x be 30.

So, Radian value for 30 degree is 0.52359.

So, the value of Sin(30) is 0.5.

Program:-

#include<stdio.h>

int main()

int i, n;

float x, sum=1, t=1,t1,sum1;

printf(" Enter the value for x : ");

scanf("%f",&x);

printf(" Enter the value for (no of terms to sum) n : ");

scanf("%d",&n);

x=x*3.14159/180;

t1=x;

sum1=x;

/* Loop to calculate the value of Cosine */

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 35


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

t=t*(-1)*x*x/(2*i*(2*i-1));

sum=sum+t;

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

t1=(t1*(-1)*x*x)/(2*i*(2*i+1));

sum1=sum1+t1;

printf(" The value of Cos(%f) is : %.4f", x, sum);

printf(" \n The value of Sin(%f) = %.4f",x,sum1);

return 0;

}
Output:-
Enter the value for x : 45
Enter the value for (no of terms to sum) n : 5
The value of Cos(0.785398) is : 0.7071
The value of Sin(0.785398) = 0.7071

iv) Checking a number palindrome

#include<stdio.h>
int main()
{
int n,r,sum=0,temp;
printf("enter the number=");
scanf("%d",&n);
temp=n;
while(n>0)

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 36


{
r=n%10;
sum=(sum*10)+r;
n=n/10;
}
if(temp==sum)
printf("palindrome number ");
else
printf("not palindrome");
return 0;
}

Output:-

enter the number=151


palindrome number

enter the number=150


not palindrome

v) Construct a pyramid of numbers.

#include <stdio.h>
int main() {
int i, space, rows, k = 0, count = 0, count1 = 0;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i) {
for (space = 1; space <= rows - i; ++space) {
printf(" ");
++count;
}
while (k != 2 * i - 1) {
if (count <= rows - 1) {
printf("%d ", i + k);
++count;
} else {
++count1;
printf("%d ", (i + k - 2 * count1));
}

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 37


++k;
}
count1 = count = k = 0;
printf("\n");
}
return 0;
}

Output:-
Enter the number of rows: 5
1
232
34543
4567654
567898765

Lab 7:1D Array manipulation, linear search


i) Find the min and max of a 1-D integer array.
ii) Perform linear search on1D array.
iii) The reverse of a 1D integer array
iv) Find 2’s complement of the given binary number.
v) Eliminate duplicate elements in an array.

i) Find the min and max of a 1-D integer array.

#include <stdio.h>
int main()
{
int a[1000],i,n,min,max;

printf("Enter size of the array : ");


scanf("%d",&n);

printf("Enter elements in array : ");


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

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 38


min=max=a[0];
for(i=1; i<n; i++)
{
if(min>a[i])
min=a[i];
if(max<a[i])
max=a[i];
}
printf("minimum element of array is : %d",min);
printf("\n maximum element of array is : %d",max);

return 0;
}

Output:-
Enter size of the array : 5
Enter elements in array : 23
21
56
43
8
minimum element of array is : 8
maximum element of array is : 56

ii) Perform linear search on1D array.

#include <stdio.h>
int main()
{
int array[100], search, c, n;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d integer(s)\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter a number to search\n");

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 39


scanf("%d", &search);
for (c = 0; c < n; c++)
{
if (array[c] == search) /* If required element is found */
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if (c == n)
printf("%d isn't present in the array.\n", search);

return 0;
}
Output:-
Enter number of elements in array
5
Enter 5 integer(s)
23
43
12
56
77
Enter a number to search
12
12 is present at location 3.

iii) The reverse of a 1D integer array

#include<stdio.h>
int main()

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 40


{
int n, arr[20], i;
printf("Enter the size of the array: ");
scanf("%d", &n);
printf("Enter the elements: ");
for(i = 0; i<n;i++)
{
scanf("%d", &arr[i]);
}
int rev[n], j = 0;
for(i = n-1; i >= 0; i--)
{
rev[j] = arr[i];
j++;
}
printf("The Reversed array: ");
for(i = 0; i < n; i++)
{
printf("%d ", rev[i]);
}
return 0;
}
Output:-
Enter the size of the array: 5
Enter the elements: 10
20
30
40
50
The Reversed array: 50 40 30 20 10
iv) Find 2’s complement of the given binary number.

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 41


The 2s complement is generated from the 1s complement. As we know that the 1s complement
of a binary number is created by transforming bit 1 to 0 and 0 to 1; the 2s complement of a
binary number is generated by adding one to the 1s complement of a binary number.

In short, we can say that the 2s complement is defined as the sum of the one's complement and
one.

Program:-
#include <stdio.h>
int main()
{
int n; // variable declaration
printf("Enter the number of bits do you want to enter :");
scanf("%d",&n);
char binary[n+1]; // binary array declaration;
char onescomplement[n+1]; // onescomplement array declaration
char twoscomplement[n+1]; // twoscomplement array declaration
int carry=1; // variable initialization
printf("\nEnter the binary number : ");
scanf("%s", binary);
printf("The given binary number is :%s", binary);
printf("\nThe ones complement of the binary number is :");

// Finding onescomplement in C
for(int i=0;i<n;i++)
{
if(binary[i]=='0')

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 42


onescomplement[i]='1';
else if(binary[i]=='1')
onescomplement[i]='0';
}
onescomplement[n]='\0';
printf("%s",onescomplement);
printf("\nThe twos complement of a binary number is : ");
// Finding twoscomplement in C
for(int i=n-1; i>=0; i--)
{
if(onescomplement[i] == '1' && carry == 1)
{
twoscomplement[i] = '0';
}
else if(onescomplement[i] == '0' && carry == 1)
{
twoscomplement[i] = '1';
carry = 0;
}
else
{
twoscomplement[i] = onescomplement[i];
}
}
twoscomplement[n]='\0';
printf("%s",twoscomplement);
return 0;
}
Output:-
Enter the number of bits do you want to enter :4
Enter the binary number : 1010

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 43


The given binary number is:1010
The ones complement of the binary number is: 0101
The twos complement of a binary number is: 0110
v. Eliminate duplicate elements in an array.
#include<stdio.h>
#include<stdlib.h>
int main(){
int a[50],i,j,k, count = 0, dup[50], number;
printf("Enter size of the array");
scanf("%d",&number);
printf("Enter Elements of the array:");
for(i=0;i<number;i++){
scanf("%d",&a[i]);
dup[i] = -1;
}
printf("Entered element are: ");
for(i=0;i<number;i++){
printf("%d ",a[i]);
}
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("\n After deleting the duplicate element the Array is:");

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 44


for(i=0;i<number;i++){
printf("%d ",a[i]);
}}
Output:-
Enter size of the array 8
Enter Elements of the array: 1
2
1
5
9
5
2
9
Entered elements are: 1 2 1 5 9 5 2 9
After deleting the duplicate element the Array is:1 2 5 9
Lab 8: Matrix problems, String operations, Bubble sort
i) Addition of two matrices
ii) Multiplication two matrices
iii) Sort array elements using bubble sort
iv) Concatenate two strings without built-in functions
v) Reverse a string using built-in and without built-in string functions

i) Addition of two matrices


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

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

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 45


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}
printf("Enter elements of 2nd matrix:\n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element b%d%d: ", i + 1, j + 1);
scanf("%d", &b[i][j]);
}
// adding two matrices
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
sum[i][j] = a[i][j] + b[i][j];
}
// printing the result
printf("\nSum of two matrices: \n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("%d ", sum[i][j]);
if (j == c - 1) {
printf("\n\n");
}
}

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

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 46


Enter elements of 1st matrix:
Enter element a11: 1
Enter element a12: 2
Enter element a21: 3
Enter element a22: 4
Enter elements of 2nd matrix:
Enter element b11: 5
Enter element b12: 6
Enter element b21: 7
Enter element b22: 8
Sum of two matrices:
6 8
10 12

ii) Multiplication two matrices

#include<stdio.h>
int main()
{
int r1,r2,c1,c2;
printf("Enter number of rows for First Matrix:\n");
scanf("%d",&r1);
printf("Enter number of columns for First Matrix:\n");
scanf("%d",&c1);
printf("Enter number of rows for Second Matrix:\n");
scanf("%d",&r2);
printf("Enter number of columns for Second Matrix:\n");
scanf("%d",&c2);
if(c1!=r2)
{
printf("Matrices Can't be multiplied together");

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 47


}
else
{
int m1[r1][c1],m2[r2][c2];
printf("Enter first matrix elements \n");
for(int i=0;i<r1;i++)
{
for(int j=0;j<c1;j++)
{
scanf("%d",&m1[i][j]);
}
}
printf("Enter Second matrix elements\n");
for(int i=0;i<r2;i++)
{
for(int j=0;j<c2;j++)
{
scanf("%d",&m2[i][j]);
}
}
int mul[r1][c2];
for(int i=0;i<r1;i++)
{
for(int j=0;j<c2;j++)
{
mul[i][j]=0;
// Multiplying i‟th row with j‟th column
for(int k=0;k<c1;k++)
{
mul[i][j]+=m1[i][k]*m2[k][j];
}

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 48


}
}
printf("Multiplied matrix\n");
for(int i=0;i<r1;i++)
{
for(int j=0;j<c2;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
}
return 0;
}
Output:-
Enter number of rows for First Matrix:
3
Enter number of columns for First Matrix:
3
Enter number of rows for Second Matrix:
3
Enter number of columns for Second Matrix:
3
Enter first matrix elements
1
2
3
4
5
6
7

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 49


8
9

Enter Second matrix elements


9
8
77
6
5
4
3
2
1

Multiplied matrix
30 24 88
84 69 334
138 114 580

iii) Sort array elements using bubble sort


Problem Solution
1. In Bubble sort algorithm we compare the first two elements of an array and swap them if
required.
2. If we want to sort the elements of array in ascending order and if the first element is
greater than second then, we need to swap the elements.
3. If the first element is smaller than second, we don‟t need to swap the elements. This
process goes on until last and second last element is compared and swapped.

2. For example:
If we have the array as {40,10,50,70,30}
and we apply bubble sort to sort the array,
then the resultant array after each iteration will be as follows:
Original array: {40, 10, 50, 70, 30}

Array after first iteration 10 -> 40 -> 50 -> 30 -> 70


Array after second iteration 10 -> 40 -> 30 -> 50 -> 70

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 50


Array after third iteration 10 -> 30 -> 40 -> 50 -> 70
Array after fourth iteration 10 -> 30 -> 40 -> 50 -> 70
Sorted array is 10 30 40 50 70

Program:-

#include <stdio.h>
int main()
{
int array[100], n, c, d, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0 ; c < n - 1; c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use '<' instead of '>' */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
printf("Sorted list in ascending order:\n");
for (c = 0; c < n; c++)
printf("%d\n", array[c]);
return 0;
}
Output:-
Enter number of elements
5
Enter 5 integers
2
1
4
3
0
Sorted list in ascending order:
0

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 51


1
2
3
4
iv) Concatenate two strings without built-in functions

#include<stdio.h>
int main(void)
{
char str1[25],str2[25];
int i=0,j=0;
printf("\nEnter First String:");
gets(str1);
printf("\nEnter Second String:");
gets(str2);
while(str1[i]!='\0')
i++;
while(str2[j]!='\0')
{
str1[i]=str2[j];
j++;
i++;
}
str1[i]='\0';
printf("\nConcatenated String is %s",str1);
return 0;
}

Output:-
Enter First String:hai

Enter Second String:hello

Concatenated String is haihello

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

Reverse a string using built-in string functions


#include <stdio.h>
#include <string.h>
int main()

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 52


{
char str[40]; // declare the size of character string
printf (" \n Enter a string to be reversed: ");
scanf ("%s", str);

// use strrev() function to reverse a string


printf (" \n After the reverse of a string: %s ", strrev(str));
return 0;
}
Output:-
Enter a string to be reversed: abc
After the reverse of a string: cba
Reverse a string using without built-in string functions
#include <stdio.h>
int main()
{
char s[1000], r[1000];
int begin, end, count = 0;
printf("Input a string\n");
gets(s);
// Calculating string length
while (s[count] != '\0')
count++;
end = count - 1;
for (begin = 0; begin < count; begin++) {
r[begin] = s[end];
end--;
}
r[begin] = '\0';
printf("%s\n", r);
return 0;

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 53


}

Output:-
Input a string
srikar
rakirs

Lab 9: Pointers and structures, memory dereference.


i) Write a C program to find the sum of a 1D array using malloc()
ii) Write a C program to find the total, average of n students using structures
iii) Enter n students data using calloc() and display failed students list
iv) Read student name and marks from the command line and display the student details
along with the total.
v) Write a C program to implement realloc()

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

#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
int count;
int *arr;
int sum = 0;
printf("Enter the total number of elements you want to enter : ");
scanf("%d", &count);
arr = (int *)malloc(count * sizeof(int));
for (i = 0; i < count; i++)
{
printf("Enter element %d : ", (i + 1));
scanf("%d", arr + i);
sum += *(arr + i);
}

printf("sum is %d \n", sum);

free(arr);

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 54


return 0;
}

Output:-

Enter the total number of elements you want to enter : 5


Enter element 1 : 10
Enter element 2 : 20
Enter element 3 : 30
Enter element 4 : 40
Enter element 5 : 50
sum is 150

ii) Write a C program to find the total, average of n students using structures
#include<stdio.h>
struct student
{
char name[10];
float m1,m2,m3;
float avg,total;
};
void main()
{
struct student s[20];
int n,i;
float tavg,sum=0.0;
printf("Enter the number of student=");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the detail of student-%d \n",i+1);
printf("Enter Name=");
scanf("%s",s[i].name);
printf("Enter the subject-1 score :");
scanf("%f",&s[i].m1);
printf("\n Enter the subject-2 score :");
scanf("%f",&s[i].m2);
printf("\n Enter the subject-3 score :");
scanf("%f",&s[i].m3);
s[i].total=s[i].m1+s[i].m2+s[i].m3;
s[i].avg=s[i].total/3;
}
for(i=0;i<n;i++)
{
printf("\n student-%d details ",i+1);

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 55


printf("\n total marks :%f",s[i].total);
printf("\n average marks : %f",s[i].avg);
}
}
Output:-

Enter the number of student=2


Enter the detail of student-1
Enter Name=ravi
Enter the subject-1 score :67

Enter the subject-2 score :87

Enter the subject-3 score :99


Enter the detail of student-2
Enter Name=srinu
Enter the subject-1 score :77

Enter the subject-2 score :87

Enter the subject-3 score :79

student-1 details
total marks :253.000000
average marks : 84.333336
student-2 details
total marks :243.000000
average marks : 81.000000

iii) Enter n students data using calloc() and display failed students list

#include <stdio.h>
#include <stdlib.h>
int main(void) {

// student structure
struct student {
char roll_no[10];
char name[64];
int m1,m2,m3,m4,m5;
};

// new type

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 56


typedef struct student candidate;

// student structure pointer


candidate *sptr;
candidate *tmp;

// variables
int no_of_students;
int i,total,count=0;
printf("Enter the no_of students: ");
scanf("%d",&no_of_students);

// allocate memory blocks


sptr = (candidate *) calloc (no_of_students, sizeof(candidate));

// get student details


for(i = 0, tmp = sptr; i < no_of_students; i++, tmp++) {
printf("Enter detail of student #%d\n", (i+1));
printf("Roll no: ");
scanf("%s", tmp->roll_no);
printf("Student Name: ");
scanf("%s", tmp->name);
printf("Enter the marks in english: ");
scanf("%d", &tmp->m1);
printf("Enter the marks in maths: ");
scanf("%d", &tmp->m2);
printf("Enter the marks in Computers: ");
scanf("%d", &tmp->m3);
printf("Enter the marks in Science: ");
scanf("%d", &tmp->m4);
printf("Enter the marks in Social: ");
scanf("%d", &tmp->m5);
}

for(i = 0, tmp = sptr; i < no_of_students; i++, tmp++)


{
if(((tmp->m1)<35)||((tmp->m1)<35)||((tmp->m1)<35)||((tmp->m1)<35)||((tmp->m1)<35))

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 57


{
printf("Following are failed students details");
//printf("\nDetail of student #%d", (i+1));
printf("\nRoll no: %s\t", tmp->roll_no);
printf("Student Name: %s\n", tmp->name);
printf("\nMarks in english:%d",tmp->m1);
printf("\tMarks in maths:%d",tmp->m2);
printf("\tMarks in Computers: %d",tmp->m3);
printf("\nMarks in Science: %d",tmp->m4);
printf("\tMarks in Social:%d",tmp->m5);
total=tmp->m1+tmp->m2+tmp->m3+tmp->m4+tmp->m5;
printf("\tTotal=%d",total);
count++;
}
}
if(count==0)
printf("No student failed");

// free memory location


free(sptr);
return 0;
}
Output:-
Enter the no_of students: 2
Enter detail of student #1
Roll no: 1
Student Name: srinu
Enter the marks in english: 45
Enter the marks in maths: 67
Enter the marks in Computers: 44
Enter the marks in Science: 78
Enter the marks in Social: 56
Enter detail of student #2
Roll no: 2
Student Name: vasu
Enter the marks in english: 34
Enter the marks in maths: 65
Enter the marks in Computers: 32
Enter the marks in Science: 67

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 58


Enter the marks in Social: 55

Following are failed students details


Roll no: 2 Student Name: vasu

Marks in english: 34 Marks in maths:65 Marks in Computers: 32


Marks in Science: 67 Marks in Social:55 Total=253

iv) Read student name and marks from the command line and display the student details
along with the total.
#include<stdio.h>
int main(int argc,char *argv[])
{
int i,avg,count=0;sum=0;
int c=argc;
printf(“Name of the student=%s”,argv[1]);
for(i=2;i<c;i++)
{
Sum+=atoi(argv[i]);
Count++;
}
Avg=sum/count;
Printf(“\n Sum=%d”,sum);
Printf(“\n Average=%d”,avg);
}
Output:-
C:\TURBOC3\SOURCE>ss.exe srikar 10 20 30 40
Name of the student= srikar
Sum =100
Average=25

v) Write a C program to implement realloc()

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

int main() {
int *ptr = (int*) malloc(3 * sizeof(int));
ptr[0] = 1;
ptr[1] = 2;
C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 59
ptr[2] = 3;

// resize the memory block to hold 5 integers


ptr = (int*) realloc(ptr, 5 * sizeof(int));
ptr[3] = 4;
ptr[4] = 5;

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


printf("%d ", ptr[i]);
}
// free the memory block
free(ptr);
return 0;
}

Output :-
12345

Lab10 : Bitfields, linked lists


Read and print a date using dd/mm/yyyy format using bit-fields and differentiate the same
without using bit- fields
i) Create and display a singly linked list using self-referential structure.
ii) Demonstrate the differences between structures and unions using a C program.
iii) Write a C program to shift/rotate using bitfields.
iv) Write a C program to copy one structure variable to another structure of the same type.

i) Create and display a singly linked list using self-referential structure.

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

struct node
{
int num; //Data of the node
struct node *nextptr; //Address of the node
}*stnode;

void createNodeList(int n); //function to create the list

void displayList(); //function to display the list

int main()
{

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 60


int n,totalNode;

printf(" Input the number of nodes : ");


scanf("%d", &n);
createNodeList(n);
printf("\n Data entered in the list are : \n");
displayList();
return 0;
}
void createNodeList(int n)
{
struct node *fnNode, *tmp;
int num, i;
stnode = (struct node *)malloc(sizeof(struct node));
if(stnode == NULL) //check whether the stnode is NULL and if so no memory allocation
{
printf(" Memory cannot be allocated.");
}
else
{
// reads data for the node through keyboard
printf(" Input data for node 1 : ");
scanf("%d", &num);
stnode-> num = num;
stnode-> nextptr = NULL; //Links the address field to NULL
tmp = stnode;
//Creates n nodes and adds to linked list
for(i=2; i<=n; i++)
{
fnNode = (struct node *)malloc(sizeof(struct node));
if(fnNode == NULL) //check whether the fnnode is NULL and if so no memory
allocation
{
printf(" Memory cannot be allocated.");
break;
}
else
{
printf(" Input data for node %d : ", i);
scanf(" %d", &num);
fnNode->num = num; // links the num field of fnNode with num
fnNode->nextptr = NULL; // links the address field of fnNode with NULL

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 61


tmp->nextptr = fnNode; // links previous node i.e. tmp to the fnNode
tmp = tmp->nextptr;
}
}
}
}

void displayList()
{
int i=1;
struct node *tmp;
if(stnode == NULL)
{
printf(" No data found in the list.");
}
else
{
tmp = stnode;
while(tmp != NULL)
{
printf(" node - %i Data = %d\n", i,tmp->num); // prints the data of current node
tmp = tmp->nextptr;
i++;// advances the position of current node
}
}
}

Output:-
Input the number of nodes : 3
Input data for node 1 : 10
Input data for node 2 : 20
Input data for node 3 : 30

Data entered in the list are :


node - 1 Data = 10
node - 2 Data = 20
node - 3 Data = 30
ii) Demonstrate the differences between structures and unions using a C program.

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 62


Structures in C are internally implemented. There is separate memory location allotted for each
input member. While in case Union memory is allocated only to one member having largest size
among all other input variables and the same location is being get shared among all of these.
Program:-
#include<stdio.h>
struct size{
double a;
int b;
char c;
float d;
};
union and{
double a;
int b;
char c;
float d;
};
int main(){
struct size s;
union and u;
printf("Size of structure is: %ld",sizeof(s));
printf("\n Size of union is: %ld",sizeof(u));
}
Output:-
Size of structure is: 24
Size of union is: 8

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


#include<stdio.h>
int main()
{
int n,d,c,e;
printf("Enter the number :");
scanf("%d",&n);
printf("\nEnter the no of rotations:");
scanf("%d",&d);
printf("\n Left Rotation of %d by %d bits is : ", n, d);
c=(n<<d);

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 63


printf("%d",c);
printf("\n Right Rotation of %d by %d bits is: ", n, d);
e=(n>>2);
printf("%d",e);
return 0;
}
Output:-
Enter the number :10
Enter the no of rotations:4
Left Rotation of 10 by 4 bits is : 160
Right Rotation of 10 by 4 bits is: 2

iv) Write a C program to copy one structure variable to another structure of the same type.

Lab 11: Simple functions using call by value, solving differential equations using Eulers
theorem.
i) Write a C function to calculate NCR value.
ii) Write a C function to find the length of a string.
iii) Write a C function to transpose of a matrix.
iv) Write a C function to demonstrate numerical integration of differential equations using
Euler’s method

i) Write a C function to calculate NCR value.

The total number of ways for selecting r elements out of n options are
nCr = (n!) / (r! * (n-r)!)

#include <stdio.h>
int fact(int z);
void main()
{
int n, r, nCr;
printf("Enter the value of n and r?");
scanf("%d %d",&n,&r);
nCr = fact(n) / (fact(r) * fact(n - r));
printf("\nnCr = %d", nCr);
}
int fact(int z)

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 64


{
int f = 1, i;
if (z == 0)
{
return(f);
}
else
{
for (i = 1; i <= z; i++)
{
f = f * i;
}
}
return(f);
}
Output:-
Enter the value of n and r?4 2
nCr = 6

ii) Write a C function to find the length of a string.

#include<stdio.h>
int FindLength(char str[]);
int main() {
char str[100];
int length;

printf("\nEnter the String : ");


gets(str);

length = FindLength(str);

printf("\nLength of the String is : %d", length);


return(0);
}

int FindLength(char str[]) {


int len = 0;

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 65


while (str[len] != '\0')
len++;
return (len);
}
Output:-
Enter the String : srikar

Length of the String is : 6

iii) Write a C function to transpose of a matrix.

#include <stdio.h>

void transpose_matrix(int m,int n, int a[10][10])


{
//transposing array matrix
int transpose[10][10];
for (int i = 0;i < m;i++)
{
for (int j = 0; j < n; j++)
{
transpose[j][i] = a[i][j];
}
}
printf("Transpose of matrix is \n");
for (int i = 0; i< n; i++)
{
for (int j = 0; j < m; j++)
{
printf("%d ", transpose[i][j]);
}
printf("\n");
}
}

void main()
{
static int a[10][10];

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 66


int i, j, m, n;

printf("Enter the order of the matrix \n");


scanf("%d %d", &m, &n);
printf("Enter the coefficients of the matrix\n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
scanf("%d", &a[i][j]);
}
}
printf("The given matrix is \n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
printf("%d ", a[i][j]);
}
printf("\n");
}
transpose_matrix(m,n,a);
}
Output:-
Enter the order of the matrix
32
Enter the coefficients of the matrix
1
2
3
4
5
6
The given matrix is
12

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 67


34
56
Transpose of matrix is
135
246
iv) Write a C function to demonstrate numerical integration of differential equations using
Euler’s method
Euler’s Method in C Program is a numerical method that is used to solve nonlinear differential
equations. In this article, I will explain how to solve a differential equation by Euler‟s method in
C. Euler‟s method is a simple technique and it is used for finding the roots of a function. Solving
an ordinary differential equation (ODE) or initial value problem means finding a clear expression
for y in terms of a finite number of elementary functions of x. Euler‟s method is one of the
simplest methods for the numerical solution of such an equation or problem. This C program
for Euler’s method considers ordinary differential equations, and the initial values of x and y
are known.

Mathematically, here, the curve of the solution is approximated by a sequence of short lines i.e.
by the tangent line in each interval. (Derivation) Using this information, the value of the value
of „yn‟ corresponding to the value of „xn„ is to determined by dividing the length (xn – x) into n
strips.Therefore, strip width= (xn – x)/n and xn=x0+ nh.
Again, if m be the slope of the curve at point, y1= y0 + m(x0 , yo)h.

Program :-

#include<stdio.h>
float fun(float x,float y)
{
float f;
f=x+y;
return f;
}
main()
{
float a,b,x,y,h,t,k;
printf("\nEnter x0,y0,h,xn: ");
scanf("%f%f%f%f",&a,&b,&h,&t);
x=a;
y=b;

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 68


printf("\n x\t y\n");
while(x<=t)
{
k=h*fun(x,y);
y=y+k;
x=x+h;
printf("%0.3f\t%0.3f\n",x,y);
}
}
Output:-
Enter x0,y0,h,xn: 1 2 3 4

x y
4.000 11.000
7.000 56.000

Lab 12: Recursive functions


i) Write a recursive function to generate Fibonacci series.
ii) Write a recursive function to find the lcm of two numbers.
iii) Write a recursive function to find the factorial of a number.
iv) Write a C Program to implement Ackermann function using recursion.
v) Write a recursive function to find the sum of series.

i) Write a recursive function to generate Fibonacci series.


#include<stdio.h>
void printFibonacci(int n){
static int n1=0,n2=1,n3;
if(n>0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
printf("%d ",n3);
printFibonacci(n-1);
}
}
int main(){

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 69


int n;
printf("Enter the number of elements: ");
scanf("%d",&n);
printf("Fibonacci Series: ");
printf("%d %d ",0,1);
printFibonacci(n-2);//n-2 because 2 numbers are already printed
return 0;
}
Output:-
Enter the number of elements: 5
Fibonacci Series: 0 1 1 2 3

ii) Write a recursive function to find the lcm of two numbers.

LCM (Least Common Multiple)

LCM stands for Least Common Multiple. It is a method to find the lowest common multiple
between the two numbers. LCM of two numbers is the lowest possible number that is divisible
by both numbers.
Examples: LCM(10,15) = 30, LCM(18,26) = 234.

Program:-

#include <stdio.h>
int lcm(int, int);
int main()
{
int a, b, result;
printf("Enter two numbers: ");
scanf("%d%d", &a, &b);
result = lcm(a, b); //call the function lcm recursively.
printf("The LCM of %d and %d is %d\n", a, b, result);
return 0;
}

int lcm(int a, int b)


{
static int common = 1;
if (common % a == 0 && common % b == 0)

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 70


{
return common;
}
common++;
lcm(a, b); //call the function lcm recursively.
}
Output:-
Enter two numbers: 12 30
The LCM of 12 and 30 is 60

iii) Write a recursive function to find the factorial of a number.

#include<stdio.h>
long int factorial(int n);
int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, factorial(n));
return 0;
}

long int factorial(int n) {


if (n>=1)
return n*factorial(n-1);
else
return 1;
}
Output:-
Enter a positive integer: 5
Factorial of 5 = 120

iv) Write a C Program to implement Ackermann function using recursion.

The Ackermann function, named after the German mathematician Wilhelm Ackermann, is a
recursive mathematical function that takes two non-negative integers as inputs and produces a
non-negative integer as its output. In C, the Ackermann function can be implemented using
recursion.

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 71


Program:-
#include<stdio.h>
int A(int m, int n);
int main()
{
int m,n;
printf("Enter two numbers :: \n");
scanf("%d%d",&m,&n);
printf("\nResult :: %d\n",A(m,n));
return 0;
}

int A(int m, int n)


{
if(m==0)
return n+1;
else if(n==0)
return A(m-1,1);
else
return A(m-1,A(m,n-1));
}

Output:-
Enter two numbers ::
2
3

Result :: 9

v) Write a recursive function to find the sum of series.


#include <stdio.h>

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 72


void display_sum(int);

int main()
{
int num;

printf("Enter the Nth number: ");


scanf("%d", &num);
display_sum(num);
return 0;
}

void display_sum(int num)


{
static int sum = 0;

if (num == 0)
{
printf("Sum of first N numbers is %d\n", sum);
return;
}
else
{
sum += num;
display_sum(--num);
}
}

Output:-
Enter the Nth number: 5
Sum of first N numbers is 15

Lab 13: Simple functions using Call by reference, Dangling pointers.


i) Write a C program to swap two numbers using call by reference.
ii) Demonstrate Dangling pointer problem using a C program.
iii) Write a C program to copy one string into another using pointer.
iv) Write a C program to find no of lowercase, uppercase, digits and other characters using
pointers.

i) Write a C program to swap two numbers using call by reference.

#include <stdio.h>
void swap(int*, int*);
int main()
C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 73
{
int x, y;
printf("Enter the value of x and y\n");
scanf("%d%d",&x,&y);
printf("Before Swapping\nx = %d\ny = %d\n", x, y);
swap(&x, &y);
printf("After Swapping\nx = %d\ny = %d\n", x, y);
return 0;
}

void swap(int *a, int *b)


{
int temp;
temp = *b;
*b = *a;
*a = temp;
}
Output:-
Enter the value of x and y
30 60
Before Swapping
x = 30
y = 60
After Swapping
x = 60

ii) Demonstrate Dangling pointer problem using a C program.

Dangling Pointers in C

The most common bugs related to pointers and memory management is dangling/wild pointers.
Sometimes the programmer fails to initialize the pointer with a valid address, and then this type
of initialized pointer is known as a dangling pointer in C.

Dangling pointer occurs at the time of the object destruction when the object is deleted or de-
allocated from memory without modifying the value of the pointer. In this case, the pointer is
pointing to the memory, which is de-allocated. The dangling pointer can point to the memory,
which contains either the program code or the code of the operating system. If we assign the
value to this pointer, then it overwrites the value of the program code or operating system
instructions; in such cases, the program will show the undesirable result or may even crash. If the

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 74


memory is re-allocated to some other process, then we dereference the dangling pointer will
cause the segmentation faults.

Program:-
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr=(int*)malloc(sizeof(int));
*ptr=10;
printf("value of ptr=%d",*ptr);
free(ptr); /free the ptr memory but still it points the memory
printf("\n At dangling point ptr value is: %d",*ptr);
ptr=NULL; // free the pointer

}
Output:-
value of ptr=10
At dangling point ptr value is: 1588739705 //garbage value

iii) Write a C program to copy one string into another using pointer.

#include<stdio.h>
#include<conio.h>
void main()
{
char *str1, *str2;
int i;
clrscr();
printf("Enter the string : ");
scanf("%s", str2);
for(i = 0; *str2 != '\0'; i++, str1++, str2++)
*str1 = *str2;
*str1 = '\0';
str1 = str1 - i;
printf("\nThe copied string is : %s", str1);
getch();
}
Output:-

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 75


Enter the string : bhuvan
The copied string is : bhuvan

iv) Write a C program to find no of lowercase, uppercase, digits and other characters using
pointers.

#include <string.h>
int main()
{
char s[1000],*p;
int alphabets=0,digits=0,specialcharacters=0;

printf("Enter the string: ");


gets(s);

p=s;

while(*p)
{
if( (*p>=65 && *p<=90) || (*p>=97 && *p<=122 ) )
alphabets++;
else if(*p>=48 && *p<=57)
digits++;
else
specialcharacters++;

p++;
}
printf("Alphabets = %d\n",alphabets);
printf("Digits = %d\n",digits);
printf("Special characters = %d", specialcharacters);
}
Output:-
Enter the string: srikar@1974
Alphabets = 6
Digits = 4
Special characters = 1

Lab 14: File operations


i) Write a C program to write and read text into a file.

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 76


ii) Write a C program to write and read text into a binary file using fread() and fwrite()
iii) Copy the contents of one file to another file.
iv) Write a C program to merge two files into the third file using command-line arguments.
v) Find no. of lines, words and characters in a file
vi) Write a C program to print last n characters of a given file.

i) Write a C program to write and read text into a file.

#include<stdio.h>
#include<stdlib.h>
main()
{
char name[30];
int i,score,n;
FILE *f1;
f1=fopen("marks.txt","w");
printf("Enter the no of students:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the name:");
scanf("%s",name);
printf("Enter the score:");
scanf("%d",&score);
fprintf(f1,"\n%s",name);
fprintf(f1,"\t%d",score);
printf("\n");
}
fclose(f1);
f1=fopen("marks.txt","r");
while(fscanf(f1,"%s%d",&name,&score)!=EOF)
{
printf("\n Name=%s",name);

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 77


printf("\tScore=%d",score);
}
fclose(f1);
}
Output:-
Enter the no of students:3
Enter the name:srikar
Enter the score:100
Enter the name:nani
Enter the score:200
Enter the name:vasu
Enter the score:300
Name=srikar Score=100
Name=nani Score=200
Name=vasu Score=300
ii) Write a C program to write and read text into a binary file using fread() and fwrite()
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>

struct threeNum
{
int n1,n2,n3;
};

main()
{
int n;
struct threeNum num;
FILE *fp;
clrscr();
if((fp=fopen("srikar1.bin","wb"))==NULL)
{
printf("Error opening file:");
exit(1);
}

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 78


printf("Enter the n value:");
scanf("%d",&n);
num.n1=n;
num.n2=5*n;
num.n3=5*n+1;
fwrite(&num,sizeof(struct threeNum),1,fp);

fread(&num,sizeof(struct threeNum),1,fp);
printf("n1=%d\tn2=%d\tn3=%d",num.n1,num.n2,num.n3);

fclose(fp);
}
Output:-
Enter the n value:5
n1=5 n2=25 n=26
iii) Copy the contents of one file to another file.

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

int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;

printf("Enter the filename to open for reading :\n");


scanf("%s", filename);

// Open one file for reading


fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}

printf("Enter the filename to open for writing :\n");


scanf("%s", filename);

// Open another file for writing


fptr2 = fopen(filename, "w");

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 79


if (fptr2 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}

// Read contents from file


c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}

printf("\nContents copied to %s", filename);


fclose(fptr1);
fclose(fptr2);
return 0;
}

Output :-

Enter the filename to open for reading : a.txt


Enter the filename to open for writing : b.txt

Contents copied to b.txt

iv) Write a C program to merge two files into the third file using command-line arguments.

#include<stdio.h>
#include<conio.h>
#include<process.h>
void main(int argc, char *argv[])
{
FILE *fp1,*fp2,*fp3;

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 80


char ch1,ch2,ch3;
int i;
clrscr();
if(argc!=4)
{
puts("can't open a file \n");
printf("The no of arguments =%d",argc);
exit(1);
}
fp1=fopen(argv[1],"w");
for(i=65;i<=90;i++)
putc(i,fp1);
fclose(fp1);
fp1=fopen(argv[1],"r");
printf("The first file content are:\n");
while((ch1=getc(fp1))!=EOF)
{
printf("%c",ch1);
}
fclose(fp1);
fp2=fopen(argv[2],"w");
for(i=97;i<=122;i++)
putc(i,fp2);
fclose(fp2);
fp2=fopen(argv[2],"r");
printf("\nThe second file content are:\n");
while((ch2=getc(fp2))!=EOF)
printf("%c",ch2);
fclose(fp2);
fp1=fopen(argv[1],"r");
fp2=fopen(argv[2],"r");
fp3=fopen(argv[3],"w");
/*while((ch1=getc(fp1))!=EOF && (ch2=fgetc(fp2))!=EOF)
{
putc(ch1,fp3);
fputc(ch2,fp3);
}
fclose(fp1);
C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 81
fclose(fp2);
fclose(fp3);*/
while((ch1=getc(fp1))!=EOF)
putc(ch1,fp3);
while((ch2=fgetc(fp2))!=EOF)
fputc(ch2,fp3);
fclose(fp1);
fclose(fp2);
fclose(fp3);
printf("\n Merged file is :\n");
fp3=fopen(argv[3],"r");
while((ch3=getc(fp3))!=EOF)
printf("%c ",ch3);
fclose(fp3);
getch();
}
Output;-
C:\TURBOC3\SOURCE>fmerge a1.txt a2.txt a3.txt

v) Find no. of lines, words and characters in a file


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

int main()
{
FILE * file;
char path[100];

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 82


char ch;
int characters, words, lines;
clrscr();
printf("Enter the source file name:");
scanf("%s",path);

/* Open source files in 'r' mode */


file = fopen(path, "r");

/* Check if file opened successfully */


if (file == NULL)
{
printf("\nUnable to open file.\n");
// printf("Please check if file exists and you have read privilege.\n");

exit(EXIT_FAILURE);
}

/*
* Logic to count characters, words and lines.
*/
characters = words = lines = 0;
while ((ch = fgetc(file)) != EOF)
{
characters++;

/* Check new line */


if (ch == '\n' || ch == '\0')
lines++;

/* Check words */
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')
words++;
}

/* Increment words and lines for last word */


if (characters > 0)
{
words++;
lines++;
}

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 83


/* Print file statistics */
printf("\n");
printf("Total characters = %d\n", characters);
printf("Total words = %d\n", words);
printf("Total lines = %d\n", lines);

/* Close files to release resources */


fclose(file);

return 0;
}
Output:-
Enter the source file name:a1.txt
Characters :26
Words: 1
Lines: 1
a1.txt
ABCDEFGHIJKLMNOPQRSTUVWXYZ

vi) Write a C program to print last n characters of a given file.

#include<stdio.h>
#include<process.h>
int main()
{
FILE *fp;
char ch;
int num;
long length;
printf("Enter the no of characters :");
scanf("%d",&num);
fp=fopen("a1.txt","r");
if(fp==NULL)
{
puts("Cannot open this file");

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 84


exit(1);
}
fseek(fp,0,SEEK_END);
length=ftell(fp);
fseek(fp,(length-num),SEEK_SET);
do
{
ch=fgetc(fp);
putchar(ch);
}while(ch!=EOF);
fclose(fp);
return 0;
}
Output:-
Enter the no of characters: 3
XYZ
a1.txt
ABCDEFGHIJKLMNOPQRSTUVWXYZ

C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 85

You might also like