You are on page 1of 60

SHADAN WOMEN’S COLLEGE OF ENGINEERING &

TECHNOLOGY

(Affiliated to JNTU, Hyderabad)

Computer Programming Lab Manual


I B.TECH II-SEMISTER
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
YEAR-2017
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

OBJECTIVES OF THE LAB

 To make the student learn a programming language.


 To teach the student to write programs in C solve the problems
 Student learn the concepts like looping ,functions ,pointers, file .concepts

Primary goal of this course is to make acquaint the students to know the programming
language and also to know how ‘C’ can be used to write serious program on IBM. Here
the main importance is given to the knowledge and concepts that are needed to exploit
the capabilities of the microcomputer through C.

More over programming is a ‘ART’ purely depends on the logic of the problem solving .
As it is said that problem solving has many methods, but the requirement is the efficient
way of solving a problem.

And more over the language C contains the control structures necessary to make
programmers readable and also allows basic concepts like looping, functions, pointers;
file .concepts is to be implemented in variety of ways.

In this course we mainly concentrate on programming concepts of C and its


implementation.

2
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

INSTRUCTIONS FOR STUDENTS

These are the instructions for the students while attending the lab:

 Before entering the lab the student should carry the following
things(mandatory)

1. Identity card issued by the college

2. Class notes

3. Lab observation book

4. Lab manual

5. Lab Record

 Student must sign in and sign out in the register provided when attending the
lab session without fail

 Come to the lab in time. Students, who are late more than 15 min.,will not be
allowed to attend the lab

 Students need to maintain 100% attendance in lab.

 All students must follow a Dress code while in the lab.

 Foods, drinks are not allowed

 All bags must be left at the indicated place

 Workspace must be kept clean and tidy after experiment is completed

 Read the manual carefully before coming to the lab and be sure about what
you are supposed to do

 Do the experiments as per the instructions given in the manual

 Copy all the programs to observation which are taught in clas before attending
the lab session

 Students are not supposed to use CD,DVD or PENDRIVES without permission


of lab-In charge

 Lab records need to be submitted on or before the date of submission

3
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

REQUIREMENTS

Hardware Requirements:
Processor Pentium I
RAM: 64MB
Hard Disk 100 MB

Software Requirements:

Language: ANSI C Compiler with Supporting Editors

Hard ware Requirement to run C language

Processor PIV(166 MHZ)


RAM 64 MB
HDD 100 MB
Monitor 14’’Color
Keyboard Normal

4
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

INTRODUCTION ABOUT C

History of C

The milestones in C's development as a language are listed below:

 UNIX developed c. 1969 -- DEC PDP-7 Assembly Language


 BCPL -- a user friendly OS providing powerful development tools developed
from BCPL. Assembler tedious long and error prone.
 A new language ``B'' a second attempt. c. 1970.
 A totally new language ``C'' a successor to ``B''. c. 1971
 By 1973 UNIX OS almost totally written in ``C''.

ABOUT C LANGUAGE :

C is a programming language developed at AT&T’s BELL Laboratory of USA in 1972.


Dennis Ritchie designed it. Because of its reliability. C is very popular. C stands
between high-level language (HLL) and Low Level Language (LLL). C’s compactness
and coherence is mainly due to the fact that it is a one-man language.

C is highly portable & it is well suited for structured programming. C program


consists of collection of functions.

STRUCTURE OF ‘C’ PROGRAM :

Each instruction in a C program is written as a separate statement. The program


starts with a main function followed by the opening braces which indicates the start
of the function then the variable and constant declarations followed by the
statements, which includes input and output statements.

C program may contain one or more sections as shown below.

DOCUMENTATION SECTION

LINK SECTION

DEFINITION SECTION

GLOBAL DECLARATION SECTION

main() Function section

Declaration part

Executable part

SUBPROGRAM SECTION

User defined functions

5
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

PROGRAM DEVELOPMENT STEPS

To develop the program in high level language and translate into machine level
language we are having following steps.

1) Writing and editing the program


2) Compiling the program
3) Linking the program with the required library modules
4) Executing the program

PROGRAM DEVELOPMENT TOOLS

Program Development Tools


There are three stages in the program development- algorithm
development, flowchart representation, and programme.
• Algorithm
• Flowchart
• Programme

I. Algorithm

Definition: A method of representing the step – by – step logical procedure for


solving a problem in natural language (like English, etc. ) is called as algorithm.
Algorithm can also be defined as an ordered sequence of well-defined and effective
operations that, when executed, will always produce a result and eventually
terminate in a finite amount of time.

Note: Algorithm written in English language is called Pseudo code.


On the whole an algorithm is a recipe for finding a right answer to a problem
by breaking it down into simple steps.

 Finiteness :- It terminates with finite no of steps


 Definiteness:- each step of algorithm is exactly defined
 Effectiveness:-All the operations used in the algorithm can be performed
exactly in a fixed duration of time
 Input:-An algorithm must have an input before the execution of program
begins
 Output:- An algorithm has one or more outputs after the execution

6
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

Properties an Algorithm should possess:


a. Generality: The algorithm must be complete in itself so that it can be also used to
solve all problems of a specific type for any input data.

b. Input / Output: Each algorithm can take zero. One or more input data and must
produce one or more output values.

c. Optimization: Unnecessary steps should be eliminated so as to make the algorithm


to terminate in finite number of steps.

d. Effectiveness: Each step must be effective in the sense that it should be primitive
( easily convertible into program statement) and can be performed exactly in a finite
amount of time.

e. Definiteness: Each step of the algorithm should be precisely and unambiguously


stated.
Example of algorithm to find sum of two numbers:

Step1: Begin
Step2: read a,b
Step3: add a and b and store in variable c
Step4: display c

Step5: stop

II. Flowchart

Definition: It is a diagrammatic representation of an algorithm. It is constructed


using different types of boxes and symbols.

The main advantages of flow charts are:

1. It is possible that the person who formulates the problem is not aware of the
k2details of programming. The programmer is not in a position to formulate the
problem. The flow chart acts as a link between the person who formulates the
problem and the programmer.

2. If the program written by one person is read by another, the job of understanding
the logic is made easier by reference to the flow chart. The flow chart helps the
programmer to modify the existing program.

7
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

Standard symbols used in drawing flowcharts:

Oval Terminal Start / stop / begin / end

Parallelogram Input / Making data available for


output Processing (input) or
recording of the
processed information
(output)
Document Printout Show data output in the
form of document

Diamond Decision Decision or switching


type of operations.

Rectangle Process Any processing to be


performed.
A process changes or
moves data. An
assignment operation.
Circle Connector Used to connect different
parts of flowchart

Arrow Flow Joins two symbols and


also represents flow of
execution
Bracket with --------- Annotation Descriptive comments or
broken line explanation
Junction Repetitions Multiple control flows
converge.
More than one arrow
coming into it.
Double sided Predefined Modules or subroutines
rectangle process specified elsewhere

