0% found this document useful (0 votes)
20 views

CP Lab Record

Uploaded by

mnrmukesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

CP Lab Record

Uploaded by

mnrmukesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

C PROGRAMMING LAB IS-23 REGULATION

Lab-1 Familiarization with programming environment.


i) Basic Linux environment and editors like vi, vim and emacs
Aim: Basic Linux environment and its editors like Vi, Vim & Emacs etc.
Software Required: Linux
Theory: Creating a basic Linux environment and installing text editors like Vi, Vim, and Emacs
can be done on a Linux-based system. Here's a step-by-step guide to set up a basic Linux
environment and install these text editors:
1. **Choose a Linux Distribution**:
We can choose a Linux distribution that suits our preferences. Popular choices include
Ubuntu, Debian, Fedora, CentOS, and others. We can download the ISO image of the
distribution we prefer from the official website and install it on a virtual machine or a
physical computer.

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.

3. **Update the System**:


After installation, open a terminal and update our system to ensure we have the latest
software packages. Use the package manager that comes with our distribution:
On Debian/Ubuntu:
```bash
sudo apt update
sudo apt upgrade
```
On Fedora:
```bash
sudo dnf update
```
4. **Install Text Editors**: -

**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

M.V.R NARASIMHARAO ISTS FOR WOMEN 1


C PROGRAMMING LAB IS-23 REGULATION

sudo apt install emacs # On Debian/Ubuntu


sudo dnf install emacs # On Fedora ```

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.

ii) Exposure to Turbo C,gcc


Aim: Exposure to Turbo C,gcc
Software Required: Turbo C
Theory: Exposure to Turbo C and GCC (GNU Compiler Collection) can be valuable
for individuals interested in programming and software development, especially in the
C and C++ programming languages. These two development environments have been
widely used for many years and offer different advantages.

1. **Turbo C**: - **Overview**:


Turbo C was a popular Integrated Development Environment (IDE) and compiler
for C and C++ programming in the MS-DOS environment. It was developed by
Borland and was widely used during the 1980s and 1990s. –
**Advantages**:
- Simple and easy-to-use IDE, especially for beginners.
- Well-suited for learning C and C++ programming basics.
- Provided a compact and efficient development environment for its time.

**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.

M.V.R NARASIMHARAO ISTS FOR WOMEN 2


C PROGRAMMING LAB IS-23 REGULATION

2. **GCC (GNU Compiler Collection)**:


**Overview**:
GCC is a powerful and widely used collection of compilers and tools for various
programming languages, including C, C++, and others. It is open-source software
and can be used on various platforms.

**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.

- Requires familiarity with the command-line interface.


Exposure to both Turbo C and GCC can provide a balanced understanding of the
history and evolution of C and C++ development tools:

- 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++.

iii) Simple Program Using printf( ),scanf( )


Aim: Implement a simple program using printf( ),scanf( )

Software Required: Turbo C

Theory: The input and output functions used in C language.


printf( ) is a output statement used to display the output on the console device .
scanf( ) is the input statement which is used to read the information from the user.
These functions can be used by including the header file “stdio.h” in the program.

M.V.R NARASIMHARAO ISTS FOR WOMEN 3


C PROGRAMMING LAB IS-23 REGULATION

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 :

M.V.R NARASIMHARAO ISTS FOR WOMEN 4


C PROGRAMMING LAB IS-23 REGULATION

LAB-2 : Converting algorithms / Flowcharts into C Source code.


Developing the algorithms / Flowcharts for the following sample programs.

i) Sum and average of 3 numbers


Aim: Implement a C program to find sum and average of three numbers.
Software Required: TURBO C
Theory:
• In this program, first we declared four variables x, y, z, sum in an integer data type.
• To create another variable named avg in a float data type.
• After declaring the variables, we take three input numbers from the user and store
those values in the x, y, z variables using scanf() function.
• Next, we Calculate the sum of three numbers using the formula (sum = x + y + z )
and stored its result in the sum variable.
• We Calculate the average of three numbers using the formula (average = sum/count)
and stored its result in the avg variable.
• Finally, we print the sum and average using printf() function.

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 :

M.V.R NARASIMHARAO ISTS FOR WOMEN 5


C PROGRAMMING LAB IS-23 REGULATION

ii) Conversion of Fahrenheit to Celsius and Vice Versa


Aim: Implement a C program for conversion of Fahrenheit to Celsius and vice versa
Software Required: TURBO C
Theory: Celsius is represented by oC and Fahrenheit is represented by oF. There is a formula
to convert Celsius to Fahrenheit, using which we will be able to convert Celsius to Fahrenheit.
Similarly, there is also a formula to convert Fahrenheit to Celsius, using which we will be
able to convert Fahrenheit to Celsius.
Formula to Convert Temperature From Celsius To Fahrenheit
Fahrenheit = (celsius * 1.8) + 32
Formula to Convert Temperature From Fahrenheit to Celsius
Celsius = ((Fahrenheit-32)*5)/9
Program:
#include<stdio.h>
void main()
{
float t1, t2,c,f;
printf("Enter Temperature in Celsius : ");
scanf("%f",&t1);
printf("\nEnter Temperature in Fahrenheit : ");
scanf("%f",&t2);
f=(t1*9/5)+32;
c = ((t2-32)*5)/9;
printf("\nTemperature in Fahrenheit : %f",f);
printf("\nTemperature in Celsius : %f",c);
}

