0% found this document useful (0 votes)
180 views52 pages

CP Lab Manual FInal.

The document outlines various programming exercises for a C programming lab manual, including exercises on basics of C programming, control flow, functions, arrays, pointers, dynamic memory allocation, strings, files, and operating system commands. It provides example programs to perform tasks like calculating simple math operations from command line input, checking for leap years, and converting between Celsius and Fahrenheit scales. The exercises are intended to help students learn and practice various fundamental and advanced C programming concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
180 views52 pages

CP Lab Manual FInal.

The document outlines various programming exercises for a C programming lab manual, including exercises on basics of C programming, control flow, functions, arrays, pointers, dynamic memory allocation, strings, files, and operating system commands. It provides example programs to perform tasks like calculating simple math operations from command line input, checking for leap years, and converting between Celsius and Fahrenheit scales. The exercises are intended to help students learn and practice various fundamental and advanced C programming concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

LINGAYA’S INSTITUTE OF MANAGEMENT & TECHNOLOGY

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

C PROGRAMMING LAB MANUAL (JNTUK-R16)

AssitProf. HemanthKumar Palli


mail:[email protected]

Page 1
COMPUTER PROGRAMMING LAB R16 CSE

Exercise - 1 Basics
a) What is an OS Command, Familiarization of Editors - vi, Emacs
b) Using commands like mkdir, ls, cp, mv, cat, pwd, and man
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 at Motion
b) Write a C Program to convert Celsius to Fahrenheit and vice versa

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 Number is
i) Prime Number
ii) Armstrong Number
b) Write a C program to print Floyd Triangle
c) Write a C Program to print Pascal Triangle

Exercise – 5 Functions
a) Write a C Program demonstrating of parameter passing in Functions and returning values.
b) Write a C Program illustrating Fibonacci, Factorial with Recursion without Recursion

Exercise – 6 Control Flow - III


a) Write a C Program to make a simple Calculator to Add, 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


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 on Matrix.

Exercises - 9 Structures
a)Write a C Program to Store Information of a Movie Using Structure
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 a Function

Page 2
Exercise - 10 Arrays and Pointers
a)Write a C Program to Access Elements of an Array Using Pointer
b) Write a C Program to find the sum of numbers with arrays and pointers.

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 library function.
i) copy ii) concatenate iii) length iv) compare
b) Implementation of string manipulation operations without library function.
i) copy ii) concatenate iii) length iv) compare

Exercise -13 Files


a)Write a C programming code to open a file and to print it 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) Write a C program to delete a file.

Exercise - 15
a) System Assembling, Disassembling and identification of Parts / Peripherals. b) Operating
System Installation-Install Operating Systems like Windows, Linux along with necessary Device
Drivers.

Exercise - 16
a) MS-Office / Open Office
i) Word - Formatting, Page Borders, Reviewing, Equations, symbols.
ii) Spread Sheet - organize data, usage of formula, graphs, charts.
iii) Powerpoint - features of power point, guidelines for preparing an effective
presentation.
b) Network Configuration & Software Installation-Configuring TCP/IP, Proxy, and firewall
settings. Installing application software, system software & tools.

Page 3
1 a) What is an OS Command, Familiarization of Editors - vi, Emacs

OPERATING SYSTEM:

An operating system (OS) is system software that manages computer


hardware and software resources and provides common services for computer
programs. All computer programs, excluding firmware, require an operating
system to function.
The UNIX operating system is a set of programs that act as a link between the
computer and the user.
The computer programs that allocate the system resources and coordinate all the
details of the computer's internals is called the operating system or kernel. Users
communicate with the kernel through a program known as the shell. The shell is a
command line interpreter; it translates commands entered by the user and
converts them into a language that is understood by the kernel.

TEXT EDITORS:

1. vi : Vi iMproved, a programmer’s text editor :

This command starts the vi text editor. You can use vi editor to create ordinary files on
any Unix system.

Syntax: –
vi < filename >

2. emacs : Emacs Editor :

Emacs is an extensible, customizable, self-documenting real-time display editor.

General instructions:

o Ctrl + v move forward one screenful


