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

CP Formatted Manual 26-02-2018

This document provides information about the Computer Programming Lab at the Department of Computer Science and Engineering at Malla Reddy Engineering College. It outlines the objectives of the lab, which are to teach students logical problem solving skills, C programming development, analyzing problem complexity, using functions and pointers, and documenting algorithms. It also provides a list of 12 experiments covering topics like DOS commands, algorithms, C basics, math problems, strings, structures, files, sorting, and searching. Each experiment has multiple programming problems to solve related to the overall topic.

Uploaded by

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

CP Formatted Manual 26-02-2018

This document provides information about the Computer Programming Lab at the Department of Computer Science and Engineering at Malla Reddy Engineering College. It outlines the objectives of the lab, which are to teach students logical problem solving skills, C programming development, analyzing problem complexity, using functions and pointers, and documenting algorithms. It also provides a list of 12 experiments covering topics like DOS commands, algorithms, C basics, math problems, strings, structures, files, sorting, and searching. Each experiment has multiple programming problems to solve related to the overall topic.

Uploaded by

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

DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

PROGRAMMING FOR PROBLEM SOLVING LAB

MALLA REDDY ENGINEERING COLLEGE


(AUTONOMOUS)
(An Autonomous institution, Autonomy granted by UGC and affiliated
to JNTUH, Accredited by NAAC with ‘A’ Grade, Accredited by NBA
(2008-11) & Recipient of World Bank Assistance under TEQIP phase –
II S.C.1.1for the period (2011-14))
Maisammaguda, Dhulapally (Post. Via. Kompally), Secunderabad

500100.

Website: www.mrec.ac.in

MREC (A) Page 1


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

COMPUTER PROGRAMMING LAB

OBJECTIVES:

• After completion of this course, the students would be able to

apply and practice logical ability to solve the problems.


• Understand C programming development environment, compiling,
debugging, linking and executing a program using the
development environment
• Analyzing the complexity of problems, Modularize the problems
into small modules and then convert them into programs
• Understand and apply the in-built functions and customized
functions for solving the problems.
• Understand and apply the pointers, memory allocation
techniques and use of files for dealing with variety of
problems.
• Document and present the algorithms, flowcharts and programs
in form of user-manuals

MREC (A) Page 2


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

LIST OF EXPERIMENTS
1.
a. Practice various Internal and External DOS Commands.
b. Implement various programs logics using algorithms and flowcharts.
c. Write sample examples of C programs to implement basic operations.
2.
a. Write a C program to find smallest and largest of given three numbers.
b. Write a C program to find the roots of a quadratic equation.
3
a. Write a C program to find the sum of individual digits of a positive integer.
b. A Fibonacci sequence is defined as follows: the first and second terms in the sequence
are 0 and 1. Subsequent terms are found by adding the preceding two terms in the
sequence.
c. Write a C program to generate the first n terms of the sequence.
4.
a. Write a C program to find whether the given number is palindrome, perfect, Armstrong
or strong.
b. Write a C program to generate all the prime numbers between n1 and n2, where n1 and
n2 are values supplied by the user.
5.
Write C programs that use both recursive and non-recursive functions
a. To find the factorial of a given integer.
b. To find the GCD (greatest common divisor) of two given integers.
6.
a. Write a C program to find both the largest and smallest number in a list of integers.
b. Write a C program that uses functions to perform the following:
i. Addition of Two Matrices
ii. Multiplication of Two Matrices
7.
a. Write a C program that uses functions to perform the following operations:
i. To insert a sub-string into given main string from a given position.
ii. To delete n characters from a given position in a given string.
b. Write a C program to determine if the given string is a palindrome or not
c. Write a C program to find substring in a given string.
d. Write a C program to count the lines, words and characters in a given text.
8.
a. Write a C program to implement functions arguments with different returns values.
b. Write a C program to implement call by value and call by reference using functions.

9.
a. Write a C program to find grades of a student’s using structures.
b. Write a C program to implement nested structures.
10.
a. Write a C program which copies one file to another.
b. Write a C program to command line arguments.

MREC (A) Page 3


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

11.
a. Write a C program that uses non-recursive function to search for a Key value in a given
list of integers using linear search.
b. Write a C program that uses recursive and non -function to search for a Key value in a
given sorted list of integers using Binary search.
12.
a. Write a C program that implements the Selection sort method to sort a given array of
integers in ascending order.
b. Write a C program that implements the Bubble sort method to sort a given list of names
in ascending order.

INDEX

Program Name Page


No
1 a. Various DOS internal and external commands 6
b. To implement various programs logics using algorithms and
flowcharts. 9
c. Write sample examples of C program to Implement basic operation
11
2 a. To find smallest and largest of given three numbers. 13
15
b. To find the roots of a quadratic equation
3 a. To find the sum of individual digits of a positive integer. 17

b. A Fibonacci sequence is defined as follows: the first and second terms


in the sequence are 0 and 1. Subsequent terms are found by adding the 18
preceding two terms in the sequence.
c. Write a C program to generate the first n terms integers 18

4 a. To find whether the given number is palindrome, perfect, Armstrong or 20


strong
b. Write a C program to generate all the prime numbers between n1 and 23
n2 are values supplied by user.

5 Write C programs that use both recursive and non-recursive functions


a. To find the factorial of a given integer. 24
b. To find the GCD (greatest common divisor) of two given integers. 26

