Sunteți pe pagina 1din 85

JNTUK C Programming Lab Manual

COMPUTER PROGRAMMING LAB

Learning Objectives:
• Understand the basic concept of C Programming, and its different modules
that includesconditional and looping expressions, Arrays, Strings, Functions,
Pointers, Structures and File programming.
• Acquire knowledge about the basic concept of writing aprogram.
• Role of constants, variables, identifiers, operators, type conversion and other
building blocks of CLanguage.
• Use of conditional expressions and looping statements to solve problems
associated withconditionsandrepetitions.
• Role of Functions involving the idea ofmodularity.

Programming:

Exercise – 1: Basics
a) What is an OS Command, Familiarization of Editors - vi,Emacs
b) Using commands like mkdir, ls, cp, mv, cat, pwd, andman
c) C Program to Perform Adding, Subtraction, Multiplication and Division of two
numbers From Command line

Exercise – 2: Basic Math


a) Write a C Program to Simulate 3 Laws of Motion
b) Write a C Program to convert Celsius to Fahrenheit and viceversa

Exercise – 3: Control Flow - I


a)Write a C Program to Find Whether the Given Year is a Leap Year or not.
b)Write a C Program to Add Digits & Multiplication of a number

Exercise – 4: Control Flow - II


a) Write a C Program to Find Whether the Given Numberis
i) PrimeNumber
ii) ArmstrongNumber
b) Write a C program to print FloydTriangle
c) Write a C Program to print PascalTriangle

Exercise – 5: Functions
a) Write a C Program demonstrating of parameter passing in Functions and
returningvalues.
b) Write a C Program illustrating Fibonacci, Factorial with Recursion withoutRecursion

1
JNTUK C Programming Lab Manual

Exercise – 6: Control Flow - III


a) Write a C Program to make a simple Calculator toAdd, Subtract, Multiply or
Divide Using switch…case
b) Write a C Program to convert decimal to binary and hex (using switch call
function the function)

Exercise – 7: Functions – Continued..


a) Write a C Program to compute the values ofsin x and cos x and e^x values using
Series expansion. (use factorial function)

Exercise – 8: Arrays
Demonstration of arrays
a) Search-Linear.
b) Sorting-Bubble,Selection.
c) Operations onMatrix.

Exercises – 9: Structures
a) Write a C Program to Store Information of a Movie UsingStructure
b)Write a C Program to Store Information Using Structures with Dynamically
Memory Allocation
c) Write a C Program to Add Two Complex Numbers by Passing Structure to aFunction

Exercise – 10: Arrays and Pointers


a) Write a C Program to Access Elements of an Array UsingPointer
b) Write a C Program to find the sum of numbers with arrays andpointers.

Exercise – 11: Dynamic Memory Allocations


a) Write a C program to find sum of n elements entered by user. To perform this
program, allocate memory dynamically using malloc()function.

b) Write a C program to find sum of n elements entered by user. To perform


this program, allocate memory dynamically using calloc()function.

Understand the difference between the above two programs

Exercise – 12: Strings


a) Implementation of string manipulation operations with libraryfunction.
i) copy
ii) concatenate
iii) length
iv) compare

2
JNTUK C Programming Lab Manual

b) Implementation of string manipulation operations without libraryfunction.

i) copy
ii) concatenate
iii) length
iv) compare

Exercise -13: Files


a)Write a C programming code to open a file and to print its contents on screen.
b)Write a C program to copy files

Exercise – 14: Files Continued


a) Write a C program merges two files and stores their contents in another file.
b) b)Write a C program to delete afile.

Outcomes:

 Apply and practice logical ability to solve theproblems.


 Understand C programming development environment, compiling,
debugging, and linkingand executing a program using the
developmentenvironment
 Analyzing the complexity of problems, Modularize the problems into small
modules andthen convert them intoprograms
 Understand and apply the in-built functions and customized functions for
solving theproblems.
 Understand and apply the pointers, memory allocation techniques and use of
files fordealing with variety ofproblems.
 Document and present the algorithms, flowcharts and programs in form ofuser-
manuals
 Identification of various computer components, Installation ofsoftware

Note:

a) All the Programs must be executed in the Linux Environment.(Mandatory)


b) The Lab record must be a print of the LATEX(.tex)Format.

3
JNTUK C Programming Lab Manual

EXERCISE 1 - Basics

1.a. What is OS Command, familiarization of Editors- vi, Emacs.


OS Command:
In computers, a command is a specific order from a user to the computer's operating system
or to an application to perform a service, such as "Show me all my files" or "Run this
program for me." Operating systems such as DOS that do not have a graphical user
interface(GUI) offer a simple command line interface in which you type the command on a
designated line in a display panel. In a system such as Windows, a graphical user
interface lets you implicitly enter commands by selecting objects or word selections
and clicking your mouse button on them. (Windows does offer a command line
interface for certain facilities if you select the "MS-DOS Prompt" under "Programs.")
SYNTAX :
OS-COMMAND
[ SILENT | NO-WAIT | NO-CONSOLE ]
[ command-token | VALUE ( expression ) ]...

SILENT
After processing an operating system command, the AVM shell pauses. To exit the window
in Windows GUI platforms, you must type exit. To exit the window in Windows character
platforms, you must type exit and press RETURN or SPACEBAR. You can use the
SILENT option to eliminate this pause. Use this option only if you are sure that the program,
command, or batch file does not generate any output to the screen. Cannot be used with NO-
WAIT.

NO-WAIT
In a multi-tasking environment, causes the AVM to immediately pass control back to next
statement after the OS-COMMAND without waiting for the operating system command to
terminate. Cannot be used with SILENT. This option is supported in Windows only.

NO-CONSOLE
While processing an operating system command, the AVM creates a console window. The
console window may not be cleaned up after the command is executed. You can use the NO-
CONSOLE option to prevent this window from being created in the first place.

command-token|VALUE( expression)
One or more command words and symbols that you want to pass the operating system to
execute. The VALUE option generates the command tokens included in expression, a
character string expression. The specified combination of command-token and
VALUE(expression) options can form any legal combination of commands and command
options permitted by the operating system. These can contain Unicode characters.

4
JNTUK C Programming Lab Manual

Example
There are two principal uses for the OS-COMMAND statement: to execute a utility that has
the same syntax on two or more different operating systems, and to execute an operating
system statement input by a user.
In both instances, the OS-COMMAND statement eliminates the need to use the OPSYS
statement to determine the operating system and then use conditional logic to execute the
appropriate code. The OS-COMMAND statement, therefore, makes an application more
portable.
This procedure prompts the user for an operating system command and then uses the OS-
COMMAND statement to execute the command:

r-os-com.p
DEFINE VARIABLE comm-line AS CHARACTER NO-UNDO FORMAT "x(70)".
REPEAT:
UPDATE comm-line.
OS-COMMAND VALUE(comm-line).
END.

Familiarization of Editors :- vi,Emacs.


Vi editor:
The vi editor (short for visual editor) is a screen editor which is available on almost all Unix
systems. Once you have learned vi, you will find that it is a fast and powerful editor. vi has
no menus but instead uses combinations of keystrokes in order to accomplish commands.

Emacs editor:
GNU Emacs is a free, portable, extensible text editor. That it is free means
specifically that the source code is freely copyable and redistributable. That it is
portable means that it runs on many machines under many different operating systems, so
that you can probably count on being able to use the same editor no matter what machine
you're using. That it is extensible means that you can not only customize all aspects of its
usage (from key bindings through fonts, colors, windows, mousage and menus), but you can
program Emacs to do entirely new things that its designers never thought of.

5
JNTUK C Programming Lab Manual

1.b. Using commands like mkdir, ls, cp, mv, cat, pwd, andman.

LINUX DOS Description