Run-1
Input :

Output :

Run-2
Input :

Output :

Run-3
Input :

Output :

M.V.R NARASIMHARAO ISTS FOR WOMEN 6


C PROGRAMMING LAB IS-23 REGULATION

iii) Simple Interest Calculation


Aim: Implementing a C program to find simple interest calculation

Software Developed: Turbo C

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 :

M.V.R NARASIMHARAO ISTS FOR WOMEN 7


C PROGRAMMING LAB IS-23 REGULATION

LAB-3
i) Square Root of a Given Number

Aim: Implementing a C program to find the square root of a given number.

Software Required: Turbo C 3.


A Square root of a number is a value that, when multiplied by itself, gives the number.
Program:
#include<stdio.h>
#include<math.h>
void main()
{
int a;
float square;
printf("Enter the value for which you want to find sqare root::");
scanf("%d",&a);
square=sqrt(a);
printf("\n The square root of %d is =%f",a,square);
getch();
}

Run-1
Input :

Output :

Run-2
Input :

Output :

Run-3
Input :

Output :

M.V.R NARASIMHARAO ISTS FOR WOMEN 8


C PROGRAMMING LAB IS-23 REGULATION

ii) Compound Interest


Aim: Implementing a C program to find compound interest.

Software Required: Turbo C

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 :

M.V.R NARASIMHARAO ISTS FOR WOMEN 9


C PROGRAMMING LAB IS-23 REGULATION

iii) Triangle Using Heron’s Formulae


Aim: Implementing a C program to find area of triangle using heron’s formulae.

Software Required: Turbo C

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

Given a=5, b=9, c=6


Area = sqrt((s) * (s-a) * (s-b) * (s-c))
So, s = (a + b + c)/2 = (5 + 9 + 6)/2 = 10
Area = sqrt (10 * (10 – 5) * (10 – 9) * (10 – 6)) = sqrt(10 * 5 * 1 * 4) = 14.142.

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 :

M.V.R NARASIMHARAO ISTS FOR WOMEN 10


C PROGRAMMING LAB IS-23 REGULATION

iv) Distance Travelled by an Object


Aim: Implementing a C program to find the distance travelled by an object.

Software Required: TURBO C


Theory:
The distance covered by a body in a given time t under uniform acceleration is given by;
s=ut+1/2at2 ,
Where, s = Distance travelled by the body
u = Initial velocity of the body
a = Uniform acceleration in the body
t=time

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 :

M.V.R NARASIMHARAO ISTS FOR WOMEN 11


C PROGRAMMING LAB IS-23 REGULATION

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 :

M.V.R NARASIMHARAO ISTS FOR WOMEN 12


C PROGRAMMING LAB IS-23 REGULATION

ii) Maximum of Three Numbers Using Conditional Operator

Aim: Implementing a C program to find the maximum of three numbers using conditional
operator.

Software Required: TURBO C

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 :

M.V.R NARASIMHARAO ISTS FOR WOMEN 13


C PROGRAMMING LAB IS-23 REGULATION

iii) Calculating Marks


Aim: Implementing a C program for calculating marks of 5 subjects in integers, and find the
total, average in float.
Software Required: TURBO C

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

M.V.R NARASIMHARAO ISTS FOR WOMEN 15


C PROGRAMMING LAB IS-23 REGULATION

Run-1
Input :

Output :

Run-2
Input :

Output :

Run-3
Input :

Output :

M.V.R NARASIMHARAO ISTS FOR WOMEN 16


C PROGRAMMING LAB IS-23 REGULATION

ii) Generate Electricity Bill


Aim: Implement a C program to generate electricity bill.
Software Required: TURBO C .
Theory :
To input electricity unit charge and calculate the total electricity bill according to the given
condition:
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>
void main()
{
int omr,pmr,unit;
float amt, total_amt, sur_charge;
printf("\nEnter Previous meter reading : “);
scanf("%d", &omr);
printf("\nEnter Present meter reading : “);
scanf("%d", &pmr);
unit=pmr-omr;
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 * 20/100;
total_amt = amt + sur_charge;
printf("Electricity Bill = Rs. %6.2f", total_amt);
}

Run-1
Input :

Output :

Run-2
Input :
Output :
Run-3
Input :
Output :

M.V.R NARASIMHARAO ISTS FOR WOMEN 17


C PROGRAMMING LAB IS-23 REGULATION

iii) Roots of Quadratic Equation


Aim: Implement a C program to find roots of quadratic equation.
Software Required: TURBO C
The standard form of a quadratic equation is:

ax2 + bx + c = 0, where a, b and c are real numbers and a != 0

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

M.V.R NARASIMHARAO ISTS FOR WOMEN 18


C PROGRAMMING LAB IS-23 REGULATION

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 :

M.V.R NARASIMHARAO ISTS FOR WOMEN 19


C PROGRAMMING LAB IS-23 REGULATION

iv) Calculator Using Switch Case