a. Write a C program to find both the largest and smallest number in a list 29
6 of integers.
b. Write a C program that uses functions to perform the following:
i. Addition of Two Matrices 30
ii. Multiplication of Two Matrices

MREC (A) Page 4


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

7 a. Write a C program that uses functions to perform the following 32


operations:
i. To insert a sub-string into given main string from a given
position.
ii. To delete n characters from a given position in a given string.
b. Write a C program to determine if the given string is a palindrome or 35
not
c. Write a C program to find substring in a given string. 37
d. Write a C program to count the lines, words and characters in a given 39
text.

8 a. Write a C program to implement functions arguments with different 40


returns values.
b. Write a C program to implement call by value and call by reference
using functions. 43

9 a. Write a C program to find grades of a student’s using structures. 46


b. Write a C program to implement nested structures.
47
10 a. Write a C program which copies one file to another. 49
b. Write a C program to command line arguments. 50

11 a. Write a C program that uses non-recursive function to search for a 52


Key value in a given list of integers using linear search.
b. Write a C program that uses recursive and non -function to search for a
Key value in a given sorted list of integers using Binary search. 53

12 a. Write a C program that implements the Selection sort method to sort 58


a given array of integers in ascending order.
b. Write a C program that implements the Bubble sort method to sort a
given list of names in ascending order. 60

MREC (A) Page 5


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

1.
a. Practice various DOS internal and external commands.

Fundamentals of DOS

Character: A Character is nothing but ‘A’ – ‘Z’ both upper,


lower, 0 – 9 numerical and special characters like! @, #, $, %,
^, &, *, (, ),-, _, =,+,\, /.

File: A file consists of group of characters. A file consists of


two parts:
1. File name like MYFILE (maximum length is 8 characters)
2. Extension like .TXT, .EXE, .COM, .DOC, .DAT, .PAS, .C,
.CPP, and .BAT (maximum length is 3 characters)

Directory: A directory is nothing but group of files like:

MY.C 24 12-09-98 11.27P


GTK.C 1024 04-15-99 10.00P
SNIST.COB 22 09-19-98 11.30P
↑ ↑ ↑ File name File size Date of creation
Time of creation

Internal Commands

CLS : Command that allows a user to clear the complete contents


of the screen and leave only a prompt.

Syntax:
CLS
Running the CLS command at the command prompt would clear your
screen of all previous text and only return the prompt.

DATE: When this command is called from the command line or a


batch script, it will display the date and wait for the user to
type a new date and press RETURN. The parameter '/T' will bypass
asking the user to reset the date.
Syntax:
DATE [/T | date]
DIR: The dir command allows you to see the available files in a
directory.
Syntax:
DIR [drive:][path][filename] [/A[[:]attributes]] [/B] [/C] [/D]
[/L] [/N]
[/O[[:]sortorder]] [/P] [/Q] [/S] [/T[[:]timefield]] [/W] [/X]
[/4]

MREC (A) Page 6


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

COPY:Allows the user to copy one or more files to an alternate


location
Syntax:
Copies one or more files to another location.
COPY [/A | /B] source [/A | /B] [+ source [/A | /B] [+ ...]]
[destination] [/A | /B]] [/V][/Y | /-Y]

COPY CON:
An internal command for creating a quick batch file in DOS or
Windows. For example, to create the WRITE batch file, type copy
con write.bat
After pressing Enter, you'll get a blank line. Type your text
and press Enter to end the line. When done, press F6 (ctrl-Z),
then press Enter.
Copy Con works a line at a time. You cannot go back and change
lines, but you can use backspace to delete characters on the
same line.
TYPE: Displays the contents of a text file.
Syntax:
TYPE [drive:][path]filename

RENAME: Used to rename files and directories from the original


name to a new name.
Syantax:
Renames a file/directory or files/directories.
RENAME [drive:][path][directoryname1 | filename1]
[directoryname2 | filename2]
REN [drive:][path][directoryname1 | filename1] [directoryname2 |
filename2]
DEL: del is a command used to delete files from the computer.
Syntax:
Deletes one or more files.
DEL [drive:][path]filename[/P]
ERASE [drive:][path]filename [/P]

MD: Allows you to create your own directories in MS-DOS.


Syntax:
MKDIR [drive:] path
MD [drive:] path
If Command Extensions are enabled MKDIR changes as follows:
MKDIR creates any intermediate directories in the path, if
needed.
For example, assume \a does not exist then:
mkdir \a\b\c\d
is the same as:

MREC (A) Page 7


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

mkdir \a
chdir \a
mkdir b
chdir b
mkdir c
chdir c
mkdir d

CD: CD (Change Directory) is a command used to switch


directories in MS-DOS.
Syntax:
CHDIR [/D] [drive:][path]
CHDIR [..]
CD [/D] [drive:][path]
CD [..]
Specifies that you want to change to the parent directory.
Type CD drive: to display the current directory in the specified
drive.
Type CD without parameters to display the current drive and
directory.
Use the /D switch to change current drive in addition to
changing current directory for a drive.
If Command Extensions are enabled CHDIR changes as follows:
The current directory string is converted to use the same case
as the on disk names. So
CD C:\TEMP would actually set the current directory to C:\Temp
if that is the case on disk.

CHDIR: command does not treat spaces as delimiters, so it is


possible to CD into a subdirectory name that contains a space
without surrounding the name with quotes.

Syntax:
CHDIR [drive:][path]
CHDIR[..]
CD [dri]