Command Command
mkdir md Make Directory. Example: mkdir /tmp/myfiles/
List all files in the current directory, in column
ls dir /w format.
List the files in the specified directory. Example:
ls directory dir directory ls /var/log
List files in “long” format, one file per line. This
ls–l dir also shows you additional info about the file, such
as ownership, permissions, date, and size.
List all files, including “hidden” files. Hidden
ls -a dir /a files are those files that begin with a “.”, e.g. The
.bash_history file in your home directory.
A “long” list of “directory”, but instead of
showing the directory contents, show the
ls -ld directory directory's detailed information. For example,
compare the output of the following two
commands: ls -l /usr/bin ls -ld /usr/bin
List all files whose names begin with the letter
ls /usr/bin/d* dir d*.*
“d” in the /usr/bin directory.
Copies a file from one location to another.
Cp copy Example: cp mp3files.txt /tmp (copies the
mp3files.txt file to the /tmp directory)
rename, ren, Moves a file to a new location, or renames it.
mv Forexample: mv mp3files.txt /tmp (copy the
move
Display the contents of a text file on the screen.
cat type For example: cat mp3files.txt would display the
file we created in the previous section.
“Print Working Directory”. Shows the current
pwd cd
location in the directory tree
Help of all commands of current os. Ex: man ls
man help
Describe about ls command.

6
JNTUK C Programming Lab Manual

1.c. Write a C Program to Perform Adding, Subtraction, Multiplication


and Division of two numbers.

Problem Statement : To write a C Program to Perform Adding, Subtraction, Multiplication


and Division of two numbers.

Algorithm :
Step-1 : Start
Step-2 : Input first number say a
Step-3 : Input second number say b
Step-4 : Sum = a + b
Difference = a – b
Multiplication = a * b
Division = a / b
Step-5 : Display Sum
Display Difference
Display Multiplication
Display Division
Step-6 : Stop

Program Code :
#include <stdio.h>
#include <conio.h>
int main()
{
/* Variable declation */
int a, b;
int sum, difference, multiply;
float divide;
clrscr();

/* Taking input from user and storing it in firstNumber and secondNumber */


printf("Enter a, b Values : ");
scanf("%d%d", &a, &b);

/* Adding two numbers */


sum = a+b;
/* Subtracting two numbers */
difference = a-b;
/* Multiplying two numbers*/
multiply = a*b;
/* Dividing two numbers by typecasting one operand to float*/
divide = (float)a/b;

7
JNTUK C Programming Lab Manual

printf("Sum = %d", sum);


printf("\nDifference = %d", difference);
printf("\nMultiplication = %d", multiply);
printf("\nDivision = %.3f", divide);
getch();
return 0;
}

Expected Output :
Enter a, b Values : 24 15
Sum = 39
Difference = 9
Multiply = 360
Division = 1.600

Actual Output :
Enter a, b Values : 2 4
Sum = 6
Difference = -2
Multiply = 8
Division = 0.500

8
JNTUK C Programming Lab Manual

EXERCISE 2 – Basic Math


2.a. Write a C Program to Simulate 3 Laws of Motion

Problem Statement : To write a C Program to Simulate 3 Laws of Motion.

Algorithm :
Step-1 : Start
Step-2 : Read values of m, a
Step-3 : Enter Mass and Acceleration Values
Step-4 : Calculate the force f value by multiplying mass m and acceleration a
Step-5 : Display Result
Step-6 : Stop

Program Code :
#include<stdio.h>
void main()
{
intf,m,a;
clrscr();
printf("Enter mass and acceleration : ");
scanf("%d %d",&m,&a);
f=m*a;
printf("\nF = %d",f);
}

Expected Output :
Enter mass and acceleration :43 2
F = 86

Actual Output :
Enter mass and acceleration : 24 21
F = 504

9
JNTUK C Programming Lab Manual

2.b. Write a C Program to convert Celsius to Fahrenheit and vice versa.

Problem Statement : To write a C Program to convert Celsius to Fahrenheit and vice versa.

Algorithm :
Step-1 : Start
Step-2 :Read the values c, f
Step-3 :Enter the temperature in Celsius
Step-4 :Calculate Fahrenheit value f=1.8*c+32
Step-5 :Display Fahrenheit value
Step-6 :Enter the temperature in Fahrenheit
Step-7 :Calculate Celsius value c=(f-32)/1.8
Step-8 : Display Celsius value

Program Code :
#include <stdio.h>
#include <conio.h>
main()
{
float c,f;
clrscr();
printf(“Enter the temperature in Celsius : ”);
scanf(“%f”,&c);
f=1.8*c+32;
printf(“Fahrenheit = %f”,f);
printf(“Enter the temperature in Fahrenheit : ”);
scanf(“%f”,&f);
c=(f-32)/1.8;
printf(“Celsius = %f”,c);
getch();
return 0;
}

Expected Output :
Enter the temperature in Celsius : 35
Fahrenheit = 95.000000
Enter the temperature in Fahrenheit : 76
Celsius = 24.444444

Actual Output :
Enter the temperature in Celsius :25
Fahrenheit = 77.000000
Enter the temperature in Fahrenheit : 23
Celsius = -5

10
JNTUK C Programming Lab Manual

EXERCISE 3 – Control Flow I


3.a. Write a C Program to Find Whether the Given Year is a Leap Year or
not.

Problem Statement :To write a C Program to convert Find Whether the Given Year is a
Leap Year or not.

Algorithm :
Step-1 : Start
Step-2 : Take a year as input.
Step-3 : Check whether a given year is divisible by 400.
Step-4 : Check whether a given year is divisible by 100.
Step-5 : Check whether a given year is divisible by 4.
Step-6 : If the condition at step 3 and 5 becomes true, then the year is a leap year.
Step-7 : If the condition at step 4 becomes true, then the year is not a leap year.
Step 8 : Stop

Program Code :
#include<stdio.h>
void main()
{
int year;
clrscr();
printf("Enter year : ");
scanf("%d", &year);
// year is divisible by 400, hence the year is a leap year
if ((year % 400) == 0)
printf("%d is a leap year", year);
else if ((year % 100) == 0)
printf("%d is a not leap year", year);
else if ((year % 4) == 0)
printf("%d is a leap year", year);
else
printf("%d is not a leap year", year);
}

Expected Output :
Enter year : 1990
1990 is not a leap year

Actual Output :
Enter year : 2020
2020 is a leap year

11
JNTUK C Programming Lab Manual

3.b. Write a C Program to Add Digits & Multiplication of a number.

Problem Statement :To write a C Program to Add Digits & Multiplication of a number.

Algorithm :
Step-1 : Start
Step-2 : Take the integers as input.
Step-3 : Initialize the variable sum to zero and mul to 1.
Step-4 : Divide the input integer by 10 and obtain its remainder.
Step-5 : Store the remainder in the variable digit.
Step-6 : Increment the variable sum with variable digit.
Step-7 : Multiply the variable mul with variable digit.
Step-8 : Display Sum of digits.
Step-9 : Display Multiplication of digits.
Step-10 : Stop.

Program Code :
#include<stdio.h>
int main()
{
int sum=0,mul=1,n,r;
printf("Enter number : ");
scanf("%d",&n);
while(n!=0)
{
r=n%10;
sum=sum+r;
mul=mul*r;
n=n/10;
}
printf("Sum of digits = %d",sum);
printf("Multiplication of digits = %d",mul);
}

Expected Output :
Enter number : 78
Sum of digits = 15
Multiplication of digits =56

Actual Output :
Enter number : 66
Sum of digits = 12
Multiplication of digits =36

12
JNTUK C Programming Lab Manual

EXERCISE 4 – Control Flow II


4.a.(i) Write a C Program to Find Whether the Given Number is Prime
number.

Problem Statement :To write a C Program to Find Whether the Given Number is Prime
number.

Algorithm :
Step-1 : Start
Step-2 : Initiate the variables and flag to 1.
Step-3 : Enter a positive integer.
Step-4 : Read the value of n.
Step-5 : Using for loop, check if the input number is divisible by any of the natural numbers
starting from 2.
Step-6 : If it is, then it is not a prime number. Otherwise it is a prime number.
Step-7 : Stop.

Program Code :
#include<stdio.h>
#include<conio.h>
int main()
{
intn,i,flag=0;
clrscr();
printf(“Enter a positive integer : “);
scanf(“%d”,&n);

for(i=2;i<=n/2;++i)
{
if(n%i==0)
{
flag=1;
break;
}
}

if(n==1)
{
printf(“1 is neither prime nor composite“);
}

else
{
if(flag==0)
printf(“%d is a prime number”,n);
else

13
JNTUK C Programming Lab Manual

printf(“%d is not a prime number”,n);


getch();
}
return 0;
}

Expected Output :
Enter a positive integer : 7
7 is a prime number

Actual Output :
Enter a positive integer : 10
10 is not a prime number

Enter a positive integer : 1


1 is neither prime nor composite

14
JNTUK C Programming Lab Manual

4.a.(ii) Write a C Program to Find Whether the Given Number is


Armstrong number.

Problem Statement :To write a C Program to Find Whether the Given Number is Armstrong
number.

Algorithm :
Step-1 : Start
Step-2 : Declare and initialize the variables.
Step-3 : Enter the value in which the Armstrong numbers are to be displayed.
Step-4 : Read the value
Step-5 :Repeat until num!=0
Step-6 : num=num/10
Step-7 : num=num+cube of last digit i.e., rem
Step-8 : If temp==arm
Step-8 : Print “Armstrong Number”
Step-9 : else Print “Not Armstrong Number”
Step-10 : Stop

Program Code :
#include<stdio.h>
main()
{
int num, arm=0, rem, temp;
clrscr();
printf("Enter a value : ");
scanf("%d", &num);
temp=num;

while(num!=0)
{
rem=num%10;
num=num/10;
arm=arm+(rem*rem*rem);
}

if(temp==arm)
printf("%d is armstrong",temp);
else
printf("%d is not armstrong",temp);
}

15
JNTUK C Programming Lab Manual

Expected Output :
Enter a value : 123
123 is not armstrong

Actual Output :
Enter a value : 153
153 is Armstrong

16
JNTUK C Programming Lab Manual

4.b. Write a C Program to print Floyd Triangle.

Problem Statement :To write a C Program to print Floyd Triangle.

Algorithm :
Step-1 : Start
Step-2 : Declare and initialize required variables for controlling loop, inputting number of
rows and printing numbers.
Step-3 : Enter the number of rows of Floyd's triangle to print.
Step-4 : Read n value.
Step-5 : Make outer iteration i for n times to print rows
Step-6 : Make inner iteration j to i
Step-7 : Print k value
Step-8 : Increment k value
Step-9 : Print NEWLINE character after each iteration
Step-10 : Stop

Program Code :
#include <stdio.h>
int main()
{
int n, i, j, k = 1;
clrscr();
printf("Enter the number of rows of Floyd's triangle to print : ");
scanf("%d", &n);
for (i = 1; i<= n; i++)
{
for (j = 1; j<= i; j++)
{
printf("%d\t",k);
k++;
}
printf("\n");
}
return 0;
}

Expected Output :
Enter the number of rows of Floyd's triangle to print : 4
1
2 3
4 5 6
7 8 9 10

17
JNTUK C Programming Lab Manual

Actual Output :
Enter the number of rows of Floyd's triangle to print : 6
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21

18
JNTUK C Programming Lab Manual

4.c. Write a C Program to print Pascal Triangle.

Problem Statement :To write a C Program to print Pascal Triangle.

Algorithm :
Step-1 : Start
Step-2 : Initialize the variables
Step-3 : Enter the number of rows you wish to see in Pascal triangle
Step-4 : Read the value of n
Step-5 : Using a for loop iterate i value and c value
Step-6 : Print the value using factorial(i)/(factorial(c)*factorial(i-c)))
Step-7 : Print NEWLINE character after each iteration
Step-8 : Return
Step-9 : Print NEWLINE character after each iteration
Step-10 : The other for loop is used to print the Pascal’s triangle according to the format.
Step-11 : Return Result
Step-12 : Stop

