Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
8 views63 pages

C Lab Manual r16

The document is a C Programming Lab Manual that covers various exercises including OS commands, text editors like Vi and Emacs, and basic C programming tasks such as arithmetic operations, temperature conversion, leap year determination, and prime number checking. It provides syntax for common Linux commands, sample C programs, and flowcharts for visual representation of algorithms. Each exercise includes aims, descriptions, algorithms, and example outputs to guide students in their programming practice.
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)
8 views63 pages

C Lab Manual r16

The document is a C Programming Lab Manual that covers various exercises including OS commands, text editors like Vi and Emacs, and basic C programming tasks such as arithmetic operations, temperature conversion, leap year determination, and prime number checking. It provides syntax for common Linux commands, sample C programs, and flowcharts for visual representation of algorithms. Each exercise includes aims, descriptions, algorithms, and example outputs to guide students in their programming practice.
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/ 63

C PROGRAMMING LAB MANUAL

EXERCISE 1(a):

What is OS Command?

Operating system (OS) command line interface are usually distinct programs
supplied with the operating system. A program that implements such a text interface is
often called a command line interpreter, command processes or shell.
Familiarization of Editors-vi, Emacs:

Vi Editor: it is one of the model editors. It has a few modes of operation among which user
must switch. In Linux simply write the code by using Vi Editor. The same keystrokes have
different effects in different modes. The quick reference is below, with the 4 essential
command. VI is a very good editor, but is not an operating environment like emacs. For text
editing, you might like VI.
Syntax: % vi [options] [file ..]

DESCRIPTION
 The "vi" text editor is not recommended for newbie’s.
 To exit vi (no changes saved) use these five characters: <ESC>:q!<Enter>.
 vim: Modern Linux distributions use vim (="vi improved") in place of vi, and vim is
somewhat better than the original vi.
 gvim: The GUI version of vi is also available: type gvim in an X terminal.
The most important thing to understand about vi is that is a "modal" editor.

The commands to switch modes:


Enters the mode Remarks
The key
<ESC> command mode (get back to the command mode from any editing
mode)
I "insert" editing (start inserting before the current position of the
mode cursor)
DO NOT PRESS ANY OTHER KEYES IN THE COMMAND MODE. THERE ARE MORE COMMANDS
AND MODES IN THE COMMAND MODE!
Copying, cutting and pasting (in the command mode):
v start highlighting text. Then, move the cursor to highlight text
y copy highlighted text
x cut highlighted text
p paste text that has been cut/copied
Saving and quitting (from the command mode):
:w write (=save)

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL
:w filename write the contents to the file "filename"
:x save and exit
:q quit (it won't let you if changes not saved)
:q! quit discarding changes (you will not be prompted if changes not saved)

EXAMPLE

% vi sample.c

Emacs : emacs is an editor and an operating environment. To start emacs, issue the
commandEmacs There is a tutorial for emacs that you can run to familiarize yourself with
some of the major features. To start the tutorial, first call up emacs , then issue the
command

CTRL-H T The most important command to learn is how to exit emacs


CTRL-X CTRL-C

Exercise1(b):
Using commands like mkdr , ls, cp,mv,cat,pwd,and man.

man: to see how a command is used on your particular computer. man is the system's

manual viewer; it can be used to display manual pages, scroll up and down, search for
occurrences of specific text, and other useful functions.Each argument given to man is

normally the name of a program, utility or function. The manual page associated with

each of these arguments is then found and displayed. A section number, if provided, will
direct man to look only in that section of the manual. The default action is to search in

all of the available sections, following a pre-defined order and to show only the first page

found, even if page exists in several sections.

Syntax % man
mkdir: to make directory in your computer. Is is also use named as (md).

Syntax %mkdir directory name (or) %md directory name


ls: To see a listing of the files in your directory, use the ls -l command. The -l is for a long
listing, including size, date, access rights. You can also call ls without any options for a
shorter listing.
Syntax %ls –l or %ls

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL

cp: The cp command is used to make copies of files and directories., The command for
copying files is cp. You can include full path names for the files.
Syntax %cp original file new file
Example %cp x.c y.c

Creates a copy of the file in the working directory named origfile. The copy will be
named newfile, and will be located in the working directory.CAREFUL! If the destination
file newfile already exists, it will be overwritten without aconfirmation prompt. This is the
default behavior for all cp operations.If you want to be prompted before overwriting a file,
use the -i (interactive) option. For example:

cp -i oldfile newfile

If newfile already exists, you will be prompted:

cp: overwrite ‘newfile’?

If you type y (or yes, Y, YES, or any other combination of upper and lowercase of these),
then newfile will be overwritten with a copy of origfile. Typing anything else will abort the
operation.

Copy a file into another directory:

cp origfile /directory/subdirectory

Creates a copy of the file in the working directory named origfile. The copy will be located in
the directory /directory/subdirectory, and will be named origfile.

cp origfile /directory/subdirectory/.

Same as the above command. The slash-dot ("/.") is implied in the above form of the
command. (The dot is a special file in every Linux directory which means "this directory.")

Copy a file into another directory, and give it a new name:

cp origfile /directory/subdirectory/newfile

Creates a copy of the file in the working directory named origfile. The copy will be
named newfile, and will be located in the directory /directory/subdirectory.

Copy multiple files into another directory, using a wildcard:

cp file* /directory/subdirectory

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL

Copy every file in the working directory whose name begins with file into the
directory/directory/subdirectory. The asterisk ("*") is a wildcard — a
special character which expands to match other characters. Specifically, the asterisk
wildcard matches zero or more non-whitespace characters. For instance, this command will
copy any files namedfile, file001, file.txt, fileone.jpg, file-archive.zip, etc.

cp file*.jpg /directory/subdirectory
Copy every file in the working directory whose name begins with file, and ends with the file
extension .jpg. For instance, it would make copies of any files
named file,file001.jpg, file002.jpg, or file-new.jpg, etc. The copies will be placed into the
directory /directory/subdirectory.

Copy an entire directory structure into another location:

cp -R /one/two /three/four

Copy the directory two (located in the directory /one), and everything two contains, into
the destination directory /three/four. The result will be called /three/four/two. The
directory /three must already exist for the command to succeed. If the directoryfour does
not already exist in the directory /three, it will be created.
mv: The command to move (rename) a file is mv. Move source file to destination file
Syntax %mv filename1 filename2
Example %mv hello.c bvc.c

Pwd: (%pwd) Short for print working directory, pwd is a Linux, Unix, and FTP command
to print the directory you're currently working in when at the command line.
 See the Linux and Unix pwd command page for additional information with this
command.
 See the how to use ftp help page for information about pwd and other FTP
commands.

 Pwd is an abbreviation sometimes used forpassword.

Cat: create file in specific directory.


Syntax: %cat filename

Example: %cat hai.c

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL

Exercise1(c): Write a c program to perform adding, subtraction, multiplication and


division of two numbers from command line
Aim: to perform adding, subtraction, multiplication and division of two numbers from
command line
Program: echo “ enter first number”
read a
echo “ enter second number”
read b
c=’expr $a + $b’
echo “Addition=$c”
d=’expr $a - $b’
echo “Subtraction=$d”
e=’expr $a \* $b’
echo “Miltiplication=$e”
f=’expr $a / $b’
echo “Division=$f”
Output:
Enter first number
4
Enter second number
2
Addition=6
Subtraction=2
Multiplication=8
Division=2

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL

FLOWCHART FOR TEMPERATURE CONVERSION:

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL

Start

Declare the values


F, C=0.0

Read the value of F

C=(F-32) * 5/9

Print C

Read the value of C

F=9*(C/5) +32

Print F

Stop

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL

EXERCISE 2(b):

AIM: To use basic C arithmetic operators to solve problem of temperature conversion

DESCRIPTION: This program deals with the conversion of temperature given in Fahrenheit
to Celsius and from Celsius to Fahrenheit using basic arithmetic operators like ‘+’ , ’-‘ , ’*’
and ‘/’

ALGORITHM:

Step 1: Start

Step 2: declare F, C=0.0

Step 3: read temperature in Fahrenheit

Step 4: calculate C=(F-32) * 5/9

Step 5: print C

Step 6: read temperature in Celsius

Step 7: calculate F=9*(C/5) +32

Step 8: print F

Step 9: Stop

SAMPLE PROGRAM:

#include<stdio.h>

#include<conio.h>

main()

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL
{

float F,C=0.0;

clrscr();

printf("\n Enter temperature in Fahrenheit:\t");

scanf("%f",&F);

C=(F-32)*5/9;

printf("\n Temperature in Celsius=%f",C);

printf("\n Enter Temperature in Celsius:\t");

scanf("%f",&C);

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

printf("\n Temperature in Fahrenheit=%f",F);

getch();

OUTPUT:

Enter temperature in Fahrenheit: 50

Temperature in Celsius=10.000000

Enter Temperature in Celsius: 10

Temperature in Fahrenheit=50.000000

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL

EXERCISE 3(a):

AIM: To find whether the given year is a Leap year or not.

DESCRIPTION: A leap year is exactly divisible by 4 except for century years (years
ending with 00). The century year is a leap year only if it is perfectly divisible by 400.

Program:

#include<stdio.h>

#include<conio.h>

main()

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL
{

int year;

printf(“enter a year”);

scanf(“%d”,&year);

if(year%4)==0)

if(year%100==0)

//year is divisible by 400,hence the year is a leap year

If(year%400==0)

Printf(“%d is a leap year.”,year);

else

Printf(“%d is not a leap year.”,year);

else

Printf(“%d is a leap year.”,year);

else

Printf(“%d is not a leap year.”,year);

getch();

Output1:

Enter a year: 1900

1900 is not a leap year

Output2:

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL
Enter a year: 2012

2012 is a leap year

EXERCISE 3(b):

AIM: To write a C program to add digits and multiplication of a number

DESCRIPTION: This program deals with calculating the sum of digits of a given number by
simply extracting the last digit with n%10 for each and every while loop and making the sum
to each and multiply and every extracted digit until n>0

PROGRAM:

#include<conio.h>

#include<stdio.h>
main()
{
int num,sum=0,r,m=1;
clrscr();
printf("Enter a number: ");
scanf("%d",&num);
while (num)
{
r=num%10;
num=num/10;
sum=sum+r;
m=m*r;
}
printf("Sum of digits of number: %d",sum);
printf(“multiple of a number:%d”,m);
getch();
}

output:
Enter a number: 123
Sum of digits of number: 6

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL
Multiple of a number: 6

EXERCISE: 4(a-i): write a c program the given is prime or not

Aim: to find the given number is prime or not

Program:

#include<stdio.h>

#include<conio.h>

main()

int n , i , flag=0;

clrscr();

printf(“Enter a positive integer;”);

scanf(“%d”,&n);

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

//condition for nonprime number

if(n%i==0)

flag=1;

break;

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL
}

if(flag==0)
printf(“%d is a prime number.”,n);
else
printf(“%d is not a prime number.”,n);
getch();
}

Output:

Enter positive integer 29

29 is prime number start

Read n, x, r,s=0

x=n

n>0

R=r%10,

S=s+pow(r,3)

EXERCISE 4(a-ii): N=n/10

FLOWCHART:

If(x==s)

Print x as not Armstrong


BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE

stop
C PROGRAMMING LAB MANUAL

Print x

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL

AIM: To write a C program for checking whether the given number is an Armstrong number
or not.

ALGORITHM:

Step 1: start

Step 2: Initialize n,x,r,s=0

Step 3: read n

Step 4: Assign x=n

Step 5: while n>0 then

Step 6:r=r%10,s=s*pow(r,3), n=n/10

Step 7: if(x==s)then

Step 8:print x as Armstrong number

Step 9: else print x as not Armstrong number

PROGRAM:

#include<stdio.h>
#include<conio.h>
#include<math.h>
main()
{
int n,x,r,s=0;
clrscr();
printf("\n Enter a number:\t");
BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE
C PROGRAMMING LAB MANUAL
scanf("%d",&n);
x=n;
while(n>0)
{
r=n%10;
s=s+pow(r,3);
n=n/10;
}
if(x==s)
printf("\n %d is Armstrong number",x);
else
printf("\n %d is not an armstrong number",x);
getch();
}
OUTPUT: Enter a number: 370
370 is Armstrong number

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL

EXERCISE 4(b):

Aim: Write a c program to print Floyd Triangle

Program:

#include<stdio.h>
#include<conio.h>
main()
{
int i,j,r,k=1;
clrscr();
printf("Enter the range: ");
scanf("%d",&r);
printf("FLOYD'S TRIANGLE\n\n");
for(i=1;i<=r;i++)
{
for(j=1;j<=i;j++,k++)
printf(" %d",k);
printf("\n");
}
getch();
}

Sample output:
Enter the range: 10

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL
FLOYD'S TRIANGLE

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54 55

EXERCISE 4(c):

AIM: To write a C Program to print Pascal triangle

Flow chart for Pascal triangle:

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL

start

Read N

n<-0

If r<-0
n<N

If
r<=n

stop N<-n+1

P<-fact(n)/fact(n-r)*fact(r)

Write p

rr+1

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL

start

If n=0

Return 1 Return (n*fact(n-1)

stop

ALGORITHM:

STEP-1: start

STEP-2: read n

STEP-3: for each n=0 to n<N step n=n+1 repeat the following otherwise go to step 4

STEP-4: display new value

STEP-5: for each r=0 to r<n step r=r+1 repeat the following otherwise go to step 9

STEP-6: find p=fact(n)/fact(r)*fact(n-r)

STEP-7: display p

STEP-8: stop

STEP-9: if n==0

STEP-10: return (1)

STEP-10.1: return (n*fact(n-1))

STEP-11: stop
BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE
C PROGRAMMING LAB MANUAL
PROGRAM:

#include<stdio.h>
#include <conio.h>
main()
{
unsigned int n, r, N;
unsigned long int p;
unsigned long int fact (unsigned int);
clrscr ();
printf ("\n-------PASCAL'S TRIANGLE-------\n");
printf ("\n enter the value of N:\t");
scanf ("%u", &N);
for (n=0;n<N; n++)
{ printf ("\n");
for (r=0; r<=n; r++)
{ p=fact (n)/(fact(n-r)*fact(r));
printf ("%3u", p); }
}
getch ();
}
unsigned long int fact(unsigned int n)
{
if(n==0)
return (1);
else
return (n*fact (n -1));
}

OUTPUT:

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL
-------PASCAL'S TRIANGLE-------
enter the value of N: 5
1
1 1
1 2 1
1 3 3 1
14641

EXERCISE-5(a): Write a c program demonstrating of parameter passing in functions and


returning values
A.Call -by –value:
Aim: to implement call by value program.
Program:
#include<stdio.h>
#include<conio.h>
int main()
{
int a=50,b=70;
clrscr();
swap(a,b);
printf(“a value is:%d”,a);
printf(“b value is:%d’,b);
return 0;
getch();
}
void swap(int a,int b)
{
int temp;
temp=a;
a=b;
b=temp;
}

Output:
BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE
C PROGRAMMING LAB MANUAL
a value is:50
b value is:70

B.Call-by-reference:
Aim: to implement call by reference program.
Program:
#include<stdio.h>
#include<conio.h>
int main()
{
int a=50,b=70;
clrscr();
swap(&a,&b);
printf(“a value is:%d”,a);
printf(“b value is:%d’,b);
return 0;
getch();
}
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL
Output:
a value is:70
b value is:50

EXERCISE 5(b): write a c program illustrating Fibonacci, Factorial with Recursion and without
Recursion.

Fibonacci:

i) /* to find Fibonacci sequence (recursive and nonrecursive functions) */


#include<stdio.h>
int rec_fib(int);
void nonrec_fib(int);
void main()
{
int n,i;
clrscr();
printf("\n enter n value");
scanf("%d",&n);
printf("\n FIBONACCI SERIES USING RECURSION \n");
for(i=1;i<=n;i++)
printf("%d ",rec_fib(i));
printf("\n FIBONACCI SERIES USING NON RECURSION \n");
nonrec_fib(n);
getch();
}
int rec_fib(int x)
{
if(x==1)
return 0;
else if(x==2)
return 1;
else
return rec_fib(x-1)+rec_fib(x-2);
}
BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE
C PROGRAMMING LAB MANUAL
void nonrec_fib(int x)
{
int i,f1=0,f2=1,f3;
printf("%d %d ",f1,f2);
for(i=3;i<=x;i++)
{
f3=f1+f2;
printf("%d ",f3);
f1=f2;
f2=f3;
}
}
Output: enter n value 5
FIBONACCI SERIES USING RECURSION
01123
FIBONACCI SERIES USING NON RECURSION
01123

