0% found this document useful (0 votes)
2 views74 pages

Final C Lab Manual

The document is a lab manual for a Computer Programming Lab at SRK Institute of Technology for the academic year 2023-24. It covers various programming topics, including familiarization with Linux environments, usage of the vi editor, and writing simple C programs for tasks like input/output, calculations, and conversions. The manual is structured week by week, detailing specific programming exercises and their corresponding outputs.

Uploaded by

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

Final C Lab Manual

The document is a lab manual for a Computer Programming Lab at SRK Institute of Technology for the academic year 2023-24. It covers various programming topics, including familiarization with Linux environments, usage of the vi editor, and writing simple C programs for tasks like input/output, calculations, and conversions. The manual is structured week by week, detailing specific programming exercises and their corresponding outputs.

Uploaded by

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

LAB MANUAL

COMPUTER PROGRAMMING LAB

DEPARTMENT OF SCIENCE AND HUMANITIES

SRK INSTITUTE OF TECHNOLOGY

ACADEMIC YEAR 2023-24

(I B.TECH I SEM R23 REGULATION)

Prepared By

N.Marimbi
WEEK 1

Tutorial1: problem solving using computers.

Lab1: familiarization with programming environments:

(i) Basic Linux environment and its editors like vi, vim,emac etc.
(ii) Exposure to turbo c, gcc.
(iii) Writing simple programs using printf () and scanf().

(i)Basic Linux environment and its editors like vi, vim, emac etc.

A Linux environment supports multiple text editors. There are two types of editors in Linux.

1. Command line editors are: vi ,nano, pico and more.

2. gui editors editors are: gedit(for gnome) ,k write and more.

an area that contains information about the behaviour of programs and applications is called
environment.

Vi

Vi editor is a powerful and widely used text editor in UNIX and Linux operating system. It
allows us to create, edit and manage text files. Vim is the advanced version of vi editor. There
are three modes in vi: Command mode, Last Line Mode and Insert Mode..

Modes of Operation in the vi editor

There are three modes of operation in vi:

Here are three modes of operations on the vi editor

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. If we press [Esc] when we are already in
Command Mode, then vi will beep or flash the screen.
Insert mode:
This mode enables you to insert text into the file. Everything that’s typed in this mode is
interpreted as input and finally, it is put in 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):
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.
2.Basic linux environment and its editor like vi,vim&emac etc.



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.
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 with `file_name` = geeksforgeeks
vi geeksforgeeks
2) Opening a preexisted file with `file_name` = jayesh
vi jayesh
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. If we press [Esc] when we are already in
Command Mode, then vi will beep or flash the screen.
Insert mode:
This mode enables you to insert text into the file. Everything that’s typed in this mode is
interpreted as input and finally, it is put in 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):
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.
Linux vi Commands and Examples
NOTE: vi editor in Linux is a case-sensitive.

How to insert in vi editor in Linux?

To enter in insert mode in vi editor in Linux we just need to press `i` on our keyboard and we
will be in insert mode. we can just start entering our content. (Refer to screenshot mentioned
below).

Commands Description

Moves the cursor up


`k` one line.

Moves the cursor


`j` down one line.

Moves the cursor to


the left one-character
`h` position.

Moves the cursor to


the right one-character
`l` position.
Commands Description

Positions cursor at
`0` beginning of line.

Positions cursor at end


`$` of line.

Positions cursor to the


`W` next word.

Position cursor to
previous work
`B`

Control Command (Scrolling) in vi editor in Linux:


There are the following useful commands which can be used along
with the Control Key. These commands are helpful in saving time by
navigating quickly in a file without manually scrolling.
Command Description

CTRL+d moves the screen down by half a page.

CTRL+f moves the screen down by a full page.

CTRL+u moves the screen up by half a page.

CTRL+b moves the screen up by a full page.

CTRL+e moves the screen up by one line.

CTRL+y moves the screen down by one line.

CTRL+I redraw the screen.

Common vi Editor Commands for Inserting and Replacing text:


Commands Description

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

Command Description

i Inserts text before current cursor location

a Insert text after current cursor location

A Insert text at the end of current line

Creates a new line for text entry below cursor location


o and switches to insert mode.

Creates a new line for text entry above cursor location


O and switches to insert mode.

2. Exposure to TURBO C,gcc




In this article, we will look into how to install Turbo C++ on Linux. Turbo C++ is the free and
Open-Source Software, it is a development tool for writing programs in the C/C++ language.
Turbo C++ is a compiler and IDE (Integrated development environment) originally from
Borland.
Prerequisites:
To run Turbo C++ in Linux System you must have the following:
Turbo C++ Setup

DOSBox Emulator

Note: If you have it installed on your system, just go to Linux Software Center and search for
DOSBox and install the emulator or use the below command in the terminal:
sudo apt-get install dosbox
Installing Turbo C++ on Linux:
Follow the below steps to install Turbo C++ on Linux:
Step 1: Download and Extract the zip file of Turbo C++.
Step 2: Move the extracted folder to your home folder
Step 3: Go to the Dosbox configuration file and change settings. Use the following command –
satyajit@satyajit:~$ gedit .dosbox/dosbox-0.74-3.conf
Then change the following key values on that configuration file –
fullscreen=true
fulldouble=true
fullresolution=1920x1080
windowresolution=1920x1080
output=opengl
Now to run Turbo C++ go to the terminal and write –
dosbox
It will start Turbo C++
Press Alt + Enter to switch between full screen and window mode.
Press Ctrl + F10 to release and lock the mouse on DOSBox

