0% found this document useful (0 votes)
8 views36 pages

Lab1 To Lab7

The document is a lab manual for an introduction to programming, focusing on the Linux environment and C programming. It covers basic Linux commands, usage of text editors like Vi and Turbo C, and provides examples of writing, compiling, and executing C programs. Additionally, it includes algorithms and source codes for various programming tasks such as calculating simple interest, temperature conversion, and finding the area of a triangle.

Uploaded by

SwethaRouthu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views36 pages

Lab1 To Lab7

The document is a lab manual for an introduction to programming, focusing on the Linux environment and C programming. It covers basic Linux commands, usage of text editors like Vi and Turbo C, and provides examples of writing, compiling, and executing C programs. Additionally, it includes algorithms and source codes for various programming tasks such as calculating simple interest, temperature conversion, and finding the area of a triangle.

Uploaded by

SwethaRouthu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

INTRODUCTION TO PROGRAMMING LAB MANUAL

LAB1: Familiariza on With Programming Environment


i) AIM: Basic Linux environment and its editors like Vi, Vim & Emacs etc.

Introduc on to Linux: Linux is a widely-used, open-source opera ng system.

In programming, it is known for its stability, security, and powerful tools for

so ware development. This lab focuses on the basics of the Linux environment,

which is essen al for coding in languages like C.

File and Directory Opera ons:

 pwd (Print Working Directory):


Displays the full path of the current directory.

 ls (List Files):
Lists the files and directories in the current directory.
ls -l displays detailed informa on (permissions, owner, size).
ls -a displays hidden files (star ng with).

 cd (Change Directory):
Used to navigate between directories.
mkdir (Make Directory):
Creates a new directory.

 rmdir (Remove Directory):


Deletes an empty directory.
rm (Remove File):
Deletes files or directories.

 cp (Copy File/Directory):
Copies files or directories from one loca on to another.

 mv (Move/Rename File):
Moves or renames files or director

 touch (Create Empty File):


Creates a new empty file.

Steps to Write, Compile, and Execute a C Program Using vi Editor:


Step 1: Open vi editor and create a new file.
1. Open the terminal and navigate to the directory where you want to create
your C program file.
2. Use the vi command to create a new C program file:
$ vi program.c
This will open the vi editor with the new file named program.c.

Step 2: Enter Insert Mode to Write Code.


1. Press i to enter Insert Mode.
2. Type your C program.

Step 3: Save and Exit vi.


1. Once you've finished typing the program, press Esc to exit Insert Mode.
2. To save the file and exit the editor,
3. type: :wq-This command writes the file (saves) and quits the vi editor.

Step 4: compila on & execu on Using cc (C Compiler)


cc is usually an alias for gcc on many Linux systems, but some mes, it points to
a different C compiler. You can compile your program using cc as follows:
$ cc program.c.

Step 5: Execute the Program Using a.out


To run the program, type the following command:
$ ./a.out

Emacs: Another powerful text editor, with more built-in features and
extensibility op ons.
ii) AIM: Exposure to Turbo C, gcc

1. Turbo C
Turbo C is an older C compiler originally developed by Borland. It became
quite popular in the 1990s, especially in educa onal ins tu ons, due to its
simplicity and an integrated development environment (IDE). Despite its age,
it's s ll taught in some courses for familiarity, though it's not widely used in
modern development environments.

Key Features of Turbo C:


 Integrated IDE: Combines an editor, compiler, and debugger in one.
 Simple to use, with an old-style graphical interface.
 Mainly designed for DOS-based systems, though versions exist for
Windows.

Working with Turbo C:


1. Installing Turbo C:
o You can download Turbo C or Turbo C++ from sites that provide
legacy so ware. Some versions run on DOSBox, an x86 emulator
for running old DOS programs on modern opera ng systems like
Windows.
2. Wri ng a Program:
o Open Turbo C, create a new file, and write your C program.
3. Compiling and Running the Program:
o Press Alt + C to compile.
o Press Ctrl + F9 to run the program.
o The output will be displayed in the output window.

Limita ons of Turbo C:


 Outdated and no longer maintained.
 Limited to 16-bit DOS programs.
 Not suitable for modern opera ng systems or large-scale projects.
2. GCC (GNU Compiler Collec on)
GCC is a modern and widely used compiler that supports mul ple
programming languages, including C. It is part of the GNU Project and is open
source, making it the de facto compiler for C and C++ development on Unix
like systems, including Linux and macOS.

Key Features of GCC:


 Cross-pla orm: Available on Linux, macOS, and Windows (via MinGW
or Cygwin).
 Powerful op miza on and debugging features.
 Can compile code for mul ple architectures, Constantly updated and
maintained.

Working with GCC:


1. Installing GCC:
o On Linux, GCC is usually pre-installed. If not, you can install it
using the package manager:
 Ubuntu/Debian: sudo apt-get install gcc
 Fedora:
sudo dnf install gcc
o On Windows, you can install GCC via MinGW or use
environments like Cygwin.

2. Wri ng and Compiling a Program:


Write your program in any text editor (like vi, vim, nano, or gedit).
 To compile the program, open the terminal and run:
gcc program.c -o program

 Running the Program: A er compiling, you can execute the


program with:
./program

Advantages of GCC:

 Ac vely maintained and widely used in modern systems.


 Supports advanced features and op miza ons.
 Handles larger programs and projects, Cross-pla orm and open-source.

iii) Wri ng simple programs using prin (), scanf():


PROGRAM-1:
AIM: To write a program that prints a gree ng message using prin ().

ALGORITHM:
1. Start the program.
2. Use prin () to display a gree ng message.
3. End the program.

SOURCE CODE:
#include <stdio.h>
int main() {
// Print a gree ng message
prin ("Hello, welcome to the world of C programming!\n");
return 0;
}

OUTPUT:
Hello, welcome to the world of C programming!

PROGRAM-2:
AIM: To write a program that reads an integer from the user and prints it.

ALGORITHM:
1. Start the program.
2. Declare an integer variable.
3. Use prin () to print the user for input.
4. Use scanf() to read an integer from the user and store it in the variable.
5. Use prin () to print the entered integer.
6. End the program.

SOURCE CODE:
#include <stdio.h>
int main() {
int number;
// Print the user for an integer
prin ("Enter an integer: ");
// Read the integer input
scanf("%d", &number);
// Print the entered integer
prin ("You entered: %d\n", number);
return 0;
}

OUTPUT:
Enter an integer: 25
You entered: 25
LAB 2: Conver ng algorithms/flow charts into C Source code

i) AIM: Sum and average of 3 numbers

ALGORITHM:
1. Start the program .
2. Declare three float variables for the numbers and two float variables for
the sum and average.
3. Use prin () to print the user for the first number.
4. Use scanf() to read the first number.
5. Repeat steps 3 and 4 for the second and third numbers.
6. Calculate the sum of the three numbers.
7. Calculate the average by dividing the sum by 3.
8. Use prin () to display the sum and average.
9. End the program.

SOURCE CODE:
#include <stdio.h>
int main() {
// Declare variables
float num1, num2, num3, sum, average;
// Print user to enter three numbers
prin ("Enter the first number: ");
scanf("%f", &num1);
prin ("Enter the second number: ");
scanf("%f", &num2);
prin ("Enter the third number: ");
scanf("%f", &num3);

// Calculate the sum of the three numbers


sum = num1 + num2 + num3;
// Calculate the average of the three numbers
average = sum / 3;
// Print the sum and average
prin ("Sum of the three numbers: %.2f\n", sum);
prin ("Average of the three numbers: %.2f\n", average);
return 0;
}
OUTPUT:
Enter the first number: 5.5
Enter the second number: 10.0
Enter the third number: 15.0
Sum of the three numbers: 30.50
Average of the three numbers: 10.17
ii) AIM: Conversion of Fahrenheit to Celsius and vice versa
ALGORITHM:
1. Start the program.
2. Declare variables for temperature in Celsius and Fahrenheit.
3. Use prin () to print the user for the temperature and the type of
conversion (F to C or C to F).
4. Use scanf() to read the input temperature and conversion choice.
5. Perform the conversion based on the user's choice:
o Celsius to Fahrenheit: F = C * 9/5 + 32
o Fahrenheit to Celsius: C = (F - 32) * 5/9
6. Use prin () to display the converted temperature.
7. End the program.

SOURCE CODE:
//CONVERSION OF [TEMPERATURE] FARENHEIT TO CELSIUS & VICE
VERSA
#include<stdio.h>
int main()
{
float fahrenheit,celsius;
//inser on of temperature parameters in fahrenheit degree
prin ("ENTER TEMPERATURE IN FAHRENHEIT:");
scanf("%f",&fahrenheit);
//conversion of Fahrenheit to celsius formula
celsius = (fahrenheit - 32)*5/9;
prin ("\nAFTER CONVERSION OF FAHRENHEIT %f TO CELSIUS
IS: %f",fahrenheit, celsius);

//inser on of temperature parameters in celsius degree


prin ("\n\nENTER TEMPERATURE IN CELSIUS:");
scanf("%f",&celsius);
//conversion of celsius to fahrenheit formula
fahrenheit = (1.8 * celsius) + 32;
prin ("\nAFTER CONVERSION OF CELSIUS %f TO FAHRENHEIT
IS: %f",celsius,fahrenheit);
return 0;
}

OUTPUT:
Enter temperature in Celsius: 25
Temperature in Fahrenheit: 77.00
(Choice 2 - Fahrenheit to Celsius):
Enter temperature in Fahrenheit: 98.6
Temperature in Celsius: 37.00
iii) AIM: Simple interest calcula on
ALGORITHM:
1. Start the program.
2. Declare variables for principal, rate, me, and interest.
3. Use prin () to print the user for the principal amount, rate of interest, and
me period.
4. Use scanf() to read the input values.
5. Calculate the simple interest using the formula: Interest = (Principal *
Rate * Time) / 100
6. Use prin () to display the calculated interest.
7. End the program.

SOURCE CODE:
#include <stdio.h>
int main() {
// Declare variables for principal, rate, me, and interest
float principal, rate, me, interest;
// Print user for principal amount
prin ("Enter the principal amount: ");
scanf("%f", &principal);
// Print user for rate of interest
prin ("Enter the rate of interest (in percent): ");
scanf("%f", &rate);
// Print user for me period
prin ("Enter the me period (in years): ");
scanf("%f", & me);
// Calculate simple interest
interest = (principal * rate * me) / 100;
// Print the calculated interest
prin ("Simple Interest: %.2f\n", interest);
return 0;
}
OUTPUT:
Enter the principal amount: 1000
Enter the rate of interest (in percent): 5
Enter the me period (in years): 2
Simple Interest: 100.00
Lab 3: Simple computa onal problems using arithme c expressions

i) AIM: Finding the square root of a given number