III. Programming

A computer program is the list of instructions a computer follows in carrying out its
computations.

The process of writing a program is called programming.

8
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

Steps involved in Computer programming:


 Problem Definition
 Problem Understanding
 Program writing
 Error analysis
 Validation & Verification
 Documentation & Maintenance

Properties of Computer Programming:


All the properties of an algorithm hold well, even for effective programming in
addition with the following one:
a. Repetitiveness: The program should be able to check the results for various inputs
in a single run. This are one of the key properties of good programming.
Note: All the properties of an algorithm holds good for programming.
Example:
Question: Generate and print the first N terms of Fibonacci Series, where N is greater
than or equal to 1.
The Fibonacci series is 0, 1, 1, 2, 3, 5, 8, 13…

a. Problem understanding:
 In Fibonacci series only the first two numbers (0 and 1) are defined.
 Each number, after the first, is derived from the sum of its two nearest
predecessors.
 Therefore we can say that
New number = sum of last two numbers.
1 = 0+1
2 = 1+1
K2 3 = 1+2
5 = 2+3
8 = 3+5

b. Problem Definition:
Define three variables one for new number and two for the last two numbers, as SUM,
A and B.
A – used to store the number previous to the last number,
B – used to store the last number,
SUM – used to store the sum of A and B.
c. Algorithm development:
Step 1: Read the total number of required values in the series, N.
Step 2: Initialize the variables A and B to 0 and 1 respectively and SUM to 0.
Step 3: Also initialize a Counter I to 2.
Step 4: Compute the next value by adding A and B and store it in SUM.
Step 5: Display the value of SUM.
Step 6: Transfer the value of B to A and SUM to B.
Step 7: Increment the Counter I by 1.
Step 8: If the value of I is less than or equal to N, then go to step4, else go to step 9.
Step 9: End of the program

9
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

KEYWORDS

C89 has 32 keywords (reserved words with special meaning): auto, break, case,
char, const, continue, default, do, double, else, enum, extern, float, for, goto, if,
int, long, register, return, short, signed, sizeof, static, struct, switch, typedef,
union, unsigned, void, volatile, and while.

C99 adds five more keywords: inline, restrict, _Bool, _Complex, and _Imaginary.

OPERATORS

C supports a rich set of operators, which are symbols used within an expression to
specify the manipulations to be performed while evaluating that expression. C has
operators for:

 arithmetic: +, -, *, /, %
 assignment: =
 augmented assignment: +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
 bitwise logic: ~, &, |, ^
 bitwise shifts: <<, >>
 boolean logic: !, &&, ||
 conditional evaluation: ? :
 equality testing: ==, !=
 calling functions: ( )
 increment and decrement: ++ and --
 Member selection: ., ->
 object size: sizeof
 order relations: <, <=, >, >=
 reference and dereference: &, *, [ ]
 sequencing: ,
 sub expression grouping: ( )
 type conversion: (typename)

10
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

PROGRAMS

Week: 1 (A)

Write a C program to find the factorial of a positive integer

Description:
To find factors of a given number is nothing but factorial of a number
Ex: factorial of 5 is 5*4*3*2*1=120.

Algorithm:
Step 1. Start
Step 2. Read the number n
step 3. [Initialize]
i=1, fact=1
step 4. Repeat step 4 through 6 until i=n
step 5. fact=fact*i
step 6. i=i+1
step 7. Print fact
step 8. Stop

Flow Chart:

11
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

1-A) Write a C program to find the factorial of a positive integer

Program:
#include<stdio.h>
#include<conio.h>
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,fact=1;
printf("Enter any number : ");
scanf("%d", &n);
for(i=1; i<=n; i++)
fact = fact * i;
printf("Factorial value of %d = %d",n,fact);
}

Output:
Enter any number : 5
Factorial value of 5 is :120.
Record at least 3 results

Week- 1 (B)
Write a C program to find the roots of a quadratic equation
Description
Nature of roots of quadratic equation can be known from the quadrant = b2-4ac
If b2-4ac >0 then roots are real and unequal
If b2-4ac =0 then roots are real and equal
If b2-4ac <0 then roots are imaginary
Algorithm:
Step 1: start
Step 2: read the a,b,c value
Step 3: if b*b-4ac>0 then
Root 1= (-b+ pow((b*b-4*a*c),0.5))/2*a Root 2= (-b-
pow((b*b-4*a*c),0.5))/2*a
Step 4: if b*b-4ac=0 then
Root1 = Root2 = -b/(2*a)
Step 5: Otherwise Print Imaginary roots. Goto step 7.
Step 6: print roots
Step 7: stop

12
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

1-B). Write a C program to find the roots of a quadratic equation

Program:
#include<stdio.h>
#include<math.h>
void main()
{
float a,b,c,r1,r2,d; clrscr();
printf("Enter the values for equation:");
scanf("%f%f%f",&a,&b,&c);
/* check the condition */
if(a==0)
printf("Enter value should not be zero ");
else
{
d=b*b-4*a*c;
/* check the condition */
if(d>0)
{
13
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

r1=(-b+sqrt(d)/(2*a));
r2=(-b-sqrt(d)/(2*a));
printf("roots are real and unequal\n");
printf("%f\n%f\n",r1,r2);
}
else if(d==0)
{
r1=-b/(2*a);
r2=-b/(2*a);
printf("roots are real and equal\n");
printf("root=%f\n",r1);
printf("root=%f\n",r2);
}
else
printf("roots are imaginary");
}
getch();
}
Output:
1. Enter the values for equation: 1, 6, 9
Roots are real and equal
Root= -3.0000 Root= -
3.0000
2. Enter the values for equation: 2, 7, 6
Roots are real and unequal
Root= -6.75
Root= -7.25
3. Enter the values for equation: 1, 2, 3
Roots are imaginary
Record
2 at least 3 results

14
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

Week – 2
2-A) Write a C program to determine if the given number is a prime number or not.

Description:

Prime number is a number which is exactly divisible by one and itself only
Ex: 2, 3,5,7,………;
Program:
#include <stdio.h>

void main()
{
int n, i, flag = 0;
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;
}
}

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

Enter the number: 5


5 is a prime number.
Record
2 at least 3 results

15
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

2-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. Write a C program to generate the first n terms of the
sequence.
Description:
 A Fibonacci series is defined as follows:
 The first term in the sequence is 0
 The second term in the sequence is 1
 The sub sequent terms 1 found by adding the preceding two terms in the
sequence Formula: let t1,t2,…………tn be terms in Fibonacci sequence
t1=0, t2=1 tn=tn-2+tn-1……where n>2
Algorithm:
Step 1: start
Step 2: initialize the=0, b=1
Step 3: read n
Step 4: if n== 1 print a go to step 7. else goto step 5
Step 5: if n== 2 print a, b go to step 7 else print a,b
Step 6: initialize i=3
i) if i<= n do as follows. If not goto step 7
c=a+b
print c
a=b b=c
increment i value
goto step 6(i)
Step 7: stop