Factorial:
/* ii) factorial of a number (recursive and nonrecursive functions) */
#include <stdio.h>
#include <conio.h>
main()
{
unsigned int n;
unsigned long int nr,r;
unsigned long int fact_rec(unsigned int);
unsigned long int fact_nonrec(unsigned int);
clrscr();
printf("\n------FACTORIAL OF A NUMBER------\n");
printf("\n enter a number (positive integer) \t");
scanf("%u",&n);
nr=fact_nonrec(n);

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL
printf("\n factorial (non recursive function) of %u is %lu ",n,nr);
r=fact_rec(n);
printf("\n\nfactorial (recursive function) of %u is %lu",n,r);
getch();
}
unsigned long int fact_nonrec(unsigned int n)
{
int i;
unsigned long int f=1;
for(i=n;i>=1;i--)
f=f*i;
return(f);
}

unsigned long int fact_rec(unsigned int n)


{
if(n==0)
return(1);
else
return(n*fact_rec(n-1));
}

Output:

------FACTORIAL OF A NUMBER------

enter a number (positive integer) 5

factorial (non recursive function) of 5 is 120

factorial (recursive function) of 5 is 120

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL

Start

Read n1,n2

Read operator

EXERCISE 6(a):

FLOW CHART FOR ARITHMETIC OPERATIONS:


Switch(op)

Value=’+’ Res=n1+n2

Value=’-’
Res=n1-n2

Value=’*’ Res=n1*n2

Value=’/’
Res=n1/n2

Value=’%’
Res=n1%n2

Default Display
“Invalid”

BONAM VENKATA CHALAMAYYA INSTITUTE


Display Res OF TECHNOLOGY AND SCIENCE

Stop
C PROGRAMMING LAB MANUAL

AIM: To Write a C program to perform arithmetic operations using switch case

DESCRIPTION: The theme of the program is to perform various arithmetic operations by


considering the various cases including in the switch statement and the corresponding case
will be executed according to the choice given by the user.
ALGORITHM:

Step 1: Start

Step 2: Declare n1,n2,res,div,op

Step 3: Read n1, n2

Step 4: read the operator

Step 5: Check the following cases

Step 5.1: if op= ‘+’ Then compute res=n1+n2 and display res otherwise

go to step 5.2

Step 5.2: if op= ‘-’ Then compute res=n1-n2 and display res otherwise

go to step 5.3

Step 5.3: if op= ‘*’ Then compute res=n1*n2 and display res otherwise

go to step 5.4

Step 5.4: if op= ‘/’ Then compute res=n1/n2 and display res otherwise

goto step 5.5


BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE
C PROGRAMMING LAB MANUAL
Step 5.5: if op= ‘%’ Then compute res=n1%n2 and display res otherwise

go to step 5.6

Step 5.6: Display “invalid operator”

Step 6: Stop

SAMPLE PROGRAM:

#include<stdio.h>

#include<conio.h>

main()

int n1,n2,res;

float div;

char op;

clrscr();

printf("enter the two values\n");

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

fflush(stdin);

printf("enter the operator");

fflush(stdin);

op=getchar();

switch(op)

case '+': res=n1+n2;

printf("Addition %2d +%2d=%2d",n1,n2,res);

break;

case '-': res=n1-n2;

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL
printf("SUBTRACTION %2d - %2d=%2d",n1,n2,res);

break;

case '*': res=n1*n2;

printf("MULTIPLICATION %2d * %2d=%2d",n1,n2,res);

break;

case '/' : div=(float)n1/n2;

printf("DIVISION %2d / %2d=%2d",n1,n2,div);

break;

case '%':res=n1 % n2;

printf("MODULO DIVISION %2d % %2d=%2d",n1,n2,res);

break;

default : printf("\ninvlaid selection of operator");

getch();

SAMPLE OUTPUT:

1) enter the two values

1 2

enter the operator +

ADDITION 1 + 2=3

Exercise 6 (b): write a c program to convert decimal to binary and hex (using switch call
function the function)
Program:

#include<stdio.h>
#include<conio.h>

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL
#include<math.h>
int D2B(int);
int D2H(int);
main()
{
int ch,num;
clrscr();
printf(“\n1.Decimal to Binary.”);
printf(“\n2.Decimal to hexa.”);
printf(“\n3.Exit.”);
printf(“\n Enter your choice.”);
scanf(“%d”,&ch);
switch(ch)
{
Case 1: printf(“\n enter any decimal number”);
Scanf(“%d”,&num);
if(num!=0 && num>0)
D2B(num);//calling function
else
printf(“\n not allowed!”);
break;
case 2: : printf(“\n enter any decimal number”);
scanf(“%d”,&num);
if(num!=0 && num>0)
D2H(num);//calling function
else
printf(“\n not allowed!”);
break;
case 3: exit(0);
default: printf(“\n enter proper choice:”);
break;
}
getch();
}
BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE
C PROGRAMMING LAB MANUAL
int D2B(int dec)//decimal to binary
{
int bin=0,*bin_arr,count=0;
while (dec>0)
{
bin=dec%2;
dec/=2;
*(bin_arr+count)=bin;
count++;
}
printf(“\n binary=”);
While(count>0)
{
--count;
printf(“%d”,*(bin_arr+count));
}
return 0;
}
int D2H(int dec)//decimal to hexa
{
int hexa=0,*hex_arr,count=0;
while(dec>0)
{
hexa=dec%16;
dec/=16;
*(hexa_arr+count)=hexa;
count++;
}
printf(“\n Hexa=”);
while(count>0)
{
--count;
switch(*(hexa _arr+count))
{
BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE
C PROGRAMMING LAB MANUAL
case 10: printf(“A”);
break;
case 11: printf(“B”);
break;
case 12: printf(“C”);
break;
case 13 : printf(“D”);
break;
case 14: printf(“E”);
break;
case 15: printf(“F”);
break;
default: printf(“%d”,*(hex_arr+count));
break;
}
}
return 0;
}
Output:
1. Decimal to binary
2. Decimal to Hexa
3. Exit
Enter your choice 1
Enter decimal number 12
1100