Program Code :
#include <stdio.h>
long factorial(int);
int main()
{
int i, n, c;
clrscr();
printf("Enter the number of rows you wish to see in pascal triangle : ");
scanf("%d",&n);
for (i = 0; i< n; i++)
{
for (c = 0; c <= (n - i - 2); c++)
printf(" ");
for (c = 0 ; c <= i; c++)
printf("%ld ",factorial(i)/(factorial(c)*factorial(i-c)));
printf("\n");
}
return 0;
}

long factorial(int n)
{
int c;
long result = 1;
for (c = 1; c <= n; c++)
result = result*c;

19
JNTUK C Programming Lab Manual

return result;
}

Expected Output :
Enter the number of rows you wish to see in pascal triangle : 4
1
1 1
1 2 1
1 3 3 1

Actual Output :
Enter the number of rows you wish to see in pascal triangle : 6
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

20
JNTUK C Programming Lab Manual

EXERCISE 5 – Functions
5.a. Write a C Program demonstrating of parameter passing in Functions
and returning values.
Problem Statement :To write a C Program to demonstrate parameter passing in Functions
and returning values.

Algorithm :
Step-1 : Start
Step-2 : Declare variables
Step-3 : Enter the radius of circle
Step-4 : Read the radius of circle value
Step-5 : Calculate Area of circle using the formula area=3.14*radius*radius
Step-6 : Display Area of circle
Step-7 : Return result value
Step-7 : Stop

Program Code :
/*
1. We can see that inside main function we are calling a user defined calculate_area()
function.
2. We are passing integer argument to the function which after area calculation returns
floating point area value.
*/
#include<stdio.h>
float calculate_area(int);
int main()
{
int radius;
float area;
clrscr();
printf("Enter the radius of circle : ");
scanf("%d",&radius);
area=calculate_area(radius);
printf("Area of circle = %f",area);
return 0;
}

float calculate_area(int r)
{
float result;
result=3.14*r*r;
return(result);
}

21
JNTUK C Programming Lab Manual

Expected Output :
Enter the radius of circle : 5
Area of circle = 78.500000

Actual Output :
Enter the radius of circle : 10
Area of circle = 314.000000

22
JNTUK C Programming Lab Manual

5.b. Write a C Program illustrating Fibonacci, Factorial with Recursion


without Recursion.

5.b.(i).a. Write a C Program illustrating Fibonacci with Recursion.


Problem Statement :To write a C Program to illustrate Fibonacci with Recursion.

Algorithm :
Step-1 : Start
Step-2 : Declare the variables
Step-3 : Enter the value of n
Step-4 : Read the value of n
Step-5 : Enter Fibonacci series with recursion
Step-6 : Increment the value with i
Step-7 : if n=0 return 0
Step-8 : if n=1 return 1
Step-9 : if n=0 return 0
Step-10 : else return Fibonacci(n-1) + Fibonacci(n-2)
Step-11: Display Fibonacci series with recursion
Step-12 : Stop

Program Code :
#include<stdio.h>
int Fibonacci(int);
int main()
{
int n, i = 0, c;
clrscr();
printf("Enter n value : ");
scanf("%d",&n);
printf("Fibonacci series with recursion : \n");
for ( c = 1 ; c <= n ; c++ )
{
printf("%d\n", Fibonacci(i));
i++;
}
return 0;
}

int Fibonacci(int n)
{
if ( n == 0 )
return 0;

23
JNTUK C Programming Lab Manual

else if ( n == 1 )
return 1;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}

Expected Output :
Enter n value : 3
0
1
1

Actual Output :
Enter n value : 5
0
1
1
2
3

24
JNTUK C Programming Lab Manual

5.b.(i).b.Write a C Program illustrating Fibonacci without Recursion.

Problem Statement :To write a C Program to illustrate Fibonacci without Recursion.

Algorithm :
Step-1 : Start
Step-2 : Declare variables
Step-3 : Enter n value
Step-4 : Read the value of n
Step-5 : Repeat steps 6,7,8 until i<n
Step-6 : c=a+b
Step-7 : a=b
Step-8 : b=c
Step-9 : Display Fibonacci series
Step-10 : Stop

Program Code :
#include<stdio.h>
int main()
{
int n, a=0,b=1,c,i;
clrscr();
printf("Enter n value : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("%d\t",a);
c=a+b;
a=b;
b=c;
}
getch();
}

Expected Output :
Enter n value : 6
0 1 1 2 3 5

Actual Output :
Enter n value : 4
0 1 1 2

25
JNTUK C Programming Lab Manual

5.b.(ii).a. Write a C Program illustrating Factorial with Recursion.

Problem Statement :To write a C Program to illustrate Factorial with Recursion.

Algorithm :
Step-1 : Start
Step-2 : Declare the function factorial with return type int with one integer argument.
Step-3 : Initialize variables
Step-4 : Read the value of n in main( ) function
Step-5 : Call the function factorial(n) from the main( )
Step-6 : If n=1 then return 1
Step-7 : Otherwise, call the function factorial recursively by n*factorial (n-1)
Step-8 : Return the result of the factorial(n) to the main procedure and display the result
Step-9 : Stop

Program Code :
#include<stdio.h>
int fact(int n);
main()
{
int n,k;
clrscr();
printf("Enter n value : ");
scanf("%d",&n);
k=fact(n);
printf("Factorial = %d",k);
}

int fact(int n)
{
if(n==1)
return 1;
else
return (n*fact(n-1));
}

Expected Output :
Enter n value : 7
Factorial value = 5040

Actual Output :
Enter n value : 4
Factorial value = 24

26
JNTUK C Programming Lab Manual

5.b.(ii).b. Write a C Program illustrating Factorial without Recursion.


Problem Statement :To write a C Program to illustrate Factorial without Recursion.

Algorithm :
Step-1 : Start
Step-2 : Declare the variables n and fact to 1
Step-3 : Enter n value
Step-4 : Read n value
Step-5 : If n is greater than zero, then fact=fact*n
Step-6 : Display Factorial value
Step-7 : Stop

Program Code :
#include<stdio.h>
#include<conio.h>
void main()
{
int fact=1,n;
clrscr();
printf("Enter n value : ");
scanf("%d",&n);
while(n>0)
{
fact=fact*n;
n--;
}
printf("Factorial value = %d",fact);
getch();
}

Expected Output :
Enter n value : 6
Factorial value = 720

Actual Output :
Enter n value : 10
Factorial value = 24320

27
JNTUK C Programming Lab Manual

EXERCISE 6 – Control Flow - III


6.a. Write a C Program to make a simple Calculator to Add, Subtract,
Multiply or Divide Using switch…case.
Problem Statement :To write a C Program to make a simple Calculator to Add, Subtract,
Multiply or Divide Using switch…case.

Algorithm :
Step-1 : Start
Step-2 : Declare the variables a, b, c, ch, n
Step-3 : Read the two variable a and b
Step-4 : Display menu
Step-5 : Enter the option code
Step-6 : Evaluate option code with case statements
Step-7 : In case 1, c=a+b, print c. Goto step 12.
Step-8 : In case 2, c=a-b, print c. Goto step 12.
Step-9 : In case 3, c=a*b, print c. Goto step 12.
Step-10 : In case 4, c=(float)a/b, print c. Goto step 12.
Step-11 : Entered case option is invalid code the print “Invalid Option”
Step-12 : Stop

Program Code :
#include<stdio.h>
main()
{
int a,b,c,ch,n;
float d;
clrscr();
while(1)
{
printf("\n1.ADD\n2.SUB\n3.MUL\n4.DIV\n5.EXIT\n");
printf("Enter Your Choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("Enter a b values : ");
scanf("%d %d",&a,&b);
c=a+b;
printf("Sum = %d\n",c);
break;

case 2: printf("Enter a b values : ");


scanf("%d %d",&a,&b);
c=a-b;

28
JNTUK C Programming Lab Manual

printf("Subtraction = %d\n",c);
break;

case 3: printf("Enter a b values : ");


scanf("%d %d",&a,&b);
c=a*b;
printf("Multiplication = %d\n",c);
break;

case 4: printf("Enter a b values : ");


scanf("%d %d",&a,&b);
d=(float)a/b;
printf("Division = %f\n",d);
break;

case 5: exit(0);
default: printf("\n\tINVALID OPTION\n");break;
}
}
}

Expected Output :
1.ADD
2.SUB
3.MUL
4.DIV
5.EXIT
Enter Your Choice : 1
Enter a b values : 6 5
Sum = 11

1.ADD
2.SUB
3.MUL
4.DIV
5.EXIT
Enter Your Choice : 2
Enter a b values : 2 4
Subtraction = -2

1.ADD
2.SUB
3.MUL
4.DIV

29
JNTUK C Programming Lab Manual

5.EXIT
Enter Your Choice : 3
Enter a b values : 5 8
Multiplication = 40