Aim: Implement a C program to simulate a calculator using switch case.
Software Required: TURBO C
Theory :
Switch case is often used to create menu driven program. In this program we will learn to create
menu driven program that accepts user choice to perform arithmetic operation. Based on the
user choice the program performs arithmetic operation. This program takes an arithmetic
operator +,-,*,/ and two operands from the user. Then, it performs the calculation on the two
operands depending upon the operator entered by the user.
Program:
#include <stdio.h>
void main()
{
char op;
float num1, num2, result=0.0;
printf("Enter arithmetic expression like 5+6, 2-9, 5*3, 5/7 \n");
scanf("%f %c %f", &num1, &op, &num2);
switch(op)
{
case '+': result = num1 + num2;
break;
case '-': result = num1 - num2;
break;
case '*': result = num1 * num2;
break;
case '/': result = num1 / num2;
break;
default: printf("Invalid operator");
}
printf("%.2f %c %.2f = %.2f", num1, op, num2, result);
}

Run-1
Input :

Output :

Run-2
Input :

Output :

Run-3
Input :

Output :

M.V.R NARASIMHARAO ISTS FOR WOMEN 20


C PROGRAMMING LAB IS-23 REGULATION

v) Leap Year or Not


Aim: Implement a C program to find the given year is a leap year or not.
Software Required: TURBO C
Theory :
A leap year is a year that contains an additional day, February 29th, making it 366 days
long instead of the usual 365 days. Leap years are necessary to keep our calendar in
alignment with the Earth’s revolutions around the Sun.
A year is a leap year if the following conditions are satisfied:
1. The year is multiple of 400.
2. The year is a multiple of 4 and not a multiple of 100.

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 :

M.V.R NARASIMHARAO ISTS FOR WOMEN 21


C PROGRAMMING LAB IS-23 REGULATION

Lab 6: Iterative problems e.g., the sum of series

i) Factorial Of Given Number Using Loop


Aim: Implement a C program to find the factorial of given number using any loop.
Software Required: TURBO C

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 :

M.V.R NARASIMHARAO ISTS FOR WOMEN 22


C PROGRAMMING LAB IS-23 REGULATION

ii) Prime Or Not


Aim: Implement a C program to find given number is a prime or not.
Software Required: TURBO C
Theory :
A prime number is a natural number greater than 1 that is completely divisible only
by 1 and itself. For example, 2, 3, 5, 7, 11, etc. are the first few prime numbers.
We will explore a few prime number programs in C to check whether the given
number is a prime number or not.
We will check if any number between 2 to (N/2) can divide N completely. If such a
number exists, it means that the number N is not a prime number as it is divisible by
a number other than 1 and itself.
Note: We take (N/2) as the upper limit because there are no numbers between (N/2)
and N that can divide N completely.

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 :

M.V.R NARASIMHARAO ISTS FOR WOMEN 23


C PROGRAMMING LAB IS-23 REGULATION

iii) Sine and Cos Series


Aim: Implement a C program to compute sine and cos series
Software Required: TURBO C
Theory :

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

M.V.R NARASIMHARAO ISTS FOR WOMEN 24


C PROGRAMMING LAB IS-23 REGULATION

iv) Number Palindrome


Aim: Implement a C program to Checking a number palindrome
Software Required: TURBO C
Theory:
Program:
#include<stdio.h>
void main( )
{
int num, r, rev = 0, t;
printf("Input a number: ");
scanf("%d", &num);
t=num;
while( num != 0)
{
r = num % 10;
rev = rev * 10 + r;
num=num/10;
}
if(t == rev)
printf("%d is a palindrome number.\n", t);
else
printf("%d is not a palindrome number.\n", t);
}

M.V.R NARASIMHARAO ISTS FOR WOMEN 25


C PROGRAMMING LAB IS-23 REGULATION

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

M.V.R NARASIMHARAO ISTS FOR WOMEN 26


C PROGRAMMING LAB IS-23 REGULATION

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

M.V.R NARASIMHARAO ISTS FOR WOMEN 27


C PROGRAMMING LAB IS-23 REGULATION

ii) Linear Search On 1D Array


Aim: Implement a C program to Perform linear search on 1D array.
Software Required: TURBO C
Program:
#include<stdio.h>
void main( )
{
int a[10], search, i, n;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d integers \n", n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("Enter a number to be search\n");
scanf("%d", &search);
for (i = 0; i < n; i++)
{
if (a[i] == search)
break;
}
if (i == n)
printf("%d isn't present in the array.\n", search);
else
printf("%d is present at location %d.\n", search, i+1);
}

M.V.R NARASIMHARAO ISTS FOR WOMEN 28


C PROGRAMMING LAB IS-23 REGULATION