3. Aim: To write a simple programs using printf(),scanf()


Program:

#include<stdio.h>

int main()//main function starts//

int x;

printf("enter the number =");

scanf("%d",&x);

printf("The number is=%d",x);

return 0;
}

Output:

enter the number =4

The number is=4


WEEK 2
1. Aim: To write a c program sum and average of 3 numbers.

Alogorithm:

 Program Start
 Declaring Variables
 Input Three Numbers from User
 Calculating Sum of Three Numbers (sum = x + y + z)
 Displaying the Sum of Three Numbers
 Calculating Average of Three Numbers (average = sum/count)
 Displaying the Average of Three Numbers
 Program End

Program:

#include<stdio.h>
int main()
{
//Declaring Three Variables

int x, y, z, sum;
float avg;//float can be defines numeric values with floating decimal point//

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 Numebers is : %d", sum);

//Calculating Average of three numbers

avg=sum/3;
printf("\n Average of Three Numebers is : %f", avg);

return 0;//prog will executes successfully//


}
Output:
Enter Three Numbers :
10 20 30
Sum of Three Numebers is : 60
Average of Three Numebers is : 20.000000

2. A) Write a c program Conversion of Fahrenheit to Celsius and vice versa.

 Program Start
 Declaring Variables
 Input Fahrenheit from User
 Calculating Celsius c=(f-32)*5/9
 Displaying the Celsius
 Program End

Aim: To write a c program conversion of Fahrenheit to Celsius and vice versa

Program: Fahrenheit to Celsius

#include <stdio.h>

int main()

float f;

float c;

printf("enter f value");

scanf("%f",&f);

c=(f-32)*5/9;//Fahrenheit to Celsius formula//

printf("%f",c);

return 0;

Out put:
enter f value98

36.666668
2. B.) Celsius to Fahrenheit

#include <stdio.h>

int main()

float f;

float c;

printf("enter c value");

scanf("%f",&c);

f=(c*9)/5+32; //F=9/5*C+32//

printf("%f",f);

return 0;

Output:

enter c value38

100.400002
3. Aim: To write a c program simple interest.

#include <stdio.h>

int main()

float principle,time,rate,SI;

//input principle ,rate and time//

printf("enter principal(amount):");

scanf("%f", &principle);

printf("enter time:");
scanf("%f", &time);

printf("enter rate:");

scanf("%f", &rate);

//calculate simple intrest//

SI = (principle *time *rate)/100;

//print the resultant value of si//

printf("simple intrest = %f", SI);

return 0;

Output:

enter principal(amount):5000

enter time:2

enter rate:2

simple intrest = 200.000000


WEEK 3

1. Aim: To write a c program to find the square root of a given number.

The sqrt() function is defined in math.h header file.

#include <math.h>

#include <stdio.h>

int main()

double number, squareRoot;

printf("Enter a number: ");

scanf("%lf", &number);

// computing the square root

squareRoot = sqrt(number);

printf("Square root of %.2lf = %.2lf", number, squareRoot);

return 0;

Output:

Enter a number: 12

Square root of 12.00 = 3.46


2. Aim: To write a c program to find the compound interest.

Formula to calculate compound interest annually is given by.

Where,
P is principle amount
R is the rate and
T is the time span

Algorithm : Step by step descriptive logic to find compound interest.

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:

/**

* C program to calculate Compound Interest

*/

#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

3. Aim: To write a c program to find the area of a triangle using heron’s formula .

Area = √(s*(s-a)*(s-b)*(s-c))
s = (a + b + c)/2 (Here s = semi perimeter and a, b, c are the three sides of a triangle)

The perimeter of a Triangle = a+b+c.


#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

8
Perimeter of Traiangle = 21.00

Semi Perimeter of Traiangle = 10.50

Area of triangle = 20.33

4. Aim: To write a c program to find distance travelled by an object.

Accept initial velocity(u),acceleration(a),and time(t).

Print the final velocity(v) and distance(s) traveled.

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);

v=u+a*t;

s=u*t+(1/2)*a*t*t;

printf("\n The final Velocity is : %f",v);


printf("\n \n The distance traveled is : %f \n \n",s);

Output:

Enter initial velocity: 12

Enter acceleration: 10

Enter time required: 10

The final Velocity is : 112.000000

The distance traveled is : 120.000000

WEEK4

1. Aim: write a C program Find the max of three numbers using conditional operator

#include <stdio.h>

int main()

int num1, num2, num3, max;

/*

* Input three numbers from user

*/

printf("Enter three numbers: ");

scanf("%d%d%d", &num1, &num2, &num3);

/*

* If num1 > num2 and num1 > num3 then

* assign num1 to max


* else if num2 > num3 then

* assign num2 to max

* else

* assign num3 to max

*/