Flow Chart:

16
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

2-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. Write a C program to generate the first n terms of the sequence.

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,n,i;
clrscr();
printf("enter n value");
scanf("%d",&n);
a=0;
b=1;
if(n==1)
printf("%d",a);
else if(n==2)
printf("%d%d",a,b);
else
{
printf("%d%d",a,b);
//LOOP WILL RUN FOR 2 TIME LESS IN SERIES AS THESE WAS
PRINTED IN ADVANCE
for(i=2;i<n;i++)
{
c=a+b;
printf("%d",c);
a=b;
b=c;
}
}
getch();
}

Output:
1. Enter n value : 5
01123
2 Record at least 3 results

17
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

Week – 3
3-A). Write a C program to construct a pyramid of numbers

Description:
 In this program the we have to construct output in the pyramid shape manner

Program:

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,n;
clrscr();
printf("Enter pyramid range:");
scanf("%d",&n);

for(i=0;i<n;i++)
{
for(j=0;j<n-i;j++)
printf(" ");

for(j=0;j<i;j++)
printf("%d ",i);
printf("\n");
}
getch();
}

Output:

Enter pyramid range: 6

1
22
333
4444
55555
Record at least 3 results

18
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

3-B) Write a C program to calculate the following Sum:


Sum=1-x2/2! +x4/4!-x6/6!+x8/8!-x10/10!

Algorithm:
Main program:
Step 1: start
Step 2: declare x,i,n,s=0,c
Step 3: read x value
Step 4: for i=0 , n=0; i<=10; i=i+2, n++ goto step 5
Step 5: s=s+(pow(-1,n)*pow(x,i)/fact(i))
Step 6: print s value
Step 7: stop

Sub program:
Step 1: while x!=0 goto Step 2
Step 2: y=y+x; x—
Step 3: return y
Step 4: return to main program
Flow Chart:

19
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

Program:

#include<stdio.h>
#include<math.h>
long fact(int);
void main()
{
int x,i,n;
float s=0,c;
clrscr();
printf("\n enter the value of x\t");
scanf("%d",&x);
/*perform the looping operation*/
for(i=0,n=0;i<=10;i=i+2,n++)
s=s+(pow(-1,n)*pow(x,i)/fact(i));
printf("\n the result is %f",s);
getch();

}
/* calling sub program*/
long fact(int x)

{
long int y=1;
while(x!=0)

{
y=y*x;
x--;
}
return y;
}
Output:
1. Enter the value of x : 1
The result is 0.540302
Record at least 3 results

20
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

Week – 4
4-A).The least common multiple (LCM) of two positive integers a and b is the smallest
integer that is evenly divisible by both a and b. Write a C program that reads two
integers and calls LCM (a, b) function that takes two integer arguments and
returns their LCM. The LCM (a, b) function should calculate the least common
multiple by calling the GCD (a, b) function and using the following relation:

LCM (a, b) = ab / GCD (a, b)

Description:
 LCM of these sets of numbers. Multiply each factor the greatest number of times it
occurs in any of the numbers. 9 has two 3s, and 21 has one 7, so we multiply
3 two times, and 7 once. This gives us 63, the smallest number that can be divided
evenly by 3, 9, and 21.
 GCD means Greatest Common Divisor. i.e the highest number which divides the
given number
Ex: GCD (12,24) is 12
Formula: GCD= product of numbers/ LCM of numbers
 LCM (Least Common Multiple) of two numbers is the smallest number which can be
divided by both numbers.
 For example LCM of 15 and 20 is 60 and LCM of 5 and 7 is 35.
 LCM of two numbers ‘a’ and ‘b’ can be calculated using following formula.
a x b = LCM(a, b) * GCD (a, b)
LCM(a, b) = (a x b) / GCD(a, b)

Program:

#include <stdio.h>

// Recursive function to return gcd of a and b

int gcd(int a, int b)


{
// base case
if (a == b)
return a;

// a is greater
if (a > b)
return gcd(a-b, b);
return gcd(a, b-a);
}

// Function to return LCM of two numbers


int lcm(int a, int b)
{

21
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

return (a*b)/gcd(a, b);


}

// Driver program to test above function

void main()

{
int a, b;
clrscr();
printf(“\n Enter a, b values:\n”);
scanf(“%d%d”,&a,&b);
printf("\n LCM of %d and %d is %d ", a, b, lcm(a, b));
getch();
}

Output:
Enter a, b values:
15
20
LCM of 15 and 20 is 60
Record at least 3 results

4- B). Write a C program that reads two integers n and r to compute the ncr value
using the following relation:
nC (n, r) = n! / r! (n-r)! . Use a function for computing the factorial value of an
r
integer.

Description:

The number of different, unordered combinations of r objects from a set of n objects.


Program:

#include<stdio.h>
void main()
{
int n,r,ncr;
clrscr();
printf("\n Enter the value of n and r: ");
scanf("%d %d",&n,&r);
ncr=fact(n)/(fact(r)*fact(n-r));
printf("\n The NCR factor of %d and %d is %d",n,r,ncr);
getch();
}

22
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

int fact(int n)
{
int i=1;
while(n!=0){
i=i*n;
n--;
}
return i;
}
OUTPUT

Enter the value of n and r:


5
2
The NCR factor of 5 and 2 is 10.
2 Record at least 2 results

Week – 5
5- A). Write C program that reads two integers x and n and calls a recursive function
to compute xn.

Program: USING RECURSION

#include <stdio.h>

#include <conio.h>

/* Power function declaration */

double power(double num, int power);

void main()
{
int x, y;
double result;
clrscr();
printf("Enter any number: ");
scanf("%d", &x);
printf("Enter power of the number: ");
scanf("%d", &y);

result = power(x, y); //Calls power function


23
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

printf("\n %d raised to %d = %.2f\n", x, y, result);

getch ();
}

double power(double num, int result)


{
if(result == 0)
return 1;
return num * pow(num, result-1);
}

Output:

Enter any number: 10


Enter power of the number: 3
10 raised to 3 = 1000.00
2 Record at least 2 results

Week – 5
5-B). Write a C program that uses a recursive function to solve the Towers of Hanoi
problem.

Description:

 Printing the solution of Tower of Hanoi is a well-known problem in C programming


language, and its solution using recursive function is very popular.
 Before going through the program for Tower of Hanoi in C, here, I’d like to give a brief
introduction to Tower of Hanoi and the working procedure of the C source code for
this puzzle. Tower of Hanoi is a mathematical puzzle with three rods and ‘n’ numbers
of discs; the puzzle was invented by the French mathematician Edouard Lucas in
1883. The objective of this puzzle is to transfer the entire stack to another rod.