o Alt + v move backward one screenful
o Ctrl + l clear screen and redisplay all the text

Syntax: –
emacs < filename > . < filetype >

Page 4
1 b) Using commands like mkdir, ls, cp, mv, cat, pwd, and man

SOME UNIX COMMANDS:

1. mkdir : Make Directories


This command will make a new subdirectory.

Syntax: -
mkdir <directory>

Example:-
mkdir csedept

2. ls : List Directory Contents


This command will list the files stored in a directory.

Syntax: -
ls <directory_name>

Example:-
ls csedept

3. cp : Copy Files/Directories
This command copies a file, preserving the original and creating an identical
copy.

Syntax: -
cp <source> <directory/New_File>

Example:-
cp add add.c

Page 5
4. mv : Move Files
This command will move a file. Also to change the name of a file uses the mv
command.

Syntax: -

Move : mv <source> <directory>

Rename : mv <original_file_name> <new_file_name>

Example:-
mv add.c csedept ( Moving a File )

mv add add.c ( Renaming a File )

5. cat : Concatenation of files


This command outputs the contents of a text file. You can use it to read brief
files or to concatenate files together.

Syntax: -

cat <file_Name>

cat <file1> <file2> <file> … <file_n> >> <new_file_name>

Example:-
cat add.c (Content Of the file )

cat add add.c >> Aaa ( Concatenate Files )

Page 6
6. pwd : Print Working Directory
This command reports the current directory path.

Syntax: -
pwd <File_Name>

Example:-
pwd add.c

7. man : Manual Page


This command displays the manual page for a particular command. This
command is useful when you are in situation where you are unsure on how to
use a command or when you want to find out all other options related to it.

Syntax: -
man <command/argument>

Example:-
man ls

Page 7
1 c) Write a C Program to Perform Adding, Subtraction, Multiplication
and Division of two numbers from Command line

#include<stdio.h>
main()
{
int a,b,c,d,e,f;
printf("Enter a and b Values: ");
scanf("%d%d",&a,&b);
c=a+b;
d=a-b;
e=a*b;
f=a/b;
printf("Addition : %d \n",c);
printf("Subraction : %d \n",d);
printf("Multiplication : %d \n",e);
printf("Division : %d \n",f);
}

Page 8
2 a) Write a C Program to Simulate 3 Laws at Motion

#include<stdio.h>
main()
{
float m,v,a,t,F,p,rf;
a=9.8;
printf("\n NEWTON'S LAWS OF MOTION \n \n First Law : ");
printf("\n Enter Mass m Value:");
scanf("%f",&m);
printf(" acceleration due to gravity, a=9.8");
F=m*a;
printf("\n Force (F )= %f ",F);
printf("\n \n Second Law : ");
printf("\n Enter Velocity v Value: ");
scanf("%f",&v);
p=m*v;
printf(" Momentum, p = %f ",p);
printf("\n \n Third Law: \n");
printf(" Enter Time t Value:");
scanf("%f",&t);
rf=p/t;
printf(" Rate of force = %f \n\n ",rf);
}

Page 9
2 b) Write a C Program to convert Celsius to Fahrenheit and vice versa

#include<stdio.h>
main()
{
float f,c,fh,cel;
printf("Enter the temperature in Celsius : ");
scanf("%f",&c);
f=(1.8*c)+32;
printf("The temperature in Fahrenheit is : %f \n",f);
printf("Enter the temperature in Fahrenheit : ");
scanf("%f",&fh);
cel=(fh-32)/1.8;
printf("The temperature in Celsius is : %f \n",cel);
}

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

#include<stdio.h>
main()
{
int year;
printf("Enter a year to check if it is a leap year : ");
scanf("%i",&year);
if(year%4==0)
printf("The given year is a leap year \n");
else
printf("The given year is not a leap year \n");
}

Page 11
3 b)Write a C Program to Add Digits & Multiplication of a number

#include<stdio.h>
main()
{
int n,t,z,r,sum=0,mul=1;
int count=0;
printf("Enter an integer: ");
scanf("%d",&n);
t = n;
z=n;
while(n!=0)
{
n /= 10;
++count;
}

printf("Number of digits : %d \n",count);

while (t != 0)
{
r = t % 10;
sum=sum+r;
mul=mul*r;
t = t/10;
}
printf("Sum of digits of %d is %d \n", z, sum);
printf("Multiplication of digits of %d is %d \n",z,mul);
}