SOURCE CODE:
#include <stdio.h>
#include <math.h> // For the sqrt() func on
int main() {
// Declare variable to store the input number and result
double number, squareRoot;
// Print user to enter a number
prin ("Enter a number to find its square root: ");
scanf("%lf", &number);
// Calculate the square root of the number
squareRoot = sqrt(number);
// Print the square root
prin ("Square root of %.2lf is: %.2lf\n", number, squareRoot);

return 0;
}

OUTPUT:
Enter a number to find its square root: 16
Square root of 16.00 is: 4.00

ii) AIM: Finding compound interest

SOURCE CODE:
#include <stdio.h>
#include <math.h>
int main() {
// Ini alize variables for the principal amount, interest rate, me,
// No. of compounding periods, compound interest (CI), and final amount (A)
double principle, rate, me, n, CI, A;
// Print the user to enter the principal amount
prin ("Enter the principal amount: ");
// Take the principal amount as input
scanf("%lf", &principle);
// Print the user to enter an annual interest rate in percentage (for example, 5%
for five years).
prin ("Enter the annual interest rate (e.g., for 5%%, enter 5): ");
// Take the annual interest rate as input
scanf("%lf", &rate);
// Convert the entered interest rate to a decimal
rate = rate / 100;
// Print the user to enter the me in years
prin ("Enter the me (in years): ");
// Take the me as input
scanf("%lf", & me);
// Print the user to enter the number of mes that interest is compounded peryear

prin ("Enter the number of mes that interest is compounded annually: ");
// Take the number of compounding periods as input
scanf("%lf", &n);
// Calculate the final amount a er me 't' with compound interest
A = principle * pow((1 + rate / n), n * me);
// Calculate the compound interest by subtrac ng the principal from the final
amount
CI = A - principle;
// Print the compound interest
prin ("The compound interest is: %.2lf\n", CI);
return 0;
}
OUTPUT:
Enter the principal amount: 1000
Enter the annual interest rate (e.g., for 5%, enter 5): 8
Enter the me (in years): 6
Enter the number of mes that interest is compounded annually: 4
The compound interest is: 608.44

iii) AIM: Area of a triangle using Heron’s Formulae

SOURCE CODE:
#include <stdio.h>
#include <math.h> // For the sqrt() func on
int main() { // Declare variables for the sides of the triangle and the area
double a, b, c, s, area;
// Print user for the lengths of the sides of the triangle
prin ("Enter the length of side a: ");
scanf("%lf", &a);
prin ("Enter the length of side b: ");
scanf("%lf", &b);
prin ("Enter the length of side c: ");
scanf("%lf", &c);
// Calculate the semi-perimeter
s = (a + b + c) / 2;
// Calculate the area using Heron's Formula
area = sqrt(s * (s - a) * (s - b) * (s - c)); // Print the area of the triangle
prin ("Area of the triangle: %.2lf\n", area);
return 0;
}

OUTPUT:
Enter the length of side a: 5
Enter the length of side b: 6
Enter the length of side c: 7
Area of the triangle: 14.70

iv) AIM: Distance travelled by an object

SOURCE CODE:
#include <stdio.h>
int main() {
// Declare variables for speed, me, and distance
double speed, me, distance;
// Prompt user for speed of the object
prin ("Enter the speed of the object (in km/h): ");
scanf("%lf", &speed);
// Prompt user for me of travel
prin ("Enter the me of travel (in hours): ");
scanf("%lf", & me);
// Calculate the distance travelled using the formula
distance = speed * me;
// Print the distance travelled
prin ("Distance travelled: %.2lf km\n", distance);
return 0;
}

OUTPUT:
Enter the speed of the object (in km/h): 60
Enter the me of travel (in hours): 3
Distance travelled: 180.00 km
LAB 4: Simple computa onal problems using “OPERATOR’S” the precedence
and associa vity.
i) Evaluate the following expressions.
a. A+B*C+(D*E) + F*G
b. A/B*C-B+A*D/3
c. A+++B---A
d. J= (i++) + (++i)
ALGORITHM:
Step 1: Declare A,B,C,D,E,F,G,i,j.
Step 2: Read A,B,C,D,E,F,G,i,j Values.
Step 3: Evaluate the below expressions
result_a = A + B * C + (D * E) + F * G.
result_b = A / B * C - B + A * D / 3.
result_c = A++ + ++B - --A.
J = (i++) + (++i).
Step 4: Print result_a,result_b,result_c,j
Step 5: Exit or terminate the program.