1.ADD
2.SUB
3.MUL
4.DIV
5.EXIT
Enter Your Choice : 4
Enter a b values : 7 3
Division = 2.333333

1.ADD
2.SUB
3.MUL
4.DIV
5.EXIT
Enter Your Choice : 5

Actual Output :
1.ADD
2.SUB
3.MUL
4.DIV
5.EXIT
Enter Your Choice : 1
Enter a b values : 23 43
Sum = 66

1.ADD
2.SUB
3.MUL
4.DIV
5.EXIT
Enter Your Choice : 2
Enter a b values : 23 21
Subtraction = 2

1.ADD
2.SUB
3.MUL

30
JNTUK C Programming Lab Manual

4.DIV
5.EXIT
Enter Your Choice : 3
Enter a b values : 35 24
Multiplication = 840

1.ADD
2.SUB
3.MUL
4.DIV
5.EXIT
Enter Your Choice : 4
Enter a b values : 23 35
Division = 0.657143

1.ADD
2.SUB
3.MUL
4.DIV
5.EXIT
Enter Your Choice : 5

31
JNTUK C Programming Lab Manual

6.b. Write a C Program to convert decimal to binary and hex (using


switch call function the function)
Problem Statement :To write a C Program to convert decimal to binary and hex (using
switch call function the function)

Algorithm :
Step-1 : Start
Step-2 : Declare the variable
Step-3 : Display menu
Step-4 : Enter your choice
Step-5 : Evaluate option code with case statements
Step-6 : In case 1, enter the decimal number and read the values.
Step-7 : Display binary value
Step-8 : In case 2, enter the decimal number and read the values.
Step-9 : Display hexadecimal value
Step-10 : Entered case option is invalid code the print “Invalid Option”
Step-11 : Stop

Program Code :
#include<stdio.h>
main()
{
int ch;
clrscr();
while(1)
{
printf("\n1.DEC TO BIN\n2.DEC TO HEX\n3.EXIT\n");
printf("Enter Your Choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1: binary();
break;
case 2 : hexa();
break;
case 3 : exit(0);
default : printf("\n\tINVALID OPTION\n");
break;
}
}
}

32
JNTUK C Programming Lab Manual

binary()
{
int bin[100],d,r,i=-1;
printf("Enter the decimal number : ");
scanf("%d",&d);
while(d!=0)
{
i++;
r=d%2;
bin[i]=r;
d=d/2;
}
printf("Binary value = ");
while(i>=0)
{
printf("%d",bin[i]);
i--;
}
}

hexa()
{
intd,r,i=-1;
char hexa[100],ch;
printf("Enter the decimal number : ");
scanf("%d",&d);
while(d!=0)
{
i++;
r=d%16;
if(r>9)
ch=r+55;
else
ch=r+48;
hexa[i] = ch;
d=d/16;
}
printf("Hexa value = ");
while(i>=0)
{
printf("%c",hexa[i]);
i--;
}
}

33
JNTUK C Programming Lab Manual

Expected Output :
1. DEC TO BIN
2. DEC TO HEX
3. EXIT
Enter Your Choice : 1
Enter the decimal number : 234
Binary value = 11101010

1. DEC TO BIN
2. DEC TO HEX
3. EXIT
Enter Your Choice : 2
Enter the decimal number : 21
Hexa value = 15

1. DEC TO BIN
2. DEC TO HEX
3. EXIT
Enter Your Choice : 3

Actual Output :
1. DEC TO BIN
2. DEC TO HEX
3. EXIT
Enter Your Choice : 1
Enter the decimal number : 421
Binary value = 110100101

1. DEC TO BIN
2. DEC TO HEX
3. EXIT
Enter Your Choice : 2
Enter the decimal number : 535
Hexa value = 217

1. DEC TO BIN
2. DEC TO HEX
3. EXIT
Enter Your Choice : 3

34
JNTUK C Programming Lab Manual

EXERCISE 7 – Functions – Continued..


7.a. Write a C Program to compute the values of sin x and cos x and e^x
values using Series expansion. (use factorial function)

7.a.(i) Write a C Program to compute the values of sin x values using


Series expansion. (use factorial function)

Problem Statement :To write a C Program to compute the values of sin x values using
Series expansion using factorial function.

Algorithm :
Step-1 : Start
Step-2 : Declare the variables
Step-3 : Enter the radius value
Step-4 : Read the radius value
Step-5 : Now convert radius value r=(x*3.14f)/180
Step-6 : Using for loop calculate sum=sum+( (pow(r,i)/fact(i)) * sign )
Step-7 : If the condition is true, then execute the iteration of the loop
Step-8 : Compute the sum of the sine series with the factorial function
Step-9 : Display the sinx result
Step-10 : Stop

Program Code :
/* A C program to compute value of sin(x) using series expansion */
#include<stdio.h>
#include<math.h>
unsigned long int fact(int n);
void main()
{
int sign=1,x,i;
double sum=0,r;
clrscr();
printf("Enter the radius : ");
scanf("%d",&x);
r=(x*3.14f)/180; /* Converting radius value */
for(i=1;i<=10;i+=2)
{
sum=sum+( (pow(r,i)/fact(i)) * sign );
sign= -sign;
}
printf("Sin(%d) = %lf\n",x,sum);
}

35
JNTUK C Programming Lab Manual

unsigned long int fact(int n)


{
unsigned long int f=1;
int i;
for(i=1;i<=n;i++)
{
f=f*i;
}
return f;
}

Expected Output :
Enter the radius : 45
Sin(45) = 0.706825

Actual Output :
Enter the radius : 90
Sin(90) = 1.000003

36
JNTUK C Programming Lab Manual

7.a.(ii) Write a C Program to compute the values of cos x values using


Series expansion. (use factorial function)

Problem Statement :To write a C Program to compute the values of cos x values using
Series expansion using factorial function.

Algorithm :
Step-1 : Start
Step-2 : Declare the variables
Step-3 : Enter the radius value
Step-4 : Read the radius value
Step-5 : Now convert radius value r=(x*3.14f)/180
Step-6 : Using for loop calculate sum=sum+( (pow(r,i)/fact(i)) * sign )
Step-7 : If the condition is true, then execute the iteration of the loop
Step-8 : Compute the sum of the cos series with the factorial function
Step-9 : Display the cosx result
Step-10 : Stop

Program Code :
/* A C program to computer value of cos(x) using series expansion */
#include<stdio.h>
#include<math.h>
unsigned long int fact(int n);
void main()
{
int sign=1,x,i;
double sum=1,r;
clrscr();
printf("Enter the radius : ");
scanf("%d",&x);
r=(x*3.14f)/180; /* Converting radius value */
for(i=2;i<=10;i+=2)
{
sign=-sign;
sum=sum+( (pow(r,i)/fact(i)) * sign );
}
printf("Cos(%d) = %lf\n", x,sum);
}

unsigned long int fact(int n)


{
unsigned long int f=1;
int i;

37
JNTUK C Programming Lab Manual

for(i=1;i<=n;i++)
{
f=f*i;
}
return f;
}

Expected Output :
Enter the radius : 45
Cos(45) = 0.707388

Actual Output :
Enter the radius : 15
Cos(15) = 0.965960

38
JNTUK C Programming Lab Manual

7.a.(iii) Write a C Program to compute the values of e power x(e^x)


values using Series expansion. (use factorial function)

Problem Statement :To write a C Program to compute the values of e power x(e^x)
values using Series expansion using factorial function.

Algorithm :
Step-1 : Start
Step-2 : Declare the variables
Step-3 : Enter the radius value
Step-4 : Read the radius value
Step-5 : Add sum with x value
Step-6 : Using for loop calculate sum=sum+( (pow(r,i)/fact(i)) * sign )
Step-7 : If the condition is true, then execute the iteration of the loop
Step-8 : Compute the sum of e power x(e^x) series with the factorial function
Step-9 : Display the e power x(e^x) result
Step-10 : Stop

Program Code :
/* A C program to computer value of e power x using series expansion */
#include<stdio.h>
#include<math.h>
unsigned long int fact(int n);
void main()
{
double sum=1;
intx,i;
clrscr();
printf("Enter x value : ");
scanf("%d",&x);
sum=sum+x;
for(i=2;i<=10;i++)
{
sum=sum+( (pow(x,i)/fact(i)) );
}
printf("e(%d) = %lf\n", x, sum);
}

unsigned long int fact(int n)


{
unsigned long int f=1;
int i;
for(i=1;i<=n;i++)

39
JNTUK C Programming Lab Manual

{
f=f*i;
}
return f;
}

Expected Output :
Enter x value : 45
e(45) = 11973089922.409040

Actual Output :
Enter x value : 3
e(3) = 4.000000

40
JNTUK C Programming Lab Manual

EXERCISE 8 – Arrays
Demonstration of arrays
8.a. Write a C Program to perform Linear Search.

Problem Statement :To write a C Program to perform Linear Search.

Algorithm :
Step-1 : Start
Step-2 : Declare the variables
Step-3 : Enter the array size
Step-4 : Read the value of n
Step-5 : Enter the array size of elements
Step-6 : Enter the element to search
Step-7 : Read the value of s
Step-8 : Using for loop, check if flag is equal to 1
Step-9 : If flag is equal to 1, then element will be found.
Step-10 : If flag is not equal to 1, then element will not be found.
Step-11 : Stop