Exercise-7: Write a c program to compute the values of sin x and cosx and e^x values using
series expansion(use factorial function.

Aim: to compute the values of sin x and cosx and e^x values using series expansion(use
factorial function.

Program:
#include<stdio.h>

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL
#include<math.h>
#define PI 3.1415

float exp_x( int, int );


double sin_x( int, int );
double cos_x( int, int );
int fact( int );

int main()
{
int choice, x, n;
do
{
printf( "\nMenu\n[1] e^(x)\n[2] Sin(x)\n[3] Cos(x)\n[4] Exit\n" );
scanf( "%d", &choice );
switch ( choice )
{

case 1: // to find exponential value


printf( "e^x\nEnter x and n:\t" );
scanf( "%d %d", &x, &n );
printf( "e^%d(%d) = %f\n", x, n, exp_x( x, n ) );
break;

case 2: // to find sinx


printf( "sin(x)\nEnter x and n:\t" );
scanf( "%d %d", &x, &n );
printf( "\nsin(%d)(%d) = %f\n", x, n, sin_x( x, n ) );
break;

case 3: // to find cosx

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL
printf( "cos(x)\nEnter x and n:\t" );
scanf( "%d %d", &x, &n );
printf( "\ncos(%d)(%d) = %f\n", x, n, cos_x( x, n ) );
break;

case 4: // exit
break;

default: // wrong choice


printf( "Wrong choice" );
break;
}
}
while ( choice != 4 );
}

float exp_x( int x, int n )


{
int i = 1;
float ex = 1;

while ( i < n )
{
ex += ( float ) pow( x, i ) / fact( i );
++i;
}

return ex;
}

double sin_x( int ang_deg, int no_of_terms )


{
int term, j;

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL
double value = 0.0, ang_rad = 0.0;
ang_rad = ( double ) ang_deg * PI / 180;

for ( term = 1, j = 2;term < no_of_terms*2;term += 2, j++ )


{
value += ( double ) pow( -1.0, j ) * pow( ang_rad, term ) / fact( term );
}

return value;
}

double cos_x( int ang_deg, int no_of_terms )


{
int term, j;
double value = 1.0, ang_rad = 0.0;
ang_rad = ( double ) ang_deg * PI / 180;

for ( term = 2, j = 1;term <= no_of_terms;term += 2, j++ )


{
value += ( double ) pow( -1.0, j ) * pow( ang_rad, term ) / fact( term );
}

return value;
}

int fact( int num )


{
int f = 0;

if ( num == 1 )
return 1;
else
BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE
C PROGRAMMING LAB MANUAL
f = num * fact( num - 1 );

return f;
}

Output:
Menu
[1] e^(x)
[2] Sin(x)
[3] Cos(x)
[4] Exit
1
e^x
Enter x and n: 2 3
e^2(3)=5.000000
Menu
[1] e^(x)
[2] Sin(x)
[3] Cos(x)
[4] Exit
2
Sin(x)
Enter x and n: 90 2
Sin(90)(2)=0.924843
Menu
[1] e^(x)
[2] Sin(x)
[3] Cos(x)
[4] Exit
3
Cos(x)
Enter x and n: 90 1
Cos(90)(1)=.000000
Menu
BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE
C PROGRAMMING LAB MANUAL
[1] e^(x)
[2] Sin(x)
[3] Cos(x)
[4] Exit
4

Exercise-8(a): Write a c program to implement linear search

Aim: to implement linear search program

Program:

#include<stdio.h>
main()
{
int a[10],i,n,key,flag=0,pos;
printf("\n enter n value ");
scanf("%d",&n);
printf("\n enter %d array elements",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\n enter key element to find ");
scanf("%d",&key);
for(i=0;i<n;i++)
{
if(key==a[i])
{
flag=1;
pos=i;
break;
}
}
if(flag==1)

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL
printf("\n key element is found at %d",pos);
else
printf("\nkey element not found ");
}
Output:
Enter n value 5
Enter 5 elements
56437
Enter key element 4
Key element is found at 2
Exercise (8b-a): write a c program to implement Bubble sort

Aim: To implement bubble sort program

Description:

BUBBLE SORT: The bubble sort is also known as the ripple sort. The bubble sort is probably
the first, reasonably complex module that any beginning programmer has to write. It is a
very simple construct which introduces the student to the fundamentals of how sorting
works.

A bubble sort makes use of an array and some sort of "swapping" mechanism. Most
programming languages have a built-in function to swap elements of an array. Even if a
swapping function does not exist, only a couple of extra lines of code are required to store
one array element in a temporary field in order to swap a second element into its place.
Then the first element is moved out of the temporary field and back into the array at the
second element's position.

Here is a simple example of how a bubble sort works: Suppose you have a row of children's
toy blocks with letters on them. They are in random order and you wish to arrange them in
alphabetical order from left to right.
Step 1. Begin with the first block. In this case, the letter G. (Fig. 1.)

Fig. 1
Step 2. Look at the block just to the right of it.

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL
Step 3. If the block to the right should come before the block on the left, swap them
so that they are in order (Fig. 2.)

Fig. 2
If you were doing this by hand, you might just pick the blocks to be moved with one
in each hand and cross your arms to swap them. Or you might move the first one out
of its position temporarily, move the second one in its place, them move the first
one to the now empty position (this is the difference between having a single
function to do the swap, or writing some code to do it).

Step 4. Compare the next block in line with the first, and repeat step 3. Do this until
you run out of blocks. Then begin step one again with the second block. (Fig. 3,4,5,6)

Fig. 3 - Pass #2

Fig. 4 - Pass #3

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL

Fig. 5 - Pass #4

Fig. 6 - Completed Sort


PROGRAM: To Implement Bubble sort using arrays

#include<stdio.h>
#include<conio.h>
main()
{
int a[100],n,i;
clrscr();
printf("\n Enter number of elements:");
scanf("%d",&n);
printf("\n Enter the elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\n Elements in the list before sorting:\n");
for(i=0;i<n;i++)
printf("%3d",a[i]);
bubblesort(a,n);
printf("\n Elements in the list after sorting:\n");
for(i=0;i<n;i++)
printf(" %5d ",a[i]);
getch();

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL
}
bubblesort(int a[], int n)
{
int temp,i,j;
for(i=0;i<(n-1);i++)
{
for(j=0;j<n-(i+1);j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}

OUTPUT:
Enter number of elements:5
Enter the elements:89 4 12 41 3
Elements in the list before sorting:
89 4 12 41 3
Elements in the list after sorting:
3 4 12 41 89
Exercise (8b-b): write a c program to implement selection sort

Aim: To implement selection sort program

Program:

#include<stdio.h>
main()
BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE
C PROGRAMMING LAB MANUAL
{
int s,i,j,temp,a[20];
clrscr();
printf("Enter total elements: ");
scanf("%d",&s);
printf("Enter %d elements: ",s);
for(i=0;i<s;i++)
scanf("%d",&a[i]);
for(i=0;i<s;i++)
{
for(j=i+1;j<s;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("After sorting is: ");
for(i=0;i<s;i++)
printf(" %d",a[i]);
getch();
}
Output:
Enter total elements: 5
Enter 5 elements: 4 5 0 21 7
The array after sorting is: 0 4 5 7 21
Exercise-8(c): write a c program to implement matrixes operations

Aim: To implement matrixes operations

#include<stdio.h>
main()
BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE
C PROGRAMMING LAB MANUAL
{
int a[10][10],b[10][10],c[10][10],m,n,p,q,i,j,k,ch;
clrscr();
printf("\n menu \n");
printf("\n 1 . Matrix Addition ");
printf("\n 2. Matrix Multiplication ");
printf("\n enter choice ");
scanf("%d",&ch);
printf("\n enter order of 1st matrix ");
scanf("%d%d",&m,&n);
printf("\n enter order of 2nd matrix ");
scanf("%d%d",&p,&q);
if((m==p && n==q) || (n==p))
{
printf("\n enter elements of 1st matrix " );
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\n enter elements of 2nd matrix ");
for(i=0;i<p;i++)
for(j=0;j<n;j++)
scanf("%d",&b[i][j]);
}
else
printf("\n wrong order ");
switch(ch)
{
case 1: printf("\n addition \n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL
printf("%d\t",c[i][j]);
}
printf("\n");
}
break;

case 2:printf("\n multiplication \n");


for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<p;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
printf("%d\t",c[i][j]);
}
printf("\n");
}
break;
default:printf("\n choice is invalid ");

}
getch();
}

Output :
menu
1. Matrix addition
2. Matrix multiplication
Enter choice 1
Enter order of 1st matrix 2 2

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL
Enter order of 2nd matrix 2 2
Enter elements of 1st matrix 1 2 3 4
Enter elements of 2nd matrix 1 2 3 4
Addition
24
68

Exercise-9(a): Write a c program to store information of a movie using structure

Aim: To implement to store information of a movie using structure.

Program:

#include<stdio.h>
struct movie
{
char name[20];
char hero[20];
char heroine[20];
char director[20];
char musicdir[20];
char producer[20];
char price[20];
};
main()
{
Struct movie m1={"janath",”jrNTR”,”Samantha”,”koratala ”,”devisri”,”mythri”,”60cr”};
clrscr();
printf("\n movie name %s",m1.name);
printf("\n movie hero %s",m1.hero);
printf("\n movie heroine %s",m1.heroine);
printf("\n movie director%s",m1.director);
printf("\n music dirctor %s",m1.musicdir);
printf("\n movie producer %s",m1.producer);
printf("\n movie price %s",m1.price);

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL
getch();
}

Output:
movie name janatha
movie hero jrNTR
movie heroine smantha
movie director koratala
music dirctor devisri
movie producer mythri
movie price 60cr

Exercise-9(b): write c program to store information using structure with Dynamically


memory Allocation.
Aim: To store information using structure with Dynamically memory Allocation
Program:
#include<stdio.h>
#include<conio.h>
Struct name
{
int a;
char c[30];
};
int main()
{
struct name *ptr;
int I,n;
printf(“enter a n value\t”);
scanf(“%d”,&n);
ptr=(struct name*)malloc(n*sizeof(struct name));
for(i=0;i<n;++i)
{
printf(“ enter string and integer respectively \n”);
scanf(“%s%d”,&(ptr+i)->c,&(ptr+i)->a);
BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE
C PROGRAMMING LAB MANUAL
}
printf(“Displaying information:\n”);
for(i=0;i<n;++i)

printf(“%s\t%d\t\n”,(ptr+i)->c,(ptr+i)->a);
return 0;
}
Output:
Enter n:2
Enter string and integer respectively:
Programming
22
Enter string and integer respectively:
Structure
33
Displaying information
Programming 22
Structure 33

Exercise-9(c): Write a c program to add two complex numbers by passing structure to a


function.

AIM: To write a C program that uses functions to perform operations structure


DESCRIPTION: The aim of the program is to read two complex numbers, write the complex
numbers and perform operations like addition. Addition of two complex numbers given by
considering real part x.r=a.r+b.r and imaginary part as x.im=a.im+b.im.
ALGORITHM:
Step 1: Start

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL
Step 2: Define the structure complex with real and img
Step 3: Declare c1,c2,cadd,cmul
Step 4: Call sub function real to read first complex number
Step 5: Call sub function real to read second complex number
Step 6: Call the sub function add and assign the value to cadd
Step 7: Call the sub function mul and assign the value to cmul
Step 8: Call the sub function write to display first complex number
Step 9: Call the sub function write to display second complex number
Step 10: Stop
ALGORITHM FOR SUB FUNCTION real:
Step 1: Read the real part
Step 2: Read the imaginary part
Step 3: return
ALGORITHM FOR SUB FUNCTION write:
Step 1: Display real and imaginary parts
Step 2: Return
ALGORITHM FOR SUB FUNCTION add:
Step 1: Add the real part of first complex number with real part of second
complex number and assign to real.
Step 2: Add the imaginary part of first complex number with imagi8nary part of
second complex number and assign to img.
Step 3: return

SAMPLE PROGRAM:
#include<stdio.h>
#include<math.h>
typedef struct
{
float real;
float img;
}COMPLEX;
main()
BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE
C PROGRAMMING LAB MANUAL
{
COMPLEX c1,c2,cadd;
void real(COMPLEX *);
void write(COMPLEX);
COMPLEX add(COMPLEX, COMPLEX);
clrscr();
printf(“enter first complex number”);
rea(&c1);
printf(“enter second complex number”);
real(&c2);
cadd=add(c1,c2);
printf(“\n first complex number \t”);
write(c1);
printf(“\n Second complex number \t”);
write(c2);
printf(“\n addition of two complex numbers is \t”);
write(cadd);
getch();
}
void real(COMPLEX *cp)
{
printf(“\n enter the real part\t”);
scanf(“%f”,&cp->real);
printf(“enter the imaginary part\t”);
scanf(“%f”,&cp->img);
return;
}

void write(COMPLEX c)
{
printf(“%.2f%+.2fi”,c.real,c.img);
return;
BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE
C PROGRAMMING LAB MANUAL
}
COMPLEX add(COMPLEX c1,COMPLEX c2)
{
COMPLEX ca;
ca.real=c1.real+c2.real;
ca.img=c1.img+c2.img;
return(ca);
}
SAMPLE OUTPUT:
enter first complex number
enter real part 5
enter imaginary part 2
enter second complex number
enter real part 1
enter imaginary part 2
first complex number 5.00+2.00i
second complex number 1.00+2.00i
addition of two complex numbers is 6.000000+4.000000i

Exercise-10(a): write a c program to access elements of an array using pointers.


Aim: To implement access elements of an array using pointers.
Program:

#include<stdio.h>
main()
{
int data[5],i;
clrscr();
printf(“enter elements”);
for(i=0;i<5;i++)
scanf(“%d\t”,data+i);
BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE
C PROGRAMMING LAB MANUAL
printf(“the elements are”);
for(i=0;i<5;i++)
printf(“%d\t”,*(data+i));
getch();
}
Output:
Enter elements 1 2 3 4 5
The elements are 1 2 3 4 5
Exercise-10(b): Write a c program to find the sum of numbers with arrays and pointers.
Aim: To find the sum of numbers with arrays and pointers.
Program:
#include<stdio.h>
#include<conio.h>
main()
{
int numArray[10];
int i, sum = 0;
int *ptr;
printf("\nEnter 10 elements : ");
for (i = 0; i < 10; i++)
scanf("%d", &numArray[i]);
ptr = numArray; /* a=&a[0] */
for (i = 0; i < 10; i++)
{
sum = sum + *ptr;
ptr++;
}
printf("The sum of array elements : %d", sum);
}
Output:
Enter 10 elements: 11 12 13 14 15 16 17 18 19 20
The sum of array elements is 155
Exercise-11: Write a c program to implement dynamic memory allocation methods.
Aim: To implement dynamic memory allocation methods.
Program:
Malloc:
#include <stdio.h>
#include <stdlib.h>
int main(){
int n,i,*ptr,sum=0;

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i){
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d\n",sum);
free(ptr);
return 0;
}
Output:
Enter number of elements:4
Enter elements of array:10 20 30 40
Sum:100
Calloc:

Program:

#include <stdio.h>
#include <stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int));
if(ptr==NULL){
printf("Error! memory not allocated.");
exit(0);
BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE
C PROGRAMMING LAB MANUAL
}
printf("Enter elements of array: ");
for(i=0;i<n;++i){
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
Output:

Enter number of elements:4


Enter elements of array:10 20 30 40
Sum:100

Exercise-12(a): Implementation of string manipulation with library function

i)copy:

#include <stdio.h>
#include <string.h>
main()
{
char s1[30] = "string 1";
char s2[30] = "string 2 : I’m gonna copied into s1";
clrscr();

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL
/* this function has copied s2 into s1*/
strcpy(s1,s2);
printf("String s1 is: %s", s1);
getch();
}
Output:

String s1 is: string 2: I’m gonna copied into s1

ii) Concatenate:
#include <stdio.h>
#include <string.h>
main()
{
char s1[10] = "Hello";
char s2[10] = "World";
clrscr();
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
getch();
}
Output:

Output string after concatenation: HelloWorld

iii) Length:
#include <stdio.h>
#include <string.h>
main()
{
char str1[20] = "BeginnersBook";
printf("Length of string str1: %d", strlen(str1));
getch();
}
Output:

Length of string str1: 13

Iv) Compare:
#include <stdio.h>
#include <string.h>
main()
{
char s1[20] = "BeginnersBook";
char s2[20] = "BeginnersBook.COM";
BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE
C PROGRAMMING LAB MANUAL
if (strcmp(s1, s2) ==0)
{
printf("string 1 and string 2 are equal");
}else
{
printf("string 1 and 2 are different");
}
getch();
}
Output:

string 1 and 2 are different

Exercise-12(b): Implementation of string manipulation operations without library function


i)Length:
program:
#include<stdio.h>