iii) Reverse A 1D Integer Array


Aim: Implement a C program to reverse a 1D integer array.
Software Required: TURBO C
Program:
#include<stdio.h>
void main( )
{
int n, i, j, a[10],t;
printf("Enter the number of elements in array\n");
scanf("%d", &n);
printf("Enter the array elements\n");
for (i = 0; i < n ; i++)
scanf("%d", &a[i]);
i=0;
j=n-1;
while(i<j)
{
t=a[i];
a[i]=a[j];
a[j]=t;
i++;
j--;
}
printf("Reverse array is\n");
for (i = 0; i < n; i++)
printf(" %5d ", a[i]);
}

M.V.R NARASIMHARAO ISTS FOR WOMEN 29


C PROGRAMMING LAB IS-23 REGULATION

iv) 2’s Complement of The Given Binary Number


Aim: Implement a C program to find 2’s complement of the given binary number.
Software Required: TURBO C
Program:
#include<stdio.h>
#define SIZE 8
void main( )
{
char binary[SIZE + 1], onesComp[SIZE + 1], twosComp[SIZE + 1];
int i, carry=1;
printf("Enter %d bit binary value: ", SIZE);
/* Input 8-bit binary string */
gets(binary);
/* Find ones complement of the binary number */
for(i=0;i<SIZE;i++)
{
if(binary[i] == '1')
onesComp[i] = '0';
else
onesComp[i] = '1';
}
onesComp[SIZE] = '\0';
/* Add 1 to the ones complement */
for(i=SIZE-1; i>=0; i--)
{
if(onesComp[i] == '1' && carry == 1)
twosComp[i] = '0';
else
if(onesComp[i] == '0' && carry == 1)
{
twosComp[i] = '1';
carry = 0;
}
else
{
twosComp[i] = onesComp[i];
}
}
twosComp[SIZE] = '\0';
printf("\n Original binary = %s", binary);
printf("\n Ones complement = %s", onesComp);
printf("\n Twos complement = %s", twosComp);
}

M.V.R NARASIMHARAO ISTS FOR WOMEN 30


C PROGRAMMING LAB IS-23 REGULATION

v) Eliminate Duplicate Elements in An Array


Aim: Implement a C program to Eliminate duplicate elements in an array.
Software Required: TURBO C
Program:
#include<stdio.h>
void main( )
{
int a[50],i,j,k, count = 0, dup[50], n;
printf("\nEnter size of the array : ");
scanf("%d",&n);
printf("\n Enter Elements of the array : ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);

for(i=0;i< n; i++)
for(j=i+1;j<n;j++)
if(a[i] == a[j])
{
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]);
}

M.V.R NARASIMHARAO ISTS FOR WOMEN 31


C PROGRAMMING LAB IS-23 REGULATION

LAB-8

i) Addition of Two Matrices


Aim: Implement a C program for Addition of two matrices.
Software Required: TURBO C
Program:
#include<stdio.h>
void main( )
{
int r1, c1,r2,c2, a[10][10], b[10][10], sum[10][10], i, j;
printf("\nEnter the number of rows : ");
scanf("%d", &r1);
printf("\nEnter the number of columns : ");
scanf("%d", &c1);
printf("\nEnter elements of 1st matrix:\n");
for (i = 0; i < r1; ++i)
for (j = 0; j < c1; ++j)
{
printf("\nEnter element a %d %d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}
printf("\nEnter the number of rows for matrix-2 : ");
scanf("%d", &r2);
printf("\nEnter the number of columns for matrix-2 : ");
scanf("%d", &c2);
printf("\n Enter elements of 2nd matrix:\n");
for (i = 0; i < r2; ++i)
for (j = 0; j < c2; ++j)
{
printf("\nEnter element b %d %d: ", i + 1, j + 1);
scanf("%d", &b[i][j]);
}
if(r1!=r2 || c1!=c2)
printf("\n Matrix Addition is not Possible");
else
{
for (i = 0; i < r1; ++i)
for (j = 0; j < c1; ++j)
sum[i][j] = a[i][j] + b[i][j];
printf("\nSum of two matrices: \n");
for (i = 0; i < r1; ++i)
{
for (j = 0; j < c1; ++j)
printf("%d ", sum[i][j]);
printf(“\n”);
}
}
}

M.V.R NARASIMHARAO ISTS FOR WOMEN 32


C PROGRAMMING LAB IS-23 REGULATION

ii) Multiplication of Two Matrices


Aim: Implement a C program for Multiplication of two matrices.
Software Required: TURBO C
Program:
#include<stdio.h>
void main( )
{
int r1, c1,r2,c2, a[10][10], b[10][10], sum[10][10], i, j,k;
printf("\nEnter the number of rows : ");
scanf("%d",&r1);
printf("\nEnter the number of columns : ");
scanf("%d",&c1);
printf("\nEnter elements of 1st matrix:\n");
for (i = 0; i < r1; ++i)
for (j = 0; j < c1; ++j)
{
printf("\nEnter element a %d %d: ", i + 1, j + 1);
scanf("%d",&a[i][j]);
}
printf("\nEnter the number of rows for matrix-2 : ");
scanf("%d", &r2);
printf("\nEnter the number of columns for matrix-2 : ");
scanf("%d",&c2);
printf("\n Enter elements of 2nd matrix:\n");
for (i = 0; i < r2; ++i)
for (j = 0; j < c2; ++j)
{
printf("\nEnter element b %d %d: ", i + 1, j + 1);
scanf("%d", &b[i][j]);
}
if(c1!=r2)
printf("\n Matrix Multiplication is not Possible");
else
{
for (i = 0; i < r1; ++i)
{
for (j = 0; j < c1; ++j)
{
sum[i][j] = 0;
for(k=0;k<c1;k++)
sum[i][j]=sum[i][j]+a[i][k]*b[k][j];
}
}
}
printf("\nMultiplication of two matrices: \n");
for (i = 0; i < r1; ++i)
{
for (j = 0; j < c1; ++j)
printf("%d ", sum[i][j]);
printf(“\n”);

M.V.R NARASIMHARAO ISTS FOR WOMEN 33


C PROGRAMMING LAB IS-23 REGULATION

}
}
}