Page 12
4 a) Write a C Program to Find Whether the Given Number is

i) Prime Number

#include<stdio.h>
main()
{
int num,i,count=0;
printf("Enter a number : ");
scanf("%d",&num);
for (i=2; i<=num/2; i++)
{
if (num%i==0)
{
count++;
break;
}
}
if (count==0)
printf("%d is a prime number \n", num);
else
printf("%d is not a prime number \n", num);
}

Page 13
4 a) Write a C Program to Find Whether the Given Number is

ii) Armstrong Number

#include<stdio.h>
main()
{
int num,r,sum=0,temp;
printf("Enter a number : ");
scanf("%d",&num);
temp=num;
while(num!=0)
{
r=num%10;
num=num/10;
sum=sum+(r*r*r);
}
if(sum==temp)
printf("%d is an Armstrong Number \n",temp);
else
printf("%d is not an Armstrong Number \n",temp);
}

Page 14
4 b) Write a C program to print Floyd Triangle

#include<stdio.h>
main()
{
int i,n,c,a=1;
printf("Enter the number of rows in the Floyd's Triangle : ");
scanf("%i",&n);
for(i=1;i<=n;i++)
{
for(c=1;c<=i;c++)
{
printf("%d ",a);
a++;
}
printf("\n");
}
}

Page 15
4 c) Write a C Program to print Pascal Triangle

#include<stdio.h>
main()
{
int r,a=1,space,i,j;
printf("Enter number of rows : ");
scanf("%d",&r);
for(i=0;i<r;i++)
{
for(space=1;space<=r-i;space++)
printf(" ");
for(j=0;j<=i;j++)
{
if(j==0||i==0)
a=1;
else
a=a*(i-j+1)/j;
printf("%4d",a);
}
printf("\n");
}
}

Page 16
5 a) Write a C Program demonstrating of parameter passing in
Functions and returning values

#include<stdio.h>
float area(int);
main()
{
int r;
float a;
printf("\n Enter the radius of the circle:");
scanf("%d",&r);
a=area(r);
printf("\n Area of Circle :%f \n",a);
}
float area(int r)
{
float cir;
cir=3.14*r*r;
return cir;
}

Page 17
5 b) Write a C Program illustrating Factorial with Recursion without
Recursion

#include <stdio.h>
long factorial(int);
main()
{
int c, n, fact = 1,ch;
long f;
printf("\n 1.Factorial Without Recursion \t 2.Factorial Using Recurssion \t
Other to Exit \n");
printf("Enter Your Choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Enter a number to calculate it's factorial : ");
scanf("%d", &n);
for (c = 1; c <= n; c++)
fact = fact * c;
printf("Factorial of %d = %d \n", n, fact);
break;

case 2:
printf("Enter an integer to find factorial : ");
scanf("%d", &n);
if (n < 0)
printf("Negative integers are not allowed.\n");
else
{
f = factorial(n);
printf("%d! = %ld\n", n, f);
}
break;
default:
printf("\n Exit \n");
exit(1);

}
}

Page 18
long factorial(int n)
{
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}

Page 19
5 b) Write a C Program illustrating Fibonacci with Recursion without
Recursion

#include<stdio.h>
int Fibonacci(int);
main()
{
int n, first = 0, second = 1, next, c,i=0,ch;
printf("\n 1.Fibonacci Series Without Recursion \t 2.Fibonacci Using
Recurssion \t Other selections to Exit \n");
printf("Enter Your Choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:

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


scanf("%d",&n);
printf("First %d terms of Fibonacci series are : ",n);

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


{
if ( c <= 1 )
next = c;
else
{
next = first + second;
first = second;
second = next;
}
printf("%d \t",next);
}
printf("\n");
break;

case 2:

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


scanf("%d",&n);

Page 20
printf("Fibonacci series : \n");
for ( c = 1 ; c <= n ; c++ )
{
printf("%d \t", Fibonacci(i));
i++;
}
printf("\n");
break;
default:
exit(1);
}
}

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

Page 21
6 a) Write a C Program to make a simple Calculator to Add, Subtract,
Multiply or Divide Using switch…case