SOURCE CODE:
#include <stdio.h>
int 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;
// a. Evaluate A+B*C+(D*E) + F*G
result_a = A + B * C + (D * E) + F * G;
prin ("a. Result of expression A+B*C+(D*E) + F*G is: %d\n", result_a);
// b. Evaluate A/B*C-B+A*D/3
result_b = A / B * C - B + A * D / 3;
prin ("b. Result of expression A/B*C-B+A*D/3 is: %d\n", result_b);
// c. Evaluate A+++B---A
result_c = A++ + ++B - --A;
prin ("c. Result of expression A+++B---A is: %d\n", result_c);
// d. Evaluate J = (i++) + (++i)
j = (i++) + (++i);
prin ("d. Value of J a er J = (i++) + (++i) is: %d\n",
j); return 0;
}
OUTPUT:
a.Result of expression A+B*C+(D*E) + F*G is: 70
b.Result of expression A/B*C-B+A*D/3 is:1
c.Result of expression A+++B---A is:11
d.Value of J a er J = (i++) + (++i) is:12
ii) AIM: Find the maximum of three numbers using condi onal operator

ALGORITHM:
1. Start
2. Input three numbers a, b, and c.
3. Use the condi onal operator to compare the numbers:
o Compare a with b. If a is greater, compare a with c. Otherwise,
compare b with c.
4. The result of the condi onal expression will give the maximum of the
three numbers.
5. Output the maximum number.
6. End

SOURCE CODE:
#include <stdio.h>
int main() {
// Declare variables
int a, b, c, max;
// Input three numbers
prin ("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);
// Find the maximum using condi onal operator
max = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
// Output the maximum number
prin ("The maximum of the three numbers is: %d\n", max);
return 0;
}

OUTPUT:
Enter three numbers: 10 25 15
The maximum of the three numbers is: 25

iii) AIM: Take marks of 5 subjects in integers, and find the total, average in
float

ALGORITHM:
1. Start
2. Declare variables to store marks of 5 subjects, the total, and the average.
3. Input the marks of 5 subjects.
4. Calculate the total by summing up the marks of all subjects.
5. Calculate the average by dividing the total by 5.
6. Display the total as an integer.
7. Display the average as a floa ng-point number.
8. End
SOURCE CODE:
#include <stdio.h>
int main() {
// Declare variables to store marks, total, and average
int sub1, sub2, sub3, sub4, sub5, total;
float average;
// Input marks of 5 subjects
prin ("Enter the marks of 5 subjects: ");
scanf("%d %d %d %d %d", &sub1, &sub2, &sub3, &sub4, &sub5);
// Calculate total marks
total = sub1 + sub2 + sub3 + sub4 + sub5;
// Calculate average
average = total / 5.0;
// Output total and average
prin ("Total Marks: %d\n", total);

prin ("Average Marks: %.2f\n", average);


return 0;
}
OUTPUT:
Enter the marks of 5 subjects: 85 90 78 92 88
Total Marks: 433
Average Marks: 86.60
Lab 5: Problems involving if-then-else structures.
i) AIM: Write a C program to find the max and min of four numbers using if
else.

SOURCE CODE:

#include<stdio.h>
int main()
{
// Declare variables to store four numbers
int a1,a2,a3,a4,max,min;
// Prompt user to input four numbers
prin ("Input four numbers: \n");
scanf("%d %d %d %d",&a1,&a2,&a3,&a4);
// Find the maximum among the four numbers
if (a1 >= a2 && a1 >= a3 && a1 >= a4)
max = a1;
else if (a2 >= a1 && a2 >= a3 && a2 >= a4)
max = a2;
else if (a3 >= a1 && a3 >= a2 && a3 >= a4)
max = a3;
else
max = a4;
// Find the minimum among the four numbers
if (a1 <= a2 && a1 <= a3 && a1 <= a4)
min = a1;
else if (a2 <= a1 && a2 <= a3 && a2 <= a4)
min = a2;
else if (a3 <= a1 && a3 <= a2 && a3 <= a4)
min = a3;
else
min = a4;
// Calculate and display the difference between max and min
prin ("MAXIMUM is %d\n",max);
prin ("MINIMUM is %d\n",min);
return 0;
}
OUTPUT:
Input four numbers:
1
2
3
4
MAXIMUM is 4
MINIMUM is 1
ii) AIM: Write a C program to generate electricity bill.
ALGORITHM:
1. Start the program.
2. Declare variables to store the number of units consumed and the bill
amount.
3. Prompt the user to input the number of electricity units consumed.
4. Read the input value using scanf().
5. Apply the slab rates:
o If the units are ≤ 50, calculate the bill at ₹3.50 per unit.
o If the units are between 51 and 150, calculate the bill for the first
50 units at ₹3.50, and the remaining units at ₹4.00 per unit.
o If the units are > 150, calculate the bill for the first 50 units at
₹3.50, the next 100 units at ₹4.00, and the remaining units at ₹5.00
per unit.
6. Display the final bill amount using prin ().
7. End the program.