iii) Bubble Sort


Aim: Implement a C program Sort array elements using bubble sort.
Software Required: TURBO C
Theory: Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the
adjacent elements if they are in the wrong order.
In Bubble Sort algorithm,
 traverse from left and compare adjacent elements and the higher one is placed at right
side.
 In this way, the largest element is moved to the rightmost end at first.
 This process is then continued to find the second largest and place it and so on until the
data is sorted.

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

for (step = 0; step < size - 1; ++step)


{
for (int i = 0; i < size - step - 1; ++i)
{
if (data[i] > data[i + 1])
{
temp = data[i];
data[i] = data[i + 1];
data[i + 1] = temp;
}
}
}
printf("Sorted Array in Ascending Order:\n");
for ( i = 0; i <size; i++)
printf("%d ", data[i]);
}

M.V.R NARASIMHARAO ISTS FOR WOMEN 34


C PROGRAMMING LAB IS-23 REGULATION

iv) Concatenating Two Strings Without Built-In Functions


Aim: Implement a C program for Concatenating two strings without built-in functions
Software Required: TURBO C
Theory :
String concatenation in C can be simply defined as the addition of two strings. In C language
we can add two or more strings end to end or can update them using the concatenation process.
The concatenation helps to combine two or more strings together and provide them as a single
string value. Suppose we have two strings, the first one being Artificial and the second one
– Intelligence and we want to combine these two strings as a single string, so we use String
Concatenation and the result will be: ArtificialIntelligence.
Now a while loop is implemented which checks whether str1[i] does not equal to '\0' or not,
and increments the value of i by 1. Another while is used after this which checks whether str2[i]
not equals to '\0', if the condition becomes true, the loop will get executed and where it is given
the value of str2[j] gets initialized to str1[i]; Then increments the value of i and j by 1. And
finally, initializes the str1[i] as '\0' i.e. null character terminator. At last printf() is used to
display the value of the concatenated string.
Program:
void 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);
}

M.V.R NARASIMHARAO ISTS FOR WOMEN 35


C PROGRAMMING LAB IS-23 REGULATION

v) Reverse A String Using Built-In and Without Built-In String Functions


Aim: Implement a C program to Reverse a string using built-in and without built-in string
functions
Software Required: TURBO C
Theory :
The strrev() function is a built-in function in C and is defined in string.h header file. The
strrev() function is used to reverse the given string.
Syntax: char *strrev(char *str);
Parameter: str: The given string which is needed to be reversed.

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--;
}

printf("After reverse string without function is : %s\n",str);


printf("Input the string : ");
scanf(“%s”,str);

printf("After reversing string is =%s", strrev(str));


}

************* STOP WRITING HERE **********************

M.V.R NARASIMHARAO ISTS FOR WOMEN 36


C PROGRAMMING LAB IS-23 REGULATION

Lab-9 :

Sum of a 1D Array Using Malloc()


Aim: Implement a C program to find the sum of a 1D array using malloc().
Software Required: TURBO C
Theory :
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() in C : ptr = (cast-type*) malloc(byte-size)

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;

M.V.R NARASIMHARAO ISTS FOR WOMEN 37


C PROGRAMMING LAB IS-23 REGULATION

....
....
};

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

M.V.R NARASIMHARAO ISTS FOR WOMEN 38


C PROGRAMMING LAB IS-23 REGULATION

Lab-9 :

Sum of a 1D Array Using Malloc()


Aim: Implement a C program to find the sum of a 1D array using malloc().
Software Required: TURBO C
Theory :
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() in C : ptr = (cast-type*) malloc(byte-size)

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

M.V.R NARASIMHARAO ISTS FOR WOMEN 1


C PROGRAMMING LAB IS-23 REGULATION

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

M.V.R NARASIMHARAO ISTS FOR WOMEN 2


C PROGRAMMING LAB IS-23 REGULATION

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 :

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