RD: Removes empty directories in MS-DOS. To delete directories


with files or directories within them the user must use the
deltree command, or if you are running Microsoft Windows 2000 or
Windows XP use the /S option.
Syntax:
Removes (deletes) a directory.
RMDIR [drive:]path
RD [drive:]path

External Commands

MREC (A) Page 8


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

LABEL: Label is used to view or change the label of the computer


disk drives.
Syntax:
Creates, changes, or deletes the volume label of a disk.
LABEL [drive:][label]

MOVE: Allows you to move files or directories from one folder to


another, or from one drive to another.
Syntax:
Moves files and renames files and directories.
To move one or more files:
MOVE [/Y | /-Y] [drive:][path]filename1[,...] destination
To rename a directory:
MOVE [/Y | /-Y] [drive:][path]dirname1 dirname2

SORT: Sorts the input and displays the output to the screen.
Syntax:
Sorts input and writes results to the screen, a file, or another
device
SORT [/R] [/+n] [[drive1:][path1]filename1] [>
[drive2:][path2]filename2]
[command |] SORT [/R] [/+n] [> [drive2:][path2]filename2]

MORE: More allows information to be displayed one page at a


time.
Syntax:
MORE [drive:][path]filename
MORE < [drive:][path]filename
command-name | MORE [drive:][path][filename]

FIND: Allows you to search for text within a file. Although MS-
DOS itself is not case sensitive, when typing in the string that
you are looking for with the find command, it is case sensitive.

Syntax:
FIND [/V] [/C] [/N] [/I] "string" [[drive:][path]filename[ ...]]

1.b)Implement various programs logics using algorithms and


flowcharts.

Example 1: Aim: An algorithm and draw flowchart to “Buy a Pen”

Algorithm:
Step 1: start
Step 2: Go to stationary shop

MREC (A) Page 9


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

Stept 3: Select a pen


Step 4: Pay the price
Step 5: Take the pen
Step 6: Come back home.
Step 7: Stop.

Flowchart:

Example 2: C program to add given two numbers


Algorithm:
Step 1:Begin
Step 2:Take the two numbers
Step 3:Add the numbers
Step 4:Write result
Step 5:End
Flowchart:

MREC (A) Page 10


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

Program :
#include<stdio.h>
main()
{
int a, b, c;
clrscr();
printf("Enter two numbers to add\n");
scanf ("%d%d",&a,&b);
c = a + b;
printf("Sum of entered numbers = %d\n",c);
getch();
}
Output:

1.c) Write a C program to implement basic arithmetic operations.

Description:
Perform all the basic arithmetic operations i.e. addition,
subtraction, multiplication and division operations using switch
case.

Program:
#include<stdio.h>
#include<conio.h>
main ()
{
MREC (A) Page 11
DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

int a,b;
char choice;
clrscr();
printf("Press'+'for addition\n'-' for subtraction\n'/'for
divide\n");
printf("'*'for multiply\n'%' for remainder value\n");
printf("Enter your choice:\n");
scanf("%c", &choice);
printf("Enter two numbers:\n");
scanf("%d %d", &a, &b);
switch(choice)
{
case '+':
printf ("addition=%d\n", a + b);
break;
case '-':
printf("sub=%d\n",a-b);
break;
case '/':
printf("division=%d\n",a/b);
break;
case '*':
printf("multiply=%d\n",a*b);
break;
case ‘%’:
printf(“remainder=%d\n”,a%b);
break;
default :
printf("invalid choice\n");
break;
}
getch();
}

Output:

MREC (A) Page 12


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

2.a)Write a C program to find smallest and largest of given


three numbers.

Description:

Compares the given three numbers and finds the smallest and
largest number among the given three numbers.

Algorithm:
Step 1: start
Step 2: read a,b,c
Step 3: If ((a >b)&&(a>c))
largest = a
Else if(b>c)
largest = b
else
largest=c
Step 4: if( (a < b) && (b < c) )
smallest= a
else if(b < c)
smallest=b
else
smallest=c
Step 5: Stop.

MREC (A) Page 13


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

Flow chart:

Program:
#include<stdio.h>
void main()
{
int a,b,c;
clrscr();
printf(“\n\n\t ENTER THREE NUMBERS a,b,c…(separated by commas):
“);
scanf(“%d,%d,%d”, &a, &b, &c);
printf(“\n\n\t THE BIGGEST NUMBER IS…: “);
if( (a > b) && (a > c) )
printf(“%d”, a);
else if(b > c)
printf(“%d”, b);
else
printf(“%d”, c);
printf(“\n\n\t THE SMALLEST NUMBER IS…: “);
if( (a < b) && (b < c) )
printf(“%d”, a);
else if(b < c)
printf(“%d”, b);

MREC (A) Page 14


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

else
printf(“%d”,c);
getch();
}

Output:

2.b)Write a C program to find the roots of a quadratic equation.

Description:
Determines the discriminant of the given quadratic equation and
depending on the value of the discriminant, it finds the roots.

FLOWCHART:

MREC (A) Page 15


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

Program:

#include<stdio.h>
#include<math.h>
#include<conio.h>
void main()
{
float a,b,c,d,r1,r2,real,imag;
clrscr();
printf("enter a,b,c values for quadratic equation");
scanf("%f%f%f",&a,&b,&c);
d=b*b-4*a*c;
if(d>0)
{
r1=(-b+sqrt(d))/(2*a);
r2=(-b-sqrt(d))/(2*a);
printf(“Roots are real and unequal\n”);
printf("Roots are:%f\t\t%f",r1,r2);
}

else if(d==0)
{
r1=r2=-b/(2*a);
printf(“Roots are real and equal\n”);

MREC (A) Page 16


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

printf("Roots are:%f\t\t%f",r1,r2);
}
else
{
real=(-b/(2*a));
imag=sqrt(-d)/(2*a);
printf(“Roots are imaginary\n”);
printf("Roots are:%f+%fi\t%f-%fi",real,imag,real,imag);
}
getch();
}

Output:

3.a)Write a C program to find the sum of individual digits of a


positive integer.

Description:

Find sum of the individual digits of an integer i.e. 12->1+2

Program:
#include <stdio.h>
void main ( )

MREC (A) Page 17


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

{
int num, sum = 0, rem=0;
clrscr( );
printf("Enter a number to calculate sum of its individual
digits \n");
scanf("%d",&num);
while(num > 0)
{
rem = num % 10;
sum = sum + rem;
num = num / 10;
}
printf("Sum of digits of entered number = %d\n",sum);
}
getch();
}
Output :

3.b) Write a C program to generate Fibonacci series for the first


n terms of the sequence.

Description:

Program to generate Fibonacci series for the first n terms of the


sequence i.e. the series is in the form of 0 1 1 2 3
5........i.e. first term is 0, second term is 1, third term is

MREC (A) Page 18


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

0+1=1, fourth term is 1+1=2 and so on.

Program :
#include<stdio.h>
#include<conio.h>
void main()
{
int n,a=0,b=1,c=0,i=0;
clrscr();
printf("Enter the no of elements in the fibonacci series \n");
scanf("%d",&n);
printf("The fibonacci series is : \n");
printf("%d \t %d",a,b);
for(i=3;i<=n;i++)
{
c=a+b;
printf("\t %d",c);
a=b;
b=c;
}
getch();
}
Output :

MREC (A) Page 19


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

4.a)Write a C program to find whether the given number is


palindrome, perfect, Armstrong or not.

Description:

If the reverse of the number is equal to the given number then


that number is said to be Palindrome.
Ex: 121, 2442.

If the sum of the factors of the number is equal to the given


number then that number is said to be Perfect. Ex: Factors of 6
are 2,3->2+3=6, then 6 is a Perfect number.

If the sum of the cubes of the individual digits of a number is


equal to the given number then that number is said to be
Armstrong. Ex: 153-> 13+53+33=153, then 153 is an Armstrong
number.

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,c,r,s,t,temp,i;
clrscr();
do
{
printf("\nEnter the choice!\n");
printf("\nEnter 1 for checking Armstrong number!\nEnter 2 for
checking Palindrome number!\nEnter 3 for checking Perfect
number!\nEnter 0 to exit!\n");
printf("\nEnter your choice:");
scanf("%d", &c);
if(c==0)
{
printf("\nClosing the program!!");
getch();
exit(0);
}
printf("\nEnter the number for checking:");
scanf("%d", &n);

MREC (A) Page 20


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

switch(c)
{
case 1:
{
t=n;
s=0;
while(t!=0)
{
r=t%10;
t=t/10;
s=s+r*r*r;
}
if(s==n)
printf("\nEntered number is an Armstrong number!");
else
printf("\nEntered number is not an Armstrong number!");
break;
}
case 2:
{
s=0;
temp=n;
while(n)
{
r=n%10;
n=n/10;
s=s*10+r;
}
if(temp==s)
printf("%d is a Palindrome",temp);
else
printf("%d is not a Palindrome",temp);

break;
}
case 3:
{
s=0;
for(i=1;i<=n/2;i++)
{
if(n%i==0)
{

MREC (A) Page 21


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

s=s+i;
}
}
if(s==n)
printf("\nThe number is perfect!!");
else
printf("\nThe number is not perfect!!");
break;
}
default:
printf("\nWrong choice entered!!");
break;
}
}while(n!=0);
getch();
}

Output:

MREC (A) Page 22


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

4. b)Write a C program to generate all the prime numbers between


limits supplied by the user

Description:

The number which is divisible by 1 and itself is a Prime number.


Ex: 3,5,7,11,13 etc

Program :

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,count=0,i,j, primecount=0;
clrscr();
printf("Enter a range to print prime numbers in between that
range \n");
scanf("%d%d",&a,&b);
for(i=a;i<=b;i++)
{
count=0;
for(j=2;j< i ;j++)
{
if(i%j == 0)
{
count++;
break;
}
}
if(count == 0)
{
printf("%d \t",i);
primecount++;
}
}
printf("\n The total prime numbers in the given range %d and
%d is %d",a,b,primecount);
getch();
}

Output:

MREC (A) Page 23


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

5. a)To find the factorial of a given integer( non-recursive)

Description:

The factorial of an integer n, denoted by n!, is the product of


all positive integers less than or equal to n i.e.
n!=1*2*3*……..*n.
Program :
#include<stdio.h>
#include<conio.h>
void main()
{
int n,fact=1,i;
clrscr();
printf("Enter a number to find the factorial \n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
fact=fact*i;
}
printf("The factorial of given number %d is %d",n,fact);
getch();
}
Output:

5. a)To find the factorial of a given integer(recursive)

MREC (A) Page 24


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

Description:

The factorial of an integer n, denoted by n!, is the product of