SOURCE CODE:
// Program to generate an electricity bill
#include <stdio.h>
int main() {
// Declare variables
int units;
// units consumed
float billAmount;

//Get the number of units consumed


prin ("Enter the number of electricity units consumed: ");
// Prompt the user to input the number of units consumed
scanf("%d", &units); // Read the integer input and store it in the variable 'units'
// Calculate bill based on the slab system
/* The slab system:
- First 50 units @ ₹3.50 per unit
- Next 100 units @ ₹4.00 per unit (units 51 to 150)
- Above 150 units @ ₹5.00 per unit
*/
if (units <= 50) {
// If units are less than or equal to 50, mul ply units by ₹3.50 per unit
billAmount = units * 3.50;
} else if (units <= 150) {
// If units are between 51 and 150, calculate for first 50 units at ₹3.50,
// then calculate remaining units (units - 50) at ₹4.00 per unit

billAmount = (50 * 3.50) + ((units - 50) * 4.00);


} else {
// If units are greater than 150, calculate for first 50 units at ₹3.50,
// next 100 units at ₹4.00, and the remaining units (units - 150) at ₹5.00
billAmount = (50 * 3.50) + (100 * 4.00) + ((units - 150) * 5.00);
}

// Output the calculated bill amount


// Display the bill amount using '%.2f' to show the result up to 2 decimal places

prin ("Electricity bill for %d units is: ₹%.2f\n", units, billAmount);

return 0; // End of the program


}

OUTPUT-1:
Enter the number of electricity units consumed: 45
Electricity bill for 45 units is: ₹157.50

OUTPUT-2:
Enter the number of electricity units consumed: 170
Electricity bill for 170 units is: ₹665.00

iii) AIM: Find the roots of the quadra c equa on.

ALGORITHM:
1. Start the program.
2. Declare variables to store coefficients a, b, c, discriminant, and the roots.
3. Prompt the user to input the coefficients of the quadra c equa on.
4. Read the input values using scanf().
5. Calculate the discriminant D=b2−4acD = b^2 - 4acD=b2−4ac.
6. Use the value of discriminant to determine the nature of roots:
o If D>0D > 0D>0, the roots are real and different.
o If D=0D = 0D=0, the roots are real and equal.
o If D<0D < 0D<0, the roots are imaginary (complex).
7. Compute the roots using the quadra c formula.
8. Display the roots based on the discriminant value.
9. End the program.

SOURCE CODE:
// Program to find the roots of a quadra c equa on
#include <stdio.h> // This header file is used for input-output func ons
#include <math.h> // This header file provides the sqrt() func on for square
int main() {
// Declare variables to store coefficients and roots
float a, b, c; // Coefficients of the quadra c equa on
float discriminant, root1, root2, realPart, imaginaryPart;
// Get the coefficients from the user
prin ("Enter coefficients a, b, and c: ");

// Prompt the user to enter values of a, b, and c


scanf("%f %f %f", &a, &b, &c); // Read three floa ng-point values a,b,c
// Calculate the discriminant
discriminant = b * b - 4 * a * c;
// Determine the nature of the roots based on the discriminant
if (discriminant > 0) {
// If discriminant is posi ve, the roots are real and different
root1 = (-b + sqrt(discriminant)) / (2 * a); // First root
root2 = (-b - sqrt(discriminant)) / (2 * a); // Second root
prin ("Roots are real and different: root1 = %.2f, root2 = %.2f\n", root1,
root2);
} else if (discriminant == 0) {
// If discriminant is zero, the roots are real and equal
root1 = -b / (2 * a); // Both roots are the same
prin ("Roots are real and equal: root1 = root2 = %.2f\n", root1);
} else {
// If discriminant is nega ve, the roots are imaginary (complex)
realPart = -b / (2 * a); // Real part of the complex root
imaginaryPart = sqrt(-discriminant) / (2 * a); // Imaginary part
prin ("Roots are complex: root1 = %.2f + %.2fi, root2 = %.2f - %.2fi\n",
realPart, imaginaryPart, realPart, imaginaryPart);
}
return 0; // End of the program
}

OUTPUT-1:
Enter coefficients a, b, and c: 1 -3 2
Roots are real and different: root1 = 2.00, root2 = 1.00

OUTPUT-2:
Enter coefficients a, b, and c: 1 -2 1
Roots are real and equal: root1 = root2 = 1.00

iv) AIM: Write a C program to simulate a calculator using switch case.