{
body of the main function
}
argc (ARGument Count) is an integer variable that stores the number of command-
line arguments passed by the user including the name of the program. So if we pass
a value to a program, the value of argc would be 2 (one for argument and one for
program name). The value of argc should be non-negative.
argv (ARGument Vector) is an array of character pointers listing all the arguments.
 If argc is greater than zero, the array elements from argv[0] to argv[argc-1] will
contain pointers to strings.
 argv[0] is the name of the program , After that till argv[argc-1] every element is
command -line arguments.

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)
{

M.V.R NARASIMHARAO ISTS FOR WOMEN 4


C PROGRAMMING LAB IS-23 REGULATION

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

M.V.R NARASIMHARAO ISTS FOR WOMEN 5


C PROGRAMMING LAB IS-23 REGULATION

1.Aim: Implement a C program for realloc() function.


2.Software Required: TURBO C
3.Teheory :

The free() function in C is used to free or deallocate the dynamically allocated


memory and helps in reducing memory wastage. The C free() function cannot be used
to free the statically allocated memory (e.g., local variables) or memory allocated on
the stack. It can only be used to deallocate the heap memory previously allocated using
malloc(), calloc() and realloc() functions.
The free() function is defined inside <stdlib.h> header file.
Syntax of free() Function : void free(void *ptr);
Parameters : ptr is the pointer to the memory block that needs to be freed or
deallocated.
Return Value : The free() function does not return any value.

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

M.V.R NARASIMHARAO ISTS FOR WOMEN 6


C PROGRAMMING LAB IS-23 REGULATION

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;

M.V.R NARASIMHARAO ISTS FOR WOMEN 7


C PROGRAMMING LAB IS-23 REGULATION

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

M.V.R NARASIMHARAO ISTS FOR WOMEN 8


C PROGRAMMING LAB IS-23 REGULATION

{
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);
}

1.Aim: Implement a C program to shift/rotate using bitfields.


2.Software Required: TURBO C
3. Program:
#include<stdio.h>
struct BitfieldRotation
{
unsigned int data : 4;
};
void leftRotate(struct BitfieldRotation *bf)
{
bf->data = ((bf->data << 1) | (bf->data >> 3)) & 0x0F;
}

M.V.R NARASIMHARAO ISTS FOR WOMEN 9


C PROGRAMMING LAB IS-23 REGULATION

void rightRotate(struct BitfieldRotation *bf)


{
bf->data = ((bf->data >> 1) | (bf->data << 3)) & 0x0F;
}
void displayBitfield(struct BitfieldRotation bf)
{
printf("Bitfield Data: %X\n", bf.data);
}
void main( )
{
struct BitfieldRotation bitfield; bitfield.data = 0xC;
printf("Original Bitfield:\n");
displayBitfield(bitfield);
leftRotate(&bitfield);
printf("\nAfter Left Rotation:\n");
displayBitfield(bitfield);
rightRotate(&bitfield);
printf("\nAfter Right Rotation:\n");
displayBitfield(bitfield);
}

1.Aim: Implement a C program to copy one structure variable to another structure of


the same type.
2.Software Required: TURBO C
3.Program:
#include<stdio.h>
struct Student
{
char name[50];
int age;
float marks;
};
void copyStruct(struct Student *dest, const struct Student *src)
{
strcpy(dest->name, src->name);
dest->age = src->age;
dest->marks = src->marks;
}
void displayStudent(const struct Student *student)

M.V.R NARASIMHARAO ISTS FOR WOMEN 10


C PROGRAMMING LAB IS-23 REGULATION

{
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);
}

M.V.R NARASIMHARAO ISTS FOR WOMEN 11


C PROGRAMMING LAB IS-23 REGULATION

LAB-11

1.Aim: Implement a C program to calculate NCR value using Functions.


2.Software Required: TURBO C
3. Theory

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

Create a Function or Function Definition


To create (often referred to as declare) your own function, specify the name of the
function, followed by parentheses () and curly brackets {}:
Syntax :
return_type function_name (data_type para1_name, data_type para2_name, . . .,
data_type paran_name )
{
// body of the function
}

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

M.V.R NARASIMHARAO ISTS FOR WOMEN 12


C PROGRAMMING LAB IS-23 REGULATION

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

1.Aim: Implement a C program to find the length of a string using Functions.


2.Software Required: TURBO C
3. Theory
C Standard Library Functions
C Standard library functions or simply C Library functions are inbuilt functions in C
programming. The prototype and data definitions of these functions are present in their
respective header files. To use these functions we need to include the header file in our
program. For example, If we want to use the printf() function, the header
file <stdio.h> should be included.
C programming language provides a set of pre-defined functions called string handling
functions to work with string values. The string handling functions are defined in a
header file called string.h. Whenever we want to use any string handling function we
must include the header file called string.h.
The strlen() function defined in string.h header file calculates the length of the given
string or char array excluding the null character in C.
The syntax of the strlen() function in C is as follows:
int strlen(const char *str);
In the above syntax, str refers to the string whose length has to be calculated.

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