Rules of Tower of Hanoi

 Only a single disc is allowed to be transferred at a time.


 Each transfer or move should consists of taking the upper disk from one of the
stack and then placing it on the top of another stack i.e. only a top most disk on
the stack can be moved.
 Larger disk cannot be placed over smaller disk; placing of disk should be in
increasing order.

24
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

How Tower of Hanoi in C works?


 The source code for solving Tower of Hanoi in C is based on recursion. So, the key to
solving this puzzle is to break the problem down into a number of smaller problems
and further break these into even smaller ones, so that it is made a typical best
suited problem for the application of recursive function.

 The algorithm or the working procedure, which is to be repeated for a finite number
of steps, is illustrated below:

A, B and C are rods or pegs and n is the total number of discs, 1 is the largest disk and 5
is the smallest one.

 Move n-1 discs from rod A to B which causes disc n alone in on the rod A
 Transfer the disc n from A to C
 Transfer n-1 discs from rod B to C so that they sit over disc n

Program:
/* C Program to Solve Towers of Hanoi Problem */
#include<stdio.h>

void hanoi(int, char, char, char);

void main()
{
int disks;
char source, destination, aux;
clrscr();
printf("\nEnter No. of Disks:");
scanf("%d",&disks);
printf("\nEnter Source, Destination and Auxillary Disk Names:");
scanf("%s%s%s",source, destination, aux);
hanoi(disks,source,destination,aux);
getch();
}

25
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

void hanoi(int n, char s, char d, char a)


{
if(n>0)
{
hanoi(n-1,s,a,d);
printf("\n%d is moved from %s to %s",n,s,d);
hanoi(n-1,a,d,s);
}

Output:

26
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

5- C). Write a C program that reads two integers and calls a recursive function to
compute ncr
Description:

 Recursion is the process of repeating items in a self-similar way. In programming


languages, if a program allows you to call a function inside the same function, then it
is called a recursive call of the function.
 The C programming language supports recursion, i.e., a function to call itself. But
while using recursion, programmers need to be careful to define an exit condition
from the function, otherwise it will go into an infinite loop.

Example:
void recursion()
{
recursion(); /* function calls itself */
}

int main()
{
recursion();
}

Program:

# include <stdio.h>
# include <conio.h>
long fact(int) ; //function is declared at the top first.
void main()
{
long i, ncr ;
int n, r ;
clrscr() ;
printf("Enter the value for N : ") ;
scanf("%d", &n) ;
printf("\nEnter the value for R : ") ;
scanf("%d", &r) ;
if(n >= r)
{
ncr = fact(n) / (fact(n-r) * fact(r)) ;
printf("\n The NCR value is : %ld", ncr) ;
}
else
printf("\n Calculating NCR value is not possible") ;
getch() ;
}
27
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

long fact(int i)
{
long x ;
if(i == 0)
return 1 ;
else
{
x = i * fact(i - 1) ;
return x ;
}
}

OUTPUT:

Enter the value for N: 7


Enter the value for R: 5
The NCR value is: 21

Week- 6
6- A) Write a C program to generate all the prime numbers between 1 and n, where n
is a value supplied by the user using Sieve of Eratosthenes algorithm.

Description:
Prime number is a number which is exactly divisible by one and itself only
Ex: 2, 3, 5, 7…

Algorithm:
Step 1: start
Step 2: read n
Step 3: initialize i=1,c=0
Step 4:if i<=n goto step 5 If not goto
step 10
Step 5: initialize j=1
Step 6: if j<=1 do as the follow. If no goto step 7 i)ifi%j==0
increment c
ii) increment j
iii) goto Step 6
Step 7: if c== 2 print i
Step 8: increment i
Step 9: goto step 4
28
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

Step 10: stop

Flow Chart:

Program:

#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,fact,j;
clrscr();
printf("\n Enter the number:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
fact=0;
//THIS LOOP WILL CHECK A NO TO BE PRIME NO. OR NOT.
for(j=1;j<=i;j++)
{
if(i%j==0)
fact++;
}
if(fact==2)
printf("\n %d",i);
}
getch( );

29
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

Output:

Enter the number: 5


2
3
5
2 Record at least 3 results

6-B). Write a C program that uses non recursive function to search for a Key value in
a given list of integers. Use linear search method.
Description:
 The linear search is most simple searching method. It does not expect the list
 To be sorted. The key which is to be searched is compared with each element of the
list one by one. If a match exists, the search is terminated. If the end of list is
reached it
 If the search has failed and key has no matching in the list.

Algorithm:
1. Start

2. Read the value of n

3. for i=1 to n increment in steps of 1


Read the value of ith element into array

4. Read the element(x) to be searched

5. search<--linear(a,n,x)

6. if search equal to 0 goto step 7 otherwise goto step 8

7. print unsuccessful search

8. print successful search

9. stop

30
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

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

void main()
{
int i,j,n,a[10],key;
clrscr();

printf("\n Enter range for array:");


scanf("%d",&n);
printf("\n Enter elements into array:");
for(i=0;i<=n;i++)
scanf("%d",&a[i]);
printf("enter the search element:");
scanf("%d",&key);

for(i=0;i<=n;i++)
{
if(key==a[i])
{
printf("\nElement %d found at %d",key,i+1);
break;
}
}
if(i==n)
printf("\n Element %d not found in array",key);

getch();
}
Output:
enter range for array:4
enter elements into array:
56 43 12 88 9

enter the search element:9


element 9 found at 4
Record 2 outputs:

31
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

Week – 7
7- A). Write a menu-driven C program that allows a user to enter n numbers and then
choose between finding the smallest, largest, sum, or average. The menu and
all the choices are to be functions. Use a switch statement to determine what
action to take. Display an error message if an invalid choice is entered.

Program:

#include<stdio.h>
void main()
{
int array[50],c,small,large,sum=0,n,i;
float avg;
printf("Enter the size of the elements\n");
scanf("%d",&n);
printf("Enter the elements into the array\n");
for(i=0;i<n;i++)
scanf("%d",&array[i]);
printf("1: Smallest\n2:Largest\n3:Sum\n4:Average\n");
printf("Enter your choice\n");
scanf("%d",&c);
switch(c)
{
case 1: small=array[0];
for(i=0;i<n;i++)
{
if(small>array[i])
small=array[i];
}
printf("Smallest element in the list=%d",small);
break;
case 2:large=array[0];
for(i=0;i<n;i++)
{
if(large<array[i])
large=array[i];
}
printf("Largest element in the list=%d",large);
break;
case 3:
for(i=0;i<n;i++)
{
sum=sum+array[i];
}
printf("sum of elements in the list=%d",sum);
break;
case 4:for(i=0;i<n;i++)
{
sum=sum+array[i];

32
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

}
avg=sum/n;
printf("avg of elements in the list=%f",avg);
break;
default:
printf("Invalid choice\n");
}
}