SOURCE CODE:
// C program to simulate a calculator using switch case
#include <stdio.h> // Includes standard input-output func ons
int main() {
// Declare two float variables to store the numbers, and a variable to store the result
float num1, num2, result;
char operator; // Declare a character variable to store the operator
// Prompt the user to enter the numbers
prin ("Enter two numbers: ");
// Read the input values from the user
scanf("%f %f", &num1, &num2);
// Ask the user to enter the operator for the opera on
prin ("Enter an operator (+, -, *, /): ");
// Read the operator
scanf(" %c", &operator); // No ce the space before %c to avoid reading
newline
// Use switch to perform the opera on based on the input operator
switch (operator) {
case '+':
result = num1 + num2; // Addi on of num1 and num2
prin ("Result: %.2f + %.2f = %.2f\n", num1, num2, result); // Print result
break;

case '-':
result = num1 - num2; // Subtrac on of num2 from num1

prin ("Result: %.2f - %.2f = %.2f\n", num1, num2, result);


break;

case '*':
result = num1 * num2; // Mul plica on of num1 and num2
prin ("Result: %.2f * %.2f = %.2f\n", num1, num2, result);
break;

case '/':
if (num2 != 0) { // Ensure the denominator is not zero
result = num1 / num2; // Division of num1 by num2
prin ("Result: %.2f / %.2f = %.2f\n", num1, num2, result);
}
else {
prin ("Error! Division by zero is not allowed.\n");
}
break;

default:
prin ("Error! Invalid operator.\n"); // If the user enters an invalid operator
break;
}
return 0; // End of the program
}
OUTPUT-1:
Enter two numbers: 5 3
Enter an operator (+, -, *, /): +
Result: 5.00 + 3.00 = 8.00
OUTPUT-2:
Enter two numbers: 10 4
Enter an operator (+, -, *, /): -
Result: 10.00 - 4.00 = 6.00
OUTPUT-3:
Enter two numbers: 6 7
Enter an operator (+, -, *, /): *
Result: 6.00 * 7.00 = 42.00
OUTPUT-4:
Enter two numbers: 9 3
Enter an operator (+, -, *, /): /
Result: 9.00 / 3.00 = 3.00
OUTPUT-5:
Enter two numbers: 5 0
Enter an operator (+, -, *, /): /
Error! Division by zero is not allowed.
OUTPUT-6:
Enter two numbers: 8 2
Enter an operator (+, -, *, /): &
Error! Invalid operator.

v) AIM: Write a C program to find the given year is a leap year or not.

SOURCE CODE:
// Program to check whether a given year is a leap year or not

#include <stdio.h>
int main() {
int year; // Declare an integer variable to store the year
// Prompt the user to enter a year
prin ("Enter a year: ");
// Read the input year from the user
scanf("%d", &year);
// Check if the year is a leap year
// A leap year is divisible by 4 and not divisible by 100 unless it is divisible by 400
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
prin ("%d is a leap year.\n", year); // Print if it is a leap year
} else {
prin ("%d is not a leap year.\n", year); // Print if it is not a leap year
}
return 0; // End of the program
}

OUTPUT-1 (Leap Year):


Enter a year: 2020
2020 is a leap year.
OUTPUT-2 (Not a Leap Year):
Enter a year: 2021
2021 is not a leap year.

OUTPUT-3 (Century Year - Leap Year):


Enter a year: 2000
2000 is a leap year.

OUTPUT-4 (Century Year - Not a Leap Year):


Enter a year: 1900
1900 is not a leap year.
Lab 6: Itera ve problems e.g., the sum of series - Loops, while and for
loops.

i) AIM: Find the factorial of given number using any loop.

SOURCE CODE:
// Program to find the factorial of a given number using a loop
#include <stdio.h> // Standard input-output header file
int main() {
int number; // Declare an integer variable to store the input number
int factorial = 1; // Ini alize factorial to 1
// Prompt the user to enter a posi ve integer
prin ("Enter a posi ve integer: ");
// Read the input number from the user
scanf("%d", &number);
// Check if the input number is nega ve
if (number < 0) {
prin ("Error! Factorial of a nega ve number doesn't exist.\n");
} else {
// Calculate factorial using a for loop
for (int i = 1; i <= number; ++i) {
factorial *= i; // Mul ply factorial by i
}
// Print the factorial of the given number
prin ("Factorial of %d = %d\n", number, factorial);
}

return 0; // End of the program


}

OUTPUT-1:
Enter a posi ve integer: 5
Factorial of 5 = 120

OUTPUT-2 (Zero):
Enter a posi ve integer: 0
Factorial of 0 = 1

OUTPUT-3 (Nega ve Integer):


Enter a posi ve integer: -3
Error! Factorial of a nega ve number doesn't exist.
ii) AIM: Find the given number is a prime or not.

SOURCE CODE:
#include <stdio.h>
int main()
{
int n, i, flag = 0;
prin ("Enter a posi ve integer: ");
scanf("%d", &n);
// 0 and 1 are not prime numbers
// change flag to 1 for non-prime number
if (n == 0 || n == 1)
flag = 1;
for (i = 2; i <= n / 2; ++i) {
// if n is divisible by i, then n is not prime
// change flag to 1 for non-prime number
if (n % i == 0) {
flag = 1;
break;
}
} // flag is 0 for prime numbers
if (flag == 0)
prin ("%d is a prime number.", n);
else
prin ("%d is not a prime number.", n);
return 0;
}