Program Code :
#include<stdio.h>
main()
{
int a[50],i,n,s,flag=0;
clrscr();
printf("Enter the array size : ");
scanf("%d",&n);
printf("Enter the array size of elements : ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the element to search : ");
scanf("%d",&s);

for(i=0;i<n;i++)
{
if(a[i]==s)
{
flag=1;
break;
}
}

if(flag==1)
printf("Element found at %d",i);

41
JNTUK C Programming Lab Manual

else
printf("Element not found");
}

Expected Output :
Enter the array size : 5
Enter the array size of elements : 23 56 78 90 32
Enter the element to search : 90
Element found at 3

Enter the array size : 4


Enter the array size of elements : 2 5 6 8
Enter the element to search : 7
Element not found

Actual Output :
Enter the array size : 5
Enter the array size of elements : 56 58 71 96 35
Enter the element to search : 56
Element found at 0

Enter the array size : 6


Enter the array size of elements : 85 96 74 25 36 12
Enter the element to search : 24
Element not found

42
JNTUK C Programming Lab Manual

8.b. Write a C Program to perform Bubble sort and Selection Sort.

8.b.(i). Write a C Program to perform Bubble sort.

Problem Statement :To write a C Program to perform Bubble Sort.

Algorithm :
Step-1 : Start
Step-2 : Declare the variables
Step-3 : Enter the size of array
Step-4 : Read the value of n
Step-5 : Enter the array of elements
Step-6 : Using the for loop, sort the elements
Step-7 : Display the sorted elements
Step-8 : Stop

Program Code :
#include<stdio.h>
main()
{
int a[50],i,j,t,n;
clrscr();
printf("Enter the size of array : ");
scanf("%d",&n);
printf("Enter the array of elements : ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);

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

printf("Sorted elements are : ");


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

43
JNTUK C Programming Lab Manual

printf("%d ",a[i]);
}

Expected Output :
Enter the size of array : 5
Enter the array of elements : 5 8 9 6 3
Sorted elements are : 3 5 6 8 9

Actual Output :
Enter the size of array : 6
Enter the array of elements : 20 19 17 49 36 25
Sorted elements are : 17 19 20 25 36 49

44
JNTUK C Programming Lab Manual

8.b.(ii). Write a C Program to perform Selection Sort.

Problem Statement :To write a C Program to perform Selection Sort.

Algorithm :
Step-1 : Start
Step-2 : Declare the variables
Step-3 : Enter the size of array
Step-4 : Read the value of n
Step-5 : Enter the array of elements
Step-6 : Using the for loop, sort the elements
Step-7 : Display the sorted elements
Step-8 : Stop

Program Code :
#include<stdio.h>
main()
{
int a[50],i,j,t,n;
clrscr();
printf("Enter the size of array : ");
scanf("%d",&n);
printf("Enter the array of elements : ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
printf("The sorted elements are : ");
for(i=0;i<n;i++)
printf("%d ",a[i]);
}

45
JNTUK C Programming Lab Manual

Expected Output :
Enter the size of array : 5
Enter the array of elements :4 7 2 9 1
Sorted elements are : 1 2 4 7 9

Actual Output :
Enter the size of array : 5
Enter the array of elements :5 4 3 2 1
Sorted elements are :1 2 3 4 5

46
JNTUK C Programming Lab Manual

8.c. Write a C Program to perform Operations on Matrix.

8.c.(i). Write a C Program to perform Addition Operation on Matrix.

Problem Statement :To write a C Program to perform Addition Operation on Matrix.

Algorithm :
Step-1 : Start
Step-2 : Declare the variables with its array size
Step-3 : Enter matrix A values
Step-4 : Read the value of a[i][j]
Step-5 : Enter matrix B values
Step-6 : Read the value of b[i][j]
Step-7 : Now calculate the addition of matrix A and matrix B values using
c[i][j]=a[i][j]+b[i][j]
Step-8 : Display the Addition matrix
Step-9 : Stop

Program Code :
#include<stdio.h>
main()
{
int a[2][2],b[2][2],c[2][2],i,j;
clrscr();
printf("Enter matrix A values : ");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf("%d",&a[i][j]);
printf("Enter matrix B values : ");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf("%d",&b[i][j]);
for(i=0;i<2;i++)
for(j=0;j<2;j++)
c[i][j]=a[i][j]+b[i][j];
printf("The Addition matrix is : \n");

for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d\t",c[i][j]);
}

47
JNTUK C Programming Lab Manual

printf("\n");
}
}

Expected Output :
Enter matrix A values : 4 7 2 4
Enter matrix B values : 5 8 3 2
The Addition matrix is :
9 15
5 6

Actual Output :
Enter matrix A values : 9 6 2 6
Enter matrix B values : 3 1 6 8
The Addition matrix is :
12 7
8 14

48
JNTUK C Programming Lab Manual

8.c.(ii). Write a C Program to perform Subtraction Operation on Matrix.

Problem Statement :To write a C Program to perform Subtraction Operation on Matrix.

Algorithm :
Step-1 : Start
Step-2 : Declare the variables with its array size
Step-3 : Enter the number of rows and columns of matrix
Step-4 : Read the value of first[c][d]
Step-5 : Enter the elements of second matrix
Step-6 : Read the value of second[c][d]
Step-7 : Now calculate the difference of difference[c][d] = first[c][d] - second[c][d]
Step-8 : Display the Subtraction matrix
Step-9 : Stop