OUTPUT:
Enter the size of the elements 2
Enter the elements into the array
46
1: Smallest
2:Largest
3:Sum
4:Average
Enter your choice 1
Smallest element in the list=4
7- B) Write a C program that uses non recursive function to search for a Key value in
a given sorted list of integers. Use binary search method.
Description:
 Binary search is a vast improvement over the sequential search.
 For binary search to work, the item in the list must be in assorted order.
 The approach employed in the binary search is divide and conquer.
 If the list to be sorted for a specific item is not Sorted, binary search fails.

ALGORITHM:

BINARY SEARCH

1. Start
2. Read the value of n
3. for i=1 to n increment in steps of 1
Read the value of ith element into array
4. Read the element(x) to be searched
5. search<--binary(a,n,x)
6. if search equal to 0 goto step 7 otherwise goto step 8
7. print unsuccessful search
8. print successful search
9. stop

BINARY SEARCH FUNCTION


33
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

1. start
2. initialise low to 1 ,high to n, test to 0
3. if low<= high repeat through steps 4 to 9 otherwise goto step 10

4. assign (low+high)/2 to mid


5. if m<k[mid] goto step 6 otherwise goto step 7
6. assign mid-1 to high goto step 3
7. if m>k[mid] goto step 8 otherwise goto step 9
8. assign mid+1 to low
9. return mid
10. return 0
11. Stop

Program:
/*write a c program for implementing binary search method using function */
#include<stdio.h>
#include<conio.h>
int BinarySearching(int arr[20], int max, int element)
{
int low = 0, high = max - 1, middle;
while(low <= high)
{
middle = (low + high) / 2;
if(element > arr[middle])
low = middle + 1;
else if(element < arr[middle])
high = middle - 1;
else
return middle;
}
return -1;
}

void main()
{
int i, element, limit, arr[50], position;
printf("Enter the Limit of Elements in Array:\t");
scanf("%d", &limit);
printf("Enter %d Elements in Array: \n", limit);
for(i = 0; i < limit; i++)
scanf("%d", &arr[i]);
34
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}

printf("\nthe array in sorted order:-\n");


for(i=0;i<n;i++)
printf("%d\n",a[i]);
printf("Enter Element to Search:\t");
scanf("%d", &element);
position = BinarySearching(arr, limit, element);
if(position == -1)
{
printf("Element %d Not Found\n", element);
}
else
{
printf("Element %d Found at Position %d\n", element, position + 1);
}
getch();
}
OUTPUT
Enter the Limit of Elements in Array:-5
Enter 5 Elements in Array:
6
9
8
7
4

35
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

The array in sorted order:-


4
6
7
8
9

Enter number to search:-6

Element 6 Found at Position 2

Week – 8 (A)
Write a C program that implements the Bubble sort method to sort a given list of
integers in ascending order.
Description:
 Bubble sort is the simplest and oldest sorting technique.
 This method takes two elements at a time. It compares these two elements. If first
elements are less than second one, they are left un-disturbed. If the first element is
greater than second one then they are swapped.
 The procedure continues with the next two elements goes and ends when all the
elements are sorted.
 But bubble sort is an inefficient algorithm.
 The order of bubble sort algorithm is O(n2).

Algorithm: Bubble Sort:

1. start
2. read the value of n
3. for i= 1 to n increment in steps of 1
Read the value of ith element into array
4. call function to sort (bubble_sort(a,n))
5. for i= 1 to n increment in steps of 1
print the value of ith element in the array
6. stop

BUBBLE SORT FUNCTION


1. start
2. initialise last to n
3. for i= 1 to n increment in steps of 1 begin
4. initialise ex to 0
5. for i= 1 to last-1 increment in steps of 1 begin
36
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

6. if k[i]>k[i+1] goto step 7 otherwise goto step 5 begin


7. assign k[i] to temp assign k[i+1] to k[i] assign temp to
k[i+1] increment ex by 1 end-if
8. end inner for loop
9. if ex!=0
assign last-1 to last
end for loop
10. Stop.

Program:

#include<stdio.h>
void main()
{
int i,j,t,a[5],n;
clrscr();
printf("\n Enter the range of array:");
scanf("%d",&n);

printf("\n Enter elements into array:");


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

for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
printf("\n The sorted order is:");
for(i=0;i<n;i++)
printf("\t%d",a[i]);
getch();
}

Input/Output:
Enter the range of array: 3
Enter elements into array: 3 2 1
the sorted order
is: 1 2 3

37
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

Week – 8 (B)
Write a C program that reads two matrices and uses functions to perform the
following:
(i). Addition of two matrices
(ii).Multiplication of two matrices

Description:
Program takes the two matrixes of same size and performs the addition an also
takes the two matrixes of different sizes and checks for possibility of
multiplication and perform multiplication if possible.
Algorithm:
Step 1: start
Step 2: read the size of matrices A,B – m,n
Step 3: read the elements of matrix A
Step 4: read the elements of matrix B

Step 5: select the choice for you want. If you select case 1 then goto matric
addition.Else goto Step 7.
Step 6: print Sum of matrix A and B
Step 7: if you select case 2 then goto matrix multiplication
Step 8: check if n=p, if not print matrices cannot be multiplied
Step 9: Otherwise perform the multiplication of matrices

Step 10: Print the resultant matrix


Step 11: Stop

Program:

#include<stdio.h>
void main()
{
int ch,i,j,m,n,p,q,k,r1,c1,a[10][10],b[10][10],c[10][10];
clrscr();
printf("************************************");
printf("\n\t\tMENU");
printf("\n**********************************");
printf("\n[1]ADDITION OF TWO MATRICES");
printf("\n[2]MULTIPLICATION OF TWO MATRICES");
printf("\n[0]EXIT");
printf("\n**********************************");
printf("\n\tEnter your choice:\n");

scanf("%d",&ch);

if(ch<=2 &ch>0)
{
38
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

printf("Valid Choice\n");
}

switch(ch)
{
case 1:
printf("Input rows and columns of A & B
Matrix:");
scanf("%d%d",&r1,&c1);
printf("Enter elements of matrix
A(r1*C1):\n"); for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
scanf("%d",&a[i][j]);
}
printf("Enter elements of matrix
B(r1*C1):\n"); for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
scanf("%d",&b[i][j]);
}
printf("\n =====Matrix Addition=====\n");
for(i=0;i<r1;i++)
{
For(j=0;j<c1;j++)
printf("%5d",a[i][j]+b[i][j]);

printf("\n");
}
break;

case 2:
printf("Input rows and columns of A matrix:");
scanf("%d%d",&m,&n);
printf("Input rows and columns of B matrix:");
scanf("%d%d",&p,&q);
if(n==p)
{
printf("matrices can be multiplied\n");
printf("resultant matrix is %d*%d\n",m,q);
printf("Input A matrix\n");
read_matrix(a,m,n);
printf("Input B matrix\n"); /*Function call to read
matrix*/
read_matrix(b,p,q);
/*Function for Multiplication of two matrices*/
printf("\n =====Matrix Multiplication=====\n");
for(i=0;i<m;++i)
for(j=0;j<q;++j)
{
39
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

c[i][j]=0;
for(k=0;k<n;++k)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}

printf("Resultant of two matrices:\n");


write_matrix(c,m,q);
}
/*end if*/ else
{
printf("Matrices cannot be multiplied.");
}
/*end else*/
break;

case 0:
printf("\n Choice Terminated"); exit();
break;

default:
printf("\n Invalid Choice");

}
getch();
}

/*Function read matrix*/


int read_matrix(int a[10][10],int m, int n)
{
int i,j;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
return 0;
}

/*Function to write the matrix*/


Int write_matrix(int a[10][10],int m, int n)
{
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%5d",a[i][j]);
printf("\n");
}
return 0;
}