main()
{
char str[30],i;
printf("\n enter a string ");
gets(str);
i=0;
while(str[i]!='\0')
i++;
printf("\n length of the string is %d",i);
}
Output:
enter a string welcome
Length of the string is 7

ii)Compare:
/* compare two strings */
#include<stdio.h>
main()
{
char str1[20],str2[20];
int i=0,flag;
clrscr();
printf("\n enter a string ");
scanf("%s",str1);
printf("\n enter another string ");
scanf("%s",str2);
while(str1[i]!='0')
{

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL
if(str1[i]==str2[i])
flag=1;
else if(str1[i]<str2[i])
{
flag=2;
break;
}
else
{
flag=0;
break;
}
i++;
}
if(flag==1)
printf("\n both strings are equal");
else if(flag==2)
printf("\n string1 comes before string2");
else
printf("\n string1 comes after string2");
getch();
}

Output:
enter a string ram
enter another string sai
string1 comes before string2

iii) Concatenate:
/* To concatenate two strings. */
#include<stdio.h>
main()
{
char str1[20],str2[20],str3[20];
int i=0,j=0;
clrscr();
printf("\n enter a string ");
scanf("%s",str1);
printf("\n enter another string ");
scanf("%s",str2);
while(str1[i]!='\0')
{
str3[j]=str1[i];
i++;
j++;
}
i=0;

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL
while(str2[i]!='\0')
{
str3[j]=str2[i];
i++;
j++;
}
str3[j]='\0';
printf("\n after concatenation %s",str3);
getch();
}
Output:
enter a string ram
enter another string sai
after concatenation ramsai