Program Code :
#include <stdio.h>
int main()
{
int m, n, c, d, first[10][10], second[10][10], difference[10][10];
clrscr();
printf("Enter the number of rows and columns of matrix : ");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix : ");
for (c = 0; c < m; c++)
for (d = 0 ; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter the elements of second matrix : ");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &second[c][d]);
printf("Difference of entered matrices : \n");

for (c = 0; c < m; c++)


{
for (d = 0; d < n; d++)
{
difference[c][d] = first[c][d] - second[c][d];
printf("%d\t",difference[c][d]);
}
printf("\n");
}
return 0;
}

49
JNTUK C Programming Lab Manual

Expected Output :
Enter the number of rows and columns of matrix : 2 2
Enter the elements of first matrix : 3 5 7 9
Enter the elements of second matrix : 7 3 8 6
Difference of entered matrices :
-4 2
-1 3

Actual Output :
Enter the number of rows and columns of matrix : 2 2
Enter the elements of first matrix : 5 6 4 4
Enter the elements of second matrix : 7 8 5 4
Difference of entered matrices :
-2 -2
-1 0

50
JNTUK C Programming Lab Manual

8.c.(ii). Write a C Program to perform Multiplication Operation on


Matrix.

Problem Statement :To write a C Program to perform Multiplication Operation on Matrix.

Algorithm :
Step-1 : Start
Step-2 : Declare the variables with its array size
Step-3 : Enter matrix A values
Step-4 : Read the value of a[i][j]
Step-5 : Enter matrix B values
Step-6 : Read the value of b[i][j]
Step-7 : Now calculate the multiplication of matrix A and matrix B values using
c[i][j]=c[i][j]+(a[i][k]*b[k][j])
Step-8 : Display the multiplication matrix
Step-9 : Stop

Program Code :
#include<stdio.h>
main()
{
int a[2][2],b[2][2],c[2][2],i,j,k;
clrscr();
printf("Enter matrix A values : ");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf("%d",&a[i][j]);
printf("Enter matrix B values : ");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf("%d",&b[i][j]);

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

printf("The Multiplication matrix is :\n");


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

51
JNTUK C Programming Lab Manual

{
for(j=0;j<2;j++)
{
printf("%d ",c[i][j]);
}
printf("\n");
}
}

Expected Output :
Enter matrix A values : 4 7 2 4
Enter matrix B values : 5 8 3 2
The Multiplication matrix is :
41 46
22 24

Actual Output :
Enter matrix A values : 9 6 2 6
Enter matrix B values : 3 1 6 8
The Multiplication matrix is :
63 57
42 50

52
JNTUK C Programming Lab Manual

EXERCISE 9 – Structures

9.a. Write a C Program to Store Information of a Movie Using Structure.


Problem Statement : To write a C Program to Store Information of a Movie Using
Structure.

Algorithm :
Step-1 : Start
Step-2 : Create the structure movie with fields name, lang, time, cost
Step-3 : Enter information
Step-4 : Read the value m.name
Step-5 : Enter Movie Name
Step-6 : Read the value m.lang
Step-7 : Enter Movie Time in hours
Step-8 : Read the value m.time
Step-9 : Enter Movie Ticket Cost in Rs.
Step-10 : Read the value m.cost
Step-11 : Display Information for the entered data
Step-12 : Stop

Program Code :
#include <stdio.h>
struct movie
{
char name[50];
char lang[20];
float time;
long int cost;
}m;

main()
{
clrscr();
printf("Enter information : \n");
printf("Enter Movie Name : ");
scanf("%s", m.name);
printf("Enter Movie Language : ");
scanf("%s", m.lang);
printf("Enter Movie Time in hours : ");
scanf("%f", &m.time);
printf("Enter Movie Ticket Cost in Rs. : ");
scanf("%ld", &m.cost);
printf("\nDisplaying Information : \n");

53
JNTUK C Programming Lab Manual

printf("Movie Name : %s",m.name);


printf("\nMovie Language : %s",m.lang);
printf("\nMovie Time in hours : %f",m.time);
printf("\nMovie Ticket Cost in Rs. : %ld",m.cost);
}

Expected Output :
Enter information :
Enter Movie Name :Bahubali
Enter Movie Language :Telugu
Enter Movie Time in hours :2
Enter Movie Ticket Cost in Rs. :150

Displaying Information :
Movie Name :Bahubali
Movie Language :Telugu
Movie Time in hours :2.000000
Movie Ticket Cost in Rs. :150

Actual Output :
Enter information :
Enter Movie Name :Brahmastra
Enter Movie Language :Hindi
Enter Movie Time in hours :3
Enter Movie Ticket Cost in Rs. :200

Displaying Information :
Movie Name :Brahmastra
Movie Language :Hindi
Movie Time in hours :3.000000
Movie Ticket Cost in Rs. :200

54
JNTUK C Programming Lab Manual

9.b. Write a C Program to Store Information Using Structures with


Dynamically Memory Allocation.

Problem Statement :To write a C Program to Store Information Using Structures with
Dynamically Memory Allocation.

Algorithm :
Step-1 : Start
Step-2 : Create the structure course with fields marks, subject
Step-3 : Declare the remaining variables i, noOfRecords
Step-4 : Enter number of records
Step-5 : Read the value of number of records
Step-6 : Enter name of the subject and marks respectively
Step-7 : Read the value of (ptr+i)->subject, &(ptr+i)->marks
Step-8 : Display result information
Step-9 : Stop

Program Code :
#include <stdio.h>
#include<stdlib.h>

struct course
{
int marks;
char subject[30];
};

int main()
{
struct course *ptr;
int i, noOfRecords;
clrscr();
printf("Enter number of records : ");
scanf("%d", &noOfRecords);

// Allocates the memory for noOfRecords structures with pointer ptr


pointing to the base address.
ptr = (struct course*) malloc (noOfRecords * sizeof(struct course));

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


{
printf("Enter name of the subject and marks respectively : ");
scanf("%s %d", &(ptr+i)->subject, &(ptr+i)->marks);

55
JNTUK C Programming Lab Manual

}
printf("Displaying Information :\n");
for(i = 0; i <noOfRecords ; ++i)
printf("%s\t%d\n", (ptr+i)->subject, (ptr+i)->marks);
return 0;
}

Expected Output :
Enter number of records : 2
Enter name of the subject and marks respectively : Programming 50
Enter name of the subject and marks respectively : Databases 60
Displaying Information :
Programming 50
Databases 60

Actual Output :
Enter number of records : 3
Enter name of the subject and marks respectively : Graphics 50
Enter name of the subject and marks respectively : Networking 60
Enter name of the subject and marks respectively : English 60
Displaying Information :
Graphics 50
Networking 60
English 60

56
JNTUK C Programming Lab Manual

9.c. Write a C Program to Add Two Complex Numbers by Passing


Structure to a Function.

Problem Statement : To write a C Program to Add Two Complex Numbers by Passing


Structure to a Function.

Algorithm :
Step-1 : Start
Step-2 : Create structure complex and declare variables real and imag
Step-3 : Declare variables n1, n2, temp
Step-4 : For 1st complex number, Enter real and imaginary part respectively
Step-5 : Read the value of n1.real, n1.imag
Step-6 : For 2nd complex number, Enter real and imaginary part respectively
Step-7 : Read the value of n2.real, n2.imag
Step-8 : Calculate temp.real = n1.real + n2.real, temp.imag = n1.imag + n2.imag
Step-9 : Return value
Step-10 : Stop

Program Code :
#include <stdio.h>
typedefstruct complex
{
float real;
float imag;
} complex;
complex add(complex n1,complex n2);

int main()
{
complex n1, n2, temp;
clrscr();
printf("For 1st complex number \n");
printf("Enter real and imaginary part respectively : ");
scanf("%f %f", &n1.real, &n1.imag);

printf("For 2nd complex number \n");


printf("Enter real and imaginary part respectively : ");
scanf("%f %f", &n2.real, &n2.imag);

temp = add(n1, n2);


printf("Sum = %.1f + %.1fi", temp.real, temp.imag);
return 0;
}

57
JNTUK C Programming Lab Manual

complex add(complex n1, complex n2)


{
complex temp;
temp.real = n1.real + n2.real;
temp.imag = n1.imag + n2.imag;
return(temp);
}

Expected Output :
For 1st complex number
Enter real and imaginary part respectively : 6 7
For 2nd complex number
Enter real and imaginary part respectively : 1 2
Sum = 7.0 + 9.0i

Actual Output :
For 1st complex number
Enter real and imaginary part respectively : 3 5
For 2nd complex number
Enter real and imaginary part respectively : 2 3
Sum = 5.0 + 8.0i

58
JNTUK C Programming Lab Manual

EXERCISE 10 – Arrays and Pointers

10.a. Write a C Program to Access Elements of an Array Using Pointers.


Problem Statement :To write a C Program to Access Elements of an Array Using Pointers.

Algorithm :
Step-1 : Start
Step-2 : Declare integer array and variable
Step-3 : Enter the number of array elements
Step-4 : Read the number of array elements
Step-5 : Read the array elements through pointer
Step-6 : Display the array elements which you entered
Step-7 : Stop

Program Code :

#include <stdio.h>
int main()
{
int data[5], i;
clrscr();
printf("Enter array elements : ");
for(i = 0; i < 5; ++i)
scanf("%d", data + i);
printf("The array elements which you entered are : ");
for(i = 0; i < 5; ++i)
printf("%d", *(data + i));
return 0;
}

Expected Output :
Enter array elements : 5 7 9 8 6
The array elements which you entered are : 5 7 9 8 6

Actual Output :
Enter array elements : 1 8 9 6 3
The array elements which you entered are : 1 8 9 6 3

59
JNTUK C Programming Lab Manual

10.b. Write a C Program to find the sum of numbers with arrays and
pointers.

Problem Statement : To write a C Program to find the sum of numbers with arrays and
pointers.

Algorithm :
Step-1 : Start
Step-2 : Declare integer array, integer pointer and variables
Step-3 : Assign the address of the array value to the pointer
Step-4 : Enter the number of array values
Step-5 : Read the array value
Step-6 : Using for loop, Calculate sum with its pointer value
Step-7 : Increment pointer value
Step-8 : Display the sum of array elements using pointer
Step-9 : Stop

Program Code :

#include<stdio.h>
main()
{
int *p,a[5],i,sum=0;
p=&a[0];
clrscr();
printf("Enter the array values: ");
for(i=0;i<5;i++)
scanf("%d",&a[i]);
for(i=0;i<5;i++)
{
sum = sum + *p;
p++;
}
printf("The sum of array elements using pointer is : %d",sum);
}

Expected Output :
Enter the array values: 5 8 9 7 1
The sum of array elements using pointer is : 30

Actual Output :
Enter the array values: 3 6 5 2 9
The sum of array elements using pointer is : 25

60
JNTUK C Programming Lab Manual

EXERCISE 11 – Dynamic Memory Allocations


11.a. Write a C program to find sum of n elements entered by user. To
perform this program, allocate memory dynamically using malloc()
function.
Problem Statement :To write a C Program to find sum of n elements entered by user
using dynamic memory allocation using malloc() function.

Algorithm :
Step-1 : Start
Step-2 : Declare integer pointer and variables
Step-3 : Enter the elements size
Step-4 : Read the elements size value
Step-5 : Enter the array values
Step-6 : Read the array values
Step-7 : Calculate p=(int *)malloc(n * sizeof(int)) value
/* malloc() allocates memory block of given size (in bytes) and returns a pointer to the
beginning of the block. malloc() doesn’t initialize the allocated memory. If we try to acess
the content of memory block then we’ll get garbage values. */
Step-8 : Using for loop, Calculate sum with its pointer value
Step-9 : Increment pointer value
Step-10 : Display the sum elements
Step-11 : Stop

Program Code :
#include<stdio.h>
#include<stdlib.h>
main()
{
int *p,i,n,sum=0;
clrscr();
printf("Enter the elements size : ");
scanf("%d",&n);
p=(int *)malloc(n * sizeof(int));
printf("Enter the array values : ");
for(i=0;i<n;i++)
scanf("%d",p+i);

for(i=0;i<n;i++)
{
sum = sum + *p;
p++;
}

61
JNTUK C Programming Lab Manual

printf("The sum of elements = %d\n",sum);


}

Expected Output :
Enter the elements size : 3
Enter the array values : 3 4 5
The sum of elements = 12

Actual Output :
Enter the elements size : 4
Enter the array values : 4 3 2 1
The sum of elements = 10

62
JNTUK C Programming Lab Manual

11.b. Write a C program to find sum of n elements entered by user. To


perform this program, allocate memory dynamically using calloc()
function.
Problem Statement :To write a C Program to find sum of n elements entered by user
using dynamic memory allocation using calloc() function.

Algorithm :
Step-1 : Start
Step-2 : Declare integer pointer and variables
Step-3 : Enter the elements size
Step-4 : Read the elements size value
Step-5 : Enter the array values
Step-6 : Read the array values
Step-7 : Calculate p=(int *)calloc(n, sizeof(int)) value
/* calloc() allocates the memory and also initializes the allocates memory block to zero.
If we try to access the content of these blocks then we’ll get 0. */
Step-8 : Using for loop, Calculate sum with its pointer value
Step-9 : Increment pointer value
Step-10 : Display the sum elements
Step-11 : Stop

Program Code :
#include<stdio.h>
#include<stdlib.h>
main()
{
int *p,i,n,sum=0;
clrscr();
printf("Enter the elements size : ");
scanf("%d",&n);
p=(int *)calloc(n, sizeof(int));
printf("Enter the array of elements values : ");
for(i=0;i<n;i++)
scanf("%d",p+i);
for(i=0;i<n;i++)
{
sum = sum + *p;
p++;
}
printf("The sum of elements is: %d\n",sum);
}

63
JNTUK C Programming Lab Manual

Expected Output :
Enter the elements size : 5
Enter the array of elements values : 2 3 7 1 6
The sum of elements is : 19

Actual Output :
Enter the elements size : 5
Enter the array of elements values : 5 4 3 2 1
The sum of elements is : 15

64
JNTUK C Programming Lab Manual

EXERCISE 12 – Strings

12.a. Implementation of string manipulation operations with library


function.
i. copy
ii. concatenate
iii. length
iv. compare

12.a.(i) Write a C program to copy one string to another string with library
function.

Problem Statement : To write a C Program to copy one string to another string with library
function.

Algorithm :
Step-1 : Start
Step-2 : Declare Input string from user and store it to some variable say name1
Step-3 : Declare another variable to store copy of first string in name2
Step-4 : Input string for name1 and name2
Step-5 : Using the strcpy() function, copy the string pointed by source ) to the character
array destination
Step-6 : Copied name will be displayed
Step-7 : Stop