#include<stdio.h>
main()
{
char op;
int a,b;
printf("\n Enter your choice : + Add \t - Sub \t * Mult \t / Div \t % Mod : ");
scanf("%c",&op);
printf("Enter Two Values for a,b : ");
scanf("%d%d",&a,&b);
switch(op)
{
case '+':
printf(" %d + %d = %d \n ",a,b,a+b);
break;
case '-':
printf(" %d - %d = %d \n ",a,b,a-b);
break;
case '*':
printf(" %d * %d = %d \n ",a,b,a*b);
break;
case '/':
printf(" %d / %d = %d \n ",a,b,a/b);
break;
case '%':
printf(" %d % %d = %d \n ",a,b,a%b);
break;
default:
printf("\n Operator Entered is not matched \n");
break;
}

Page 22
Page 23
6 b) Write a C Program to convert decimal to binary and hex (using switch
call function the function)

#include <stdio.h>

main()
{
long num, de, re, base = 1, binary = 0, quotient;
int i, j = 0,op;
char hd[100];
printf("\n Enter a Decimal Number: ");
scanf("%ld",&de);
printf("\n Enter Your Choice 1. Decimal to Binary \t 2. Deimal to Hexa Decimal: ");
scanf("%d",&op);
switch(op)
{
case 1:
num=de;
while (num > 0)
{
re = num % 2;
binary = binary + re * base;
num = num / 2;
base = base * 10;
}
printf("Its binary equivalent is = %ld \n", binary);
break;

case 2:

quotient = de;
while (quotient != 0)
{
re = quotient % 16;
if (re < 10)
hd[j++] = 48 + re;
else
hd[j++] = 55 + re;
quotient = quotient / 16;

Page 24
}
printf("Hexa Decimal Number: ");
for (i = j; i >= 0; i--)
printf(" %c ", hd[i]);
printf("\n");
return 0;
default:
printf("\n Invalid Choice \n");
exit(1);
}
}

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

#include<stdio.h>
#include<math.h>
int factorial(int num)
{
int ctr;
int fact=1;
for(ctr=1;ctr<=num;ctr++)
fact=fact*ctr;
return fact;
}
main()
{
int terms;
int ctr;
printf("\nEnter the number of terms of expansion: ");
scanf("%d",&terms);
double sum=0.0,x;
printf("\nEnter the value for x : ");
scanf("%lf",&x);
printf("\n1+x+x^2/2!+x^3/3!....... exp(x) \n");
for(ctr=0;ctr<terms;ctr++)
sum+=pow(x,ctr)/factorial(ctr);
printf("\nThe value from the expansion is %.03lf\n",sum);
sum=0.0;
printf("\n1-x^2/2!+x^4/4!....... cosine(x)\n");
for(ctr=0;ctr/2<terms;ctr+=2)
sum=sum+pow(-1,ctr/2)*pow(x,ctr)/(factorial(ctr));
printf("\nThe value of cosine expansion is %.03lf\n",sum);
sum=0.0;
printf("\nx-x^3/3!+x^5/5!....... sine(x)\n");
for(ctr=1;(ctr-1)/2<terms;ctr+=2)
sum=sum+pow(-1,(ctr-1)/2)*pow(x,ctr)/(factorial(ctr));
printf("\nThe value of sine expansion is %.03lf\n\n",sum);

Page 26
Page 27
8 a) Search-Linear.

#include <stdio.h>

main()
{
int array[100], search, c, n;
printf("Enter the number of elements in array : ");
scanf("%d",&n);
printf("Enter %d integer(s) : ", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("\nEnter the number to search : ");
scanf("%d", &search);
for (c = 0; c < n; c++)
{
if (array[c] == search
{
printf("%d is present at location %d\n", search, c+1);
break;
}
}
if (c == n)
printf("%d is not present in array\n", search);
return 0;
}

Page 28
8 b) Sorting-Bubble

#include <stdio.h>
main()
{
int array[100], n, c, d, swap;
printf("\nEnter number of Elements : ");
scanf("%d", &n);
printf("\nEnter %d integers : ", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);

for (c = 0 ; c < ( n - 1 ); c++)


{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1])
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
printf("Sorted list in ascending order : ");
for ( c = 0 ; c < n ; c++ )
printf("%d\t", array[c]);
return 0;
}