all positive integers less than or equal to n i.e.
n!=1*2*3*……..*n.

Program:
#include<stdio.h>
#include<conio.h>
long int fact (long int);
void main()
{
long int n,f;
clrscr();
printf(“Enter a number to find the factorial”);
scanf(“%d”, &n);
f=fact(n);
printf(“\n The factorial of given number %d is %d”,n,f);
getch();
}
long int fact(long int n)
{
long int f=1;
if(n==0||n==1)
return f;
else
f=n*fact(n-1);
return f;
}
Output:

MREC (A) Page 25


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

5.b)To find GCD of two given integers(non-recursion)

Description:

The greatest common divisor (gcd) of two or more integers, when


at least one of them is not zero, is the largest positive
integer that divides the numbers without a remainder.
For example, the GCD of 8 and 12 is 4.

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int m,n,rem;
clrscr();
printf("Enter two numbers to find their GCD : \n");
scanf("%d%d",&m,&n);
while(n%m !=0)
{
rem=n%m;
n=m;
m=rem;
}
printf("The gcd of given numbers is %d", m);
getch();
}

MREC (A) Page 26


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

Output:

5.b) To find GCD of two given integers (recursion)

Description:

The greatest common divisor (gcd) of two or more integers, when


at least one of them is not zero, is the largest positive
integer that divides the numbers without a remainder.
For example, the GCD of 8 and 12 is 4.

Program:
#include<stdio.h>
#include<conio.h>
int find_gcd(int,int);
void main()
{
int n1,n2,gcd;
printf(“\n Enter two numbers to find their gcd”);
scanf(“%d%d,“,n1,n2);
gcd=find_gcd(n1,n2);
printf("The gcd of given numbers is %d",gcd);
getch();
}
int find_gcd (int x,int y)
{
while(x!=y)

MREC (A) Page 27


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

{
if(x>y)
return find_gcd(x-y,y);
else
return find_gcd(x,y-x);
}
return x;
}

Output:

MREC (A) Page 28


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

6. a)Write a C program to find both the largest and smallest


number in a list of integers.

Description:

Compares the given list of integers and finds both the largest
and smallest number from that given list.

Program:
#include <stdio.h>
void main()
{
int a[10],i,max,min;
clrscr();
printf("\n Enter the elements in array ");
for (i=0;i<10;i++)
scanf("%d",&a[i]);
max = a[0];
min=a[0];
for(i=1;i<10;i++)
{
if (max < a[i])
max = a[i];
if (min>a[i])
min=a[i];
}
printf("\n The largest element is %d",max);
printf("\n The least element is %d",min);
getch();
}

Output:

MREC (A) Page 29


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

6.
b. Write a C program that performs using functions:
i. Addition of Two Matrices
ii. Multiplication of Two Matrices

Description:

A matrix (plural matrices) is a rectangular array of numbers,


symbols, or expressions, arranged in rows and columns. The
dimensions of the matrix below are 2 × 3 (read "two by three"),
because there are two rows and three columns. The individual
items in a matrix are called its elements or entries.

Program:

#include<stdio.h>
#include<conio.h>
void read_arr(int a[10][10],int row,int col)
{
int i,j;
for(i=1;i<=row;i++)
{
for(j=1;j<=col;j++)
{
printf("Enter Element %d %d : ",i,j);
scanf("%d",&a[i][j]);
}
}
}
void add_arr(int m1[10][10],int m2[10][10],int m3[10][10],int
row,int col)
{
int i,j;
printf("Sum of entered matrices:\n");
for(i=1;i<=row;i++)
{
for(j=1;j<=col;j++)
{
m3[i][j] = (m1[i][j] + m2[i][j]);
}
}
}
void mul_arr(int m1[10][10],int m2[10][10],int m3[10][10],int
row,int col)
{

MREC (A) Page 30


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

int i,j,k;
printf("Multiplication of entered matrices:\n");
for(i=1;i<=row;i++)
{
for(j=1;j<=col;j++)
{
m3[i][j]=0;
for (k=1;k<=row;k++)
{
m3[i][j] = m3[i][j] + (m1[i][k] * m2[k][j]);
}
}
}
}

void print_arr(int m[10][10],int row,int col)


{
int i,j;
for(i=1;i<=row;i++)
{
for(j=1;j<=col;j++)
{
printf("%d ",m[i][j]);
}
printf("\n");
}
}
void main()
{
int m1[10][10],m2[10][10],m3[10][10],row,col;
clrscr();
printf("Enter number of rows :");
scanf("%d",&row);
printf("Enter number of colomns :");
scanf("%d",&col);
read_arr(m1,row,col);
read_arr(m2,row,col);
add_arr(m1,m2,m3,row,col);
print_arr(m3,row,col);
mul_arr(m1,m2,m3,row,col);
print_arr(m3,row,col);
getch();
}

MREC (A) Page 31


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

Output:

7.a)
i.Write a C program to insert a sub-string in to given main
string from a given position using function.

Description:

Insert a sub-string into a given main string from a given


position using functions.
Ex: Initially main string is SDENTS
The sub-string is TU. The given position is 2.
After insertion now the string is STUDENTS.

Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s1[40],s2[40],s[40];
int i,j,c,ind=0;
clrscr();
printf("Enter org string and substring");
scanf("%s %s",s1,s2);
printf("\n Enter position where to be inserted");

MREC (A) Page 32


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