max = (num1 > num2 && num1 > num3) ? num1 :

(num2 > num3) ? num2 : num3;

printf("\nMaximum between %d, %d and %d = %d", num1, num2, num3, max);

return 0;

2. Aim: Write a C program, Take marks of 5 subjects in integers, and find the total,
average in float

#include <stdio.h>

int main()

float eng, phy, chem, math, comp;

float total, average, percentage;

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

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

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

average = total / 5.0;

percentage = (total / 500.0) * 100;


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

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

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

return 0;

WEEK5

1. Aim: To Write a C program to find the max and min of four numbers using if-else.

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

int num1, num2, num3, num4,max;


printf("Enter 4 numbers here...\n");
scanf("%d %d %d %d", &num1, &num2, &num3, &num4);

if(num1>num2&&num1>num3&&num1>num4)
max=num1;
else if(num2>num3&&num2>num4)
max=num2;
else if(num3>num4)
max=num3;
else
max=num4;
printf("the max value is %d",max);
return 0;

Output:
Enter 4 numbers here...
10
50
80
90
the max value is 90

2. Aim: To Write a C program to generate electricity bill.

#include <stdio.h>

int main()
{
int unit;
float amt;
printf("Enter total units consumed: ");
scanf("%d", &unit);

if(unit <= 50)


{
amt = unit * 2;
}
else if(unit <= 100)
{
amt = 50*2 + ((unit-50) * 4);
}
else if(unit <= 200)
{
amt = 50*2 +50*4+ ((unit-100) * 6);
}
else
{
amt = 50*2+50*4+100*6+ ((unit-200) * 8);
}

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

return 0;
}

Output:
Enter total units consumed: 200

Electricity Bill = Rs. 900.000000

3. Aim: To Find the roots of the quadratic equation.

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

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

if (dis > 0)
{
root1 = (-b + sqrt(dis)) / (2 * a);
root2 = (-b - sqrt(dis)) / (2 * a);
printf("real and different roots ,root1 = %f and root2 = %f", root1, root2);
}
else if (dis == 0)
{
root1 = root2 = -b / (2 * a);
printf("real and equal roots,root1 = root2 = %f;", root1);
}
else
{
printf("roots are imaginary");
}
return 0;
}

Output:

Enter coefficients a, b and c: 1

roots are imaginary


4. Aim: To Write a C program to simulate a calculator using switch case.

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

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

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

return 0;
}

Output:

Enter an operator (+, -, *, /): *

Enter two operands: 20

20

20.000000 * 20.000000 = 400.000000

5. Aim: To Write a C program to find the given year is a leap year or not.
#include <stdio.h>
int main()
{
int year;
printf("Enter a year: ");
scanf("%d", &year);

if (year%100!= 0&&year%4 == 0||year%400 == 0)


printf("%d is a leap year.", year);
else
printf("%d is not a leap year.", year);

return 0;
}

Output:

Enter a year: 2004

2004 is a leap year.

WEEK 6

1. Aim: To Find the factorial of given number using any loop.

#include <stdio.h>
int main() {
int n, i;
unsigned long fact = 1;
printf("Enter an integer: ");
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
fact =fact*i;
}
printf("Factorial of %d = %lu", n, fact);
return 0;
}

Output:
Enter an integer: 5
Factorial of 5 = 120

2. Aim: write a c program to Find the given number is a prime or not.


program:

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

if (n == 0 || n == 1)
flag = 1;
for (i = 2; i <= n / 2; i++)
{
if (n % i == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
return 0;
}

Output:
Enter a number: 23
23 s a prime number.

3. Aim: write a C program to Compute sine and cos series.

#include<stdio.h>
int main()
{
int i, n;
float x, sum, t;
printf(" Enter the value for x : ");
scanf("%f",&x);

printf(" Enter the no of terms : ");


scanf("%d",&n);

x=x*3.14159/180;
//cos series
sum=1, t=1;
for(i=1;i<=n;i++)
{
t=t*(-1)*x*x/(2*i*(2*i-1));
sum=sum+t;
}
printf(" The value of Cos(%f) is : %.4f", x, sum);

//sin series
t=x;
sum=x;
for(i=1;i<=n;i++)
{
t=(t*(-1)*x*x)/(2*i*(2*i+1));
sum=sum+t;
}
printf(" \n The value of Sin(%f) = %.4f",x,sum);
return(0);
}

Output:
Enter the value for x : 30
Enter the value for n : 5
The value of Cos(0.523598) is : 0.8660
The value of Sin(0.523598) = 0.5000

4. Aim: write a C program Checking a number palindrome

#include <stdio.h>
int main()
{
int n, reverse = 0, remainder, original;
printf("Enter an integer: ");
scanf("%d", &n);
original = n;
while (n != 0) {
remainder = n % 10;
reverse = reverse * 10 + remainder;
n /= 10;
}

// palindrome if orignal and reversed are equal


if (original == reverse)
printf("%d is a palindrome.", original);
else
printf("%d is not a palindrome.", original);

return 0;
}

Output:

Enter an integer: 121


121 is a palindrome.

5. Aim: write a c program to Construct a pyramid of numbers.

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

// first loop to print all rows


for ( i = 1; i <= rows; i++) {

// inner loop 1 to print white spaces


for ( j = 1; j <= 2 * (rows - i); j++)
{
printf(" ");
}

// inner loop 2 to print numbers


for (int k = 1; k < 2 * i; k++) {
printf("%d ", i);
}
printf("\n");
}
return 0;
}