Program Code :
#include<stdio.h>
#include<string.h> /* strcpy() function is defined in string.h header file */
main()
{
char name1[40],name2[20];
clrscr();

/* Input string from the user */


printf("Enter name 1 : ");
scanf("%s",name1);
printf("Enter name 2 : ");
scanf("%s",name2);

65
JNTUK C Programming Lab Manual

/* strcpy() function copies the string pointed by source (including the null character) to
the character array destination */
strcpy(name1,name2);
printf("Copied name is : %s\n",name1);
}

Expected Output :
Enter name 1 : John
Enter name 2 : Bob
Copied name is : Bob

Actual Output :
Enter name 1 : Paul
Enter name 2 : George
Copied name is : George

66
JNTUK C Programming Lab Manual

12.a.(ii) Write a C program to concatenate one string to another string with


library function.

Problem Statement : To write a C Program to concatenate one string to another string with
library function.

Algorithm :
Step-1 : Start
Step-2 : Declare Input string from user and store it to some variable say fname
Step-3 : Declare another variable to concatenate the string in lname
Step-4 : Input string for fname and lname
Step-5 : Using the strcat() function, concatenates (joins) two strings fname and lname
Step-6 : Full name will be displayed
Step-7 : Stop

Program Code :
#include<stdio.h>
#include<string.h> /* strcat() function is defined in string.h header file */
main()
{
char fname[40],lname[20];
clrscr();

/* Input string from the user */


printf("Enter first name : ");
scanf("%s",fname);
printf("Enter last name : ");
scanf("%s",lname);

/* strcat() function, it concatenates (joins) two strings fname and lname */


strcat(fname,lname);
printf("Full name is : %s\n",fname);
}

Expected Output :
Enter first name : John
Enter last name : paul
Full name is : Johnpaul

Actual Output :
Enter first name : Big
Enter last name : brother
Full name is : Bigbrother

67
JNTUK C Programming Lab Manual

12.a.(iii) Write a C program to find length of string with library function.

Problem Statement : To write a C Program to find length of string with library function.

Algorithm :
Step-1 : Start
Step-2 : Declare Character Input string from user and store it to some variable say name
Step-3 : Declare another variable n
Step-4 : Input string for name
Step-5 : Using the strlen() function, it calculates the length of a given string name
Step-6 : Length of the name will be displayed
Step-7 : Stop

Program Code :
#include<stdio.h>
#include<string.h> /* strlen() function is defined in string.h header file */
main()
{
char name[40],n;
clrscr();

/* Input string from the user */


printf("Enter name : ");
scanf("%s",name);

/* strlen() function calculates the length of a given string */


n=strlen(name);
printf("Length of the name is : %d\n",n);
}

Expected Output :
Enter name : Programming
Length of the name is : 11

Actual Output :
Enter name : Coding
Length of the name is : 6

68
JNTUK C Programming Lab Manual

12.a.(iv) Write a C program to compare one string with another string with
library function.

Problem Statement : To write a C Program to compare one string with another string with
library function.

Algorithm :
Step-1 : Start
Step-2 : Declare Character Input string from user and store it to some variable say name1
Step-3 : Declare another variable to compare first string in name2
Step-4 : Input string for name1 and name2
Step-5 : Using the strcmp() function, it compares two strings name1 and name2
Step-6 : Display result
Step-7 : Stop

Program Code :
#include<stdio.h>
#include<string.h> /* strcmp() function is defined in string.h header file */
main()
{
char name1[40],name2[20];
clrscr();

/* Input string from the user */


printf("Enter name 1 : ");
scanf("%s",name1);
printf("Enter name 2 : ");
scanf("%s",name2);

/* strcmp() compares the two strings lexicographically means it starts comparison


character by character starting from the first character until the characters in both
strings are equal or a NULL character is encountered. If first character in both
strings are equal, then this function will check the second character, if this is also
equal then it will check the third and so on. This process will be continued until a
character in either string is NULL or the characters are unequal. */
if(strcmp(name1,name2)==0)
printf("Both names are equal\n");
else
printf("Both names are NOT equal\n");
}

69
JNTUK C Programming Lab Manual

Expected Output :
Enter name 1 : Program
Enter name 2 : Program
Both names are equal

Enter name 1 : Program


Enter name 2 : Coding
Both names are NOT equal

Actual Output :
Enter name 1 : Execute
Enter name 2 : Execute
Both names are equal

Enter name 1 : Compile


Enter name 2 : Execute
Both names are NOT equal

70
JNTUK C Programming Lab Manual

12.b. Implementation of string manipulation operations without library


function.
i. copy
ii. concatenate
iii. length
iv. compare

12.b.(i) Write a C program to copy one string to another string without


library function.

Problem Statement : To write a C Program to copy one string to another string without
library function.

Algorithm :
Step-1 : Start
Step-2 : Declare Input string from user and store it to some variable say name1
Step-3 : Declare another variable to store copy of first string in name2 and another variable i
Step-4 : Input string for name1 and name2
Step-5 : Run a loop from 0 to end of string. The loop structure should be like
for(i=0;name2[i]!='\0';i++)
Step-6 : Inside the loop for each character in name1 copy to name2 as name1[i]=name2[i]
Step-7 : Finally after loop make sure the copied string ends with NULL character i.e.
name1[i]='\0'
Step-8 : Copied name will be displayed
Step-9 : Stop

Program Code :
#include<stdio.h>
#include<string.h>
main()
{
char name1[40],name2[20],i;
clrscr();

/* Input string from the user */


printf("Enter name 1 : ");
scanf("%s",name1);
printf("Enter name 2 : ");
scanf("%s",name2);

/* Copy name1 to name2 character by character */


for(i=0;name2[i]!='\0';i++)

71
JNTUK C Programming Lab Manual

{
name1[i]=name2[i];
}

/* Make sure that the string is NULL terminated */


name1[i]='\0';
printf("Copied name is : %s\n",name1);
}

Expected Output :
Enter name 1 : John
Enter name 2 : Bob
Copied name is : Bob

Actual Output :
Enter name 1 : Paul
Enter name 2 : George
Copied name is : George

72
JNTUK C Programming Lab Manual

12.b.(ii) Write a C program to concatenate one string to another string


without library function.
Problem Statement : To write a C Program to concatenate one string to another string
without library function.

Algorithm :
Step-1 : Start
Step-2 : Declare two Input strings from user and store it to some variable str1 and str2
Step-3 : Declare another variable i, j
Step-4 : Input string for str1 and str2
Step-5 : Run a loop from 0 to end of string. The loop structure should be like
for(i=0;str1[i]!='\0';++i);
Step-6 : Run a loop from 0 to end of string. The loop structure should be like
for(j=0;str2[j]!='\0'; ++j,++i)
Step-7 : Inside the loop,the loop would concatenate the string str2 at the end of str1 like
str1[i]=str2[j]
Step-8 : Finally after loop make sure the copied string ends with NULL character i.e.
str1[i]='\0'
Step-9 : Concatenated String will be displayed
Step-10 : Stop