scanf("%d",&ind);
for(i=0,c=0;s1[i]!='\0';i++,c++)
{
if(i==ind)
for(j=0;s2[j]!='\0';j++,c++)
s[c]=s2[j];
s[c]=s1[i];
}
s[c]='\0';
printf("String now is :");
printf("\n %s \n",s);
getch();
}

Output:

7.a)
ii. Write a C program to delete n Characters from a given
position in a given string using function.

Description:

Delete n characters from a given main string from a given


position using functions.
Ex: Initially main string is STUDENTS

MREC (A) Page 33


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

The sub-string is TU. The given position is 2.


After deletion now the string is SDENTS.

Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void del(char[],int,int);
void main()
{
char str[50];
int n,pos;
clrscr();
puts("Enter the string");
gets(str);
printf("Enter the position");
scanf("%d",&pos);
puts("Enter no of characters to be deleted");
scanf("%d",&n);
del(str,pos,n);
getch();
}
void del(char s[],int a,int b)
{
int i;
for(i=a-1;s[i]!='\0';i++)
{
s[i]=s[a+b-1];
a++;
}
Puts(“The resultant string after deleting the specified
characters is :”);
puts(s);
}

MREC (A) Page 34


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

Output:

7.b)Write a C program to determine if the given string is a


palindrome or not.

Description:

Program to determine whether the given string is Palindrome or


not.
If the reverse of the string is equal to the given string then
that string is said to be string Palindrome.
Ex: madam, dad.

Program:

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[50],strrev[50];
int i,n=0,F=0;
clrscr();

MREC (A) Page 35


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

puts("Enter the string");


gets(str);
/*for finding length*/
for(i=0;str[i]!='\0';i++)
{
n=n+1;
}
/*no reverse string*/

i=0;
while(n>0)
{
strrev[i]=str[n-1];
n--,i++;
}
strrev[i]='\0';
/*to check the two string*/;
for(i=0;str[i]!='\0';i++)
{
if(str[i]!=strrev[i])
{
F=1;
break;
}
}
if(F==0)
printf("Given string %s is a palindrome",str);
else
printf("Not palindrome");
getch();
}

MREC (A) Page 36


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

Output:

7. c)Write a C program to find substring in a given string.

Description:

Find a sub-string into a given main string.


Ex: Initially main string is STUDENTS
The sub-string is TU.
TU is a sub-string found in the main string STUDENTS.

Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{

MREC (A) Page 37


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

char str1[90],str2[10],r[40];
int i,j;
clrscr();
puts("enter string");
gets(str1);
puts("enter sec string");
gets(str2);
for(i=0;str1[i]!='\0';i++)
{
for(j=0;str2[j]!='\0';j++)
{
if(str1[i]==str2[j])
r[j]=str2[j];
} }
r[i]='\0';
if(strcmp(r,str2)==NULL)
printf("%s is substr found",r);
else
printf("%s is not sub",r);
getch();
}
Output:

MREC (A) Page 38


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

7.d)Write a C program to count the lines, words and characters


in a given text.

Description:

Program to count the number of lines, words and characters in a


given text

Program:
#include <stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char line[100], ctr;
int i,c,
end = 0,
characters = 0,
words = 0,
lines = 0;
clrscr();
printf("ENTER YOUR TEXT, WHEN COMPLETED, PRESS
'RETURN'.\n\n\n");
while( end == 0)
{
/* Reading a line of text */
c = 0;
while((ctr=getchar()) != '\n')
line[c++] = ctr;
line[c] = '\0';

/* counting the words in a line */


if(line[0] == '\0')
break ;
else
{
words++;
for(i=0; line[i] != '\0';i++)
if(line[i] == ' ' || line[i] == '\t')
words++;
}

/* counting lines and characters */


lines = lines +1;
characters = characters + strlen(line);

MREC (A) Page 39


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

}
printf ("\n");
printf("Number of lines = %d\n", lines);
printf("Number of words = %d\n", words);
printf("Number of characters = %d\n", characters);
getch();
}
Output:

8.a)Write a C program to implement functions arguments with a


different returns values.
i). Function without argument without return value:

Program:

#include<stdio.h>
#include<conio.h>
void sum(); // function Declaration
void main()
{
sum();
getch();
}

void sum()
MREC (A) Page 40
DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

{
int val,a,b;

printf("\nEnter the Two numbers to be added : ");


scanf("%d%d",&a,&b);

val = a+b ;

printf("Sum of two numbers= %d",val);


}

Output:

ii).Function without arguments with return value:


Program:
#include<stdio.h>
#include<conio.h>
int sum(); // function Declaration
void main()
{
int val;
val=sum();
printf("Sum of two numbers= %d",val);
getch();
}
int sum()
{
int a,b;
printf("\nEnter the Two numbers to be added : ");
scanf("%d%d",&a,&b);
return(a+b);
}

Output:

MREC (A) Page 41


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

iii).Function with argument without return value:

Program:
#include<stdio.h>
#include<conio.h>
void sum(int,int); // function Declaration
void main()
{
int a,b;
printf("\nEnter the Two numbers to be added : ");
scanf("%d%d",&a,&b);
sum(a,b);
getch();
}
void sum(int a,int b)
{

int val;
val=a+b;
printf("Sum of two numbers= %d",val);

Output:

iv)Function with argument and with return value:

MREC (A) Page 42


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

Program:

#include<stdio.h>
#include<conio.h>
int sum(int,int); // function Declaration
void main()
{
int a,b,val;
printf("\nEnter the Two numbers to be added : ");
scanf("%d%d",&a,&b);
val=sum(a,b);
printf("The sum of two numbers: %d",val);
getch();
}
int sum(int a,int b)
{
return(a+b);
}

Output:

8. b)Write a C program to implement call by value using


functions.

Description:
Function call by value is the default way of calling a function
in C programming. Before we discuss function call by value, lets
understand the terminologies that we will use while explaining
this:
Actual parameters: The parameters that appear in function calls.
Formal parameters: The parameters that appear in function
declarations.

Program:

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

/* function declaration */

MREC (A) Page 43


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

void swap(int x, int y);


void main () {
/* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values */
swap(a, b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
getch();
}
/* function definition to swap the values */
void swap(int x, int y)
{
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */
return;
}

Output:

ii) Write a C program to implement call by reference using


functions.

Description:
The call by reference method of passing arguments to a function
copies the address of an argument into the formal parameter.
Inside the function, the address is used to access the actual
argument used in the call. It means the changes made to the
parameter affect the passed argument.
To pass a value by reference, argument pointers are passed to
the functions just like any other value. So accordingly you need
to declare the function parameters as pointer types as in the

MREC (A) Page 44


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

following function swap(), which exchanges the values of the two


integer variables pointed to, by their arguments.

Program:

#include <stdio.h>
#include<conio.h>
/* function declaration */
void swap(int *x, int *y);
void main () {
/* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values.
* &a indicates pointer to a ie. address of variable a and
* &b indicates pointer to b ie. address of variable b.
*/
swap(&a, &b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
getch();
}

/* function definition to swap the values */


void swap(int *x, int *y) {
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
return;
}

Output:

MREC (A) Page 45


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

9. a)Write a C program to find grades of a


student’s using structures.

Description:

Finding grades of students using structures


(collection of different data types).

Program:

#include<stdio.h>
#include<conio.h>
struct stud
{
char nam[20];
int obtain_mark;
int per;
char grad[5];
};
struct stud s[5];
int i;
void main()
{
clrscr();
for(i=1; i<=5; i++)
{
printf("Enter %d student name : ",i);
scanf("%s",&s[i].nam);
printf("Enter %d student obtained marks = ",i);
scanf("%d",&s[i].obtain_mark);
fflush(stdin);
}
for(i=1; i<=5; i++)
s[i].per=s[i].obtain_mark/5;
for(i=1; i<=5; i++)
{
if(s[i].per>=80)
strcpy(s[i].grad,"A");
else if(s[i].per>=60)
strcpy(s[i].grad,"B");
else if(s[i].per>=50)
strcpy(s[i].grad,"C");
else if(s[i].per>=40)
strcpy(s[i].grad,"D");
else
strcpy(s[i].grad,"F");
}

MREC (A) Page 46


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

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


printf("\n%d student %s has obtained grade %s
",i,s[i].nam,s[i].grad);
getch();
}

Output:

9.b)write a c program to implement nested structures.

Description:

Nested structure in C is nothing but structure within structure.


One structure can be declared inside other structure as we
declare structure members inside a structure.
The structure variables can be a normal structure variable or a
pointer variable to access the data. You can learn below concepts
in this section.

Program:

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

struct student_college_detail

MREC (A) Page 47


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

{
int college_id;
char college_name[50];
};

struct student_detail
{
int id;
char name[20];
float percentage;
// structure within structure
struct student_college_detail clg_data;
}stu_data;

void main()
{
struct student_detail stu_data = {1, "Teja", 90.5, 1234,
"Malla Reddy Engineering
College"};
printf(" Id is: %d \n", stu_data.id);
printf(" Name is: %s \n", stu_data.name);
printf(" Percentage is: %f \n\n", stu_data.percentage);

printf(" College Id is: %d \n",


stu_data.clg_data.college_id);
printf(" College Name is: %s \n",
stu_data.clg_data.college_name);
getch();
}

Output:

MREC (A) Page 48


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

10.a)Write a C program which copies one file to another.

Description:

A computer file is a resource for storing information, which is


available to a computer program and is usually based on some
kind of durable storage. A file is "durable" in the sense that
it remains available for other programs to use after the program
that created it has finished executing. Copying one file to
another file.

Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
FILE *f1,*f2;
char s,c;
clrscr();
f1=fopen("sham.txt","w");
puts("Enter data to sham file");
while((c=getchar())!=EOF)
putc(c,f1);

MREC (A) Page 49


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

fclose(f1);
f1=fopen("sham.txt","r");
f2=fopen("a.txt","w");
puts("data copied");
while((s=getc(f1))!=EOF)
{
putc(s,f2);
fprintf(stdout,"%c",s);
}
fclose(f1);
fclose(f2);
getch();
}

Output:

10.b)Write a C program to command line arguments.

Description:
It is possible to pass some values from the command line to your
C programs when they are executed. These values are called
command line arguments and many times they are important for
your program especially when you want to control your program
from outside instead of hard coding those values inside the
code.

MREC (A) Page 50


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

Program:

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

int main(int argc, char *argv[]) // command line arguments


{
if(argc!=5)
{
printf("Arguments passed through command line " \
"not equal to 5");
return 1;
}
printf("\n Program name : %s \n", argv[0]);
printf("1st arg : %s \n", argv[1]);
printf("2nd arg : %s \n", argv[2]);
printf("3rd arg : %s \n", argv[3]);
printf("4th arg : %s \n", argv[4]);
printf("5th arg : %s \n", argv[5]);
getch();
}