OUTPUT-1:
Enter a posi ve integer: 29
29 is a prime number.

OUTPUT-2:
Enter a posi ve integer: 10
10 is not a prime number.

iii) AIM: Compute sine and cos series


ALGORITHM:
1. Start.
2. Input the angle in degrees.
3. Convert the angle to radians.
4. Calculate sine and cosine using their respec ve series expansions:
o Sine series: sin(x)=x−x3 /3! + x5/ 5!−x7 / 7! +…
sin(x) = x - \frac{x^3}{3!} + \frac{x^5}{5!} - \frac{x^7}{7!} +
\dotssin(x)=x−3!x3+5!x5−7!x7+…
o Cosine series: cos⁡(x)=1−x22!+x44!−x66!+…\cos(x) = 1 -
\frac{x^2}{2!} + \frac{x^4}{4!} - \frac{x^6}{6!} +
\dotscos(x)=1−2!x2+4!x4−6!x6+…
5. Output the results.
6. End.
SOURCE CODE:
#include <stdio.h>
#include <math.h> // For M_PI and pow
int main() {
double angle_degrees, angle_radians;
double sine_value = 0.0, cosine_value = 1.0;
int terms, i;
double term;
// Input the angle in degrees
prin ("Enter the angle in degrees: ");
scanf("%lf", &angle_degrees);

// Input the number of terms for the series


prin ("Enter the number of terms: ");
scanf("%d", &terms);
// Convert the angle from degrees to radians
angle_radians = angle_degrees * (M_PI / 180.0);

// Sine series expansion


for (i = 1; i <= terms; i++) {
term = pow(angle_radians, 2 * i - 1) / (1.0);
for (int j = 1; j <= 2 * i - 1; j++) {
term /= j; // Calcula ng factorial in the loop
}
if (i % 2 == 0) {
sine_value -= term;
} else {
sine_value += term;
}
}
// Cosine series expansion
for (i = 1; i <= terms; i++) {
term = pow(angle_radians, 2 * i) / (1.0);
for (int j = 1; j <= 2 * i; j++) {
term /= j; // Calcula ng factorial in the loop
}
if (i % 2 == 0) {
cosine_value += term;

} else {
cosine_value -= term;
}
}
// Output the results
prin ("Sine(%lf) = %lf\n", angle_degrees, sine_value);
prin ("Cosine(%lf) = %lf\n", angle_degrees, cosine_value);

return 0;
}

OUTPUT-1:
Enter the angle in degrees: 30
Enter the number of terms: 5
Sine(30.000000) = 0.500000
Cosine(30.000000) = 0.866025

OUTPUT-2:
Enter the angle in degrees: 45
Enter the number of terms: 5
Sine(45.000000) = 0.707107
Cosine(45.000000) = 0.707107

iv) AIM: Checking a number palindrome

SOURCE CODE:
#include <stdio.h>
int main() {
int number, original_number, remainder, reversed_number = 0;
// Input the number
prin ("Enter a number: ");
scanf("%d", &number);
// Store the original number for comparison later
original_number = number;
// Reverse the digits of the number
while (number != 0) {
remainder = number % 10;
reversed_number = reversed_number * 10 + remainder;
number /= 10;
}
// Check if the original number is equal to the reversed number
if (original_number == reversed_number) {
prin ("%d is a palindrome.\n", original_number);
} else {
prin ("%d is not a palindrome.\n", original_number);
}

return 0;
}

Output-1:
Enter a number: 121
121 is a palindrome.

Output-2:
Enter a number: 123
123 is not a palindrome.

v) AIM: Construct a pyramid of numbers.


SOURCE CODE:
#include <stdio.h>
int main()
{ int rows, i, j, space, number;
// Input the number of rows for the pyramid
prin ("Enter the number of rows: ");
scanf("%d", &rows);
// Outer loop for each row
for (i = 1; i <= rows; i++) {
// Print spaces before the numbers
for (space = 1; space <= rows - i; space++) {
prin (" ");
}
// Print numbers in increasing order
number = 1;
for (j = 1; j <= i; j++) {
prin ("%d ", number);
number++;
}
// Move to the next line a er each row
prin ("\n");
}
return 0;
}
OUTPUT-1:
[For input of 5 rows:]
1
12
123
1234
12345

OUTPUT-2:
[For input of 3 rows:]
1
12
123
Lab 7: 1D Array manipula on, linear search

i) AIM: Find the min and max of a 1-D integer array.