Output:

Enter the number of rows: 4


1
232
34543
4567654

WEEK 7

1. Aim: To write a c progeam to Find the min and max of a 1-D integer array.

#include <stdio.h>
int main()
{
int a[10], i, n, max,min;
printf("Enter number of elements: ");
scanf("%d", &n);
for(i=0; i<n; ++i)
{
scanf("%d", &a[i]);
}
max = a[0];
min =a[0];
for(i=1; i<n; ++i)
{
if(a[i]>big)
max = a[i];
if(a[i]< min)
min = a[i];
}
printf("max is %d \n", max);
printf("min is %d", min);
}

Output:
Enter number of elements: 5
12 3 4 5 10
max is 12
min is 3

2. Aim: To Perform linear search on1D array.

#include <stdio.h>
int main() {
int a[10], i, n, found=0,search;
printf("Enter number of elements: ");
scanf("%d", &n);
for(i=0; i<n; ++i)
{
scanf("%d", &a[i]);
}
printf("enter search key:");
scanf("%d",&search);

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


{
if(a[i]==search)
{
found=1;
break;
}
}
if(found==1)
printf("element found");
else
printf("element not found");

return 0;
}

Output:
Enter number of elements: 5
12 3 4 5 6
enter search key:4
element found

3. Aim : To find The reverse of a 1D integer array