40
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

Output:
1.
************************************
MENU
**********************************
[1]ADDITION OF TWO MATRICES [2]MULTIPLICATION
OF TWO MATRICES [0]EXIT
**********************************
Enter your choice:
1
Valid Choice
Input rows and columns of A & B Matrix:2 2
Enter elements of matrix A: 2 2 2 2
Enter elements of matrix B: 2 2 2 2

=====Matrix Addition=====
4 4
4 4
************************************
MENU
**********************************
[1]ADDITION OF TWO MATRICES [2]MULTIPLICATION
OF TWO MATRICES [0]EXIT
**********************************
Enter your choice:
2
Valid Choice
Input rows and columns of A matrix:2 3
Input rows and columns of B matrix:2 2
Matrices cannot be multiplied.
************************************
MENU
**********************************
[1]ADDITION OF TWO MATRICES [2]MULTIPLICATION
OF TWO MATRICES [0]EXIT
**********************************
Enter your choice:
2
Valid Choice
Input rows and columns of A matrix: 2 2
Input rows and columns of B matrix: 2 2
Matrices can be multiplied resultant matrix
is 2*2 Input A matrix 2 2 2 2
Input B matrix 2 2 2 2
=====Matrix Multiplication=====
Resultant of two matrices:
8 8
8 8

Record 2 results:
41
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

Week – 9 (A)
Write a C program that uses functions to perform the following operations:

i). to insert a sub-string into a given main string from a given position.
ii). to delete n characters from a given position in a given string.

i). to insert a sub-string into a given main string from a given position.

Description:
In this program we need to insert a string into another string from a specified
position.

Algorithm:
Step 1: start
Step 2: read main string and sub string Step 3:
find the length of main string(r) Step 4:
find length of sub string (n)
Step 5: copy main string into sub string
Step 6: read the position to insert the sub string (p)
Step 7: copy sub string into main string from position p-1
Step 8: copy temporary string into main string from position p+n-1 Step
Step9: print the strings
Step 10: stop
Program:
#include <stdio.h>
#include <conio.h>
#include <string.h>
void main()
{
char a[10];
char b[10];
char c[10];
int p=0,r=0,i=0;
int t=0;
int x,g,s,n,o;
clrscr();
puts("\n Enter First String:");
gets(a);
puts("\n Enter Second String:");
gets(b);
printf("\n Enter the position where the item has to be inserted: ");
42
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

scanf("%d",&p);
r = strlen(a);
n = strlen(b);
i=0;
//Copying the input string into another array
while(i <= r)
{
c[i]=a[i];
i++;
}
s = n+r;
o = p+n;
//Adding the sub-string
for(i=p;i<s;i++)
{
x = c[i]; if(t<n)
{
a[i] = b[t]; t=t+1;
}
a[o]=x;
o=o+1;
}
printf("%s", a);
getch();
}
Output:
1.enter first string: computer
enter second string: gec
enter the position where the item has to be inserted:3 comgecputer
Record 2 Results:

2. To delete n characters from a given position in a given string.

#include<stdio.h>
#include<conio.h>
#include <string.h>
void delchar(char *x,int a, int b);
void main()
{
char string[10];
int n,pos,p;
clrscr();
puts("\n Enter the string:");
gets(string);
printf("\n Enter the position from where to delete: ");
scanf("%d",&pos);
printf("\n Enter the number of characters to be deleted: ");
scanf("%d",&n);

43
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

delchar(string, n,pos);
getch();
}

// Function to delete n characters

void delchar(char *x,int a, int b)

{
if ((a+b-1) <= strlen(x))
{
strcpy(&x[b-1],&x[a+b-1]);
puts(x);
}
}

Output:

1.Enter the string:


nagaraju

Enter the position from where to delete: 4


Enter the number of charcters to be deleted: 3
Nagju

Week – 9(B)
Write a C program that uses a non recursive function to determine if the given string
is a palindrome or not.
Description:
 In this program we have to read the string and check for the given string is
palindrome or not.
 Palindrome means when the string is reverse also it should be the same as
given string.
Program:
#include<stdio.h>
#include<string.h>

// A function to check if a string str is palindrome

void isPalindrome(char str[20])


{
// Start from leftmost and rightmost corners of str
int l = 0;
int h = strlen(str) - 1;

// Keep comparing characters while they are same


while (h > l)
44
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

{
if (str[l++] != str[h--])
{
printf("\n %s is Not Palindrome\n", str);
return;
}
}
printf("\n %s is palindrome\n", str);
}