Program Code :
/* C program to concatenate two strings without using standard library function strcat() */
#include <stdio.h>
int main()
{
char str1[50], str2[50], i, j;
clrscr();

/* Input string from the user */


printf("Enter first string : ");
scanf("%s",str1);
printf("Enter second string : ");
scanf("%s",str2);

/* This loop is to store the length of str1 in i. It just counts the number of characters
in str1. You can also use strlen instead of this. */
for(i=0; str1[i]!='\0'; ++i);

/* This loop would concatenate the string str2 at the end of str1 */
for(j=0; str2[j]!='\0'; ++j, ++i)
{
str1[i]=str2[j];

73
JNTUK C Programming Lab Manual

/* \0 represents end of string */


str1[i]='\0';
printf("Concatenated String : %s",str1);
return 0;
}

Expected Output :
Enter first string : John
Enter second string : paul
Concatenated String : Johnpaul

Actual Output :
Enter first string : Big
Enter second string : brother
Concatenated String : Bigbrother

74
JNTUK C Programming Lab Manual

12.b.(iii) Write a C program to find length of string without library


function.
Problem Statement : To write a C Program to find length of string without library function.

Algorithm :
Step-1 : Start
Step-2 : Take a string as input and store it in the array string[] as name[]
Step-3 : Declare i value
Step-4 : Enter inputted string
Step-5 : Using while loop count the number of characters in the array string[]
Step-6 : Display Length of the string
Step-7 : Stop

Program Code :
#include<stdio.h>
#include<string.h>
main()
{
char name[40],i=0;
clrscr();
printf("Enter string : ");
scanf("%s",name);
while(name[i]!='\0')
i++;
printf("Length of the string : %d\n",i);
}

Expected Output :
Enter string : Programming
Length of the string : 11

Actual Output :
Enter string : Coding
Length of the string : 6

75
JNTUK C Programming Lab Manual

12.b.(iv) Write a C program to compare one string with another string


without library function.
Problem Statement : To write a C Program to compare one string without another string
with library function.

Algorithm :
Step-1 : Start
Step-2 : Declare two Input strings from user and store it to some variable name1 and name2
Step-3 : Declare another variables i, j, flag and initiate them to 0
Step-4 : Enter inputted string for name1 and name2
Step-5 : Read the inputted strings
Step-6 : Using while loop, check if the strings are equal or not
Step-7 : Using for loop, check if flag is equal to one, then both strings will be equal else if
flag is equal to zero then both strings will not be equal
Step-8 : Display Result
Step-9 : Stop

Program Code :
#include<stdio.h>
#include<string.h>
main()
{
char name1[20],name2[20],i=0,j=0,flag=0;
clrscr();
printf("Enter name 1 : ");
scanf("%s",name1);
printf("Enter name 2 : ");
scanf("%s",name2);
while(name1[i]!='\0')
i++;
while(name2[j]!='\0')
j++;
if(i!=j)
{
printf("Both names are NOT equal\n");
}
else
{
for(i=0;name1[i]!='\0';i++)
{
if(name1[i]==name2[i])
flag=1;
else
flag=0;

76
JNTUK C Programming Lab Manual

}
if(flag==1)
printf("Both names are equal\n");
else
printf("Both names are NOT equal\n");
}
}

Expected Output :
Enter name 1 : Program
Enter name 2 : Program
Both names are equal

Enter name 1 : Program


Enter name 2 : Coding
Both names are NOT equal

Actual Output :
Enter name 1 : Execute
Enter name 2 : Execute
Both names are equal

Enter name 1 : Compile


Enter name 2 : Execute
Both names are NOT equal

77
JNTUK C Programming Lab Manual

EXERCISE 13 – Files

13.a. Write a C programming code to open a file and to print its contents
on screen.

Problem Statement : To write a C Program to open a file and to print its contents on
screen.

Algorithm :
Step-1 : Start
Step-2 : Declare file pointer variable
Step-3 : Declare integer array and variable
Step-4 : Enter filename as input string
Step-5 : Using while loop, it checks the files
Step-6 : If file pointer is null, error message will be displayed
Step-7 : If file pointer is not null, Program output will be displayed
Step-8 : Display result
Step-9 : Stop

Program Code :
#include<stdio.h>
#include<stdlib.h> /* For Exit Function */
main()
{
FILE *fptr;
char filename[50],c;
clrscr();
printf("Enter filename : ");
scanf("%s",filename);
fptr=fopen(filename,"r");
if(fptr ==NULL)
{
printf("Error : Cannot open file");
exit(0);
}
c=fgetc(fptr);
while(c!=EOF)
{
printf("%c",c);
c=fgetc(fptr);
}
fclose(fptr);
}

78
JNTUK C Programming Lab Manual

Expected Output :
Enter filename : a.txt
Error : Cannot open file

Enter filename : cat.C


#include<stdio.h>
#include<string.h>
main()
{
char fname[40],lname[20];
clrscr();
printf("Enter first name : ");
scanf("%s",fname);
printf("Enter last name : ");
scanf("%s",lname);
strcat(fname,lname);
printf("Full name is : %s\n",fname);
}

Actual Output :
Enter filename : c.txt
Error : Cannot open file

Enter filename : asd.C


#include <stdio.h>
int main()
{
int data[5], i;
clrscr();
printf("Enter array elements : ");
for(i = 0; i < 5; ++i)
scanf("%d", data + i);
printf("The array elements which you entered are : ");
for(i = 0; i < 5; ++i)
printf("%d ", *(data + i));
return 0;
}

79
JNTUK C Programming Lab Manual

13.b. Write a C program to copy files.

Problem Statement : To write a C Program to copy files.

Algorithm :
Step-1 : Start
Step-2 : Declare file pointers varables
Step-3 : Declare integer arrays variable and other variable
Step-4 : Enter the inputted filenames
Step-5 : Read the inputted filenames
Step-6 : Using if, check if the file pointers are copied successfully or error message is
displayed
Step-7 : Display Result
Step-8 : Stop

Program Code :
#include<stdio.h>
#include<stdlib.h>
main()
{
FILE *fptr1,*fptr2;
char filename1[50],filename2[50],c;
clrscr();
printf("Enter filename 1 : ");
scanf("%s",filename1);
printf("Enter filename 2 : ");
scanf("%s",filename2);
fptr1=fopen(filename1,"r");
if(fptr1 == NULL)
{
printf("Error : Cannot open file");
exit(0);
}
fptr2=fopen(filename2,"w");
if(fptr2 == NULL)
{
printf("Error : Cannot open file");
exit(0);
}
c=fgetc(fptr1);
while(c!=EOF)
{
fputc(c,fptr2);

80
JNTUK C Programming Lab Manual

c=fgetc(fptr1);
}
printf("File copied successfully\n");
fclose(fptr1);
fclose(fptr2);
}

Expected Output :
Enter filename 1 : d.txt
Enter filename 2 : d.C
Error : Cannot open file

Enter filename 1 : a.C


Enter filename 2 : b.C
File copied successfully

Actual Output :
Enter filename 1 : text.txt
Enter filename 2 : toy.C
Error : Cannot open file

Enter filename 1 : k.C


Enter filename 2 : copy.C
File copied successfully

81
JNTUK C Programming Lab Manual

EXERCISE 14 – Files (Continued)

14.a. Write a C program that merges two files and stores their contents in
another file.

Problem Statement : To write a C Program that merges two files and stores their contents
in another file.

Algorithm :
Step-1 : Start
Step-2 : Declare filenames with pointer
Step-3 : Declare integer array variables
Step-4 : Declare character variable
Step-5 : Enter input pathfiles to merge
Step-6 : Read those pathfiles
Step-7 : Open source files in 'r' and destination file in 'w' mode in pathfiles
Step-8 : If the pathfile is NULL, then it is unable to open that file, so exit.
Step-9 : Using the while loop, copy contents of the first file to the second file so that files
will be merged successfully.
Step-10 : Display Result
Step-11 : Stop

Program Code :
/* C program to merge contents of two files to third file. */
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *sourceFile1, *sourceFile2, *destFile;
char sourcePath1[100], sourcePath2[100], destPath[100], ch;
clrscr();

/* Input path of files to merge to third file */


printf("Enter first source file path : ");
scanf("%s", sourcePath1);
printf("Enter second source file path : ");
scanf("%s", sourcePath2);
printf("Enter destination file path : ");
scanf("%s", destPath);

82
JNTUK C Programming Lab Manual

/* Open source files in 'r' and destination file in 'w' mode */


sourceFile1 = fopen(sourcePath1, "r");
sourceFile2 = fopen(sourcePath2, "r");
destFile = fopen(destPath, "w");

/* fopen() return NULL if unable to open file in given mode. */


if (sourceFile1 == NULL || sourceFile2 == NULL || destFile == NULL)
{
/* Unable to open file hence exit */
printf("Unable to open file.\n");
printf("Please check if file exists and you have read/write privilege.\n");
exit(EXIT_FAILURE);
}

/* Copy contents of first file to destination */


while ((ch = fgetc(sourceFile1)) != EOF)
fputc(ch, destFile);

/* Copy contents of second file to destination */


while ((ch = fgetc(sourceFile2)) != EOF)
fputc(ch, destFile);
printf("Files merged successfully to '%s'.\n", destPath);

/* Close files to release resources */


fclose(sourceFile1);
fclose(sourceFile2);
fclose(destFile);
return 0;
}

Expected Output :
Enter first source file path : leapyear.c
Enter second source file path : lru.c
Enter destination file path : mou.c
Files merged successfully to ‘mou.c’.

Enter first source file path : abc.txt


Enter second source file path : rem.c
Enter destination file path : qwe.txt
Unable to open file.
Please check if file exists and you have read/write privilege.

83
JNTUK C Programming Lab Manual

Actual Output :
Enter first source file path : binary.c
Enter second source file path : linear.c
Enter destination file path : bubble.c
Files merged successfully to ‘bubble.c’.

Enter first source file path : alpha.txt


Enter second source file path : beta.c
Enter destination file path : sigma.txt
Unable to open file.
Please check if file exists and you have read/write privilege.

84
JNTUK C Programming Lab Manual

14.b. Write a C program to delete a file.


Problem Statement : To write a C Program to delete a file.

Algorithm :
Step-1 : Start
Step-2 : Declare the variables
Step-3 : Enter the name of the file you want to delete
Step-4 : Check if status is equal to zero, then file is deleted successfully else there is an error
while deleting file
Step-5 : Display result
Step-6 : Stop

Program Code :
#include<stdio.h>
#include<stdlib.h>
main()
{
int status;
char filename[50],c;
clrscr();
printf("Enter filename : ");
scanf("%s",filename);
status=remove(filename);
if(status==0)
printf("%s file is deleted successfully\n",filename);
else
printf("There is an error while deleting file\n");
}

Expected Output :
Enter filename : a.C
a.C file is deleted successfully

Enter filename : x.C


There is an error while deleting file

Actual Output :
Enter filename : ab.C
ab.C file is deleted successfully

Enter filename : xyz.C


There is an error while deleting file

85

S-ar putea să vă placă și