SOURCE CODE:
#include <stdio.h>
int main() {
int n, i, min, max;
// Asking for the number of elements in the array
prin ("Enter the number of elements in the array: ");
scanf("%d", &n);
int arr[n];
// Input the elements of the array
prin ("Enter the elements of the array:\n");
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Ini alize min and max with the first element of the array
min = arr[0];
max = arr[0];
// Loop to find the min and max
for(i = 1; i < n; i++) {
if(arr[i] < min) {
min = arr[i]; // Update min
}
if(arr[i] > max) {
max = arr[i]; // Update max
}
}
// Displaying the results
prin ("Minimum element: %d\n", min);
prin ("Maximum element: %d\n", max);
return 0;
}

OUTPUT-1:
Enter the number of elements in the array: 5
Enter the elements of the array:
12 4 56 1 23
Minimum element: 1
Maximum element: 56
OUTPUT-2:
Enter the number of elements in the array: 3
Enter the elements of the array:
9 18 3
Minimum element: 3
Maximum element: 18

ii) AIM: Perform linear search on1D array.

ALGORITHM:
1. Start.
2. Declare an array and necessary variables.
3. Input the number of elements and the elements of the array.
4. Ask the user to input the element to search for.
5. Traverse the array:
o If the element is found, display its posi on (star ng from 0).
o If the element is not found a er checking all elements, display a
message indica ng that the element is not present in the array.
6. End.

SOURCE CODE:
#include <stdio.h>
int main() {
int n, i, search, found = 0;

// Asking for the number of elements in the array


prin ("Enter the number of elements in the array: ");
scanf("%d", &n);

int arr[n];

// Input the elements of the array


prin ("Enter the elements of the array:\n");
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Asking for the element to search
prin ("Enter the element to search: ");
scanf("%d", &search);

// Linear search algorithm


for(i = 0; i < n; i++) {
if(arr[i] == search) {
prin ("Element %d found at array index %d.\n", search, i);
found = 1; // Element found
break;
}
}

// If the element is not found in the array


if(!found) {
prin ("Element %d not found in the array.\n", search);
}

return 0;
}

OUTPUT-1:
Enter the number of elements in the array: 6
Enter the elements of the array:
10 25 30 45 50 75
Enter the element to search: 45
Element 45 found at array index 3.

OUTPUT-2:
Enter the number of elements in the array: 4
Enter the elements of the array:
5 8 12 16
Enter the element to search: 20
Element 20 not found in the array.

iii)Aim: The reverse of a 1D integer array

Algorithm
1. Start.
2. Input the size n of the array.
3. Input n integers into the array a[ ].
4. Ini alize two pointers: i = 0, j = n - 1.
5. While i < j,
6. Swap a[i] and a[j].
7. Increment i and decrement j.
8. Display the reversed array.
9. Stop.
Source Code:
#include <stdio.h>

int main() {
int n, i, temp;
prin ("Enter size of array: ");
scanf("%d", &n);
int a[n];

prin ("Enter %d elements: ", n);


for(i = 0; i < n; i++)
scanf("%d", &a[i]);

// Reversing the array


for(i = 0; i < n/2; i++) {
temp = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = temp;
}

prin ("Reversed array: ");


for(i = 0; i < n; i++)
prin ("%d ", a[i]);

return 0;
}
OUTPUT
Enter size of array: 5
Enter 5 elements: 1 2 3 4 5
Reversed array: 5 4 3 2 1
iv)AIM: Find 2’s Complement of a Binary Number

ALGORITHM
1. Start.
2. Input a binary number as a string.
3. Traverse the binary number from right to le .
4. Copy all bits un l you find the first 1.
5. A er the first 1, invert all remaining bits.
6. Display the result as 2’s complement.
7. Stop.

SOURCE CODE

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

int main() {
char bin[50];
int i, foundOne = 0;

prin ("Enter a binary number: ");


scanf("%s", bin);

int n = strlen(bin);

for(i = n - 1; i >= 0; i--) {


if(foundOne)
bin[i] = (bin[i] == '0') ? '1' : '0';
if(bin[i] == '1' && !foundOne)
foundOne = 1;
}

prin ("2's Complement: %s\n", bin);


return 0;
}

OUTPUT
Enter a binary number: 10100
2's Complement: 01100
iii) AIM: Eliminate Duplicate Elements in an Array

ALGORITHM
1. Start.
2. Input the size n of the array.
3. Input n elements into array a[ ].
4. For each element a[i], compare with all previous elements.
5. If it has appeared before, skip it.
6. Store only unique elements in another array b[ ].
7. Display the unique elements.
8. Stop.

SOURCE CODE

#include <stdio.h>

int main() {
int n, i, j, k = 0, flag;
prin ("Enter size of array: ");
scanf("%d", &n);
int a[n], b[n];

prin ("Enter %d elements: ", n);


for(i = 0; i < n; i++)
scanf("%d", &a[i]);

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


flag = 0;
for(j = 0; j < k; j++) {
if(a[i] == b[j]) {
flag = 1;
break;
}
}
if(!flag)
b[k++] = a[i];
}
prin ("Array a er removing duplicates: ");

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


prin ("%d ", b[i]);

return 0;}
OUTPUT

Enter size of array: 8


Enter 8 elements: 1 2 3 2 4 3 5 1
Array a er removing duplicates: 1 2 3 4 5

You might also like