void main()
{
char string[40];
clrscr();
printf("\n ****Program to test if the given string is a
palindrome****\n"); printf("\n Enter a string:");
scanf("%s",string);
isPalindrome(string);
getch();
}

Output:
1. Enter the string: malayalam
malayalam is a palindrome

2. Enter the string:india


india is not a palindrome

Week – 10 (A)

Write a C program to replace a substring with another in a given line of text.

Program:
#include <stdio.h>
#include <string.h>
#include<conio.h>
void main()
{
char text[100],word[10],rpwrd[10],str[10][10];
int i=0,j=0,k=0,w,p;
clrscr();

printf("\n PLEASE WRITE ANY TEXT:\n");


printf("\n GIVE ONLY ONE SPACE AFTER EVERY WORD\n");
printf("\n WHEN COMPLETE PRESS Ctrl+Z : \n");
gets(text);

45
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

printf("\nENTER WHICH WORD IS TO BE REPLACED\n");


scanf("%s",word);
printf("\nENTER BY WHICH WORD THE %s IS TO BE REPLACED\n",word);
scanf("%s",rpwrd);
p=strlen(text);
for (k=0; k<p; k++)
{

if (text[k]!=' ')
{
str[i][j] = text[k];
j++;
}
else
{
str[i][j]='\0';
j=0; i++;
}
}
str[i][j]='\0';
w=i;
for (i=0; i<=w; i++)
{
if(strcmp(str[i],word)==0)
strcpy(str[i],rpwrd);

printf("%s ",str[i]);
}
getch();
}
Output:

PLEASE WRITE ANY TEXT:


GIVE ONLY ONE SPACE AFTER EVERY WORD
WHEN COMPLETE PRESS Ctrl+Z:

Raju IS A GOOD GIRL

ENTER WHICH WORD IS TO BE REPLACED: GIRIL


ENTER BY WHICH WORD THE BOY IS TO BE REPLACED

Raju IS A GOOD BOY

46
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

Week – 10 (B)
Write a C program that reads 15 names each of up to 30 characters, stores them in
an array, and uses an array of pointers to display them in ascending (i.e. alphabetical)
order
Description:
In this program we have to take 15 names, and print them in ascending order

Program:

#include <stdio.h>
#include <string.h>
void main()
{
char name[10][8], tname[10][8], temp[8];
int i, j, n;
clrscr();
printf("Enter the value of n \n");
scanf("%d", &n);
printf("Enter the names n”);
for (i = 0; i < n; i++)
{
scanf("%s", name[i]);
strcpy(tname[i], name[i]);
}
for (i = 0; i < n - 1 ; i++)
{
for (j = i + 1; j < n; j++)
{
if (strcmp(name[i], name[j]) > 0)
{
strcpy(temp, name[i]);
strcpy(name[i], name[j]);
strcpy(name[j], temp);
}
}
}
printf("\n----------------------------------------\n");
printf("Input NamestSorted names\n");
printf("------------------------------------------\n");
for (i = 0; i < n; i++)
{
printf("%s\t\t%s\n", tname[i], name[i]);
}
printf("------------------------------------------\n");
getch();
}
47
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

Output:

Enter the value of n


7
Enter 7 names
heap
stack
queue
object
class
program
project

----------------------------------------
Input Names Sorted names
------------------------------------------
heap class
stack heap
queue object
object program
class project
program queue
project stack
------------------------------------------

Week – 11(A)
2’s complement of a number is obtained by scanning it from right to left and
complementing all the bits after the first appearance of a 1. Thus 2’s complement of
11100 is 00100. Write a C program to find the 2’s complement of a binary number.
Description:
 In this program the given binary number is first covert the numbers 0 to1 and 1 to 0.
 And finally add the 1 to the converted number. Then we will get the 2’s complement
number.
Algorithm:
Step 1: Start
Step 2: declare the subprogram “complement(char *a)” Step 3:
initialize the variable i
Step 4: read the binary number
Step 5: perform the loop operation. if it is true then follows. if not goto step 7
i) for(i=0;a[i]!=’\0’;i++)
ii) if(a[i]!=’0’&&a[i]!=’1’) then displayed the number is not valid. enter the
correct number.
iii) Exit the loop
Step 6: call sub program ‘complemt(a)’ . Step 7: stop
Sub program:
48
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

Step 1: initialize the variable I,c=0,b[160 Step 2:


1=strlen(a)
Step 3: perform the loop operation. if it is true then follows. if not goto
i)for(i=l-1;i>=0;i--)
ii)if(a[i]==’0’) then b[i]=’1’ else iii)b[i]=’0’
Step 4: for(i=l-1;i>=0;i--) is true
i) if(i==l-1) then
ii) if(b[i]==’0’) then b[i]=’1’ else
iii) b[i]=’0’,c=1 if not goto step 5

Step 5: if(c==1&&b[i]==’0’) is true then


i) b[i]=’1’, c=0 if not goto Step 6
Step 6: if(c==1&&b[i]==’1’) then b[i]=’0’,c=1
Step 7: displayed b[l]=’\0’
Step 8: print b and return to main program
Program:
#include <stdio.h>
#include<conio.h>
void complement (char *a);
void main()
{
char a[16];
int i;
clrscr();
printf("Enter the binary number");
gets(a);
for(i=0;a[i]!='\0'; i++)
{
if (a[i]!='0' && a[i]!='1')
{
printf("The number entered is not a binary number. Enter the
correct number");
exit(0);
}
}
complement(a);
getch();
}
void complement (char *a)
{
int l, i, c=0;
char b[16];
l=strlen(a);
for (i=l-1; i>=0; i--)
{
if (a[i]=='0')
b[i]='1';
else
b[i]='0';

49
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

}
for(i=l-1; i>=0; i--)
{
if(i==l-1)
{
if (b[i]=='0')
b[i]='1';
else
{
b[i]='0';
c=1;
}
}
else
{
if(c==1 && b[i]=='0')
{
b[i]='1';
c=0;
}
else if (c==1 && b[i]=='1')
{
b[i]='0';
c=1;
}}}
b[l]='\0';
printf("The 2's complement is %s", b);
}
Output:
1. Enter the binary number101010
The 2's complement is 010110

Week – 11 (B)
Write a C program to convert a positive integer to a roman numeral. Ex. 11 is
converted to XI.
Description:
In this program we have convert the given decimal number to roman
number.

Program:
#include<stdio.h>
#include<conio.h>
#include<process.h>

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


{

50
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

FILE *fs,*ft;
char ch;
clrscr();
if(argc!=3)
{
puts("Invalid number of arguments.");
exit(0);
}
fs = fopen(argv[1],"r");
if(fs==NULL)
{
puts("Source file cannot be opened.");
exit(0);
}
ft = fopen(argv[2],"w");
if (ft==NULL) // check the condition if the file pointer is NULL or not
{
puts("Target file cannot be opened.");
fclose(fs);
exit(0);
}

while(1)
{
ch=fgetc(fs);
if (ch==EOF) // check the condition if the file is end or not
break;
else
fputc(ch,ft);
}
fclose(fs);
fclose(ft);
getch();
}

Output:
source.c
this is source text ouput.c
Command line arguments
source.c ouput.c source.c
this is source text ouput.c
this is source text
Command line arguments
source.c
Invalid number of arguments.

51
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

Week – 12 (A)
A. Write a C program to display the contents of a file to standard output device.

procedure:
1. Declare a file pointer fp in read mode
2. Read the characters of file
3. Write to characters to stdout.
This program takes the number from user and stores in file. After you compile
and run this program, you can see a text file program.txt created in C drive of
your computer. When you open that file, you can see the integer you entered.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp=fopen(“one.txt”, “w”);
printf(“\n Enter Data press Ctrl+Z:\n”);
while( ( ch=getchar() )!=EOF)
{
Putc(ch,fp);
}

fclose(fp);
fp=fopen(“one.txt”, “r”);
printf(“\n The output data is:\n”);
while( ( ch=getc() ) ! = EOF)
printf(“%c”, ch);
fclose(fp);
getch();
}

OUTPUT:
Enter Data press Ctrl+Z:
This is cp class^z
The output data is:
This is cp class

12-B) Write a C program which copies one file to another, replacing all lowercase
characters with their uppercase equivalents.

#include<stdio.h>
#include<process.h>