iv) Copy:
#include<stdio.h>
main()
{
char s1[100], s2[100];
int i;
printf("\nEnter the string :");
gets(s1);
i = 0;
while (s1[i] != '\0') {
s2[i] = s1[i];
i++;
}
s2[i] = '\0';
printf("\nCopied String is %s ", s2);
return (0);
}

Output:

Enter the string : hello


Copied String is hello

Exercise-13(a): write a c programming code to open a file and to print it contents on screen.
Aim: To open a file and to print it contents on screen.
Program:
#include <stdio.h>
#include <stdlib.h>

int main()
{
char ch, file[25];

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL
clrscr();
FILE *fp;
printf("Enter the name of file you wish to see\n");
gets(file);
fp = fopen(file,"r"); // read mode
if( fp == NULL )
{
ferror("Error while opening the file.\n");
exit(0);
}

printf("The contents of %s file are :\n", file);


while( ( ch = fgetc(fp) ) != EOF )
printf("%c",ch);
fclose(fp);
getch();
}

Output:
Enter the name of file you wish to see
Hello.c
The contents of hello.c file are good morning

Exercise-13(b): write a c program to copy files

Program:
/* copies the contents of one file to another file */

#include<stdio.h>
#include<conio.h>
main()
{
char c,source[20];
FILE *fs,*fp;
clrscr();
printf("\n enter file name ");
gets(source);
fs=fopen(source,"r");
if(fs==NULL)
{
printf("source file cannot open ");
exit(0);
}
fp=fopen("dest.txt","w");
if(fp==NULL)
{
printf("dest file cannot open");

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL
exit(0);
}
while((c=getc(fs))!=EOF)
{
putc(c,fp);
}
fclose(fp);
fp=fopen("dest.txt","r");

printf("\n copied contents are\n");


while((c=getc(fp))!=EOF)
{
putchar(c);
}
fclose(fs);
fclose(fp);
getch();
}
Output:

enter file name source.txt


copied contents are cprogramming

Exercise-14(a): write a c program merges two files and stores their contents in another file

Program:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
main()
{
FILE *fs1, *fs2, *ft;

char ch, file1[20], file2[20], file3[20];


clrscr();
printf("Enter name of first file \n");
gets(file1);
printf("Enter name of second file\n ");
gets(file2);

printf("Enter name of file which will store contents of two files\n ");
gets(file3);

fs1 = fopen(file1,"r");
fs2 = fopen(file2,"r");

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL
if( fs1 == NULL || fs2 == NULL )
{
perror("Error ");
printf("Press any key to exit...\n");
getch();
exit(EXIT_FAILURE);
}

ft = fopen(file3,"w");

if( ft == NULL )
{
perror("Error ");
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}

while( ( ch = fgetc(fs1) ) != EOF )


fputc(ch,ft);

while( ( ch = fgetc(fs2) ) != EOF )


fputc(ch,ft);

printf("Two files were merged into %s file successfully.\n",file3);

fclose(fs1);
fclose(fs2);
fclose(ft);
return 0;
getch();
}
Output:
Enter name of first file x.c
Enter name of second file y.c
Enter name of file which will store contents of two files z.c
Two files were merged into z.c file successfully

Exercise-14(b): write a c program to delete a file


Program:
#include<stdio.h>
main()
{
int status;
char filename[25];
clrscr();
printf("Enter the name of file you wish to delete\n");
gets(filename);

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE


C PROGRAMMING LAB MANUAL
status = remove(filename);
if( status == 0 )
printf("%s file deleted successfully.\n",file_name);
else
{
printf("Unable to delete the file\n");
perror("Error");
}
getch();
}

Output:
Enter the name of file you wish to delete
bvc.c
bvc.c file deleted successfully

BONAM VENKATA CHALAMAYYA INSTITUTE OF TECHNOLOGY AND SCIENCE

You might also like