Page 29
8 b) Sorting-Selection.

#include <stdio.h>

main()
{
int array[100], n, c, d, position, swap;
printf("\nEnter number of elements : ");
scanf("%d", &n);
printf("\nEnter %d integers: ", n);
for ( c = 0 ; c < n ; c++ )
scanf("%d", &array[c]);
for ( c = 0 ; c < ( n - 1 ) ; c++ )
{
position = c;
for ( d = c + 1 ; d < n ; d++ )
{
if ( array[position] > array[d] )
position = d;
}
if ( position != c )
{
swap = array[c];
array[c] = array[position];
array[position] = swap;
}
}
printf("\nSorted list in ascending order: ");
for ( c = 0 ; c < n ; c++ )
printf("%d\t", array[c]);
printf("\n");
return 0;
}

Page 30
8 c) Operations on Matrix-Addition

#include <stdio.h>

int main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
printf("\nEnter the number of rows and columns of matrix : ");
scanf("%d%d", &m, &n);
printf("\nEnter the elements of first matrix: ");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("\nEnter the elements of second matrix: ");
for (c = 0; c < m; c++)
for (d = 0 ; d < n; d++)
scanf("%d", &second[c][d]);
printf("\nSum of entered matrices:\n ");
for (c = 0; c < m; c++) {
for (d = 0 ; d < n; d++) {
sum[c][d] = first[c][d] + second[c][d];
printf("%d\t", sum[c][d]);
}
printf("\n");
}

return 0;
}

Page 31
8 c) Operations on Matrix-Multiplication

#include <stdio.h>

main()
{
int m, n, p, q, c, d, k, sum = 0;
int first[10][10], second[10][10], multiply[10][10];
printf("\nEnter the number of rows and columns of first matrix: ");
scanf("%d%d", &m, &n);
printf("\nEnter the elements of first matrix: ");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("\nEnter the number of rows and columns of second matrix: ");
scanf("%d%d", &p, &q);
if (n != p)
printf("\nMatrices with entered orders can't be multiplied with each other\n");
else
{
printf("\nEnter the elements of second matrix: ");
for (c = 0; c < p; c++)
for (d = 0; d < q; d++)
scanf("%d", &second[c][d]);
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++) {
for (k = 0; k < p; k++) {
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}

printf("\nProduct of entered matrices:\n");


for (c = 0; c < m; c++) {
for (d = 0; d < q; d++)
printf("%d\t", multiply[c][d]);
printf("\n");
}
}

return 0;
}

Page 32
Page 33
9 a) Write a C Program to Store Information of a Movie Using
Structure

#include<stdio.h>
#define size 20
struct Movie
{
char m[size],hero[size];
int rel,run;
};
main()
{
struct Movie first={"Premam","Nivin Paul",2015,150};
struct Movie second={"VIP","Dhanush",2014,100};
printf("\nMovie Title : %s" ,first.m);
printf("\nMovie Hero : %s" ,first.hero);
printf("\nReleased Year : %d" ,first.rel);
printf("\nRunned Days : %d\n",first.run);
printf("\nMovie Title : %s" ,second.m);
printf("\nMovie Hero : %s" ,second.hero);
printf("\nReleased Year : %d" ,second.rel);
printf("\nRunned Days : %d\n" ,second.run);

Page 34
9 b) Write a C Program to Store Information Using Structures with
Dynamically Memory Allocation

#include<stdio.h>
struct course
{
int marks;
char subjects[30];
};
main()
{
struct course *ptr;
int i,n;
printf("\nEnter Number of Subjects: ");
scanf("%d",&n);
ptr=(struct course*)malloc(n*sizeof(struct course));
for(i=0;i<n;i++)
{
printf("\nEnter Name of the subject & Marks Respectively: ");
scanf("%s%d",&(ptr+i)->subjects,&(ptr+i)->marks);
}
printf("\n\t\t........Displaying Information........ \n\n\n ");
for(i=0;i<n;++i)
printf("\t\t\t %s\t\t %d \n\n",(ptr+i)->subjects,(ptr+i)->marks);

Page 35
9 c) Write a C Program to Add Two Complex Numbers by Passing
Structure to a Function

#include<stdio.h>
typedef struct
{
float real;
float image;
}c;
void add(c c1,c c2);
main()
{
c c1,c2;
printf("Enter First Complex Number : ");
scanf("%f%f",&c1.real,&c1.image);
printf("Enter Second Complex Number: ");
scanf("%f%f",&c2.real,&c2.image);
add(c1,c2);
}
void add(c n1,c n2)
{
c temp;
temp.real=n1.real+n2.real;
temp.image=n1.image+n2.image;
printf("Sum=%2f+i %2f \n",temp.real,temp.image);
}

Page 36
10 a) Write a C Program to Access Elements of an Array Using Pointer

#include<stdio.h>
main()
{
int data[10],i,n;
printf("Enter Number of Elements: ");
scanf("%d",&n);
printf("Enter %d Elements: ",n);
for(i=0;i<n;i++)
{
scanf("%d",data+i);
}
printf("Entered Elements are: ");
for(i=0;i<n;++i)
printf("\t%d",*(data+i));
printf("\n");
}

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

#include<stdio.h>
main()
{
int n,arr[10],i,sum=0;
int *ptr;
printf("\n Enter n value: ");
scanf("%d",&n);
printf("\nEnter %d Elements: ",n);
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
ptr=arr;
for(i=0;i<n;i++)
{
sum=sum + *ptr;
ptr++;
}
printf("\nSum of Array Elements: %d\n",sum);
}

Page 38
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.

#include<stdio.h>
main()
{
int n,i,*ptr,sum=0;
printf("\nEnter Number of Elements: ");
scanf("%d",&n);
ptr=(int *)malloc(n*sizeof(int));
if(ptr==NULL)
{
printf("Error ..! Memory Not Allocated\n");
exit(0);
}
printf("Enter Elements of arrays: ");
for(i=0;i<n;i++)
{
scanf("%d",ptr+i);
sum+= *(ptr+i);
}
printf("Sum=%d\n\n",sum);
free(ptr);
}

Page 39
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. Understand the difference between the above two programs

#include<stdio.h>
main()
{
int n,i,*ptr,sum=0;
printf("\nEnter Number of Elements: ");
scanf("%d",&n);
ptr=(int *)calloc(n,sizeof(int));
if(ptr==NULL)
{
printf("Error ..! Memory Not Allocated\n");
exit(0);
}
printf("Enter Elements of arrays: ");
for(i=0;i<n;i++)
{
scanf("%d",ptr+i);
sum+= *(ptr+i);
}
printf("Sum=%d\n\n",sum);
free(ptr);
}

Page 40
12 a) Implementation of string manipulation operations with library
function. i) copy ii) concatenate iii) length iv) compare

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

main()
{

int ch;
printf("\nEnter Your Choice 1. Copy \t 2. Concatenate \t 3.Length \t 4.
Compare: ");
scanf("%d",&ch);
switch(ch)

{
case 1:
copy();
break;
case 2:
concatenate();
break;
case 3:
length();
break;
case 4:
compare();
break;
default:
exit(1);

}
}

copy()
{
char source[15], destination[15];
printf("\nEnter a string: ");
scanf("%s",source);
strcpy(destination, source);
printf("Source string: %s\n", source);
Page 41
printf("Destination string: %s\n", destination);
return 0;
}

concatenate()
{
char a[100], b[100];
printf("\nEnter the first string: ");
scanf("%s",a);
printf("\nEnter the second string: ");
scanf("%s",b);
strcat(a,b);
printf("\nString obtained on concatenation is: %s\n",a);
return 0;
}

length()
{
char str[50];
int len;
printf("\nEnter String: ");
scanf("%s",str);
len = strlen(str);
printf("Length of |%s| is |%d|\n", str, len);
return(0);
}

compare()
{
char str1[15];
char str2[15];
int ret;
printf("\nEnter First String: ");
scanf("%s",str1);
printf("\nEnter Second String: ");
scanf("%s",str2);
ret = strcmp(str1, str2);
if(ret < 0)
{

Page 42
printf("str1 is less than str2");
}
else if(ret > 0)
{
printf("str2 is less than str1");
}
else
{
printf("str1 is equal to str2");
}

return(0);
}

Page 43
12 b) Implementation of string manipulation operations without
library function. i) copy ii) concatenate iii) length iv) compare

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