Output:

MREC (A) Page 51


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

11.a)Write a C program to that uses non-recursive function to


search for a key value in a given list of integers using linear
search.
Description :
The following code implements linear search (Searching
algorithm) which is used to find whether a given number is
present in an array and if it is present then at what location
it occurs. It is also known as sequential search. It is
straightforward and works as follows: We keep on comparing each
element with the element to search until it is found or the list
ends. Linear search in C language for multiple occurrences and
using function.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int i, a[20], n, key, flag = 0;
clrscr();
printf("Enter the size of an array \n");
scanf("%d", &n);
printf("Enter the array elements");
for(i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
printf("Enter the key elements");
scanf("%d", &key);
for(i = 0; i < n; i++)
{
if(a[i] == key)
{

MREC (A) Page 52


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

flag = 1;
break;
}
}
if(flag == 1)
printf("The key elements is found at location %d", i + 1);
else
printf("The key element is not found in the array");
getch();
}
Output:

11.b)Write a C program that uses recursive function to search


for a key value in a given sorted list of integers using binary
search.
Description:
This code implements binary search in C language. It can only be
used for sorted arrays, but it's fast as compared to linear
search. If you wish to use binary search on an array which is
not sorted, then you must sort it using some sorting technique
say merge sort and then use the binary search algorithm to find
the desired element in the list. If the element to be searched
is found then its position is printed. The code below assumes
that the input numbers are in ascending order.

MREC (A) Page 53


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

Program:
#include<stdio.h>
#include<stdlib.h>
int binsearch(int[], int, int, int);
int main()
{
int num, i, key, position;
int low, high, list[10];
printf("\nEnter the total number of elements");
scanf("%d", &num);
printf("\nEnter the elements of list :");
for (i = 0; i < num; i++) {
scanf("%d", &list[i]);
}
low = 0;
high = num - 1;
printf("\nEnter element to be searched : ");
scanf("%d", &key);
position = binsearch(list, key, low, high);
if (position != -1) {
printf("\nNumber present at %d", (position + 1));
}
else
printf("\n The number is not present in the list");
getch();
}
// Binary Search function
int binsearch(int a[], int x, int low, int high)

MREC (A) Page 54


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

{
int mid;
if (low > high)
return -1;
mid = (low + high) / 2;
if (x == a[mid])
{
return (mid);
}
else if (x < a[mid])
{
binsearch(a, x, low, mid - 1);
}
else
{
binsearch(a, x, mid + 1, high);
}
}

Output:

MREC (A) Page 55


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

11.b)Write a C program that uses non-recursive function to


search for a key value in a given sorted list of integers using
binary search.
Description:
This code implements binary search in C language. It can only be
used for sorted arrays, but it's fast as compared to linear
search. If you wish to use binary search on an array which is
not sorted, then you must sort it using some sorting technique
say merge sort and then use the binary search algorithm to find
the desired element in the list. If the element to be searched
is found then its position is printed. The code below assumes
that the input numbers are in ascending order.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20], i, n, key, low, high, mid;
clrscr();
printf("Enter the size of array:\n");
scanf("%d",&n);

MREC (A) Page 56


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

printf("Enter the array elements in ascending order");


for(i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
printf("Enter the key element\n");
scanf("%d", &key);
low = 0;
high = n - 1;
while(high >= low)
{
mid = (low + high) / 2;
if(key == a[mid])
break;
else
{
if(key > a[mid])
low = mid + 1;
else
high = mid - 1;
}
}
if(key == a[mid])
printf("The key element is found at location %d", mid + 1);
else
printf("the key element is not found");
getch();
}
Output:

MREC (A) Page 57


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

12.a)Write a C program that implements the selection sort method


to sort a given array of integers in ascending order.
Description:
C program for selection sort to sort numbers. This code implements
selection sort algorithm to arrange numbers of an array in ascending
order. With a little modification, it will arrange numbers in
descending order.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int n, a[20], min, temp, i, j;
clrscr();
printf("Enter the size of the array\n");
scanf("%d", &n);
printf("Enter the array elements\n");
for(i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
for(i = 0; i < n - 1; i++)

MREC (A) Page 58


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

{
min = i;
for(j = i + 1; j < n; j++)
{
if(a[j] < a[min])
min = j;
}
temp = a[i];
a[i] = a[min];
a[min] = temp;
}
printf("The sorted array is\n");
for(i = 0; i < n; i++)
printf("%d\n", a[i]);
getch();
}
Output:

MREC (A) Page 59


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

12.b)Write a C program that implements the bubble sort method to


sort a list of names in ascending order.
Description:
Bubble sort is the simplest sorting algorithm that works by
repeatedly swapping the adjacent elements if they are in random
order.
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int i,j,count;
char str[25][25],temp[25];
printf("enter number of names\n");
scanf("%d",&count);
printf("enter string one by one");
for(i=0;i<=count;i++)
{
gets(str[i]);
}
for(i=0;i<=count;i++)
{
for(j=i+1;j<=count;j++)
{
if(strcmp(str[i],str[j])>0)
{
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
}

MREC (A) Page 60


DEPARTMENT OF CSE COMPUTER PROGRAMMING LAB

printf("sorted strings are:");


for(i=0;i<=count;i++)
puts(str[i]);
getch();
}
Output:

MREC (A) Page 61

You might also like