M.V.R NARASIMHARAO ISTS FOR WOMEN 13


C PROGRAMMING LAB IS-23 REGULATION

1.Aim: Implement a C program to find Transpose of a Matrix using Function.


2.Software Required: TURBO C
3.Program:
#include<stdio.h>
#define N 4
void transpose(int A[][N], int B[][N])
{
int i, j;
for (i = 0; i< N; i++)
for (j = 0; j < N; j++)
B[i][j] = A[j][i];
}
void main( )
{
int A[N][N] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } };
int B[N][N], i, j;
transpose(A, B);
printf("Result matrix is \n");
for (i = 0; i< N; i++)
{
for (j = 0; j < N; j++)
printf("%d ", B[i][j]);
printf("\n");
}
}

1.Aim: Implement a C program to demonstrate numerical integration of differential


equations using Euler’s method.
2.Software Required: TURBO C
3.Program:
#include<stdio.h>
double equation(double x, double y)
{
return x + y;
}

void eulerMethod(double x0, double y0, double h, double xn)


{
double x = x0, y = y0;
printf("Euler's Method:\n");
printf("x\t\t y\n");
while (x <= xn)
{
printf("%.4f\t%.4f\n", x, y);
y = y + h * equation(x, y); x = x + h;

M.V.R NARASIMHARAO ISTS FOR WOMEN 14


C PROGRAMMING LAB IS-23 REGULATION

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

1.Aim: Write a recursive function to find the lcm of two numbers.


2.Software Required: TURBO C
3.Program: #include<stdio.h>
int lcm(int a, int b)
{
return (a * b);
}
void main( )
{

M.V.R NARASIMHARAO ISTS FOR WOMEN 15


C PROGRAMMING LAB IS-23 REGULATION

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

1.Aim: Write a recursive function to find the factorial of a number.


2.Software Required: TURBO C
3.Program:
#include<stdio.h>
unsigned long longfactorial(int n)
{
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}
void main( )
{
int num;
printf("Enter a non-negative integer: ");
scanf("%d", &num);
if (num < 0)
printf("Please enter a non-negative integer.\n");
else
printf("Factorial of %d is: %llu\n", num, factorial(num));
}

1.Aim: Write a C Program to implement Ackermann function using recursion.


2.Software Required: TURBO C
3.Program:
#include<stdio.h>
int A(int m, int n);
void main( )
{
int m,n;
printf("Enter two numbers :: \n");
scanf("%d%d",&m,&n);
printf("\nOUTPUT :: %d\n",A(m,n));
}

M.V.R NARASIMHARAO ISTS FOR WOMEN 16


C PROGRAMMING LAB IS-23 REGULATION

int A(int m, int n)


{
if(m==0)
return n+1;
else
if(n==0)
return A(m-1,1);
else
return A(m-1,A(m,n-1));
}

1.Aim: Write a recursive function to find the sum of series.


2.Software Required: TURBO C
3.Program:
#include<stdio.h>
double seriesSum(int n)
{
if (n == 0)
{
return 0;
}
else
{
return 1.0 / n + seriesSum(n - 1);
}
}

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

M.V.R NARASIMHARAO ISTS FOR WOMEN 17


C PROGRAMMING LAB IS-23 REGULATION

LAB-13
Swapping of two numbers using call by reference

1.Aim: Write a C program to swap two numbers using call by reference.


2.Software Required: TURBO C
3.Program:
#include<stdio.h>
void swap (int *, int *);
void 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);
}
void swap (int *x, int *y)
{
*x=*x+*y;
*y=*x-*y;
*x=*x-*y;
}

M.V.R NARASIMHARAO ISTS FOR WOMEN 18


C PROGRAMMING LAB IS-23 REGULATION

1.Aim: Demonstrate Dangling pointer problem using a C program.


2.Software Required: TURBO C
3.Program:
#include<stdio.h>
#include<stdlib.h>
int* createIntArray(int size)
{
int* arr = (int*)malloc(size * sizeof(int));
return arr;
}
void main( )
{
int* arr = createIntArray(5);
for (int i = 0; i< 5; i++)
{
arr[i] = i + 1;
}
printf("Values using valid pointer:\n");
for (int i = 0; i< 5; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
free(arr);
printf("Values using dangling pointer:\n");
for (int i = 0; i< 5; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}

M.V.R NARASIMHARAO ISTS FOR WOMEN 19


C PROGRAMMING LAB IS-23 REGULATION

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';
}

M.V.R NARASIMHARAO ISTS FOR WOMEN 20


C PROGRAMMING LAB IS-23 REGULATION

1.Aim: Implement a C program to find no of lowercase, uppercase, digits and other


characters using pointers.
2.Software Required: TURBO C
3.Program:
#include<stdio.h>
#include<stdlib.h>
void main( )
{
char str[100];
int i;
int upper=0,lower=0,num=0,special=0;
printf("Please enter the string \n");
gets(str);
for(i=0; str[i] != '\0'; i++)
{
if(str[i]>='A' && str[i]<='Z')
upper++;
else
if(str[i]>='a' && str[i]<='z')
lower++;
else
if(str[i]>='1' && str[i]<='9')
num++;
else
special++;
}
printf("\nUpper case letters: %d",upper);
printf("\nLower case letters: %d",lower);
printf("\nNumbers: %d",num);
printf("\nSpecial characters: %d",special);
}

M.V.R NARASIMHARAO ISTS FOR WOMEN 21


C PROGRAMMING LAB IS-23 REGULATION

LAB: 14

1.Aim: Write a C program to write and read text into a file.


2.Software Required: TURBO C
3.Program:
#include<stdio.h>
#include<stdlib.h>
void main( )
{
FILE *file;
file = fopen("example.txt", "w");
if (file == NULL)
printf("Could not open the file for writing.\n");
else
{
fprintf(file, "Hello, this is a sample text.\n");
fprintf(file, "Writing to a file in C is easy!\n");
fclose(file);
}
file = fopen("example.txt", "r");
if (file == NULL)
printf("Could not open the file for reading.\n");
else
{
printf("Content of the file:\n");
while ((ch = fgetc(file)) != EOF)
putchar(ch);
fclose(file);
}
}

M.V.R NARASIMHARAO ISTS FOR WOMEN 22


C PROGRAMMING LAB IS-23 REGULATION

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

M.V.R NARASIMHARAO ISTS FOR WOMEN 23


C PROGRAMMING LAB IS-23 REGULATION

1.Aim: Copy the contents of one file to another file.


2.Software Required: TURBO C
3.Program:
#include<stdio.h>
#include<stdlib.h>
void main( )
{
FILE *sourceFile, *destinationFile;
char ch;
sourceFile = fopen("source.txt", "r");
if (sourceFile == NULL)
{
printf("Could not open the source file for reading.\n");
exit(1);
}
destinationFile = fopen("destination.txt", "w");
if (destinationFile == NULL)
{
printf("Could not open the destination file for writing.\n");
fclose(sourceFile);
exit(1);
}
while ((ch = fgetc(sourceFile)) != EOF)
{
fputc(ch, destinationFile);
}
fcloseall( );
printf("File contents copied successfully.\n");
}

M.V.R NARASIMHARAO ISTS FOR WOMEN 24


C PROGRAMMING LAB IS-23 REGULATION

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

while ((ch = fgetc(inputFile1)) != EOF)


{
fputc(ch, outputFile);
}
while ((ch = fgetc(inputFile2)) != EOF)
{
fputc(ch, outputFile);
}
fclose(inputFile1);

M.V.R NARASIMHARAO ISTS FOR WOMEN 25


C PROGRAMMING LAB IS-23 REGULATION

fclose(inputFile2);
fclose(outputFile);
printf("Files merged successfully.\n");
}

1.Aim: Find no. of lines, words and characters in a file


2.Software Required: TURBO C
3.Program:
#include<stdio.h>
void countLinesWordsCharacters(FILE *file, int *lines, int *words, int *characters)
{
int ch;
int inWord = 0;
*lines = *words = *characters = 0;
while ((ch = fgetc(file)) != EOF)
{
(*characters)++;
if (ch == '\n')
{
(*lines)++;
(*words)++;
}
if (ch == ' '|| ch==’.’|| ch==’,’)
(*words)++;
}
}
void main( )
{
FILE *file;
char fileName[50];
int lines, words, characters;
printf("Enter the name of the file: ");
scanf("%s", fileName);
file = fopen(fileName, "r");
if (file == NULL)
{
printf("Could not open the file for reading.\n");
exit(1);
}
countLinesWordsCharacters(file, &lines, &words, &characters);
fclose(file);
printf("Number of lines: %d\n", lines);
printf("Number of words: %d\n", words);
printf("Number of characters: %d\n", characters);
}

M.V.R NARASIMHARAO ISTS FOR WOMEN 26


C PROGRAMMING LAB IS-23 REGULATION

1.Aim: Write a C program to print last n characters of a given file.


2.Software Required: TURBO C
3.Program:
#include<stdio.h>
#include<stdlib.h>
void printLastNCharacters(FILE *file, int n)
{
int ch;
fseek(file, 0, SEEK_END);
long fileSize = ftell(file);
long startPosition = fileSize - n;
if (startPosition< 0)
{
startPosition = 0;
}
fseek(file, startPosition, SEEK_SET);
while ((ch = fgetc(file)) != EOF)
{
putchar(ch);
}
}
void main( )
{
FILE *file;
char fileName[50];
int n;
printf("Enter the name of the file: ");
scanf("%s", fileName);
file = fopen(fileName, "r");
if (file == NULL)
{
printf("Could not open the file for reading.\n");
exit(1);
}
printf("Enter the value of 'n': ");
scanf("%d", &n);
printf("Last %d characters of the file:\n", n);
printLastNCharacters(file, n);
fclose(file);
}

M.V.R NARASIMHARAO ISTS FOR WOMEN 27

You might also like