SWARNANDHRA
COLLEGE OF ENGINEERING & TECHNOLOGY
(AUTONOMOUS)
NARSAPUR – 534 280
COMPUTER PROGRAMMING LABORATORY
***RECORD***
Submitted by
Name :
Reg. No. : 24A21A
Course/Branch/Section : B.Tech. / /’ ’
Semester : I SEM
Year : 2024-2025
Submitted to
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
COMPUTER PROGRAMMING LABORATORY
(Subject Code: 23CS1L01)
*** LAB RECORD ***
Reg. NO. :24A21A
DEPT. OF COMPUTER SCIENCE AND ENGINEERING
SWARNANDHRA
COLLEGE OF ENGINEERING & TECHNOLOGY
(AUTONOMOUS)
2024-2025
SWARNANDHRA
COLLEGE OF ENGINEERING & TECHNOLOGY
(AUTONOMOUS)
Narsapur – 534 280
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
BONAFIDE CERTIFICATE
Certify that this is the record of practical work done by
Mr./Ms. a student of I B.Tech/ /I Semester
with Reg. No. 24A21A in the Computer Programming laboratory during the
year 2024 - 2025.
No. of Exercises Conducted : 14 No. of Exercises Attended : /14
Faculty In-Charge Head of the Department
Submitted for practical examination held on ……………
Internal Examiner External Examiner
POINTER
EXERCISE FACULTY
NAME OF THE EXPERIMENT PAGE DATE
No. Sign.
No.
I Familiarization with programming environment
II Problem-solving using Algorithms and Flow
charts.
III Variable types and type conversions:
IV Operators and the precedence and as associativity
V Branching and logical expressions
VI Loops, while and for loops
VII 1D Array manipulation, linear search
VIII 2 D arrays, sorting and Strings
IX Pointers, structures and dynamic memory
allocation
Bitfields, Self-Referential Structures, Linked lists
X
XI Functions, call by value, scope and extent
XII Recursion, the structure of recursive calls
XIII Call by reference, dangling pointers
XIV File handling
XV Add on programs
SYSTEM REQUIREMENTS
SOFTWARE :
Operating System : Windows 7/ Windows 10
Coding Application : Turbo C or Falcon C /C++
HARDWARE : Desktop/Laptop Computer
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
WEEK 1 Objective: Getting familiar with the programming environment on
the computer and writing the first program.
i) Basic Linux environment and its editors like Vi, Vim & Emacs etc.
Vi:
The default editor that comes with the UNIX operating system is
called vi (visual editor). Using vi editor, we can edit an existing file or create a
new file from scratch. we can also use this editor to just read a text file. To open
vi editors, we just need to type the command mentioned below.
vi [file_name]
Here, [file_name] = this is the file name we want to create or to open the pre-
existing file.
Creating a new file with `file_name` = scet
vi scet
Modes of Operation in the vi editor
There are three modes of operation in vi:
Command Mode:
When vi starts up, it is in Command Mode. This mode is where vi interprets
any characters we type as commands and thus does not display them in the
window. This mode allows us to move through a file, and delete, copy, or paste
a piece of text. Enter into Command Mode from any other mode, requires
pressing the [Esc] key. If we press [Esc] when we are already in Command
Mode, then vi will beep or flash the screen.
Insert mode:
This mode enables you to insert text into the file. Everything that’s typed in this
mode is interpreted as input and finally, it is put in the file. The vi always starts
in command mode. To enter text, you must be in insert mode. To come in insert
mode, you simply type i. To get out of insert mode, press the Esc key, which
will put you back into command mode.
Last Line Mode (Escape Mode):
Line Mode is invoked by typing a colon [:], while vi is in Command Mode. The
cursor will jump to the last line of the screen and vi will wait for a command.
This mode enables you to perform tasks such as saving files and executing
commands.
Vim:
Vim is an advanced and highly configurable text editor built to enable efficient
text editing. Vim text editor is developed by Bram Moolenaar. It supports most
file types and vim editor is also known as a programmer’s editor. We can use its
plugin based on our needs.
To open vim editors, we just need to type the command mentioned below.
vim [file_name]
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 1
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
Here, [file_name] = this is the file name we want to create or to open the pre-
existing file.
Emacs:
The Emacs is referred to a family of editors, which means it has many versions
or flavors or iterations. The most commonly used version of Emacs editor is
GNU Emacs and was created by Richard Stallman. The main difference
between text editors like vi, vim, nano, and the Emacs is that is faster, powerful,
and simple in terms of usage because of its simple user interface. Unlike the vi
editor, the Emacs editor does not use an insert mode, and it is by default in
editing mode, i.e., whatever you type will directly be written to the buffer,
unless you manually enter command mode by using keyboard shortcuts.
To open vim editors, we just need to type the command mentioned below.
emacs [file_name]
Here, [file_name] = this is the file name we want to create or to open the pre-
existing file.
ii) Exposure to Turbo C, gcc
Turbo C:
Turbo C was a software development tool for writing programs in the C language.
As an IDE, it included a source code editor, a fast compiler, a linker and an
offline help file for reference. Version 2 included a built-in debugger. Turbo C
was a follow-up product to Borland’s Turbo Pascal, which had gained
widespread use in educational institutions because the Pascal language was suited
for teaching programming to students. Although Turbo C was initially developed
by a different company, it shared a lot of features with Turbo Pascal, namely, the
look-and-feel of the interface and the various programming and debugging tools
included. However, it was not as successful as Turbo Pascal because of
competition from other C products such as Microsoft C, Watcom C, Lattice C,
etc. Nevertheless, Turbo C still had the advantage in compile speed and price.
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 2
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
gcc:
GNU Compiler Collection, commonly known as GCC, is one of the most popular
compilers for programming languages like C, C++, and Fortran. It's the default
compiler for many Linux distributions and is also available for macOS and
Windows.
Is open-source and freely available under the GNU General Public License
(GPL). This can be executed by following syntax:
gcc -o output_file source_file.c
Let us consider we have a file hello.c which consists of the following code:
#include <stdio.h>
main ()
{
printf ("Hello, world!");
return 0;
}
example:
gcc -o hello hello.c
The resulting executable ‘hello’ now uses the new main function to produce the
following output:
$ ./hello
Hello, everyone!
iii) Writing simple programs using printf(), scanf()
Program:
#include<stdio.h>
main()
{
int a,b,c;
printf("Enter a,b:\n");
scanf("%d%d",&a,&b);
c=a+b;
printf("sum= %d",c);
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 3
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
WEEK 2 Objective: Getting familiar with how to formally describe a
solution to a problem in a series of finite steps both using textual notation
and graphic notation.
i) Sum and average of 3 numbers
Algorithm: Flow chart:
step 1 start
step 2 Read x,y,z
step 3 compute sum = x + y + z
step 4 compute avg = sum/3
step 5 print sum
step 6 print avg
step 7 stop
Program:
#include<stdio.h>
main()
{
int x,y,z,avg,sum;
printf(“Enter input for X, Y, Z : ”);
scanf(“%d%d%d”,&x,&y,&z);
sum= x+y+z;
avg= sum/3;
printf(“Sum of three given numbers is: %d”,sum);
printf(“Average of three given numbers is: %d”,avg);
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 4
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
ii) Conversion of Fahrenheit to Celsius and vice versa
Flowchart:
Algorithm :
Step-1 Start
Step-2 Input temperature in Celsius say C
Step-3 F = (9.0/5.0 x C) + 32
Step-4 Display Temperature in Fahrenheit F
Step-5 Input temperature in Fahrenheit Say F
Step-6 C = (F-32)/9*5;
Step-7 Display Temperature in Celsius C
Step-8 Stop
Program:
#include <stdio.h>
main()
{
float fh,cs;
int ch;
printf("\n1. Convert Fahrenheit to celsius");
printf("\n2. Convert celsius to fahrenheit");
printf("\nEnter choice 1 or 2: ");
scanf("%d",&ch);
if(ch==1)
{
printf("\nEnter temperature in fahrenheit");
scanf("%f",&fh);
cs=(fh-32)/1.8;
printf("Temperature in celsius is %.2f",cs);
}
else if(ch==2)
{
printf("\nEnter temperature in celsius");
scanf("%f",&cs);
fh=1.8*cs+32;
printf("Temperature in fahrenheit is %.2f",fh);
}
else
{
printf("Invalid choice");
}
}
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 5
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
Output:
iii) Simple interest calculation
Algorithm: Flow chart:
Step 1:start.
Step 2: Input value of P,N,R
Step 3: SI = (P*N*R)/100
Step 4: Display SI
Step 5: Stop
Program:
#include<stdio.h>
main()
{
int p,n;
float r,si;
printf("Enter Principal Amount\n");
scanf("%d",&p);
printf("Enter No of Years\n");
scanf("%d",&n);
printf("Enter Rate Of Interest\n");
scanf("%f",&r);
si=p*n*r/100;
printf("\n Simple Interest is %f",si);
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 6
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
WEEK 3 Objective: Learn how to define variables with the desired data-
type, initialize them with appropriate values and how arithmetic operators
can be used with variables and constants.
i) Finding the square root of a given number
Program:
#include <math.h>
#include <stdio.h>
main()
{
int n;
float num;
printf("Enter a number: ");
scanf("%d", &n);
num = sqrt(n);
printf("Square root of %d = %.2f", n,num);
return 0;
}
Output:
ii) Finding compound interest
Program:
#include <stdio.h>
#include <math.h>
main()
{
float p, r, t, ci;
printf("Enter the principle :");
scanf("%f", &p);
printf("\n Enter the rate :");
scanf("%f", &r);
printf("\n Enter the time :");
scanf("%f", &t);
ci = p * pow((1 + r / 100), t) ;
printf("\n The compound interest is %.2f", ci);
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 7
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
iii) Area of a triangle using heron’s formulae
Program:
#include<stdio.h>
#include <math.h>
main()
{
int a,b,c; float
area,s;
printf("\n Enter sides of a triangle\n");
scanf("%d%d%d",&a,&b,&c);
s=(float)(a+b+c)/2;
area=sqrt(s*(s-a)*(s-b)*(s-c));
printf("Area of a triangle is %.2f",area);
}
Output:
iv) Distance travelled by an object
Program:
#include<stdio.h>
int main()
{
float u, a, d;
int t;
printf("\nEnter acceleration : ");
scanf("%f", & a);
printf("\nEnter initial velocity : ");
scanf("%f", & u);
printf("\nEnter time : ");
scanf("%d", & t);
d = (u * t) + (a * t * t) / 2;
printf("\n The Distance : %.2f", d);
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 8
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
WEEK 4 Objective: Explore the full scope of expressions, type-compatibility
of variables & constants and operators used in the expression and how
operator precedence works.
i) Evaluate the following expressions.
a. A+B*C+(D*E) + F*G
b. A/B*C-B+A*D/3
c. A+++B---A
d. J= (i++) + (++i)
Program:
#include<stdio.h>
main()
{
int a,b,c,d,e,f,g,y,z,j,i,ans;
printf("Enter the value of a,b,c,d,e,f,g:");
scanf("\n%d\n%d\n%d\n%d\n%d\n%d\n%d",&a,&b,&c,&d,&e,&f,&g);
ans=a+b+c+(d*e)+f*g;
printf("Answer is:%d",ans);
y=a/b*(-b*d/3);
printf("\ny=%d",y);
z=a+++b---a;
printf("\nz=%d",z);
j=(i++)+(++i);
printf("\nj=%d",z);
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 9
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
ii) Find the maximum of three numbers using conditional operator
Program:
#include <stdio.h>
main()
{
int a,b,c,max;
printf("Enter 3 numbers\n");
scanf("%d%d%d",&a,&b,&c);
max=(a>b && a>c)?a:((b>c)?b:c);
printf("%d is big",max);
}
Output:
iii) Take marks of 5 subjects in integers, and find the total, average in float
Program:
#include <stdio.h>
main()
{
int eng, phy, chem, math, comp;
float total, average;
printf("Enter marks of five subjects: :- ");
scanf("%d%d%d%d%d", &eng, &phy, &chem, &math, &comp);
total = eng + phy + chem + math + comp;
average = total / 5;
printf("Total marks = %.2f\n", total);
printf("Average marks = %.2f\n", average);
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 10
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
WEEK 5 Objective: Explore the full scope of different variants of “if
construct” namely if-else, nullelse, if-else if*-else, switch and nested-if
including in what scenario each one of them can be used and how to use
them. Explore all relational and logical operators while writing conditionals
for “if construct”.
i) Write a C program to find the max and min of four numbers using if-else.
Program:
#include <stdio.h>
main()
{
int a,b,c,d;
printf(" enter 4 values");
scanf("%d%d%d%d",&a,&b,&c,&d);
if(a>b && a>c && a>d)
printf("max= %d",a);
else if (b>a && b>c && b>d)
printf("max= %d",b);
else if (c>a && c>b && c>d)
printf("max= %d",c);
else
printf("max= %d",d);
if(a<b && a<c && a<d)
printf("\n min= %d",a);
else if (b<a && b<c && b<d)
printf("\n min= %d",b);
else if (c<a && c<b && c<d)
printf("\n min= %d",c);
else
printf("\n min= %d",d);
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 11
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
ii) Write a C program to generate electricity bill.
Program definition:
For first 50 units Rs. 0.50/unit
For next 100 units Rs. 0.75/unit
For next 100 units Rs. 1.20/unit
For unit above 250 Rs. 1.50/unit
An additional surcharge of 20% is added to the bill.
Program:
#include <stdio.h>
int main()
{
int unit;
float amt, total_amt, sur_charge;
printf("Enter total units consumed: ");
scanf("%d", &unit);
if(unit <= 50)
{
amt = unit * 0.50;
}
else if(unit <= 150)
{
amt = 25 + ((unit-50) * 0.75);
}
else if(unit <= 250)
{
amt = 100 + ((unit-150) * 1.20);
}
else
{
amt = 220 + ((unit-250) * 1.50);
}
sur_charge = amt * 0.20;
total_amt = amt + sur_charge;
printf("Electricity Bill = Rs. %.2f", total_amt);
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 12
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
iii) Find the roots of the quadratic equation.
Program:
#include <stdio.h>
#include <math.h>
main()
{
int a,b,c,d;
float x1,x2;
printf("Input the value of a,b & c : ");
scanf("%d%d%d",&a,&b,&c);
d=b*b-4*a*c;
if(d==0)
{
printf("Both roots are equal.\n");
x1=-b/(2.0*a);
x2=x1;
printf("First Root Root1= %f\n",x1);
printf("Second Root Root2= %f\n",x2);
}
else if(d>0)
{
printf("Both roots are real and diff-2\n");
x1=(-b+sqrt(d))/(2*a);
x2=(-b-sqrt(d))/(2*a);
printf("First Root Root1= %f\n",x1);
printf("Second Root root2= %f\n",x2);
}
else
printf("Root are imeainary;\nNo Solution. \n");
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 13
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
iv) Write a C program to simulate a calculator using switch case.
Program:
#include<stdio.h>
main()
{
int a,b; char ch;
printf("\n enter 2 numbers:");
scanf("%d%d",&a,&b);
printf("\n +.add\t-.subtract\t*.multiplication\t/.division\n");
ch=getche();
switch(ch)
{
case '+':
printf("\n addition=%d",(a+b));
break;
case '-':
printf("\n subtraction=%d",(a-b));
break;
case '*':
printf("\n multiply=%d",(a*b));
break;
case '/':
printf("\n divide=%d",(a/b));
break;
default: printf("\ninvalid choice");
}
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 14
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
v) Write a C program to find the given year is a leap year or not.
Program:
#include <stdio.h>
main()
{
int year;
printf("Enter a year: ");
scanf("%d", &year);
if (year % 400 == 0)
{
printf("%d is a leap year.", year);
}
else if (year % 100 == 0)
{
printf("%d is not a leap year.", year);
}
else if (year % 4 == 0)
{
printf("%d is a leap year.", year);
}
else
{
printf("%d is not a leap year.", year);
}
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 15
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
WEEK 6 Objective: Explore the full scope of iterative constructs namely
while loop, do-while loop and for loop in addition to structured jump
constructs like break and continue including when each of these statements
is more appropriate to use.
i) Find the factorial of given number using any loop.
Program:
#include<stdio.h>
main()
{
int i,fact=1,number;
printf("Enter a number: ");
scanf("%d",&number);
for(i=1;i<=number;i++)
{
fact=fact*i;
}
printf("Factorial of %d is: %d",number,fact);
}
Output:
ii) Find the given number is a prime or not.
Program:
#include<stdio.h>
main()
{
int i,n,c=0;
printf("Enter n\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
if(n%i==0)
{
c=c+1;
}
}
if(c==2)
{
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 16
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
printf("\n%d is prime",n);
}
else
{
printf("\n%d isnot prime",n);
}
}
Output:
iii) Compute sine and cos series
Program:
/*sin x = x - x3/3! + x5/5! - x7/7! + ……*/
#include <stdio.h>
main()
{
int i, j, n, fact, sign = - 1; float x, p, sum = 0;
printf("Enter the value of x : ");
scanf("%f", &x);
printf("Enter the value of n : ");
scanf("%d", &n);
for (i = 1; i <= n; i += 2)
{
p = 1;
fact = 1;
for (j = 1; j <= i; j++)
{
p = p * x;
fact = fact * j;
}
sign = - 1 * sign;
sum += sign * p / fact;
}
printf("sin %0.2f = %f", x, sum);
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 17
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
/*cos x = 1 - x2/2! + x4/4! - x6/6! + ……*/
#include <stdio.h>
int main()
{
int i, j, n, fact, sign = - 1;
float x, p, sum = 0;
printf("Enter the value of x : ");
scanf("%f", &x); printf("Enter the value of n : ");
scanf("%d", &n);
for (i = 2; i <= n; i += 2)
{
p = 1;
fact = 1;
for (j = 1; j <= i; j++)
{
p = p * x;
fact = fact * j;
}
sum += sign * p / fact;
sign = - 1 * sign;
}
printf("cos %0.2f = %f", x, 1+sum);
}
iv) Checking a number palindrome
Program:
#include <stdio.h>
main()
{
int n, reversed = 0, remainder, original;
printf("Enter an integer: ");
scanf("%d", &n);
original = n;
while (n != 0)
{
remainder = n % 10;
reversed = reversed * 10 + remainder;
n /= 10;
}
if (original == reversed)
printf("%d is a palindrome.", original);
else
printf("%d is not a palindrome.", original);
}
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 18
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
Output:
v) Construct a pyramid of numbers.
Program:
#include <stdio.h>
int main()
{
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i)
{
for (j = 1; j <= i; ++j)
{
printf("%d ", j);
}
printf("\n");
}
return 0;
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 19
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
WEEK 7: Objective: Explore the full scope of Arrays construct namely
defining and initializing 1-D and 2-D and more generically n-D arrays and
referencing individual array elements from the defined array. Using integer
1-D arrays, explore search solution linear search.
i) Find the min and max of a 1-D integer array.
Program:
#include <stdio.h>
#include <conio.h>
int main()
{
int a[1000],i,n,min,max;
printf("Enter size of the array : ");
scanf("%d",&n);
printf("Enter elements in array : ");
for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
}
min=max=a[0];
for(i=1; i<n; i++)
{
if(min>a[i])
min=a[i];
if(max<a[i])
max=a[i];
}
printf("minimum of array is : %d",min);
printf("\nmaximum of array is : %d",max);
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 20
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
ii) Perform linear search on 1D array.
Program:
#include <stdio.h>
int main()
{
int array[100], search, c, number;
printf("Enter the number of elements in array\n");
scanf("%d",&number);
printf("Enter %d numbers\n", number);
for ( c = 0 ; c < number ; c++ )
scanf("%d",&array[c]);
printf("Enter the number to search\n");
scanf("%d",&search);
for ( c = 0 ; c < number ; c++ )
{
if ( array[c] == search )
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if ( c == number )
printf("%d is not present in array.\n", search);
return 0;
}
Output:
iii) The reverse of a 1D integer array
Program:
include <stdio.h>
#define N 1000
int main() {
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 21
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
int i,arr[N];
int n;
printf("Enter the size of the array: ");
scanf("%d", &n);
printf("Enter an array: ");
for (i=0;i<n;i++)
{
scanf("%d", &arr[i]);
}
printf("Reversed array: ");
for (i = n-1; i>=0; i--){
printf("%d ", arr[i]);
}
}
Output:
iv) Find 2’s complement of the given binary number.
Program:
#include<stdio.h>
main()
{
int a[10],i,n;
printf("Enter no of bits \n");
scanf("%d",&n);
printf("Enter binary numbers \n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
{
if(a[i]==0)
a[i]=1;
else
a[i]=0;
}
for(i=n-1;i>=0;i--)
{
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 22
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
if(a[i]==0)
{
a[i]=1;
break;
}
else
{
a[i]=0;
if(a[i-1]==0)
{
a[i-1]=1;
break;
}
}
}
printf("The complement form is \n");
for(i=0;i<n;i++)
printf("%d",a[i]);
}
Output:
v) Eliminate duplicate elements in an array.
Program:
#include<stdio.h>
#include<stdlib.h>
main()
{
int a[50],i,j,k, count = 0, dup[50], number;
printf("Enter size of the array");
scanf("%d",&number);
printf("Enter Elements of the array:");
for(i=0;i<number;i++)
{
scanf("%d",&a[i]);
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 23
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
dup[i] = -1;
}
printf("Entered element are: ");
for(i=0;i<number;i++)
{
printf("%d ",a[i]);
}
for(i=0;i<number;i++)
{
for(j = i+1; j < number; j++)
{
if(a[i] == a[j])
{
for(k = j; k <number; k++)
{
a[k] = a[k+1];
}
j--;
number--;
}
}
}
printf("After deleting the duplicate element the Array is:");
for(i=0;i<number;i++)
{
printf("%d ",a[i]);
}
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 24
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
WEEK 8: Objective: Explore the difference between other arrays and
character arrays that can be used as Strings by using null character and get
comfortable with string by doing experiments that will reverse a string and
concatenate two strings. Explore sorting solution bubble sort using integer
arrays.
i) Addition of two matrices
Program:
#include<stdio.h>
main()
{
int a[10][10],b[10][10],c[10][10],r1,r2,c1,c2,i,j;
printf("enter size of the matrix of a \n");
scanf("%d%d",&r1,&c1);
printf("enter size of the matrix of b \n");
scanf("%d%d",&r2,&c2);
printf("enter matrix a element \n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter matrix b element \n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf("matrix a \n");
for(i=0;i<r1;i++)
{
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 25
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
for(j=0;j<c1;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
printf("matrix b \n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
printf("%d\t",b[i][j]);
}
printf("\n");
}
printf("matrix c \n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 26
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
ii) Multiplication two matrices
Program:
#include<stdio.h>
main()
{
int a[10][10],b[10][10],c[10][10],r1,r2,c1,c2,i,j,k;
printf("enter size of the matrix of a \n");
scanf("%d%d",&r1,&c1);
printf("enter size of the matrix of b \n");
scanf("%d%d",&r2,&c2);
if(c1==r2)
{
printf("enter matrix a element \n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter matrix b element \n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
c[i][j]=0;
for(k=0;k<c1;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
printf("matrix a \n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 27
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
printf("%d\t",a[i][j]);
}
printf("\n");
}
printf("matrix b \n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
printf("%d\t",b[i][j]);
}
printf("\n");
}
printf("matrix c \n");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
}
else
{
printf("matrix multiplication is not possible\n");
}
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 28
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
iii) Sort array elements using bubble sort
Program:
#include <stdio.h>
int main()
{
int arr[50], num, x, y, temp;
printf("Please Enter the Number of Elements you want in the array: ");
scanf("%d", &num);
printf("Please Enter the Value of Elements: ");
for(x = 0; x < num; x++)
scanf("%d", &arr[x]);
for(x = 0; x < num - 1; x++){
for(y = 0; y < num - x - 1; y++){
if(arr[y] > arr[y + 1]){
temp = arr[y];
arr[y] = arr[y + 1];
arr[y + 1] = temp;
}
}
}
printf("Array after implementing bubble sort: ");
for(x = 0; x < num; x++){
printf("%d ", arr[x]);
}
return 0;
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 29
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
iv) Concatenate two strings without built-in functions
Program:
#include<stdio.h>
main()
{
char str1[25],str2[25];
int i=0,j=0;
printf("\nEnter First String:");
gets(str1);
printf("\nEnter Second String:");
gets(str2);
while(str1[i]!='\0')
i++;
while(str2[j]!='\0')
{
str1[i]=str2[j];
j++;
i++;
}
str1[i]='\0';
printf("\nConcatenated String is %s",str1);
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 30
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
v) Reverse a string using built-in and without built-in string functions
Program:
/*Reverse a string using built in function*/
#include<stdio.h>
#include<string.h>
main( )
{
char s1[30];
printf("Enter string\n");
gets(s1);
printf("Given String =%s",s1);
strrev(s1);
printf("\n Given string after string reverse %s ",s1);
}
Output:
/*Without using strrev() function*/
#include <stdio.h>
#include <string.h>
main()
{
char string[20],temp;
int i,length;
printf("Enter String : ");
scanf("%s",string);
length=strlen(string)-1;
for(i=0;i<strlen(string)/2;i++){
temp=string[i];
string[i]=string[length];
string[length--]=temp;
}
printf("Reverse string :%s",string);
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 31
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
WEEK 9: Objective: Explore pointers to manage a dynamic array of
integers, including memory allocation & value initialization, resizing
changing and reordering the contents of an array and memory de-allocation
using malloc (), calloc (), realloc () and free () functions. Gain experience
processing command-line arguments received by C
i) Write a C program to find the sum of a 1D array using malloc()
Program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements: ");
for(i = 0; i < n; ++i) {
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
}
Output:
ii) Write a C program to find the total, average of n students using
structures
Program:
#include <stdio.h>
int i;
struct Student {
char name[50];
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 32
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
int marks;
};
int main()
{
int n;
printf("Enter the number of students: ");
scanf("%d", &n);
struct Student students[n];
for (i= 0; i < n; i++)
{
printf("Enter name of student %d: ", i + 1);
scanf("%s", students[i].name);
printf("Enter marks of student %d: ", i + 1);
scanf("%d", &students[i].marks);
}
int totalMarks = 0;
for (i = 0; i < n; i++)
{
totalMarks += students[i].marks;
}
float averageMarks = (float)totalMarks / n;
printf("\nTotal marks: %d\n", totalMarks);
printf("Average marks: %.2f\n", averageMarks);
}
Output:
iii) Enter n students data using calloc() and display failed students list
Program:
#include <stdio.h>
#include <stdlib.h>
struct Student
{
char name[50];
float marks;
};
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 33
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
int main()
{
int n;
printf("Enter the number of students: ");
scanf("%d", &n);
struct Student *students = (struct Student *)calloc(n, sizeof(struct Student));
if (students == NULL)
{
printf("Memory allocation failed.\n");
return 1;
}
for (int i = 0; i < n; ++i)
{
printf("\nEnter details for student %d:\n", i + 1);
printf("Name: ");
scanf("%s", students[i].name);
printf("Marks: ");
scanf("%f", &students[i].marks);
}
printf("\nList of failed students:\n");
for (int i = 0; i < n; ++i)
{
if (students[i].marks < 40)
{
printf("Name: %s\nMarks: %.2f\n\n", students[i].name, students[i].marks);
}
}
free(students);
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 34
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
iv) Read student name and marks from the command line and display the
student details along with the total.
Program:
#include <stdio.h>
int main() {
char name[50];
int rollNumber;
int marks[5];
int total = 0;
printf("Enter student name: ");
scanf("%s", name);
printf("Enter roll number: ");
scanf("%d", &rollNumber);
printf("Enter marks for 5 subjects:\n");
for (int i = 0; i < 5; ++i) {
printf("Subject %d: ", i + 1);
scanf("%d", &marks[i]);
total += marks[i];
}
float average = (float)total / 5;
printf("\nStudent Details:\n");
printf("Name: %s\n", name);
printf("Roll Number: %d\n", rollNumber);
printf("Total Marks: %d\n", total);
printf("Average Marks: %.2f\n", average);
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 35
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
v) Write a C program to implement realloc()
Program:
#include <stdio.h>
#include <stdlib.h>
int i;
int main() {
int *arr;
int initialSize, newSize;
printf("Enter the initial size of the array: ");
scanf("%d", &initialSize);
arr = (int *)malloc(initialSize * sizeof(int));
if (arr == NULL)
{
fprintf(stderr, "Memory allocation failed\n");
return 1;
}
printf("Enter %d elements for the initial array:\n", initialSize);
for (i = 0; i < initialSize; i++)
{
scanf("%d", &arr[i]);
}
printf("\nOriginal Array: ");
for (i = 0; i < initialSize; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
printf("\nEnter the new size of the array: ");
scanf("%d", &newSize);
arr = (int *)realloc(arr, newSize * sizeof(int));
if (arr == NULL)
{
fprintf(stderr, "Memory reallocation failed\n");
return 1;
}
printf("Enter %d elements for the resized array:\n", newSize);
for (i = initialSize; i < newSize; i++) {
scanf("%d", &arr[i]);
}
printf("\nResized Array: ");
for (i = 0; i < newSize; i++) {
printf("%d ", arr[i]);
}
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 36
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
printf("\n");
free(arr);
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 37
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
WEEK 10: Objective: Experiment with C Structures, Unions, bit fields and
self-referential structures (Singly linked lists) and nested structures
i) Create and display a singly linked list using self-referential structure.
Program:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
int main()
{
struct node *head = NULL;
struct node *second = NULL;
struct node *third = NULL;
head = (struct node*)malloc(sizeof(struct node));
second = (struct node*)malloc(sizeof(struct node));
third = (struct node*)malloc(sizeof(struct node));
head->data = 1;
second->data = 2;
third->data = 3;
head->next = second;
second->next = third;
third->next = NULL;
struct node *current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 38
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
ii) Demonstrate the differences between structures and unions using a C
program.
/*A simple C program showing differences between Structure and Union */
#include <stdio.h>
#include <string.h>
// declaring structure
struct struct_example {
int integer;
float decimal;
char name[20];
};
// declaraing union
union union_example {
int integer;
float decimal;
char name[20];
};
void main() {
// creating variable for structure and initializing values difference six
struct struct_example stru ={5, 15, "John"};
// creating variable for union and initializing values
union union_example uni = {5, 15, "John"};
printf("data of structure:\n integer: %d\n decimal: %.2f\n name: %s\n",
stru.integer, stru.decimal, stru.name);
printf("\ndata of union:\n integer: %d\n" "decimal: %.2f\n name: %s\n",
uni.integer, uni.decimal, uni.name);
// difference five
printf("\nAccessing all members at a time:");
stru.integer = 163;
stru.decimal = 75;
strcpy(stru.name, "John");
printf("\ndata of structure:\n integer: %d\n " "decimal: %f\n name: %s\n",
stru.integer, stru.decimal, stru.name);
uni.integer = 163;
uni.decimal = 75;
strcpy(uni.name, "John");
printf("\ndata of union:\n integeer: %d\n " "decimal: %f\n name: %s\n",
uni.integer, uni.decimal, uni.name);
printf("\nAccessing one member at a time:");
printf("\ndata of structure:");
stru.integer = 140;
stru.decimal = 150;
strcpy(stru.name, "Mike");
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 39
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
printf("\ninteger: %d", stru.integer);
printf("\ndecimal: %f", stru.decimal);
printf("\nname: %s", stru.name);
printf("\ndata of union:");
uni.integer = 140;
uni.decimal = 150;
strcpy(uni.name, "Mike");
printf("\ninteger: %d", uni.integer);
printf("\ndecimal: %f", uni.decimal);
printf("\nname: %s", uni.name);
//difference four
printf("\nAltering a member value:\n");
stru.integer = 512;
printf("data of structure:\n integer: %d\n decimal: %.2f\n name: %s\n",
stru.integer, stru.decimal, stru.name);
uni.integer = 512;
printf("data of union:\n integer: %d\n decimal: %.2f\n name: %s\n", uni.integer,
uni.decimal,uni.name);
// difference two and three
printf("\nsizeof structure: %d\n", sizeof(stru));
printf("sizeof union: %d\n", sizeof(uni));
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 40
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
iii) Write a C program to shift/rotate using bitfields.
Program:
#include<stdio.h>
#include<stdlib.h>
int main(){
int number, rotate, Msb, size;
printf("Enter any number:");
scanf("%d",&number);
printf("Enter number of rotations:");
scanf("%d",&rotate);
size = sizeof(int) * 8;
rotate %= size;
while(rotate--){
Msb = (number >> size) & 1;
number = (number << 1) | Msb;
}
printf("After Left rotation the value is = %d",number);
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 41
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
iv) Write a C program to copy one structure variable to another structure of
the same type.
Program:
#include<stdio.h>
#include<stdlib.h>
int main(){
int number,rotate, Lsb, size;
printf("Enter any number:");
scanf("%d",&number);
printf("Enter number of rotations:");
scanf("%d",&rotate);
size = sizeof(int) * 8;
rotate %= size;
while(rotate--){
Lsb = number & 1;
number = (number >> 1) &(~(1<<size));
number=number|(Lsb<<size);
}
printf("After right rotation the value is = %d",number);
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 42
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
WEEK 11: Objective: Explore the Functions, sub-routines, scope and extent
of variables, doing some experiments by parameter passing using call by
value. Basic methods of numerical integration
i) Write a C function to calculate NCR value.
Program:
#include <stdio.h>
int factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}
int nCr(int n, int r) {
if (r > n || n < 0 || r < 0)
{
return 0;
}
return factorial(n) / (factorial(r) * factorial(n - r));
}
int main() {
int n, r;
printf("Enter the value of n: ");
scanf("%d", &n);
printf("Enter the value of r: ");
scanf("%d", &r);
printf("C(%d, %d) = %d\n", n, r, nCr(n, r));
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 43
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
ii) Write a C function to find the length of a string.
Program:
#include<stdio.h>
int str_len(char s[]);
main()
{
char s[30];
int result;
printf("enter string::");
gets(s);
result=str_len(s);
printf("string length=%d",result);
}
int str_len(char s[])
{
int i,length;
for(i=0;s[i]!='\0';i++);
return i;
}
Output:
iii) Write a C function to transpose of a matrix.
Program:
#include<stdio.h>
void transpose(int a[2][2]);
main()
{
int a[2][2],i,j;
printf("insert array elements:\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("insert value a[%d][%d]:",i,j);
scanf("%d",&a[i][j]);
}
}
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 44
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
transpose(a);
}
void transpose(int a[2][2])
{
int b[2][2],i,j;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
b[i][j]=a[j][i];
}
}
printf("*** transpose matrix ***\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d\t",b[i][j]);
}
printf("\n");
}
}
Output:
iv) Write a C function to demonstrate numerical integration of differential
equations using Euler’s method
Program:
#include<stdio.h>
float fun(float x,float y)
{
float f;
f=x+y;
return f;
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 45
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
}
main()
{
float a,b,x,y,h,t,k;
printf("\nEnter x0,y0,h,xn: ");
scanf("%f%f%f%f",&a,&b,&h,&t);
x=a;
y=b;
printf("\n x\t y\n");
while(x<=t)
{
k=h*fun(x,y);
y=y+k;
x=x+h;
printf("%0.3f\t%0.3f\n",x,y);
}
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 46
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
WEEK 12: Objective: Explore how recursive solutions can be programmed
by writing recursive functions that can be invoked from the main by
programming at-least five distinct problems that have naturally recursive
solutions.
i) Write a recursive function to generate Fibonacci series.
Program
/* Fibonacci using Recursion*/
#include<stdio.h>
int fib(int); void main()
{
int i,n;
printf("enter range");
scanf("%d",&n);
printf("fibonacci series is \n");
for(i=0;i<n;i++)
{
printf("\n %d",fib(i));
}
int fib(int x)
{
if(x<=1) return x; else
return fib(x-2)+fib(x-1);
}
Output
ii) Write a recursive function to find the lcm of two numbers.
Program:
#include <stdio.h>
int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 47
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
int main() {
int num1, num2;
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
printf("LCM of %d and %d is: %d\n", num1, num2, lcm(num1, num2));
}
Output:
iii) Write a recursive function to find the factorial of a number.
Program:
#include<stdio.h>
long fact(int);
void main()
{
int n;
long f;
printf("enter n\n");
scanf("%d",&n);
f=fact(n);
printf("factorial is %ld",f);
}
long fact(int x)
{
if(x==0)
return 1;
else
return x*fact(x-1);
}
Output
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 48
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
iv) Write a C Program to implement Ackermann function using recursion.
Program:
#include <stdio.h>
int ackermann(int m, int n);
int main() {
int m, n, result;
printf("Enter values for m and n (separated by space): ");
scanf("%d %d", &m, &n);
result = ackermann(m, n);
printf("Ackermann(%d, %d) = %d\n", m, n, result);
}
int ackermann(int m, int n) {
if (m == 0) {
return n + 1;
}
else if (m > 0 && n == 0)
{
return ackermann(m - 1, 1);
}
else
{
return ackermann(m - 1, ackermann(m, n - 1));
}
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 49
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
v) Write a recursive function to find the sum of series.
Program:
#include <stdio.h>
double calculateSum(int n);
int main() {
int n;
printf("Enter the value of n: ");
scanf("%d", &n);
double result = calculateSum(n);
printf("Sum of the series: %.2f\n", result);
}
double calculateSum(int n) {
if (n == 0) {
return 0;
}
else {
return n + calculateSum(n - 1);
}
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 50
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
WEEK 13: Objective: Explore the basic difference between normal and
pointer variables, Arithmetic operations using pointers and passing
variables to functions using pointers
i) Write a C program to swap two numbers using call by reference.
Program:
#include <stdio.h>
swap (int *, int *);
int main()
{
int a, b;
printf("\nEnter value of a & b: ");
scanf("%d %d", &a, &b);
printf("\nBefore Swapping:\n");
printf("\na = %d\n\nb = %d\n", a, b);
swap(&a, &b);
printf("\nAfter Swapping:\n");
printf("\na = %d\n\nb = %d", a, b);
return 0;
}
swap (int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 51
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
ii) Demonstrate Dangling pointer problem using a C program.
Program:
#include <stdio.h>
#include <stdlib.h>
main()
{
int *ptr = (int *)malloc(sizeof(int));
if (ptr != NULL) {
printf("Enter a value: ");
scanf("%d", ptr);
printf("Value through valid pointer: %d\n", *ptr);
free(ptr);
printf("Value through dangling pointer: %d\n", *ptr);
}
}
Output:
iii) Write a C program to copy one string into another using pointer.
Program:
#include <stdio.h>
void copyString(char *destination, const char *source);
main()
{
char source[100], destination[100];
printf("Enter the source string: ");
scanf("%s", source);
copyString(destination, source);
printf("Source String: %s\n", source);
printf("Copied String: %s\n", destination);
}
void copyString(char *destination, const char *source)
{
while (*source != '\0') {
*destination = *source;
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 52
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
source++;
destination++;
}
*destination = '\0';
}
Output:
iv) Write a C program to find no of lowercase, uppercase, digits and other
characters using pointers.
Program:
#include <stdio.h>
void countCharacters(const char *str, int *lowercase, int *uppercase, int *digits,
int *others);
int main() {
char inputString[100];
printf("Enter a string: ");
fgets(inputString, sizeof(inputString), stdin);
int lowercaseCount = 0, uppercaseCount = 0, digitCount = 0, otherCount = 0;
countCharacters(inputString, &lowercaseCount, &uppercaseCount, &digitCount,
&otherCount);
printf("Lowercase characters: %d\n", lowercaseCount);
printf("Uppercase characters: %d\n", uppercaseCount);
printf("Digits: %d\n", digitCount);
printf("Other characters: %d\n", otherCount);
}
void countCharacters(const char *str, int *lowercase, int *uppercase, int *digits,
int *others)
{
while (*str != '\0') {
if (*str >= 'a' && *str <= 'z') {
(*lowercase)++;
}
else if (*str >= 'A' && *str <= 'Z')
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 53
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
{
(*uppercase)++;
}
else if (*str >= '0' && *str <= '9')
{
(*digits)++;
}
else
{
(*others)++;
}
str++;
}
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 54
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
WEEK14: Objective: To understand data files and file handling with
various file I/O functions. Explore the differences between text and binary
files.
i) Write a C program to write and read text into a file.
Program:
#include <stdio.h>
#include <stdlib.h>
main() {
FILE *file;
char text[100];
file = fopen("example.txt", "w");
if (file == NULL)
{
printf("Error opening the file.\n");
return 1;
}
printf("Enter text to write to the file: ");
fgets(text, sizeof(text), stdin);
fprintf(file, "%s", text);
fclose(file);
file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening the file for reading.\n");
return 1;
}
printf("\nContent of the file:\n");
while (fgets(text, sizeof(text), file) != NULL) {
printf("%s", text);
}
fclose(file);
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 55
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
ii) Write a C program to write and read text into a binary file using fread()
and fwrite()
Program:
#include<stdio.h>
struct student
{
int sno;
char sname [30];
float marks;
char temp;
};
main ( )
{
struct student s[60];
int i;
FILE *fp;
fp = fopen ("student1.txt", "w");
for (i=0; i<2; i++)
{
printf ("enter details of student %d", i+1);
printf("student number:");
scanf("%d",&s[i].sno);
scanf("%c",&s[i].temp);
printf("student name:");
gets(s[i].sname);
printf("student marks:");
scanf("%f",&s[i].marks);
fwrite(&s[i], sizeof(s[i]),1,fp);
}
fclose (fp);
fp = fopen ("student1.txt", "r");
for (i=0; i<2; i++)
{
printf ("details of student %d are", i+1);
fread (&s[i], sizeof (s[i]) ,1,fp);
printf("student number = %d ", s[i]. sno);
printf("student name = %s ", s[i]. sname);
printf("marks = %f ", s[i]. marks);
} fclose(fp);
getch( );
}
Output:
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 56
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
iii) Copy the contents of one file to another file.
Program:
#include<stdio.h>
main()
{
FILE *fp1, *fp2;
char file1[10], file2[10];
int ch;
printf("\n Enter source file name: ");
gets(file1);
printf("\n Enter target file name: ");
gets(file2);
fp1 = fopen(file1, "r");
if(fp1==NULL)
{
printf("\n File %s cannot be opened", file1);
}
else
{
fp2 = fopen(file2, "w");
printf("\n Copying started form %s to %s.....\n", file1, file2);
while((ch=getc(fp1))!=EOF)
{
putc(ch, fp2);
}
fclose(fp1);
fclose(fp2);
printf("\n Copying completed");
}
printf("\n After copying .....\n");
printf("\n Contents of the file %s :\n", file2);
fp2=fopen(file2, "r");
while((ch=getc(fp2))!=EOF)
printf("%c", ch);
fclose(fp2);
}
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 57
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
Output
iv) Write a C program to merge two files into the third file using command-
line arguments.
Program:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char * argv[])
{
FILE *fs1, *fs2, *ft;
char ch, file1[20], file2[20], file3[20];
if ( argc != 4 )
{
printf("There is no file names..\n");
exit(0);
}
fs1 = fopen(argv[1],"r");
fs2 = fopen(argv[2],"r");
if( fs1 == NULL || fs2 == NULL )
{
perror("Error ");
printf("Press any key to exit...\n");
exit(0);
exit(EXIT_FAILURE);
}
ft = fopen(argv[3],"w");
if( ft == NULL )
{
perror("Error ");
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 58
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
}
while( ( ch = fgetc(fs1) ) != EOF )
fputc(ch,ft);
while( ( ch = fgetc(fs2) ) != EOF )
fputc(ch,ft);
printf("Two files were merged into %s file successfully.\n",argv[3]);
fclose(fs1);
fclose(fs2);
fclose(ft);
return 0;
}
Output
C:\Users\My world\Documents>g++ exp14.c
C:\Users\My world\Documents>a abc.txt abc1.txt abc2.x
Two files were merged into abc2.x file successfully.
v) Find no. of lines, words and characters in a file
Program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * file;
char path[100];
char ch;
int characters, words, lines;
printf("Enter source file path: ");
scanf("%s", path);
file = fopen(path, "r");
if (file == NULL)
{
printf("\nUnable to open file.\n");
printf("Please check if file exists and you have read privilege.\n");
exit(EXIT_FAILURE);
}
characters = words = lines = 0;
while ((ch = fgetc(file)) != EOF)
{
characters++;
if (ch == '\n' || ch == '\0')
lines++;
if (ch == ' ' || ch == '\n' )
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 59
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
words++;
}
if (characters > 0)
{
words++;
lines++;
}
printf("\n");
printf("Total characters = %d\n", characters);
printf("Total words = %d\n", words);
printf("Total lines = %d\n", lines);
fclose(file);
}
Output
vi) Write a C program to print last n characters of a given file.
Program:
#include <stdio.h>
#include <stdlib.h>
void printLastNChars(FILE *file, int n) {
if (file == NULL) {
perror("Error opening the file");
exit(EXIT_FAILURE);
}
fseek(file, 0, SEEK_END);
long fileSize = ftell(file);
fseek(file, -n, SEEK_END);
char *lastNChars = (char *)malloc((n + 1) * sizeof(char));
fread(lastNChars, sizeof(char), n, file);
lastNChars[n] = '\0';
printf("Last %d characters of the file:\n%s\n", n, lastNChars);
free(lastNChars);
fclose(file);
}
int main() {
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 60
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
FILE *file;
char fileName[100];
int n;
printf("Enter the file name: ");
scanf("%s", fileName);
printf("Enter the number of characters to print: ");
scanf("%d", &n);
file = fopen(fileName, "r");
printLastNChars(file, n);
}
Output
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 61
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
ADD ON PROGRAMS
i.) Count frequency of each element.
Program:
#include <stdio.h>
int main()
{
int arr[10], FreqArr[10], i, j, Count, Size;
printf("\n Please Enter Number of elements in an array : ");
scanf("%d", &Size);
printf("\n Please Enter %d elements of an Array : ", Size);
for (i = 0; i < Size; i++)
{
scanf("%d", &arr[i]);
FreqArr[i] = -1;
}
for (i = 0; i < Size; i++)
{
Count = 1;
for(j = i + 1; j < Size; j++)
{
if(arr[i] == arr[j])
{
Count++;
FreqArr[j] = 0;
}
}
if(FreqArr[i] != 0)
{
FreqArr[i] = Count;
}
}
printf("\n Frequency of All the Elements in this Array are : \n");
for (i = 0; i < Size; i++)
{
if(FreqArr[i] != 0)
{
printf("%d Occurs %d Times \n", arr[i], FreqArr[i]);
}
}
}
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 62
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
Output
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 63
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
ii.) C program to print all natual numbers from 1 to n using recursion
Program:
#include <stdio.h>
int main()
{
int n;
printf("Enter the upper limit = ");
scanf("%d", & n);
printf("First %d natural numbers are : ", n);
printUptoN(n);
return 0;
}
// recursive function
void printUptoN(int n)
{
//condition for calling
if (n > 1)
printUptoN(n - 1);
printf("%d\t ", n);
}
Output
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 64
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
iii.) String palindrome or not
Program:
#include<stdio.h>
#include<string.h>
int main()
{
char str[20];
int i, len, temp=0;
int flag = 0;
printf("Enter a string:");
scanf("%s", str);
len = strlen(str);
for(i=0; i < len ; i++)
{
if(str[i] != str[len-i-1])
{ temp = 1;
break;
}
}
if (temp==0)
{
printf("String is a palindrome");
}
else
{
printf("String is not a palindrome");
}
}
Output
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 65
R23/ B.Tech /I SEM/ COMPUTER PROGRAMMING LAB
iv.) Demonstrate nested structures using a C program.
Program:
#include <stdio.h>
#include <string.h>
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}e1;
int main( )
{
//storing employee information
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
e1.doj.dd=10;
e1.doj.mm=11;
e1.doj.yyyy=2014;
//printing first employee information
printf( "employee id : %d\n", e1.id);
printf( "employee name : %s\n", e1.name);
printf( "employee DOJ(dd/mm/yyyy) : %d/%d/%d\n",
e1.doj.dd,e1.doj.mm,e1.doj.yyyy);
return 0;
}
Output
SWARNANDHRA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 66