void main()
{
FILE *fp1, *fp2;

52
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

char a;
clrscr();
fp1=fopen(“test.txt”, “w”);
printf(“\n Enter Data press Ctrl+Z:\n”);
while( ( ch=getchar() )!=EOF)
{
Putc(ch,fp1);
}
fclose(fp1);

fp1 = fopen("test.txt", "r");


if (fp1 == NULL) {
puts("cannot open this file");
exit(1);
}

fp2 = fopen("test1.txt", "w");


if (fp2 == NULL) {
puts("Not able to open this file");
fclose(fp1);
exit(1);
}

printf(“\n The text in UPPER CASE:\n”);


do {
a = fgetc(fp1);
a = toupper(a);
fputc(a, fp2);
} while (a != EOF);

fcloseall();
getch();
}
OUTPUT:
Enter Data press Ctrl+Z:
This is cp class^z
The text in UPPER CASE:
THIS IS CP CLASS

13-A) Write a C program to count the number of times a character occurs in a text
file. The file name and the character are supplied as command-line arguments.

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

FILE *fp;
char ch,temp;
int freq = 0;
53
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

clrscr();
fp=fopen(“file.txt”, “w”);
printf(“\n Enter Data press Ctrl+Z:\n”);
while( ( ch=getchar() )!=EOF)
{
Putc(ch,fp);
}
fclose(fp);

printf("\n Enter the character to be counted:\n ");


scanf("%c", &ch);

fp = fopen(“file.txt”, "r");

while(!feof(fp))
{
tmp = fgetc(fp);
if (tmp == ch)
freq++;
}

printf("\n The File has %d instances of letter '%c'.", freq, ch);


getch();
}

OUTPUT:
Enter Data press Ctrl+Z:
This is cp class ^z
Enter the character to be counted: s
The File has 4 instances of letter s.

13-B). Write a C program to compare two files, printing the first line where they
differ.

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

if (argc < 3)
{
printf("\nInsufficient Arguments: \n");
printf("\nHelp:./executable <filename1> <filename2>\n");
return;
}
54
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

else
{
fp1 = fopen(argv[1], "r");
if (fp1 == NULL)
{
printf("\nError in opening file %s", argv[1]);
return;
}

fp2 = fopen(argv[2], "r");

if (fp2 == NULL)
{
printf("\nError in opening file %s", argv[2]);
return;
}

if ((fp1 != NULL) && (fp2 != NULL))


{
compare_two_binary_files(fp1, fp2);
}
}
}

/*
* compare two binary files character by character
*/
void compare_two_binary_files(FILE *fp1, FILE *fp2)
{
char ch1, ch2;
int flag = 0;

while (((ch1 = fgetc(fp1)) != EOF) &&((ch2 = fgetc(fp2)) != EOF))


{
/*
* character by character comparision
* if equal then continue by comparing till the end of files
*/
if (ch1 == ch2)
{
flag = 1;
continue;
}
/*
* If not equal then returns the byte position
*/
else
{
fseek(fp1, -1, SEEK_CUR);
flag = 0;
55
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

break;
}
}

if (flag == 0)
{
printf("\n Two files are not equal : byte poistion at which two files differ is
%d\n", ftell(fp1)+1);
}
else
{
printf("\n Two files are Equal\n ", ftell(fp1)+1);
}
}

OUTPUT:
welcome to shadan
welcome to jntuh

14- A) Write a C program to change the nth character (byte) in a text file. Use fseek
function

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
FILE *fp;
char ch;
int n;
fp = fopen("random.txt","r+");
printf("Enter n value\n");
scanf("%d",&n);
printf("Enter charcter value\n");
scanf(" %c",&ch);
fseek(fp,n-1,0);
fputc(ch,fp);
fclose(fp);
}
Before excution
Random.txt
abcdefghijklmnopqrstuvwxyz

OUTPUT:
Enter the n value
4
Enter the character
a
after execution
abca abcdefghijklmnopqrstuvwxyz
56
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

14-B) Write a C program to reverse the first n characters in a file. The file name and n
are specified on the command line. Use fseek function.

Algorithm:
Step 1: Start
Step 2: read the command line arguments
Step 3: check if arguments = 3 or not If not print invalid no of arguments
Step 4: open source file in read mode
Step 5: if NULL pointer, then print file can not be open
Step 6: Store no of chars to reverse in k.K = *argv[2] - 48
Step 7: read the item from file stream using fread
Step 8: Store chars from last position to initial position in another string(temp)
Step 9: print the temp string
Step 10: Stop

Program:
#include<stdio.h >
#include<conio.h >
#include<string.h >
#include<process.h >
void main(int argc, char *argv[])
{
FILE *fs, *fd;
char s[20], d[20];
int c = 0, count = 0, n;
clrscr();
strcpy(s, argv[1]);
n = atoi(argv[2]);
fs = fopen(s, "r");
if(s == NULL)
printf("\n FILE ERROR");
printf("\n SOURCE FILE :\n");
while(!feof(fs))
{
printf("%c", fgetc(fs));
c++;
}
fclose(fs);
fs = fopen(s, "r+");
count = 0;
while(count < n)
{
d[count] = fgetc(fs);
count++;
}
57
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

d[count] = '\0';
fseek(fs, 0L, 0);
fputs(strrev(d), fs);
fclose(fs);
fs = fopen(s,"r");
while(!feof(fs))
{
printf(“\n REVERSE FILE: %c”, fgetc(fs));
c++;
}
fclose(fs);
getch();
}

OUTPUT

SOURCE FILE: cplab

REVERSE FILE:balpc

15-A) Write a C program to merge two files into a third file (i.e., the contents of the
firs t file followed by those of the second are put in the third file).

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

FILE *fs1, *fs2, *ft;


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

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

if( fs1 == NULL || fs2 == NULL )


{
perror("Error ");
58
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

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);
getch();
}

OUTPUT:

15- B) Define a macro that finds the maximum of two numbers. Write a C program
that uses the macro and prints the maximum of two numbers.
59
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C

#include<stdio.h>

#define MIN(X,Y)(X<Y ? X:Y)


#define MAX(X,Y)(X>Y ? X:Y)

void main()
{
int a,b;
clrscr();
printf("\n ENTER NUMBERS TO FIND MAXIMUM:\n");
printf("\nENTER FIRST NUMBER : ");
scanf("%d", &a);
printf("\nENTER SECOND NUMBER : ");
scanf("%d", &b);
printf("\nTHE MAXIMUN NUMBER IS: %d", MAX(a,b));
printf("\nThe MININUM NUMBER IS:%d", MIN(a,b));
getch();
}

OUTPUT:

ENTER NUMBERS TO FIND MAXIMUM


ENTER FIRST NUMBER: 155
ENTER SECOND NUMBER: 15
THE MAXIMUN NUMBER IS: 155
The MININUM NUMBER IS: 15

60

You might also like