CP Lab Record
CP Lab Record
2. **Install Linux**:
Follow the installation instructions for our chosen Linux distribution. During the
installation, we will be asked to create a user account and set a password. Ensure that
we have internet access.
**Vi/Vim**:
Vi is usually pre-installed on most Linux distributions. We can also install Vim (an
improved version of Vi) if it's not already installed:
```bash
sudo apt install vim # On Debian/Ubuntu
sudo dnf install vim # On Fedora
```
- **Emacs**:
We can install Emacs using our distribution's package manager:
```bash
5. **Usage**: - To open a terminal, we can use the built-in terminal emulator in our Linux
distribution. We can typically find it in our applications or use a keyboard shortcut (e.g.,
Ctrl+Alt+T).
- To use Vi or Vim, open a terminal and type `vi` or `vim` followed by the name of the
file we want to edit. For example:
```bash
vi filename.txt
```
- To use Emacs, open a terminal and type `emacs` followed by the name of the file we
want to edit. For example:
```bash
emacs filename.txt
```
6. **Learn the Editors**:
Vi, Vim, and Emacs have steep learning curves, especially if we're new to them. We
can find online tutorials, documentation, and books to help we get started and become
proficient with these editors.
**Disadvantages**:
- Outdated and no longer actively maintained.
- Limited compatibility with modern operating systems.
- May not support all the features of the latest C/C++ standards.
**Advantages**:
- Cross-platform compatibility; it can be used on various operating systems.
- Supports the latest C and C++ standards and features.
- Highly configurable and extensible.
- Continuously updated and maintained by the open-source community.
**Disadvantages**:
- May have a steeper learning curve for beginners due to its configurability.
- Turbo C can help beginners grasp the basics of C and C++ programming in a
simple and userfriendly environment.
- GCC can be essential for those who want to work on modern and cross-platform
projects, as it provides access to the latest language features and a wide range of
development tools.
In the real world, many professional C and C++ developers primarily use GCC or
other modern IDEs like Visual Studio Code, CLion, or Xcode, depending on their
platform and project requirements. However, understanding the foundations and
history of these tools can be beneficial for a well-rounded knowledge of
programming in C and C++.
Program:
#include<stdio.h>
void main()
{
int a,b;
printf("Enter a value:");
scanf("%d",&a);
printf("\nEnter b value:");
scanf("%d",&b);
printf("\n a=%d \n b=%d",a,b);
getch();
}
Run-1
Input :
Output :
Run-2
Input :
Output :
Run-3
Input :
Output :
Program:
#include<stdio.h>
void main( )
{
int a,b,c,sum;
float avg;
printf("Enter three values:");
scanf("%d%d%d",&a,&b,&c),
sum=a+b+c;
avg=sum/3.0;
printf("\nThe sum of three numbers=%f",sum);
printf("\nThe average of three numbers=%f",avg);
getch();
}
Run-1
Input :
Output :
Run-2
Input :
Output :
Run-3
Input :
Output :
Run-1
Input :
Output :
Run-2
Input :
Output :
Run-3
Input :
Output :
Theory: Simple interest is a quick method of calculating the interest charge on a loan. Simple
interest is determined by multiplying the daily interest rate by the principle by the number of
days that elapse between payments. Divide the product of these three values to convert the
percentage value of the interest rate into decimals. Simple Interest Formula
si=p*t*r/100
Where P is the principle amount, T is the time, and, R is the interest rate
Program:
#include<stdio.h>
void main( )
{
float p, t, r, interest, amount;
printf("Enter principle amount=");
scanf("%f",&p);
printf("\nEnter time period in years=");
scanf("%f",&t);
printf("\nEnter rate of interest=");
scanf("%f",&r);
interest=(p*t*r)/100;
amount=p+interest;
printf("\n Simple Interest for %f years at %f rate is =%f",t,r,interest);
printf("\n The total amount=%f",amount);
getch();
}
Run-1
Input :
Output :
Run-2
Input :
Output :
Run-3
Input :
Output :
LAB-3
i) Square Root of a Given Number
Run-1
Input :
Output :
Run-2
Input :
Output :
Run-3
Input :
Output :
Theory: Compound interest is the addition of interest to the principal sum of a loan or deposit,
or in other words, interest on interest. It is the result of reinvesting interest, rather than paying
it out, so that interest in the next period is then earned on the principal sum plus previously-
accumulated interest. Compound interest is standard in finance and economics.
Compound Interest formula:
Amount= P(1 + R/100)t
Program:
#include<stdio.h>
#include<math.h>
void main()
{
float principle, rate, time, CI;
printf("Enter principle amount: ");
scanf("%f", &principle);
printf("Enter time: ");
scanf("%f", &time);
printf("Enter rate: ");
scanf("%f", &rate);
CI = principle* (pow((1 + rate / 100), time));
printf("Compound Interest = %f", CI);
}
Run-1
Input :
Output :
Run-2
Input :
Output :
Run-3
Input :
Output :
Theory:
To find the area of a triangle using Heron's or Hero's formula. The input of the program is the
lengths of sides of the triangle. The triangle exists if the sum of any of its two sides is greater
than the third side. The program assumes that a user will enter valid input.
If all sides are specified, the area of the triangle can be calculated using Heron’s formula:
sqrt((s) * (s-a) * (s-b) * (s-c)),
where s is the semi perimeter of the triangle and and a, b & c are the sides of triangle.
S=(a+b+c(/2
Program:
#include<stdio.h>
#include<math.h>
void main()
{
float s1, s2, s3, s, area;
printf("\nEnter the length of three sides of triangle");
scanf("%f %f %f", &s1, &s2, &s3);
s = (s1 + s2 + s3)/2;
area = sqrt(s*(s-s1)*(s-s2)*(s-s3));
printf("Area of triangle : %6.4f\n", area);
}
Run-1
Input :
Output :
Run-2
Input :
Output :
Run-3
Input :
Output :
Program:
#include<stdio.h>
void main( )
{
float u,a,s;
int t;
printf("enter the values");
scanf("%f%f",&a,&u);
printf("enter the value of time");
scanf("%d",&t);
s=(u*t)+(a*t*t)/2;
printf("%6.2f",s);
}
Run-1
Input :
Output :
Run-2
Input :
Output :
Run-3
Input :
Output :
LAB - 4
i) Evaluate Expressions
Aim: Implementing a C program to 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)
Software Required: TURBO C
Theory :
The expression consists of numerical values, operators and parentheses.
The operators includes +, -, *, / where, represents, addition, subtraction, multiplication and
division. When two operators have the same precedence, they are applied to left to right.
All calculation is performed as integers, and after the decimal point should be truncated.
Now expression evaluation is nothing but operator precedence and associativity. Expression
precedence in C tells us which operator is performed first, next, and so on in an expression with
more than one operator with different precedence. This plays a crucial role while we are
performing day to day arithmetic operations. If we get 2 same precedence appear in an
expression, then it is said to be “Associativity”. Now in this case we can calculate this statement
either from Left to right or right to left because this both are having the same precedence
Program:
#include<stdio.h>
void main()
{
int A = 5, B = 10, C = 2, D = 7, E = 3, F = 4, G = 6;
int i = 5, j , result_a, result_b, result_c;
result_a = A + B * C + (D * E) + F * G;
printf("a. Result of expression A+B*C+(D*E) + F*G is: %d\n", result_a);
result_b = A / B * C - B + A * D / 3;
printf("b. Result of expression A/B*C-B+A*D/3 is: %d\n", result_b);
result_c = A++ + ++B - --A;
printf("c. Result of expression A+++B---A is: %d\n", result_c);
j = (i++) + (++i);
printf("d. Value of J after J = (i++) + (++i) is: %d\n", j);
}
Run-1
Input :
Output :
Run-2
Input :
Output :
Run-3
Input :
Output :
Aim: Implementing a C program to find the maximum of three numbers using conditional
operator.
Theory :
A Ternary Operator has the following form,
exp1 ? exp2 : exp3;
The expression exp1 will be evaluated always. Execution of exp2 and exp3 depends on the
outcome of exp1. If the outcome of exp1 is non zero then exp2 will be evaluated,
otherwise, exp3 will be evaluated.
Program:
#include<stdio.h>
void main( )
{
int num1, num2, num3, max;
printf("Enter three numbers: ");
scanf("%d %d %d", &num1, &num2, &num3);
max = (num1 > num2) ? ((num1 > num3) ? num1 : num3) : ((num2 > num3) ? num2 : num3);
printf("Maximum number is %d\n", max);
}
Run-1
Input :
Output :
Run-2
Input :
Output :
Run-3
Input :
Output :
Theory :
To input marks of five subjects of a student and calculate total, average and percentage of all
subjects.
1. Input marks of five subjects. Store it in some variables
say eng, phy, chem, math and comp.
2. Calculate sum of all subjects and store in total = eng + phy + chem + math + comp.
3. Divide sum of all subjects by total number of subject to find average i.e. average =
total / 5.
4. Calculate percentage using percentage = (total / 500) * 100.
5. Finally, print resultant values total, average and percentage.
Program:
#include<stdio.h>
void main( )
{
int marks[5] ,i;
float total = 0.0, average;
printf("Enter marks of 5 subjects: ");
for ( i = 0; i < 5; i++)
{
scanf("%d", &marks[i]);
total += marks[i];
}
average = total / 5.0;
printf("Total marks: %6.2f\n", total);
printf("Average marks: %6.2f\n", average);
}
Run-1
Input :
Output :
Run-2
Input :
Output :
Run-3
Input :
Output :
M.V.R NARASIMHARAO ISTS FOR WOMEN 14
C PROGRAMMING LAB IS-23 REGULATION
LAB-5
i) Max And Min of Four Numbers Using If-Else
Aim: Implement a C program to find the max and min of four numbers using if-else.
Software Required: TURBO C
Theory :
Logic for finding max number
1. Compare a with b, c and d. If a is greatest, print a.
2. Else compare b with a, c and d. If b is greatest, print b.
3. Else compare c with a, b and d. If c is greatest, print c.
4. Else d is greatest, print d.
Logic for finding min number
1. Compare a with b, c and d. If a is minimum, print a.
2. Else compare b with a, c and d. If b is minimum, print b.
3. Else compare c with a, b and d. If c is minimum, print c.
4. Else d is minimum, print d.
Program:
#include<stdio.h>
void main()
{
int n1, n2, n3, n4, max, min;
printf("Enter four numbers: ");
scanf("%d %d %d %d", &n1, &n2, &n3, &n4);
if (n1 > n2 && n1 >= n3 && n1 >= n4)
max = n1;
else
if (n2 >= n1 && n2 >= n3 && n2 >= n4)
max = n2;
else
if (n3 >= n1 && n3 >= n2 && n3 >= n4)
max = n3;
else
max = n4;
if (n1 <= n2 && n1 <= n3 && n1 <= n4)
min = n1;
else
if (n2 <= n1 && n2 <= n3 && n2 <= n4)
min = n2;
else
if (n3 <= n1 && n3 <= n2 && n3 <= n4)
min = n3;
else
min = n4;
printf("Maximum is: %d\n", max);
printf("Minimum is: %d\n", min);
}
Run-1
Input :
Output :
Run-2
Input :
Output :
Run-3
Input :
Output :
Run-1
Input :
Output :
Run-2
Input :
Output :
Run-3
Input :
Output :
The term b2 - 4ac is known as the discriminant of a quadratic equation. It tells the nature of
the roots.
If the discriminant is greater than 0, the roots are real and different.
If the discriminant is equal to 0, the roots are real and equal.
If the discriminant is less than 0, the roots are complex and different.
Program:
#include<stdio.h>
#include<math.h>
void main( )
{
double a, b, c, discriminant, root1, root2,realPart,imaginaryPart;
printf("Enter the coefficients of the quadratic equation a, b, c : ");
scanf("%lf %lf %lf", &a, &b, &c);
discriminant = b * b - 4 * a * c;
if (discriminant > 0)
{
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Two real and distinct roots:\n");
printf("Root 1 = %.2lf\n", root1);
printf("Root 2 = %.2lf\n", root2);
}
else
if (discriminant == 0)
{
root1 = -b / (2 * a);
printf("\nRoots are equal \n");
printf("Root = %.62lf\n", root1);
}
else
{
realPart = -b / (2 * a);
imaginaryPart = sqrt(-discriminant) / (2 * a);
printf("Roots are Imaginary :\n");
printf("Root 1 = %.2lf + %.2lfi\n", realPart, imaginaryPart);
printf("Root 2 = %.2lf - %.2lfi\n", realPart, imaginaryPart); }
}
}
Run-1
Input :
Output :
Run-2
Input :
Output :
Run-3
Input :
Output :
Run-1
Input :
Output :
Run-2
Input :
Output :
Run-3
Input :
Output :
Program:
#include<stdio.h>
void main( )
{
int year;
printf("Enter a year: ");
scanf("%d", &year);
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
printf("%d is a leap year.\n", year);
else
printf("%d is not a leap year.\n", year);
}
Run-1
Input :
Output :
Run-2
Input :
Output :
Run-3
Input :
Output :
Theory :
A factorial is the product of all the natural numbers less than or equal to the given
number n. For Example, the factorial of 6 is 6 * 5 * 4 * 3 * 2 * 1 which is 720. We
will explore a few programs to find the factorial of a number in C.
Program:
#include<stdio.h>
void main
{
int i=1, f = 1, n;
printf("Input the number : ");
scanf("%d", &n);
while (i <= n)
{
f = f * i;
i++;
}
printf("The Factorial of %d is: %d\n", n, f);
}
Run-1
Input :
Output :
Run-2
Input :
Output :
Run-3
Input :
Output :
Program:
#include<stdio.h>
void main( )
{
int n,i,flag=0;
printf("Enter the number to check prime:");
scanf("%d",&n);
for(i=2;i<=n/2;i++)
{
if(n%i==0)
{
printf("%d is not a prime",n);
flag=1;
break;
}
}
if(flag==0)
printf("%d is prime",n);
}
Run-1
Input :
Output :
Run-2
Input :
Output :
Run-3
Input :
Output :
Program:
#include<stdio.h>
#include<math.h>
void main( )
{
float x, sinX, cosX,f=1;
int n,sign=-1;
printf("Enter the angle in radians x: ");
scanf("%f",&x);
printf("Enter the number of terms in the series: ");
scanf("%d",&n);
sinX=x;
cosX=1;
printf("%f %d\n",x,n);
for (int i = 2; i <= n; i++)
{
x=x*x;
f=f*i;
if(i%2==0)
cosX=cosX+sign*(x/f);
else
sinX=sinX+sign*(x/f);
sign=-sign;
}
printf("sin(x) = %7.2f\n",sinX);
printf("cos(x) = %7.2f\n",cosX);
}
v) Pyramid Of Numbers
Aim: Implement a C program to Construct a pyramid of numbers.
Software Required: TURBO C
Theory :
Program: #include<stdio.h>
void main( )
{
int i, space, rows, k = 0, count = 0, count1 = 0;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i)
{
for (space = 1; space <= rows - i; ++space)
{
printf(" ");
++count;
}
while (k != 2 * i - 1)
{
if (count <= rows - 1)
{
printf("%d ", i + k);
++count;
}
else
{
++count1;
printf("%d ", (i + k - 2 * count1));
}
++k;
}
count1 = count = k = 0;
printf("\n");
}
}
LAB-7
i) Min And Max of A 1-D Integer Array
Aim: Implement a C program to find the min and max of a 1-D integer array.
Software Required: TURBO C
Program:
#include<stdio.h>
void main( )
{
int arr1[100];
int i, max, min, n;
printf("Input the number of elements to be stored in the array :");
scanf("%d",&n);
printf("Input %d elements in the array :\n",n);
for(i=0;i<n; i++)
scanf(“%d”,&arr1[i]);
max = arr1[0];
min = arr1[0];
for(i=1; i<n; i++)
{
if(arr1[i] <min)
min = arr1[i];
if(arr1[i] >max)
max = arr1[i];
}
printf("\n Maximum element is : %d ", max);
printf("\n Minimum element is : %d ", min);
}
for(i=0;i< n; i++)
for(j=i+1;j<n;j++)
if(a[i] == a[j])
{
for(k = j; k<n;k++)
a[k] = a[k+1];
n--;
}
printf("\nAfter deleting the duplicate element the Array is:");
for(i=0;i<n;i++)
printf(" %5d ",a[i]);
}
LAB-8
}
}
}
This algorithm is not suitable for large data sets as its average and worst-case time complexity
is quite high.
Program: // Bubble sort in C
#include <stdio.h>
void main( ) {
int data[20],step,i,temp,size;
printf("\n Enter the size of the array : ");
scanf("%d",&size);
printf("Enter elements for Array :\n");
for (int i = 0; i < size; i++)
scanf("%d", &data[i]);
Program:
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
void main( )
{
char str[100],ch;
int l, i;
printf("Input the string : ");
scanf(“%s”,str);
i=0;
while(str[i]!='\0')
{
i++;
}
l=i-1;
i=0;
while(i<l)
{
ch=str[i];
str[i]=str[l];
str[l]=ch;
i++;
l--;
}
Lab-9 :
Program:
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
void main( )
{ int i, n;
int *a, *b, *c;
printf("Enter the size of the arrays\n");
scanf("%d",&n);
a = (int *)malloc(n * sizeof(int));
b = (int *)malloc(n * sizeof(int));
c = (int *)malloc(n * sizeof(int));
printf("Enter Elements of First List\n");
for (i=0;i<n;i++)
scanf("%d",a+i);
printf("Enter Elements of Second List\n");
for (i = 0; i < n; i++)
scanf("%d", b + i);
for (i = 0; i < n; i++)
*(c + i) = *(a + i) + *(b + i);
printf("Resultant List is\n");
for (i = 0; i < n; i++)
printf("%d\n", *(c + i));
}
Aim: Implement a C program to find the total, average of n students using structures.
Software Required: TURBO C
Theory :
A structure creates a data type that can be used to group items of possibly different types into
a single type. The struct keyword is used to define the structure in the C programming
language. The items in the structure are called its member and they can be of any valid data
type.
Syntax:
struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
};
Program:
#include<stdio.h>
struct student
{
char name[10];
float m1,m2,m3, total, avg;
};
void main( )
{
struct student s[20];
int n,i;
printf("Enter the number of student=");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the detail of %d students\n",i+1);
printf("\n Enter Name=");
scanf("%s",s[i].name);
printf("Enter the three subject score\n");
scanf("%f%f%f",&s[i].m1,&s[i].m2,&s[i].m3);
s[i].total=s[i].m1+s[i].m2+s[i].m3;
s[i].avg=s[i].total/3;
}
for(i=0;i<n;i++)
{
printf("\n%s \t %f \t %f",s[i].name,s[i].total,s[i].avg);
}
}
Lab-9 :
Program:
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
void main( )
{
int i, n;
int *a, *b, *c;
printf("Enter the size of the arrays\n");
scanf("%d",&n);
a = (int *)malloc(n * sizeof(int));
b = (int *)malloc(n * sizeof(int));
c = (int *)malloc(n * sizeof(int));
printf("Enter Elements of First List\n");
for (i=0;i<n;i++)
scanf("%d",a+i);
printf("Enter Elements of Second List\n");
for (i = 0; i < n; i++)
scanf("%d", b + i);
for (i = 0; i < n; i++)
*(c + i) = *(a + i) + *(b + i);
printf("Resultant List is\n");
for (i = 0; i < n; i++)
printf("%d\n", *(c + i));
}
Aim: Implement a C program to find the total, average of n students using structures.
Theory :
A structure creates a data type that can be used to group items of possibly different types into
a single type. The struct keyword is used to define the structure in the C programming
language. The items in the structure are called its member and they can be of any valid data
type.
Syntax:
struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
};
Program:
#include<stdio.h>
struct student
{
char name[10];
float m1,m2,m3, total, avg;
};
void main( )
{
struct student s[20];
int n,i;
printf("Enter the number of student=");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the detail of %d students\n",i+1);
printf("\n Enter Name=");
scanf("%s",s[i].name);
printf("Enter the three subject score\n");
scanf("%f%f%f",&s[i].m1,&s[i].m2,&s[i].m3);
s[i].total=s[i].m1+s[i].m2+s[i].m3;
s[i].avg=s[i].total/3;
}
for(i=0;i<n;i++)
{
printf("\n%s \t %f \t %f",s[i].name,s[i].total,s[i].avg);
}
}
1.Aim: Implement a C program to Enter n students data using calloc() and display failed
students list.
2.Software Required: TURBO C
3. Theroy C malloc() method:
The “malloc” or “memory allocation” method in C is used to dynamically allocate
a single large block of memory with the specified size. It returns a pointer of type void
which can be cast into a pointer of any form. It doesn’t Initialize memory at execution
time so that it has initialized each block with the default garbage value initially.
Syntax of malloc() : ptr = (cast-type*) malloc(byte-size)
4.Program:
#include<stdio.h>
#include<stdlib.h>
struct Student
{
char name[50];
int rollNumber;
float marks;
};
void main( )
{
int n;
printf("Enter the number of students: ");
scanf("%d", &n);
struct Student *students = (struct Student *)calloc(n, sizeof(struct Student));
for (int i = 0; i< n; ++i)
{
printf("\nEnter details for student %d:\n", i + 1);
printf("Name: ");
scanf("%s", students[i].name);
printf("Roll Number: ");
scanf("%d", &students[i].rollNumber);
printf("Marks: "); scanf("%f", &students[i].marks);
}
printf("\nList of failed students:\n");
printf("Roll Number \t Name \t\t\t Marks \n”);
for (int i = 0; i< n; ++i)
{
if (students[i].marks<=40.0)
{
printf("%10d \t %s \t %8.2f \n", students[i].rollNumber,
students[i].name, students[i].marks);
}
}
free(students);
}
M.V.R NARASIMHARAO ISTS FOR WOMEN 3
C PROGRAMMING LAB IS-23 REGULATION
1.Aim: Implement a C program to Read student name and marks from the command
line and display the student details along with the total
2.Software Required: TURBO C
3.Theroy :
It is possible to pass some values from the command line to your C programs when they
are executed. These values are called command line arguments and many times they
are important for your program especially when you want to control your program from
outside instead of hard coding those values inside the code.
The command line arguments are handled using main() function arguments
where argc refers to the number of arguments passed, and argv[] is a pointer array
which points to each argument passed to the program.
Syntax :
4. Program:
#include<stdio.h>
#include<stdlib.h>
struct Student
{
char name[50];
int m1,m2,m3,total;
float avg;
};
void main(int argc, char *argv[])
{
int total=0;
if (argc>1)
{
int n = atoi(argv[1]);
struct Student *students = (struct Student *)calloc(n, sizeof(struct Student));
for (int i = 0; i< n; i++)
{
printf("Enter name of student %d: ", i + 1);
scanf("%s", students[i].name);
printf("Enter marks for three subjects %d: ", i + 1);
scanf("%d%d%d", &students[i].m1, &students[i].m2, &students[i].m3);
students[i].total=students[i].m1+students[i].m2+students[i].m3;
students[i].avg=students[i].total/3.0;
}
printf("Roll Number \t Name \t\t\t Marks \t Average \n”);
for (int i = 0; i< n; ++i)
{
if (students[i].marks<=40.0)
{
printf("%10d \t %s \t %5d \t %8.2f \n", students[i].rollNumber,
students[i].name, students[i].total, students[i].avg );
}
}
free(students);
}
4. Program:
#include<stdio.h>
#include<stdlib.h>
void main( )
{
int n = 4, i, *p, s = 0;
p = (int*) calloc(n, sizeof(int));
if(p == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array : ");
for(i = 0; i< n; ++i)
{
scanf("%d", p + i);
s += *(p + i);
}
printf("Sum : %d", s);
p = (int*) realloc(p, 6);
printf("Enter elements of array : ");
for(i = 0; i< n; ++i)
{
scanf("%d", p + i);
s += *(p + i);
}
printf("Sum : %d", s);
}
LAB-10
1.Aim: Implement a C program to Create and display a singly linked list using self-
referential structure.
2.Software Required: TURBO C
3. Theory : Self-referential structure
The self-referential structure is a structure that points to the same type of structure. It
contains one or more pointers that ultimately point to the same structure.
Self-referential structure plays a vital role in the linked list, trees, graphs, and many
more data structures.
In a linked list, the structure is used to store the data information and the address of the
next node in the given linked list. Mainly the data part is of integer type, and the link
address part is of pointer type, which holds the address of the next node, so that it can
for the Link ultimately.
Creating a node of structure type contains data part of integer type and a pointer of
structure type to hold the address of the next node.
struct node
{
int data ;
struct node * link ;
// Self referential structure link is pointing the same structure of the type node
};
4. Program:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
void main( )
{
struct node *head = NULL;
struct node *second = NULL;
struct node *third = NULL;
struct node *current;
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;
current = head;
while (current != NULL)
{
printf("%d ", current->data);
current = current->next;
}
}
1.Aim: Demonstrate the differences between structures and unions using a C program.
2.Software Required: TURBO C
3. Theory :
Structures in C is a user-defined data type available in C that allows to combining of
data items of different kinds. Structures are used to represent a record.
struct structure_name
{
member definition;
member definition;
...
member definition;
} structure variable declaration;
Union in C is a special data type available in C that allows storing different data types
in the same memory location. You can define a union with many members, but only
one member can contain a value at any given time. Unions provide an efficient way
of using the same memory location for multiple purposes.
union union_name
{
member definition;
member definition;
...
member definition;
}union variable declaration;
4.Program:
#include<stdio.h>
struct Person
{
char name[50];
int age;
};
union Data
{
int integerData;
float floatData;
};
void main( )
{
struct Person person1;
strcpy(person1.name, "John");
person1.age = 25;
union Data data1;
data1.integerData = 42;
printf("Structure - Person:\n");
printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);
printf("\n"); printf("Union - Data:\n");
printf("Integer Data: %d\n", data1.integerData);
data1.floatData = 3.14;
printf("Float Data: %f\n", data1.floatData);
}
{
printf("Name: %s\n", student->name);
printf("Age: %d\n", student->age);
printf("Marks: %.2f\n", student->marks);
}
void main( )
{
struct Student student1 = {"John Doe", 20, 85.5};
struct Student student2;
copyStruct(&student2, &student1);
printf("Original Student:\n");
displayStudent(&student1);
printf("\nCopied Student:\n");
displayStudent(&student2);
}
LAB-11
A function is a block of code which only runs when it is called. We can pass data, known
as parameters, into a function. Functions are used to perform certain actions, and they
are important for reusing code: Define the code once, and use it many times.
Function Declarations
In a function declaration, we must provide the function name, its return type, and the
number and type of its parameters. A function declaration tells the compiler that there
is a function with the given name defined somewhere else in the program.
Syntax
return_type name_of_the_function (data_type parameter_1, data_type
parameter_2 ,….., data_type parameter_n);
Call a Function
Declared functions are not executed immediately. They are "saved for later use", and
will be executed when they are called. To call a function, write the function's name
followed by two parentheses () and a semicolon ;
The total number of ways for selecting r elements out of n options are nCr
ncr = (n!) / (r! * (n-r)!)
where n! = 1 * 2 * . . . * n.
4. Program:
#include<stdio.h>
int fact(int z);
void main( )
{
int n, r, ncr;
printf("\n Enter the value for N and R \n");
scanf("%d%d", &n, &r);
ncr = fact(n) / (fact(r) * fact(n - r));
printf("\n The value of ncr is: %d", ncr);
}
int fact(int z)
{
int f = 1, i;
if (z == 0)
return(f);
else
{
for (i = 1; i<= z; i++)
{
f = f * i;
}
}
return(f);
}
4. Program:
#include<stdio.h>
#include<string.h>
void main( )
{
char str[100];
int len;
printf("\nEnter the String : ");
scanf("%s",str);
len = strlen(str);
printf("\nLength of the given string is %d", len);
}
}
}
void main( )
{
double x0 = 0.0;
double y0 = 1.0;
double h = 0.1;
double xn = 1.0;
eulerMethod(x0, y0, h, xn);
}
LAB-12
1.Aim: Write a recursive function to generate Fibonacci series.
2.Software Required: TURBO C
3.Program:
#include<stdio.h>
int fibonacci(int num)
{
if (num == 0)
return 0;
else
if (num == 1)
return 1;
else
return fibonacci(num - 1) + fibonacci(num - 2);
}
void main( )
{
int num,i;
printf("Enter the number of elements to be in the series : ");
scanf("%d", &num);
for (i = 0; i< num; i++)
printf("%d, ", fibonacci(i));
}
void main( )
{
int terms;
printf("Enter the number of terms in the series: ");
scanf("%d", &terms);
if (terms < 0)
printf("Please enter a non-negative integer for the number of terms.\n");
else
printf("Sum of the series: %lf\n", seriesSum(terms));
}
LAB-13
Swapping of two numbers using call by reference
1.Aim: Implement a C program to copy one string into another using pointer.
2.Software Required: TURBO C
3.Program:
#includestdio.h>
void copy_string(char*, char*);
void main( )
{
char source[100], target[100];
printf("Enter source string\n");
gets(source);
copy_string(target, source);
printf("Target string is \"%s\"\n", target);
}
void copy_string(char *target, char *source)
{
while(*source)
{
*target = *source;
source++;
target++;
}
*target = '\0';
}
LAB: 14
1.Aim: Implement a C program to write and read text into a binary file using fread()
and fwrite().
2.Software Required: TURBO C
3.Program:
#include<stdio.h>
#include<stdlib.h>
struct Person
{
char name[50];
int age;
};
void main( )
{
struct Person person1 = {"deepu", 25};
struct Person person2 = {"divitha", 05};
FILE *file;
file = fopen("example.bin", "wb");
if (file == NULL)
printf("Could not open the file for writing.\n");
else
{
fwrite(&person1, sizeof(struct Person), 1, file);
fwrite(&person2, sizeof(struct Person), 1, file);
fclose(file);
}
file = fopen("example.bin", "rb");
if (file == NULL)
printf("Could not open the file for reading.\n");
else
{
fread(&readPerson1, sizeof(struct Person), 1, file);
fread(&readPerson2, sizeof(struct Person), 1, file);
printf("Data read from the file:\n");
printf("Person 1: Name=%s, Age=%d\n", readPerson1.name,
readPerson1.age);
printf("Person 2: Name=%s, Age=%d\n", readPerson2.name,
readPerson2.age);
fclose(file);
}
}
1.Aim: Write a C program to merge two files into the third file using command-line
arguments.
2.Software Required: TURBO C
3.Program:
#include<stdio.h>
#include<stdlib.h>
void main(int argc, char *argv[])
{
char ch;
FILE *inputFile1, *inputFile2, *outputFile;
if (argc != 4)
{
printf("Usage: %s \n", argv[0]);
exit(1);
}
inputFile1 = fopen(argv[1], "r");
if (inputFile1 == NULL)
{
printf("Could not open the first input file for reading.\n");
exit(1);
}
inputFile2 = fopen(argv[2], "r");
if (inputFile2 == NULL)
{
printf("Could not open the second input file for reading.\n");
fclose(inputFile1);
exit(1);
}
outputFile = fopen(argv[3], "w");
if (outputFile == NULL)
{
printf("Could not open the output file for writing.\n");
fclose(inputFile1);
fclose(inputFile2);
exit(1);
}
fclose(inputFile2);
fclose(outputFile);
printf("Files merged successfully.\n");
}