main()
{

int ch;
printf("\nEnter Your Choice 1. Copy \t 2. Concatenate \t 3.Length \t 4.
Compare: ");
scanf("%d",&ch);
switch(ch)

{
case 1:
copy();
break;
case 2:
concatenate();
break;
case 3:
length();
break;
case 4:
compare();
break;
default:
exit(1);

}
}

copy()
{
char s1[100], s2[100], i;
printf("\nEnter string s1: ");
scanf("%s",s1);

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


{
s2[i] = s1[i];
}

Page 44
s2[i] = '\0';
printf("String s2: %s\n", s2);
return 0;
}

concatenate()
{
char str1[25],str2[25];
int i=0,j=0;
printf("\nEnter First String: ");
scanf("%s",str1);
printf("\nEnter Second String: ");
scanf("%s",str2);
while(str1[i]!='\0')
i++;
while(str2[j]!='\0')
{
str1[i]=str2[j];
j++;
i++;
}
str1[i]='\0';
printf("\nConcatenated String is %s\n",str1);
}

length()
{
char s[17], i;
printf("\nEnter a string: ");
scanf("%s", s);
for(i = 0; s[i] != '\0'; ++i);
printf("\nLength of string: %d\n", i);
return 0;
}

compare()
{
char a[100], b[100];
printf("\nEnter the first string: ");
scanf("%s",a);
printf("Enter the second string: ");
scanf("%s",b);
if (strcmp(a,b) == 0)

Page 45
printf("Entered strings are equal.\n");
else
printf("Entered strings are not equal.\n");
return 0;
}

Page 46
13 a) Write a C programming code to open a file and to print it
contents on screen.

#include<stdio.h>
main()
{
FILE *fp;
char ch;
fp=fopen("1c.c","r");
if(fp==NULL)
{
printf("\nCan't Open File\n");
exit(1);
}
do{
ch=getc(fp);
printf("%c",ch);
}while(ch!=EOF);
fclose(fp);
}

Page 47
13 b) Write a C program to copy files

#include<stdio.h>
main()
{
FILE *fp1,*fp2;
char ch;
fp1=fopen("1c.c","r");
fp2=fopen("oneC.c","w");
while(1)
{
ch=fgetc(fp1);
if(ch==EOF)
break;
else
putc(ch,fp2);
}
printf("\n File Copied Successfully\n ");
fclose(fp1);
fclose(fp2);
}

Page 48
Page 49
14 a) Write a C program merges two files and stores their contents
in another file.

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

int main()
{

FILE *fp1 = fopen("2a.c", "r");


FILE *fp2 = fopen("2b.c", "r");
FILE *fp3 = fopen("merge.txt", "w");
char c;
if (fp1 == NULL || fp2 == NULL || fp3 == NULL)
{
puts("Could not open files");
exit(0);
}
while ((c = fgetc(fp1)) != EOF)
fputc(c, fp3);
while ((c = fgetc(fp2)) != EOF)
fputc(c, fp3);
printf("\nMerged 2a.c and 2b.c into merge.txt\n");
fclose(fp1);
fclose(fp2);
fclose(fp3);
return 0;
}

Page 50
Page 51
14 b) Write a C program to delete a file.

#include<stdio.h>

main()
{
int status;
char file_name[25];
printf("\nEnter the name of file you wish to delete: ");
scanf("%s",file_name);
status = remove(file_name);
if( status == 0 )
printf("%s file deleted successfully.\n",file_name);
else
{
printf("Unable to delete the file\n");
perror("Error");
}

return 0;
}

Page 52

You might also like