int main()
{
int n, a[10], rev[10], i,j;
printf("Enter the size of the array: ");
scanf("%d", &n);
printf("Enter the elements: ");
for(i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
j=n-1;
for(i = 0; i <n; i++)
{
rev[j] = a[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: 3 4 5 6 7
The Reversed array: 7 6 5 4 3

4. Aim: To find 2’s complement of the given binary number.

#include <stdio.h>
int main()
{
char binary[20], onesComp[20], twosComp[20];
int i, n,carry=1;
printf("Enter the no of bits :");
scanf("%d",&n);
printf("Enter the binary data ");
scanf("%s",&binary);

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


{
if(binary[i] == '1')
{
onesComp[i] = '0';
}
else if(binary[i] == '0')
{
onesComp[i] = '1';
}
}
onesComp[n] = '\0';

for(i=n-1; i>=0; i--)


{
if(onesComp[i] == '1' && carry == 1)
{
twosComp[i] = '0';
}
else if(onesComp[i] == '0' && carry == 1)
{
twosComp[i] = '1';
carry = 0;
}
else
{
twosComp[i] = onesComp[i];
}
}
twosComp[n] = '\0';

printf("Original binary = %s\n", binary);


printf("Ones complement = %s\n", onesComp);
printf("Twos complement = %s\n", twosComp);

return 0;
}
Output:

Enter the no of bits :8

Enter the binary data 10101010

Original binary = 10101010

Ones complement = 01010101

Twos complement = 01010110

5. Aim: To Eliminate duplicate elements in an array

Program:

#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("After deleting the duplicate element the Array is:");
for(i=0;i<number;i++){
printf("%d ",a[i]);
}
}

Output:

Enter size of the array5

Enter Elements of the array:2

Entered element are: 2 2 2 2 2 after deleting the duplicate element the Array is

:2

WEEK8

1. Aim: To find the matrix addition


#include<stdio.h>
int main()
{
int a[10][10],b[10][10],c[10][10];
int i,j,m1,n1,m2,n2;

printf("enter number of rows and columns for matrix a:");


scanf("%d %d",&m1,&n1);

printf("enter number of rows and columns for matrix b:");


scanf("%d %d",&m2,&n2);
printf("enter matrix a value :\n ");
for(i=0;i<m1;i++)
for(j=0;j<n1;j++)
scanf("%d",&a[i][j]);
printf("enter matrix b value:\n");
for(i=0;i<m2;i++)
for(j=0;j<n2;j++)
scanf("%d",&b[i][j]);
for(i=0;i<m1;i++)
for(j=0;j<n1;j++)
c[i][j]=a[i][j]+b[i][j];
printf("addition is:\n");
for(i=0;i<m1;i++)
{
for(j=0;j<n1;j++)
printf("%3d",c[i][j]);
printf("\n");
}

Output:
enter number of rows and columns for matrix a:2 2
enter number of rows and columns for matrix b:2 2
enter matrix a value :
12
34
enter matrix b value:
34
56
addition is:
4 6
8 10

2. Aim: To find matrix multiplication

#include<stdio.h>
int main()
{
int a[10][10],b[10][10],c[10][10];
int i,j,k,m1,m2,n1,n2;
printf("enter no.of rows and columns for matrix a:");
scanf("%d %d",&m1,&n1);
printf("enter no.of rows and columns for matrix b:");
scanf("%d %d",&m2,&n2);

if(n1!=m2)
printf("multiplication is not possible");
else
{
printf("enter matrix a value:\n");
for(i=0;i<m1;i++)
for(j=0;j<n1;j++)
scanf("%d",&a[i][j]);
printf("enter matrix b value:\n");
for(i=0;i<m2;i++)
for(j=0;j<n2;j++)
scanf("%d",&b[i][j]);
for(i=0;i<m1;i++)
{
for(j=0;j<n2;j++)
{
c[i][j]=0;
for(k=0;k<n1;k++)
{
c[i][j]=c[i][j]+(a[i][k]*b[j][k]);
}
}
}
printf("multiplication is :\n");
for(i=0;i<m1;i++)
{
for(j=0;j<n2;j++)
printf("%d ",c[i][j]);
printf("\n");
}
}
}
Output:
enter no.of rows and columns for matrix a:2 2
enter no.of rows and columns for matrix b:2 2
enter matrix a value:
12
34
enter matrix b value:
34
56
multiplication is :
11 17
25 39

3.Aim: Multiple string sorting using bubble sort.

#include<stdio.h>
#include<string.h>
int main()
{
char x[10][15];
char temp[60];
int i,j,n;
printf("enter n value");
scanf("%d",&n);
fflush(stdin);
printf("Enter the strings\n");
for(i=0;i<n;i++)
gets(x[i]);

for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(strcmp(x[i],x[j])>0)
{
strcpy(temp,x[i]);
strcpy(x[i],x[j]);
strcpy(x[j],temp);
}
printf("sorted strings are:\n");
for(i=0;i<n;i++)
puts(x[i]);
return(0);
}

Output:
enter n value2
Enter the strings
rani
latha
sorted strings are:
latha
rani

4. Aim: To concatenation of the strings


#include<stdio.h>
#include<string.h>
int main()
{
char string1[20],string2[20];
int i,j;
printf("enter string1");
gets(string1);
printf("enter string2");
gets(string2);
for(i=0;string1[i]!='\0';i++)
{

}
for(j=0;string2[j]!='\0';j++,i++)
{
string1[i]=string2[j];
}
string1[i]='\0';
printf("the concatenate string is %s",string1);
}
Output:
enter string1hello
enter string2srkit
the concatenate string is hellosrkit

5. Aim: To reverse the Strings

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

int main()
{
char str1[20],rev[20];
int i,j;
printf("enter string:");
gets(str1);
for(i=0;str1[i]!='\0';i++){}
i=i-1;
for(j=0;i>=0;j++,i--)
rev[j]=str1[i];
rev[j]='\0';
printf("reverse without library function %s",rev);
printf(" \nthe reverse string with library function used %s",strrev(str1));
return 0;
}

Output:
enter string:hello
reverse without library function olleh
the reverse string with library function used olleh

WEEK9

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

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

int i,n,*p;

int sum = 0;

printf("Enter the total number of elements you want to enter : ");


scanf("%d", &n);

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


printf("Enter elements:");

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


{
scanf("%d", p + i);
sum = sum+ *(p + i);
}
printf("sum is %d \n", sum);
free(p);
return 0;
}
Output:

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


Enter elements:10
20
30
40
sum is 100

2. Aim: To Write a C program to find the total, average of n students using structures

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

struct student
{
int rno;
char name[30];
int marks[6];
};

int main()
{
struct student *p;
int n,i,j,total=0;
float avg;
printf("Enter the number of students: ");
scanf("%d", &n);
p = (struct student *)malloc(n * sizeof(struct student));
for (i = 0; i < n; ++i)
{
printf("Enter roll no,name and marks:\n");
scanf("%d %s", &p[i].rno,p[i].name);
for(j=0;j<6;j++)
scanf("%d", &p[i].marks[j]);
}

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


{
for(j=0;j<6;j++)
total=total+p[i].marks [ j ];
avg=(float)total/6;
printf(" student %d total=%d,average=%f\n",i+1,total,avg);
}
free(p);
return 0;
}

Output:

Enter the number of students: 2


Enter roll no,name and marks:
1
hari
1
2
3
4
5
6
Enter roll no,name and marks:
2
rani
1
2
3
4
5
6
student 1 total=21,average=3.500000
student 2 total=42,average=7.000000

3. Aim: To Enter n students data using calloc() and display failed students list
# include <stdio.h>
#include<stdlib.h>
struct student
{
char name[10];
int m[6];

}*p;
void main()
{
int i,j,n;

printf("Enter the no. of students : ");


scanf("%d",&n);
p=(struct student *) calloc(n,sizeof(struct student));
for(i=0;i<n;i++)
{
printf("Enter a name : ");
scanf("%s",p[i].name);
for(j=0;j<6;j++)
{
printf("Enter Marks of %d Subject : ",j+1);
scanf("%d",&p[i].m[j]);
}

}
printf("failed student names:\n");
for(i=0;i<n;i++)
{
for(j=0;j<6;j++)
if((p[i].m[j])<35)
{
printf("%s\n",p[i].name );
break;
}

}
}

Output:

Enter the no. of students : 2


Enter a name : latha
Enter Marks of Subject 1 : 12
Enter Marks of Subject 2 :3
Enter Marks of Subject 3 :5
Enter Marks of Subject 4 :6
Enter Marks of Subject 5 : 48
Enter Marks of Subject 6 : 78
Enter a name : rani
Enter Marks of Subject 1 : 89
Enter Marks of Subject 2 : 78
Enter Marks of Subject 3 : 96
Enter Marks of Subject 4 : 58
Enter Marks of Subject 5 : 68
Enter Marks of Subject 6 : 47
failed student names:
latha

4. Aim: To Read student name and marks from the command line and display the student
details along with the total.

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

int main(int argc, char *argv[])


{
int a,b,i,sum=0;
char name[20];
for(i=2;i<=argc;i++)
sum=sum+atoi(argv[i]);
printf("name is %s and total is %d\n",argv[1],sum);

return 0;
}
Output:
./a.out ajay 20 30

name is ajay and total is 50

5. Aim: To Write a C program to implement realloc()

# include <stdio.h>
#include<stdlib.h>
int main()
{
int *p,i;
p = (int *)malloc(sizeof(int));
p[0] = 1;
//realloc memory size to store 3 integers
p = (int *)realloc(p, 3* sizeof(int));
p[1] = 2;
p[2] = 3;
//printing values
for(i = 0; i < 3; i++)
printf("%d\n",p[i]);
free(p);
return 0;
}
Output:
1
2
3

WEEK10

1. Aim: To 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 next node
}*stnode;
int main()
{
int n;
printf("\n\n Linked List : To create and display Singly Linked List :\n");
printf("-------------------------------------------------------------\n");

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


scanf("%d", &n);
createNodeList(n);
printf("\n Data entered in the list : \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 fnnode is NULL and if so no memory allocation
{
printf(" Memory can not 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;
// Creating n nodes and adding to linked list
for(i=2; i<=n; i++)
{
fnNode = (struct node *)malloc(sizeof(struct node));

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

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


tmp = tmp->nextptr;
}
}
}
void displayList()
{
struct node *tmp;
if(stnode == NULL)
{
printf(" List is empty.");
}
else
{
tmp = stnode;
while(tmp != NULL)
{
printf(" Data = %d\n", tmp->num); // prints the data of current node
tmp = tmp->nextptr; // advances the position of current node
}
}
}

Output:

Linked List : To create and display Singly Linked List :


-------------------------------------------------------------
Input the number of nodes : 2
Input data for node 1 : 12
Input data for node 2 : 13
Data entered in the list :
Data = 12
Data = 13

2. Aim: To Demonstrate the differences between structures and unions using a C program.

Union program:

#include<stdio.h>
union item
{
int x;
int y;

};
int main( )
{
union item it;
it.y = 20;
it.x = 12;

printf("size of item is %d \n",sizeof(it));


printf("%d\n", it.x);
printf("%d\n", it.y);
return 0;
}

Output:
size of item is 4
12
12

Structure Program:

#include<stdio.h>
struct item
{
int x;
int y;

};

int main( )
{
struct item it;
it.y = 20;
it.x = 12;

printf("size of item is %d \n",sizeof(it));


printf("%d\n", it.x);
printf("%d\n", it.y);
return 0;
}

Output:
size of item is 8
12
20
3. Aim: To Write a C program to shift/rotate using bitfields.

#include<stdio.h>

int main()
{
int n = 16;
int d = 2;
printf("Left Rotation of %d by %d is ", n, d);
printf("%d", n<<d);
printf("\nRight Rotation of %d by %d is ", n, d);
printf("%d", n>>d);
return (0);
}

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

4. Aim: To Write a C program to copy one structure variable to another structure of the
same type.

struct student
{
char name[20];
char country[20];
};
void main()
{
struct student S={"ajay","india"};
struct student X;
X=S;
printf("%s %s",X.name,X.country);
}

Output:
size of item is 40

ajay india
WEEK 11

1. Aim: To Write a C function to calculate NCR value.

#include <stdio.h>
long factorial(int n)
{
int i;
long result = 1;
for (i = 1; i <= n; i++)
result = result*i;

return result;
}
int main()
{
int n, r;
long ncr;
printf("Enter the value of n and r:");
scanf("%d %d",&n,&r);

ncr = factorial(n)/(factorial(r)*factorial(n-r));

printf("%dC%d = %ld", n, r, ncr);


return 0;
}

Output:
Enter the value of n and r :5 2
5C2 = 10

2. Aim: To Write a C function to find the length of a string.

#include<stdio.h>
int length(char str[20])
{
int i;
for(i=0;str[i]!='\0';i++)
{
}
return(i);
}
main()
{
int result;
result=length("hello");
printf("length of string is %d\n",result);
printf("length of string is %d\n",length("hai"));

}
Output:
length of string is 5
length of string is 3

3. Aim: To Write a C function to transpose of a matrix.

#include<stdio.h>
int m,n;

void readmatrix(int a[10][10])


{
int i,j;

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


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

void transposematrix(int a[10][10])


{
int i,j,temp;
for( i=0; i<m; i++)
for( j=0; j<n; j++)
if(i<j)
{
temp = a[i][j];
a[i][j] = a[j][i];
a[j][i] = temp;
}

}
void displaymatrix(int a[10][10])
{
int i,j;
printf("The transposed matrix is:\n");
for(i=0; i<n; i++)
{
for(j=0; j<m; j++)
printf("%d ", a[i][j]);
printf("\n");
}

int main(){

int a[10][10];
printf("Enter the number of row and columns: ");

scanf("%d %d",&m,&n);
readmatrix(a);
transposematrix(a);
displaymatrix(a);
return(0);

Output:
Enter the number of row and columns: 3 3
Enter the elements of the matrix:
123
456
789
The transposed matrix is:
147
258
36 9

4. Aim: To Write a C function to demonstrate numerical integration of differential


equations using Euler’s method

#include<stdio.h>

void euler(float a,float b,float h,float t)


{
float x,y,k;
x=a;
y=b;
printf("\n x\t y\n");
while(x<=t)
{
k=h*(x+y);
y=y+k;
x=x+h;
printf("%0.3f\t%0.3f\n",x,y);
}
}
main()
{
float a,b,h,t;
printf("\nEnter x0,y0,h,xn: ");
scanf("%f%f%f%f",&a,&b,&h,&t);
euler(a,b,h,t);

}
Output:
Enter x0,y0,h,xn: 0 1 0.1 1

x y
0.100 1.100
0.200 1.220
0.300 1.362
0.400 1.528
0.500 1.721
0.600 1.943
0.700 2.197
0.800 2.487
0.900 2.816
1.000 3.187

WEEK 12

1. Aim: To Write a recursive function to generate Fibonacci series

Fibonacci series with recursion:

Fibonacci Series in C: In case of fibonacci series, next number is the sum of previous two
numbers for example 0, 1, 1, 2, 3, 5, 8, 13, 21 etc. The first two numbers of fibonacci series
are 0 and 1.

#include<stdio.h>

void fibonacci(int n)
{
static int n1=0,n2=1,n3;

if(n>2)
{
n3 = n1 + n2;
n1 = n2;
n2 = n3;
printf(" %d",n3);
fibonacci(n-1);
}
}
int main()
{
int n;
printf("Enter the number of elements: ");
scanf("%d",&n);
printf("Fibonacci Series: ");
printf("%d %d",0,1);
if(n>2)
fibonacci(n);
return 0;
}

Output:

Enter the number of elements:15


0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

2. Aim: To Write a recursive function to find the lcm of two numbers.

#include <stdio.h>

int lcm(int a, int b)


{
static int common = 1;

if (common % a == 0 && common % b == 0)


{
return common;
}
common++;
lcm(a, b); //call the function lcm recursively.
}

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;
}

Output:

Enter two numbers: 4 12


The LCM of 4 and 12 is 12

3. Aim: To Write a recursive function to generate Fibonacci series.

#include <stdio.h>

long factorial (int n)


{

if (n<1)
return (1);
else
return ( n*factorial(n-1));

int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, factorial(n));
return 0;
}

Output:

Enter a positive integer: 3


Factorial of 3 = 6

4. Aim: To Write a C Program to implement Ackermann function using recursion.

#include<stdio.h>
int ack(int m, int n)
{
if(m==0)
return n+1;
else if(n==0)
return ack(m-1,1);
else
return ack(m-1,ack(m,n-1));
}

void main()
{
int m,n;
printf("Enter two numbers :: \n");
scanf("%d %d",&m,&n);
printf("\nresult is :: %d\n",ack(m,n));
}

Output:

Enter two numbers ::


37

result :: 1021

5. Aim: To Write a recursive function to find the sum of series.

#include<stdio.h>
int series (int n)
{

if (n<1)
return (0);
else
return ( n+series(n-1));

}
int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("sum of series of %d = %d", n, series(n));
return 0;
}

Output:

Enter a positive integer: 5


sum of series of 5 = 15
.

WEEK13

1. Aim: To Write a C program to swap two numbers using call by reference.

#include <stdio.h>
void swap( int *var1, int *var2 )
{
int temp ;
temp = *var1 ;
*var1 = *var2 ;
*var2 = temp;
}

int main()
{
int num1, num2;
printf("\n Enter 2 numbers:");
scanf("%d %d", &num1,&num2);
printf("Before swapping: %d, %d", num1, num2);
/*calling swap function*/
swap(&num1, &num2);
printf("\nafter swapping: %d, %d", num1, num2);
}
Output:

Enter 2 numbers: 12 45

Before swapping: 12, 45

after swapping: 45, 12

2. Aim: To Demonstrate Dangling pointer problem using a C program.

When the variable goes out of the scope then the pointer pointing to the variable becomes
a dangling pointer.

dangling pointer

#include<stdio.h>
int main()
{
char *str;
{
char a = ‘A’;
str = &a;
}

printf("%c", *str);
}

Output:
A

3.Aim: To Write a C program to copy one string into another using pointer.

#include<stdio.h>
void copystrings(char *source, char *dest)
{
while (*source)
{
*dest = *source;
source++;
dest++;
}
*dest = '\0';
}

int main() {
char source[100], dest[100];

printf("Enter the source string:\n");


gets(source);
copystrings(source, dest);
printf("Copied string is: %s\n", dest);

return 0;

Output:

Enter the source string:


hello
Copied string is: hello

4. Aim: To Write a C program to find no of lowercase, uppercase, digits and other


characters using pointers.

#include<stdio.h>
void count(char *str)
{
int lower=0,upper=0,digit=0,other=0;

while (*str)
{
if(*str>=65&&*str<=90)
upper++;
else if(*str>=97&&*str<=122)
lower++;
else if(*str>=48&&*str<=57)
digit++;
else
other++;
str++;
}
printf("lower count=%d,upper count=%d,digit count=%d,other=%d",lower,upper,digit,other);
}

int main() {
char str[100];

printf("Enter the string:\n");


gets(str);
count(str);
return(0);
}

Output:
Enter the string:
helloSRK1234@#$ hh
lower count=7,upper count=3,digit count=4,other=4

WEEK14
1. Aim: To Write a C program to write and read text into a file.

#include<stdio.h>
int main()
{
FILE *fp1,*fp2;
char c;
fp1=fopen("file1.txt","r");
fp2=fopen("file2.txt","w");
while((c=getc(fp1))!=EOF)
{
putc(c,fp2);
printf(“%c”,c);
}
fclose(fp1);
fclose(fp2);
return 0;
}
Output:

We are SRKIT CSM students

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

#include<stdio.h>
struct student{
int sno;
char sname [30];
float marks;
};
int main ( )
{
struct student s[60];
int i;
FILE *fp;
fp = fopen ("student.bin", "wb");
for (i=0; i<2; i++)
{
printf ("enter details of student %d", i+1);
printf("student number:");
scanf("%d",&s[i].sno);
printf("student name:");
gets(s[i].sname);
printf("student marks:");
scanf("%f",&s[i].marks);
fwrite(&s[i], sizeof(s[i]),1,fp);
}
fclose (fp);
fp = fopen ("student1.bin", "rb");
for (i=0; i<2; i++)
{
printf ("details of student %d are", i+1);
fread (&s[i], sizeof (s[i]) ,1,fp);
printf("student number = %d", s[i]. sno);
printf("student name = %s", s[i]. sname);
printf("marks = %f", s[i]. marks);
}
fclose(fp);
return(0);
}
Output
enter details of student 1
student number:1
student name:pinky
student marks:56
enter details of student 2
student number:2
student name:rosy
student marks:87
details of student 1 are
student number = 1
student name = pinky
marks = 56.000000
details of student 2 are
student number = 2
student name = rosy
marks = 87.000000

3. Aim: To Copy the contents of one file to another file.

#include<stdio.h>
int main()
{
FILE *fp1,*fp2;
char c;
fp1=fopen("file1.txt","r");
fp2=fopen("file2.txt","w");
while((c=getc(fp1))!=EOF)
{
putc(c,fp2);
printf(“%c”,c);
}
fclose(fp1);
fclose(fp2);
return 0;
}
Output:
We are SRKIT CSM students

4. Aim: To Write a C program to merge two files into the third file using command-line
arguments.
Program:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
// Open two files to be merged
FILE *fp1 = fopen(argv[1], "r");
FILE *fp2 = fopen(argv[2], "r");

// Open file to store the result


FILE *fp3 = fopen(argv[3], "w");
char c;

// Copy contents of first file to file3.txt


while ((c = fgetc(fp1)) != EOF)
fputc(c, fp3);
// Copy contents of second file to file3.txt
while ((c = fgetc(fp2)) != EOF)
fputc(c, fp3);
printf("files are merged");
fclose(fp1);
fclose(fp2);
fclose(fp3);
return 0;
}
Output:
./a.out file1.txt file2.txt file3.txt
files are merged

5. Aim: To Find no. of lines, words and characters in a file


#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * fp;
char path[100];
char ch;
int characters, words, lines;
fp = fopen(“file1.txt”, "r");
characters = words = lines = 0;
while ((ch = fgetc(fp)) != EOF)
{
characters++;
if (ch == '\n' || ch == '\0')
lines++;
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')
words++;
}
printf("Total characters = %d\n", characters);
printf("Total words = %d\n", words+1);
printf("Total lines = %d\n", lines+1);
/* Close files to release resources */
fclose(fp);
return 0;
}
Output:
Total characters = 106
Total words = 18
Total lines =3

6. Aim: To Write a C program to print last n characters of a given file.

#include<stdio.h>
int main() {
FILE *fp;
char ch;
int n,length;
printf("Enter the value of n : ");
scanf("%d", &n);
fp = fopen("file1.txt", "r");
fseek(fp, 0, SEEK_END);
length = ftell(fp);
fseek(fp, (length - n), SEEK_SET);
do {
ch = getc(fp);
putchar(ch);
} while (ch != EOF);
fclose(fp);
return(0);
}
Output:

Enter the value of n : 60

of. Principle september she conveying did eat may extensive.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy