CP Lab Record (2024)
CP Lab Record (2024)
LAB MANUAL
ON
Vision
To be a Centre of Excellence in computer science and engineering education and training to
meet the challenging needs of the industry and society.
Mission
• To impart quality education through well-designed curriculum in tune with the growing
software needs of the industry.
• To be a Centre of Excellence in computer science and engineering education and training to
meet the challenging needs of the industry and society.
• To serve our students by inculcating in them problem solving, leadership, teamwork skills and
the value of commitment to quality, ethical behavior & respect for others.
• To foster industry-academia relationship for mutual benefit and growth.
Week 2:
1. Sumandaverageof3numbers
Problem-solving 2. Conversion of Fahrenheit to Celsius and vice
versa 12-16
using
Algorithms and 3. Simple interest calculation
Flow charts
COURSE OBJECTIVES
COURSE OUTCOMES
CO1: Read, understand, and trace the execution of programs written in C language.
CO2: Select the right control structure for solving the problem.
CO3: Develop C programs which utilize memory efficiently using programming constructs like
pointers.
CO4: Develop Debug and Execute programs to demonstrate the applications of arrays, functions,
basic concepts of pointers in C.
REFERENCES
GUIDELINES TO STUDENTS
• Equipment in the lab for the use of student community. Students need to maintain a proper
decorum in the computer lab.
• Students must use the equipment including PCs, Keyboard and Mouse with care. Any damage
is caused is punishable.
• Students are required to carry their observation and record books with completed exercises
while entering the lab.
• Students are supposed to occupy the machines allotted to them and are not supposed to talk or
make noise in the lab.
• Lab can be used in free time / lunch hours by the students. Students who need to use the
systems should take prior permission from the lab in-charge.
• Students are not supposed to use floppy disks/CDs/Pen drives etc during the Lab session.
WEEK 1:
Objective: Getting familiar with the programming environment on the computer and writing the first
program.
Suggested Experiments/Activities:
i) Basic Linux environment and its editors like Vi, Vim & Emacs etc.
Vi:
The default editor that comes with the UNIX operating system is called vi (visual editor).
Using vi editor, we can edit an existing file or create a new file from scratch. we can also use this
editor to just read a text file. The advanced version of the vi editor is the vim editor.
The vi editor has two modes:
o Command Mode: In command mode, actions are taken on the file. The vi editor starts in
command mode. Here, the typed words will act as commands in vi editor. To pass a
command, you need to be in command mode.
o Insert Mode: In insert mode, entered text will be inserted into the file. The Esc key will take
you to the command mode from insert mode.
By default, the vi editor starts in command mode. To enter text, you have to be in insert
mode, just type 'i' and you'll be in insert mode. Although, after typing i nothing will appear on the
screen but you'll be in insert mode. Now you can type anything.
To exit from insert mode press Esc key, you'll be directed to command mode.
How to open VI editor?
To open vi editors, we just need to type the command mentioned below.
vi [file_name]
Here, [file_name] = this is the file name we want to create or to open the pre-existing file.
Vim:
Vim is a free and open-source, screen-based text editor program. It is an improved clone
of Bill Joy's vi. Vim's author, Bram Moolenaar, derived Vim from a port of the Stevie editor
for Amiga and released a version to the public in 1991. Vim is designed for use both from a command-
line interface and as a standalone application in a graphical user interface.
Since its release for the Amiga, cross-platform development has made it available on many
other systems. In 2018, it was voted the most popular editor amongst Linux Journal readers; in 2015
the Stack Overflow developer survey found it to be the third most popular text editor, and in 2019 the
fifth most popular development environment.
Emacs:
GNU Emacs is a free software text editor. It was created by GNU Project founder Richard
Stallman, based on the Emacs editor developed for Unix operating systems. GNU Emacs has been
acentral component of the GNU project and a flagship project of the free software movement. Its tag
line is "the extensible self-documenting text editor."
GNU Emacs was later ported to the Unix operating system. It offered more features than
Gosling Emacs, in particular a full-featured Lisp as its extension language, and soon replaced Gosling
Emacs as the de facto Unix Emacs editor. Markus Hess exploited a security flaw in GNU Emacs's
email subsystem in his 1986 cracking spree, in which he gained superuser access to Unix computers.
gcc:
The GNU Compiler Collection (GCC) is an optimizing compiler produced by the GNU
Project supporting various programming languages, hardware architectures and operating systems.
The Free Software Foundation (FSF) distributes GCC as free software under the GNU General Public
License (GNU GPL). GCC is a key component of the GNU toolchain and the standard compiler for
most projects related to GNU and the Linux kernel. With roughly 15 million lines of code in 2019,
GCC is one of the biggest free programs in existence. It has played an important role in the growth
of free software, as both a tool and an example.
When it was first released in 1987 by Richard Stallman, GCC 1.0 was named the GNU C
Compiler since it only handled the C programming language. It was extended to compile C++ in
December of that year. Front ends were later developed for Objective-C, Objective-
C++, Fortran, Ada, D, Go and Rust, among others. The OpenMP and OpenACC specifications are also
supported in the C and C++ compilers.
GCC has been ported to more platforms and instruction set architectures than any other
compiler, and is widely deployed as a tool in the development of both free and proprietary software.
GCC is also available for many embedded systems, including ARM-based and Power ISA-based
chips.
#include <stdio.h>
intmain()
{
printf("Hello World");
return0;
}
#include <stdio.h>
intmain()
{
intx = 5;
printf("Printing Integer value %d", x);
return0;
}
#include <stdio.h>
intmain()
{
intA, B, sum = 0;
printf("Enter two numbers A and B : \n");
scanf("%d,%d", &A, &B);
sum = A + B;
printf("Sum of A and B is: %d", sum);
return0;
}
OUTPUT: Enter two numbers A and B :
15,10
Sum of A and B is:25
#include <stdio.h>
intmain()
{
intx, y;
printf("\nEnter Value of x\t ");
scanf("%d", &x);
printf("\nEnter Value of y\t ");
scanf("%d", &y);
inttemp = x;
x = y;
y = temp;
printf("\nAfter Swapping: x = %d, y = %d", x, y);
return0;
}
WEEK 2:
Objective: Getting familiar with how to formally describe a solution to a problem in a series of finite
steps both using textual notation and graphic notation.
Algorithm:
1. Start
2. Declaring Variables
3. Input Three Numbers from User
4. Calculating Sum of Three Numbers (sum = num1+num2+num3)
5. Displaying the Sum of Three Numbers
6. Calculating Average of Three Numbers (average = sum/3)
7. Displaying the Average of Three Numbers
8. Stop
Flowchart:
Program:
#include<stdio.h>
int main()
{
int num1, num2, num3, sum;
float avg;
printf("Enter Three Numbers : \n");
scanf("%d %d %d",&num1,&nnum2,&num2);
sum = num1 + num2 + num3;
printf("Sum of Three Numbers is : %d", sum);
avg=sum/3;
printf("\n Average of Three Numbers is : %f", avg);
return0;
}
OUTPUT: Enter Three Numbers :
12
14
16
Sum of Three Numbers is : 42
Average of Three Numbers is : 14
Step 1: Start
Step 2: Read the value of temperature to be converted from the user
Step 3: Assign the value to a variable, say ‘cel’
Step 4: Initialize f = 0
Step 5: f = ((9/5) * cel ) + 32
Step 6: Display f
Step 7: Stop
Flowchart:
Program:
#include<stdio.h>
int main()
{
int p,r,t,si;
printf("Enter principle, Rate of interest & time to find simple interest: \n");
scanf("%d%d%d",&p,&r,&t);
si=(p*r*t)/100;
printf("Simple interest = %d",si);
return 0;
}
Output: Enter printciple, Rate of interest & time to find simple interest:
15000
5
12
Simple interest = 9000
WEEK 3:
Objective: Learn how to define variables with the desired data-type, initialize them with appropriate
values and how arithmetic operators can be used with variables and constants.
Suggested Experiments/Activities:
Tutorial 3: Variable types and type conversions:
Lab 3: Simple computational problems using arithmetic expressions.
i) Finding the square root of a given number
ii) Finding compound interest
iii) Area of a triangle using heron’s formulae
iv)Distance travelled by an object
Flowchart:
Compound Interest:
Algorithm:
Step 1: START
Step 2: Declare variables principal,rate,time,Amount and CI
Step 3: Read values of principal,rate and time.
Step 4: Calculate “Amount = principal*(pow(1+(rate/100),time))”.
Step 5: Calculate “CI = Amount-principal”.
Step 6: Display CI(Compound Interest).
Step 7: STOP
#include <stdio.h>
#include<math.h>
int main()
{
double principal = 10000;
double rate = 5;
double time= 2;
double Amount = principal * ((pow((1 + rate / 100), time)));
double CI = Amount - principal;
printf("Compound Interest is : %lf",CI);
return 0;
}
Flowchart:
Algorithm:
Step 1: START
Step2 : Declare variables a,b,c,s and area.
Step 3: Read sides of triangles a,b,c.
Step 4: Calculate “ s = (a+b+c)/2”.
Step 5: Calculate “area = sqrt(s*(s-a)*(s-b)*(s-c))”.
Step 6: Display area(Area of the triangle).
Step 7: STOP
# include<stdio.h>
# include <math.h>
int main()
{
int a,b,c,s;
float area;
printf("Enter the length of three sides of a triangle:\n");
scanf("%d%d%d", &a,&b,&c);
s = (a+b+c)/2;
printf("The value of S is %d\n",s);
Flowchart:
{
float u,a,t,v,s;
printf("\n Enter initial velocity: ");
scanf("%f",&u);
printf("\n Enter acceleration: ");
scanf("%f",&a);
printf("\n Enter time required: ");
scanf("%f",&t);
v=u+a*t;
s=u*t+(1/2)*a*t*t;
printf("\n The final Velocity is : %f",v);
printf("\n \n The distance traveled is : %f \n \n",s);
getch();
}
Output:
Enter initial velocity: 18
Enter acceleration: 5
Enter time required:60
The final Velocity is :318.000000
The distance traveled is :1080.000000
Flowchart:
WEEK 4:
= 14 Right to left
*= /= %=
+= -= &=
^= |= <<=
>>=
, 15 Left to right
A+B*C+(D*E) + F*G
Algorithm:
1. Start
2. Input A,B,C,D,E,F,G
3. Calculate D * E
4. Calculate B * C
5. Calculate F * G
6. Calculate A + (B * C)
7. Calculate (D * E) + F * G
8. Calculate A + (B * C) + (D * E) + F * G
9. Output the result
10. End
Flow chart:
Program:
#include <stdio.h>
int main() {
int A,B,C,D,E,F,G,X;
printf("enter A,B,C,D,E,F,G values:");
scanf("%d%d%d%d%d%d%d",&A,&B,&C,&D,&E,&F,&G);
X=A+B*C+(D*E)+F*G;
printf("X=%d",X);
return 0;
}
Output:
Enter A,B,C,D,E,F,G values: 1
3
5
7
9
11
2
X=101
A/B*C-B+A*D/3
Algorithm:
1. Start
2. Read A,B,C,D
3. Calculate X= A/B*C-B+A*D/3
4. Display X
5. Stop
Flow chart:
Program:
#include <stdio.h>
int main( )
{
float A,B,C,D,X;
printf("enter A,B,C,D values:");
scanf("%f%f%f%f",&A,&B,&C,&D);
X=A/B*C-B+A*D/3;
printf("X=%f",X);
return 0;
}
Output: enter A,B,C,D values:4
3
7
8
X=17.000000
A+++B---A
Algorithm:
1. Start
2. Read A,B
3. Calculate X= A+++B---A
4. Display X
5. Stop
Flow chart:
Program:
#include <stdio.h>
int main()
{
int A,B,X;
printf("enter A,B values:");
scanf("%d%d",&A,&B);
X=A+++B---A;
printf("X=%d",X);
return 0;
}
Output: enter A,B values:12
18
X=17
J= (i++) + (++i)
Algorithm:
1. Start
2. Read i,j (values)
3. Declare J(variable)
4. Calculate J=(i++)+(++i)
5. Display J
6. Stop
Flow chart:
Program:
#include <stdio.h>
int main()
{
int i,j,J;
printf("enter i,j values:");
scanf("%d%d",&i,&j);
J=(i++)+(++i);
printf("X=%d",J);
return 0;
}
Output: enter i,j values:9
8
X=20
ALGORITHM:
1. start
2. Input: take three numbers as input and store them in variables 'a','b','c'.
3. compare: use the conditional operator to compare the numbers and find maximum:
a. a) if 'a' is greater than both 'b' and 'c' set 'maximum to 'a'.
b. b) else if 'b' is greater than 'c',set 'maximum' to 'b'.
c. c) else set 'maximum' to'c'
4. stop
Flowchart
Program:
#include <stdio.h>
int main()
{
int a, b, c, max;
printf("Enter Three Integers\n");
scanf("%d %d %d", &a, &b, &c);
max = (a > b)?((a > c)?a:c):((b > c)?b:c);
printf("Maximum Number is = %d\n", max);
return 0;
}
Output: Enter Three Integers 4
5
7
Maximum Number is =7
iii)Take marks of 5 subjects in integers ,and find the total ,average in float
ALGORITHEM:
1. START
2. Read marks of five subjects and store it in some variables say eng,phy,chem.,math and comp.
3. Calculate sum of all subjects and store in total=eng+phy+chem.+math+comp.
4. Divide sum of all subjects by total number of subjects to find average i.e., average =total/5
5. Calculate percentage using percentage=(total/500)*100
6. Display Resultant values.
7.Stop.
FLOWCHART:
PROGRAM:
#include <stdio.h>
int main()
{
float eng, phy, chem, math, comp;
float total, average, percentage;
printf("Enter marks of five subjects: \n");
scanf("%f%f%f%f%f", &eng, &phy, &chem, &math, &comp);
total = eng + phy + chem + math + comp;
average = total / 5.0;
percentage = (total / 500.0) * 100;
printf("Total marks = %.2f\n", total);
printf("Average marks = %.2f\n", average);
printf("Percentage = %.2f",percentage);
return 0;
}
Output: Enter marks of five subjects: 87
88
89
92
95
Total marks = 451
Average marks = 90.20
Percentage = 90.20
WEEK 5:
ALGORITHM:
1. Start
2. Read num1,num2,num3,num 4 (values).
3. Read ‘max’,’min’(variables).
4. Set ‘max’ and ‘min’ initially to num1.
5. Use if-else statements to compare num2,num3 and num 4 with ‘max’,’min’
6. If num 2 is greater than ‘max’,update ‘max’ to num2.If num 2 is smaller than ‘min’,update ‘min’ to
num 2.
7. Repeat step 6 for num 3 and num4
8. Display ‘max’ as the maximum number and ‘min’ as minimum number.
Flowchart:
PROGRAM:
#include <stdio.h>
int main()
{
int num1, num2, num3, num4;
int max, min;
printf("Enter four numbers: ");
scanf("%d %d %d %d", &num1, &num2, &num3, &num4);
if (num1 >= num2 && num1 >= num3 && num1 >= num4)
{
max = num1;
} else if (num2 >= num1 && num2 >= num3 && num2 >= num4)
{
max = num2;
} else if (num3 >= num1 && num3 >= num2 && num3 >= num4)
{
max = num3;
} else {
max = num4;
}
if (num1 <= num2 && num1 <= num3 && num1 <= num4)
{
min = num1;
} else if (num2 <= num1 && num2 <= num3 && num2 <= num4)
{
min = num2;
} else if (num3 <= num1 && num3 <= num2 && num3 <= num4)
{
min = num3;
}
else {
min = num4;
}
printf("Maximum number is: %d\n", max);
printf("Minimum number is: %d\n", min);
return 0;
}
Output:
Enter four numbers:12
15
9
3
Maximum number is: 15
Minimum number is: 3
ALGORITHEM:
1) START
2) Input unit consumed by customer in some variable say unit.
3) If unit consumed less or equal to 50 units. Then amt = unit * 0.50.
4) If unit consumed more than 50 units but less than 100 units. Then add the first 50 units amount
i.e. 25 to final amount and compute the rest 50 units amount. Which is given by amt = 25 + (unit-
50) * 0.75. I have used units-50, since I already calculated first 50 units which is 25.
5) Similarly check rest of the conditions and calculate total amount.
6) After calculating total amount. Calculate the surcharge amount i.e. sur_charge = total_amt * 0.20. Add
surcharge amount to net amount. Which is given by net_amt = total_amt + sur_charge.
7) STOP
Flowchart:
PROGRAM:
#include <stdio.h>
int main() {
int units;
float totalBill;
printf("Enter the number of units consumed: ");
scanf("%d", &units);
if(units <= 50) {
totalBill = units * 0.50; // Rate for first 50 units: 0.50 per unit
} else if(units <= 150) {
totalBill = 50 * 0.50 + (units - 50) * 0.75; // Rate for next 100 units: 0.75 per unit
} else if(units <= 250) {
totalBill = 50 * 0.50 + 100 * 0.75 + (units - 150) * 1.20; // Rate for next 100 units: 1.20 per unit
} else {
totalBill = 50 * 0.50 + 100 * 0.75 + 100 * 1.20 + (units - 250) * 1.50; // Rate for above 250 units:
1.50 per unit
}
ALGORITHEM:
1. START
2. Read a, b, c values
3. Compute d = b^2- 4ac
if d > 0 then
r1 = b+ sqrt (d)/(2*a)
r2 = b sqrt(d)/(2*a)
4. Otherwise if d = 0 then
compute r1 = -b/2a, r2=-b/2a
print r1,r2 values
5. Otherwise if d < 0 then print roots are imaginary
6. Stop"
Flowchart:
PROGRAM:
#include <stdio.h>
#include <math.h>
int main() {
double a, b, c, discriminant, root1, root2;
printf("Enter coefficients a, b, and 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("Roots are real and distinct: %.2lf and %.2lf\n", root1, root2);
} else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
printf("Roots are real and equal: %.2lf\n", root1);
} else {
double realPart = -b / (2 * a);
double imaginaryPart = sqrt(-discriminant) / (2 * a);
printf("Roots are complex: %.2lf + %.2lfi and %.2lf - %.2lfi\n", realPart, imaginaryPart, realPart,
imaginaryPart);
}
return 0;
}
Output: Enter coefficients a, b, and c: 1
4
3
Roots are real and distinct:-3.000000 and -5.000000
ALGORITHM:
1. Start:
- Begin the program.
2. Declare Variables:
- Declare variables `operator`, `num1`, `num2`, and `result` of appropriate data types.
3. User Input:
- Prompt the user to enter an operator (`+, -, *, /`).
- Read the entered operator and store it in the variable `operator`.
5. Switch-Case:
- Use a switch-case statement on the variable `operator` to determine the operation to be performed.
- For addition (`+`), add `num1` and `num2`, store the result in `result`, and print the result.
- For subtraction (`-`), subtract `num2` from `num1`, store the result in `result`, and print the result.
- For multiplication (`*`), multiply `num1` and `num2`, store the result in `result`, and print the
result.
- For division (`/`), check if `num2` is not zero. If true, divide `num1` by `num2`, store the result in
`result`, and print the result. If `num2` is zero, print an error message for division by zero.
- For any other operator, print an error message for an invalid operator.
6. End:
- End the program
PROGRAM:
#include <stdio.h>
int main() {
char operator;
double num1, num2, result;
printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &operator);
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
switch(operator) {
case '+':
result = num1 + num2;
printf("Result: %.2lf\n", result);
break;
case '-':
result = num1 - num2;
printf("Result: %.2lf\n", result);
break;
case '*':
result = num1 * num2;
printf("Result: %.2lf\n", result);
break;
case '/':
if(num2 != 0) {
result = num1 / num2;
printf("Result: %.2lf\n", result);
}
else {
printf("Error: Division by zero is not allowed.\n");
}
break;
default:
printf("Error: Invalid operator\n");
}
return 0;
}
Output: Enter an operator (+, -, *, /): *
Enter two numbers: 4
5
Result: 20.0
ALGORITHM:
1. Start:
- Begin the program.
2. Declare Variable:
- Declare a variable `year` of type integer.
3. User Input:
6. End:
- End the program.
FLOWCHART:
PROGRAM:
#include <stdio.h>
int 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);
}
return 0;
}
WEEK 6:
LAB-6: Iterative problems --the sum of series
FlowChart:
PROGRAM:
#include <stdio.h>
int main()
{
int number, i;
unsigned long long factorial = 1;
Algorithm:
STEP 1: Take num as input.
STEP 5: If the temp is equal to 0,Return “Num IS PRIME”.else, Return “Num IS NOT PRIME”.
STEP6: STOP
FLOWCHART:
PROGRAM:
#include <stdio.h>
int isPrime(int num)
{
if (num <= 1)
{
return 0; // Not a prime number
}
for (int i = 2; i * i <= num; i++)
{
if (num % i == 0)
{
return 0;
}
}
return 1;
}
int main()
{
int number;
printf("Enter a number: ");
scanf("%d", &number);
if (isPrime(number))
{
printf("%d is a prime number.\n", number);
}
else
{
printf("%d is not a prime number.\n", number);
}
return 0;
}
Output:
Enter a number: 31
31 is a prime number
FlowChart:
PROGRAM
#include <stdio.h>
#include <math.h>
double calculateSine(int x, int n)
{
double sine = 0;
for (int i = 0; i < n; i++)
{
sine += (pow(-1, i) * pow(x, 2 * i + 1)) / factorial(2 * i + 1);
}
return sine;
}
double calculateCosine(int x, int n)
{
double cosine = 0;
for (int i = 0; i < n; i++)
{
cosine += (pow(-1, i) * pow(x, 2 * i)) / factorial(2 * i);
}
return cosine;
}
int factorial(int num)
{
if (num == 0 || num == 1)
{
return 1;
}
return num * factorial(num - 1);
}
int main()
{
int angle, n;
printf("Enter the angle in radians: ");
scanf("%d", &angle);
printf("Enter the number of terms in the series: ");
scanf("%d", &n);
double sineValue = calculateSine(angle, n);
double cosineValue = calculateCosine(angle, n);
printf("Sine(%d) = %.4lf\n", angle, sineValue);
printf("Cosine(%d) = %.4lf\n", angle, cosineValue);
return 0;
}
Output:
Enter the angle in radians: 60
Enter the number of terms in the series: 2
Sine(60) = -35940.0000
Cosine(60) = -1799.0000
Algorithm:
Step 1: Start
Step 2: Read the input number from the user
Step 3: Declare and initialize the variable reverse and assign input to a temp variable tempNum=num
Step 4: Start the while loop until num !=0 becomes false
rem = num % 10
reverse*= 10 + rem
num = num / 10
Step 5 : Check if reverse == tempNum
Step 6: If it’s true then the number is a palindrome
FLOW CHART:
PROGRAM:
#include <stdio.h>
int main()
{
int num, reversedNum = 0, originalNum, remainder;
printf("Enter an integer: ");
scanf("%d", &num);
originalNum = num;
while (num != 0)
{
remainder = num % 10;
reversedNum = reversedNum * 10 + remainder;
num /= 10;
}
if (originalNum == reversedNum)
{
printf("%d is a palindrome.\n", originalNum);
}
else
{
printf("%d is not a palindrome.\n", originalNum);
}
return 0;
}
Output:
Enter an integer: 1285821
1285821 is a palindrome.
FLOWCHART:
PROGRM:
#include <stdio.h>
int 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");
}
return 0;
}
Output:
Enter the number of rows: 5
1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5
Week 7:
(1)Find the min and max of a 1-D integer array
Algorithm:
1. Declaration of variables:
2. User input:
3. Initialization:
4. Finding maximum and minimum:
In this loop, the program iterates through the array, comparing each element with the current
maximum and minimum. If the current element is greater than the current maximum, it updates the
maximum. If the current element is smaller than the current minimum, it updates the minimum.
5. Printing the result:
The algorithm is straightforward: it initializes the maximum and minimum with the first element of the
array, then iterates through the array to find the actual maximum and minimum values. Finally, it
prints the results.
Flowchart:
program:
#include <stdio.h>
void main()
{
int arr1[100];
int i, mx, mn, n;
printf("\n\nFind maximum and minimum element in an array :\n");
printf("the number of elements wants to be stored in the array :");
scanf("%d",&n);
printf("Input %d elements in the array :\n",n);
for(i=0;i<n;i++)
{
printf("element - %d : ",i);
scanf("%d",&arr1[i]);
}
mx = arr1[0];
mn = arr1[0];
for(i=1; i<n; i++)
{
if(arr1[i]>mx)
{
mx = arr1[i];
}
if(arr1[i]<mn)
{
mn = arr1[i];
}
}
Algorithm:
1. Start
2. Initialize the array and the target value.
3. Set a flag to indicate whether the target is found (flag = 0).
4. For each element in the array:
a. If the element is equal to the target value:
i. Set the flag to 1.
ii. Print the index of the element.
iii. Break out of the loop.
5. If the flag is still 0, print that the target value is not found.
6. End
Flowchart:
Program:
#include <stdio.h>
int linearSearch(int arr[], int n, int target) {
for (int i = 0; i < n; i++) {
if (arr[i] == target) {
printf("Element found at index %d\n", i);
return 1;
}
}
return 0;
}
int main() {
Program:
#include <stdio.h>
void reverseArray(int arr[], int size) {
int start = 0;
int end = size - 1;
while (start < end) {
// Swap elements at start and end positions
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
// Move the pointers
start++;
end--;
}
}
int main() {
int myArray[] = {1, 2, 3, 4, 5};
Program:
#include <stdio.h>
void findTwosComplement(int binaryNumber[], int n) {
int i;
for (i = 0; i < n; i++) {
binaryNumber[i] = (binaryNumber[i] == 0) ? 1 : 0;
}
int carry = 1;
for (i = 0; i < n; i++) {
Program:
#include <stdio.h>
void removeDuplicates(int arr[], int *n) {
int uniqueArr[*n];
int uniqueCount = 0;
WEEK – 8:
Objective: Explore the difference between other arrays and character arrays that can be used as
Strings by using null character and get comfortable with string by doing experiments that will
reverse a string and concatenate two strings. Explore sorting solution bubble sort using integer
arrays.
Step 1: Start
sum[i][j]=mat1[i][j] + mat2[i][j]
Set j=j+1
Step 7: Stop
FLOWCHART
PROGRAM:
#include <stdio.h>
int main ()
int mat2[3][3] = { {9, 10, 11}, {12, 13, 14}, {15, 16, 17} };
int sum[3][3], i, j;
if (j == 3 - 1)
printf ("\n\n");
if (j == 3 - 1)
printf ("\n\n");
if (j == 3 - 1)
printf ("\n\n");
return 0;
OUTPUT:
matrix 1 is :
0 1 2
3 4 5
6 7 8
matrix 2 is :
9 10 11
12 13 14
15 16 17
9 11 13
15 17 19
21 23 25
Step 1: Start
Step 2: Declare matrix mat1[row1][col1]; and matrix mat2[row2][col2]; and matrix mul[row1][col2]; row= no. of
rows, col= no. of columns
Step 6: Set an inner loop for the above loop from j=0 to j=col2
• Initialise the value of the element (i, j) of the new matrix (mul[row1][col2]) to 0.
• Set an inner loop inside the above loop from k=0 to k=row1.
• Using the add and assign operator (+=) store the value of mat1[i][k] * mat2[k][j] in the third matrix,
mul[i][j].
• Print the third matrix.
Step 7: Stop
FLOWCHART:
PROGRAM:
#include<stdio.h>
int main ()
{
int mat1[2][3] = { {0, 1, 2}, {3, 4, 5} };
int mat2[3][2] = { {1, 2}, {3, 4}, {5, 6} };
int mul[2][2], i, j, k;
printf ("matrix 1 is :\n");
for (i = 0; i < 2; i++)
{
for (j = 0; j < 3; j++)
{
printf ("%d ", mat1[i][j]);
if (j == 3 - 1)
{
printf ("\n\n");
}
}
}
printf ("matrix 2 is :\n");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 2; j++)
{
printf ("%d ", mat2[i][j]);
if (j == 2 - 1)
{
printf ("\n\n");
}
}
}
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
mul[i][j] = 0;
for (k = 0; k < 3; k++)
{
mul[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
printf ("The product of the two matrices is: \n");
OUTPUT:
matrix 1 is :
0 1 2
3 4 5
matrix 2 is :
1 2
3 4
5 6
ALGORITHM:
1. Start
2. Initialize an array of elements.
3. Repeat the following steps until no swaps are performed in a pass:
● Set a flag to indicate whether a swap is performed in the current pass.
● Iterate through the array from the first element to the second-to-last element.
o Compare each element with its adjacent element.
o If the current element is greater than the next element, swap them and set the
swap flag to true.
● If no swaps were performed in the pass, the array is sorted, and you can exit the loop.
4. Display the sorted array.
5. End
FLOWCHART:
Program:
#include <stdio.h>
int main() {
int n;
int arr[n];
return 0;
}
OUTPUT:
Enter the size of the array: 6
Enter elements of the array:
Enter element 1: 42
Enter element 2: 11
Enter element 3: 7
Enter element 4: 23
Enter element 5: 16
Enter element 6: 35
Sorted array:
7 11 16 23 35 42
IV) Reverse a string using built-in and without built-in string functions
ALGORITHM:
1. Start
2. Initialize a string.
3. Reverse with Built-in Functions:
● Use a built-in string reversal function (e.g., strrev in C).
4. Display the reversed string.
5. Reverse without Built-in Functions:
● Find the length of the string.
● Iterate from the end of the string to the beginning.
o Print each character in reverse order.
6. Display the reversed string.
7. End
FLOWCHART:
PROGRAM:
#include <stdio.h>
#include <string.h>
int main() {
char inputString[100];
// Input a string
printf("Enter a string: ");
fgets(inputString, sizeof(inputString), stdin);
return 0;
}
OUTPUT:
Week-9:
(1) write a simple c program to find the sum of 1D array using malloc()
Algorithm:
6. Frees the dynamically allocated memory using `free()` to avoid memory leaks.
Flow chart:
Program:
#include <stdio.h>
#include <stdlib.h>
int main() {
scanf("%d", &n);
if (arr == NULL) {
return 1;
scanf("%d", &arr[i]);
sum += arr[i];
free(arr);
return 0;
Output:
12
10
Algorithm:
2. Define a structure:
- `struct Student` is defined to represent a student, containing the student's name and marks.
3. Declare variables:
- An array `students` of type `struct Student` is declared to store information about each student.
- Use a `for` loop to iterate over each student and input their name and marks.
- Use another `for` loop to calculate the total marks of all students.
- Calculate the average by dividing the total by the number of students (`n`).
9. Return 0:
Flow chart:
Program:
#include <stdio.h>
struct Student {
char name[50];
int marks;
};
int main() {
int n, i;
printf("Enter the number of students: ");
scanf("%d", &n);
Output:
Name: yaseer
Marks: 80
Name: irfan
Marks: 50
3. Enter n students data using calloc () and display failed students list
Algorithm:
2. The `main` function takes the number of students as input and allocates memory for an array of
student structures using `calloc()`.
4. After inputting the data, we call the `displayFailedStudents` function to identify and display the list
of failed students based on a passing marks threshold (40 in this example).
Flow chart:
Program:
#include <stdio.h>
#include <stdlib.h>
struct Student {
char name[50];
int rollNumber;
float marks;
};
void displayFailedStudents(struct Student* students, int n, float passingMarks) {
int 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);
}
displayFailedStudents(students, n, 40.0);
free(students);
return 0;
}
Output:
Name: Boy
Marks: 25
Name: sana
Marks: 41
========================
Marks: 25.00
(4) Read student name and marks from the command line and display the student details along
with the total.
Algorithm:
1. It takes student names and marks as command line arguments. The program assumes that each
student has a name followed by marks.
2. It allocates memory for an array of `num Students` based on the number of command line
arguments.
3. It then copies the name and converts the marks from the command line arguments into the array of
`struct Student`.
4. Finally, it displays the student details along with the total marks.
5. compile and run the program,
Flowchart:
Program;
#include <stdio.h>
#include <stdlib.h>
struct Student {
char name[50];
float marks;
};
int main() {
int n;
scanf("%d", &n);
printf("Name: ");
scanf("%s", students[i].name);
printf("Marks: ");
scanf("%f", &students[i].marks);
printf("----------------------------\n");
printf("Name\t\tMarks\n");
printf("----------------------------\n");
totalMarks += students[i].marks;
printf("----------------------------\n");
printf("Total\t\t%.2f\n", totalMarks);
free(students);
return 0;
Output:
Name: Girl
Marks: 50
Name: saNA
Marks: 60
----------------------------
Name Marks
----------------------------
Girl 50.00
saNA 60.00
----------------------------
Total 110.00
Algorithm:
1. Initialize Variables:
- Declare an integer pointer `arr` and allocate memory for an array of size `initialSize` using
`malloc`.
- Check if memory allocation is successful. If not, print an error message and exit.
- Use a loop to input integers and store them in the allocated memory.
5. Reallocate Memory:
- Use `realloc` to reallocate memory for the array based on the new size (`newSize`).
- Use a loop to input integers and store them in the newly allocated memory.
9. Exit Program:
Flowchart:
Program:
#include <stdio.h>
#include <stdlib.h>
int main() {
int initialSize = 2;
if (arr == NULL) {
return 1;
scanf("%d", &arr[i]);
printf("Original Array:\n");
printf("\n");
int newSize;
scanf("%d", &newSize);
if (arr == NULL) {
return 1;
scanf("%d", &arr[i]);
printf("Updated Array:\n");
printf("\n");
free(arr);
return 0;
Output:
Enter 2 integers:
15
20
Original Array:
15 20
12
Updated Array:
15 20 12
Week 10:
(1) Create and display a singly linked list using self-referential structure in c .
Algorithm:
Start by defining a structure that represents a node in the linked list. Each node should contain a
data element and a pointer to the next node in the list.
Create a function to initialize an empty linked list. This function should return a pointer to the head
of the list, which is initially set to `NULL`.
Write a function to insert a new node at the beginning of the linked list. This involves creating a new
node, setting its data, and updating the next pointer to point to the current head of the list.
Create a function to display the elements of the linked list. Traverse the list from the head, printing
the data of each node.
In the `main` function, you can test the linked list operations. Initialize an empty list, insert some
elements, and display the list
Flowchart:
Program:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
};
newNode->data = value;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
temp = temp->next;
temp->next = newNode;
head = head->next;
printf("NULL\n");
int main() {
insertAtEnd(&head, 1);
insertAtEnd(&head, 2);
insertAtEnd(&head, 3);
displayList(head);
return 0;
Output:
Algorithm:
- The structure `Point` has two members, `x` and `y`, each of type `int`.
- The union `Coordinate` also has two members, `x` and `y`, each of type `int`.
3. Main Function:
- Print the values from both the structure and the union.
4. Size Comparison:.
Flowchart:
Program:
#include <stdio.h>
struct Point {
int x;
int y;
};
union Coordinate {
int x;
int y;
};
int main() {
// Using a structure
pointStruct.x = 10;
pointStruct.y = 20;
coordinateUnion.x = 30;
coordinateUnion.y = 40;
return 0;
Output:
Algorithm:
2. Implement a function (`rotateBits`) that takes a `BitField` structure and the number of positions to
rotate. It performs a left rotation operation on the bitfield.
3. In the `main` function, create an instance of the bitfield (`bf1`) with some initial data (in this case,
`0b10101010`).
5. Call the `rotateBits` function to rotate the bits of `bf1` by a specified number of positions (in this
case, 3 positions to the left).
Flowchart:
Program:
#include <stdio.h>
struct BitField {
unsigned int data : 8;
};
struct BitField rotateBits(struct BitField bf, int positions) {
positions = positions % 8;
bf.data = (bf.data << positions) | (bf.data >> (8 - positions));
return bf;
}
int main() {
struct BitField bf1 = { 0b10101010 };
Original BitField: AA
Rotated BitField: 55
(4)Write a C program to copy one structure variable to another structure of the same type.
Algorithm:
1. Define a structure:
- Define a structure `Person` with fields like name, age, and height.
2. Copy Function:
- Create a function `copyStruct` that takes two parameters: a pointer to the destination structure and a
pointer to the source structure.
- Use `memcpy` to copy the content of the source structure to the destination structure.
3. Main Function:
Flowchart:
Program:
#include <stdio.h>
#include <string.h>
struct Person {
char name[50];
int age;
float height;
};
void copyStruct(struct Person *dest, const struct Person *src) {
memcpy(dest, src, sizeof(struct Person));
}
int main() {
struct Person person1 = {"yaseer", 25, 5.8};
struct Person person2;
printf("Original Person 1:\n");
printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);
printf("Height: %.2f\n\n", person1.height);
copyStruct(&person2, &person1);
printf("Copied Person 2:\n");
printf("Name: %s\n", person2.name);
printf("Age: %d\n", person2.age);
printf("Height: %.2f\n", person2.height);
return 0;
}
Output:
Original Person 1:
Name: Perfect
Age: 25
Height: 5.80
Copied Person 2:
Name: Hancy
Age: 25
Height: 5.80
Week-11:
Algorithm:
1. Start
2. Read n and r
8. End
Program:
#include <stdio.h>
if (n == 0 || n == 1)
return 1;
else
if (r > n)
return 0;
int main() {
int n, r;
scanf("%d", &n);
scanf("%d", &r);
return 0;
Output:
Enter the value of n: 55
55C45 = 1
Flow chart:
#include <stdio.h>
int stringLength(const char *str) {
int length = 0;
while (str[length] != '\0') {
length++;
}
return length;
}
int main() {
char inputString[100];
printf("Enter a string: ");
scanf("%s", inputString);
int length = stringLength(inputString);
Output:
Enter a string: 3
Flow chart:
Algorithm:
1. Start
2. Declare a function transposeMatrix that takes the number of rows, number of columns, and a matrix as
input.
8. End
Program:
#include <stdio.h>
int transpose[cols][rows];
transpose[j][i] = matrix[i][j];
printf("Original Matrix:\n");
printf("%d\t", matrix[i][j]);
printf("\n");
printf("\nTransposed Matrix:\n");
printf("%d\t", transpose[i][j]);
printf("\n");
int main() {
scanf("%d", &rows);
scanf("%d", &cols);
int matrix[rows][cols];
scanf("%d", &matrix[i][j]);
return 0;
Output:
Enter the number of rows: 3
12
34
56
Original Matrix:
1 2
3 4
5 6
Transposed Matrix:
1 3 5
2 4 6
Flowchart:
Algorithm:
1. Start
2. Declare a function eulerMethod that takes initial x and y values, step size (h), and the target x-value for
integration.
4. Use a while loop to iteratively apply Euler's method until the target x-value is reached.
5. In each iteration, update the value of y using the differential equation ��/��=�+�dy/dx=x+y.
8. End
Program:
#include <stdio.h>
double x = x0;
double y = y0;
y = y + h * (x + y);
x += h;
int main() {
double h = 0.1;
return 0;
Output:
Numerical integration using Euler's method:
At x = 1.00, y = 3.161051
Flowchart:
Week-12:
12.a)Write a recursive function to generate Fibonacci series.
Algorithm:
1. Start
6. End
Program:
#include <stdio.h>
int fibonacci(int n) {
if (n <= 1) {
return n;
} else {
int main() {
int n;
scanf("%d", &n);
return 0; }
Output:
Enter the number of terms in the Fibonacci series: 10
0 1 1 2 3 5 8 13 21 34
flowchart:
Algorithm:
Input: Two integers a and b
1. Define a function gcd(a, b) to calculate the greatest common divisor using the Euclidean algorithm:
a. If b is 0, return a.
4. Calculate the LCM using the lcm function: result = lcm(num1, num2).
6. End.
Program:
#include <stdio.h>
if (b == 0) {
return a;
} else {
int main() {
scanf("%d", &num1);
scanf("%d", &num2);
return 0;
Output:
Enter the first number: 12
Flow chart:
Algorithm:
1. Start
3. If n is 0 or 1, return 1.
● Input a number.
6. End
Program:
#include <stdio.h>
if (n == 0 || n == 1) {
return 1;
} else {
int main() {
int num;
scanf("%d", &num);
return 0;
Output:
Enter a number: 5
FLow chart:
Algorithm:
1. Start
3. If m is 0, return n + 1.
● Display the result of the Ackermann function using the ackermann function.
7. End
Program:
#include <stdio.h>
if (m == 0) {
return n + 1;
} else if (n == 0) {
} else {
int main() {
int m, n;
return 0;
Output:
Enter the values of m and n: 2 3
Ackermann(2, 3) = 9
Flowchart:
Algorithm:
1. Start
3. If n is 0, return 0.
6. End
Program:
#include <stdio.h>
int sumOfSeries(int n) {
if (n == 0) {
return 0;
} else {
int main() {
int num;
scanf("%d", &num);
return 0;
Output:
Enter the number of terms in the series: 5
Flowchart:
Week-13
13.a)Write a C program to swap two numbers using call by reference.
Algorithm:
1. Start
2. Declare a function swapNumbers that takes two integer pointers (a and b) as parameters.
3. Inside the function, use a temporary variable to swap the values pointed to by a and b.
● Call the swapNumbers function by passing the addresses of num1 and num2.
5. End
Program:
#include <stdio.h>
*a = *b;
*b = temp;
int main() {
scanf("%d", &num1);
scanf("%d", &num2);
swapNumbers(&num1, &num2);
return 0;
Output:
Enter the first number: 10
Flowchart:
Algorithm:
1. Start
2. Declare a function createDanglingPointer that creates a local variable num, assigns its address to a
pointer ptr, and returns the pointer.
● Attempt to access the value through the dangling pointer (which is undefined behavior).
4. End
Program:
#include <stdio.h>
int* createDanglingPointer() {
return ptr;
int main() {
int *danglingPtr;
danglingPtr = createDanglingPointer();
return 0;
Output:
Dangling pointer value: 42
Flowchart:
Algorithm:
1. Start
2. Declare a function copyString that takes two character pointers (dest and src).
3. Use a while loop to copy characters from src to dest until a null character ('\0') is encountered.
5. End
Program:
#include <stdio.h>
int main() {
scanf("%s", sourceString);
copyString(destinationString, sourceString);
return 0;
Output:
Enter a string: Hello, World!
Flowchart:
13.d) Write a C program to find no of lowercase, uppercase, digits and other characters using
pointers.
Algorithm:
1. Start
2. Declare a function countCharacters that takes a string and four integer pointers (lowercase,
uppercase, digits, and others).
3. Use a while loop to iterate through the string and count lowercase, uppercase, digits, and other
characters.
● Declare a character array (inputString) and four integers (lowercase, uppercase, digits, and
others).
5. End
Program:
#include <stdio.h>
void countCharacters(const char *str, int *lowercase, int *uppercase, int *digits, int *others) {
(*lowercase)++;
(*uppercase)++;
(*digits)++;
} else {
(*others)++;
str++;
int main() {
char inputString[100];
scanf("%s", inputString);
return 0;
Output:
Enter a string: Hello123World!
Lowercase characters: 8
Uppercase characters: 3
Digits: 3
Other characters: 1
Flowchart:
Week-14
14.a)Write a C program to write and read text into a file.
Algorithm:
1. Start
4. Input text from the user and write it to the file using fprintf.
7. Open the same file for reading using fopen in read mode ("r").
9. Read and display the text from the file using fgets.
11. End
Program:
#include <stdio.h>
int main() {
FILE *file;
char text[100];
if (file == NULL) {
return 1;
fclose(file);
if (file == NULL) {
return 1;
printf("%s", text);
fclose(file);
return 0;
Output:
Enter text to write into the file: This is a sample text for file operations.
Flowchart:
14.b)Write a C program to write and read text into a binary file using fread() and fwrite().
Algorithm:
1. Start
2. Open a binary file for writing using fopen in binary write mode ("wb").
4. Input text from the user and write it to the binary file using fwrite.
7. Open the same binary file for reading using fopen in binary read mode ("rb").
9. Read and display the text from the binary file using fread.
11. EnD
Program:
#include <stdio.h>
int main() {
FILE *file;
char text[100];
if (file == NULL) {
return 1;
fclose(file);
if (file == NULL) {
return 1;
printf("%s", text);
fclose(file);
return 0;
Output:
Enter text to write into the binary file: hello
Flowchart:
Algorithm:
1. Start
2. Open the source file for reading using fopen in read mode ("r").
3. If the source file opening is unsuccessful, display an error message and exit.
4. Open the destination file for writing using fopen in write mode ("w").
5. If the destination file opening is unsuccessful, display an error message, close the source file, and exit.
6. Copy contents from the source file to the destination file using fgetc and fputc in a loop until EOF is
encountered.
9. End
Program:
#include <stdio.h>
int main() {
char ch;
if (sourceFile == NULL) {
return 1;
if (destinationFile == NULL) {
fclose(sourceFile);
return 1;
fputc(ch, destinationFile);
fclose(sourceFile);
fclose(destinationFile);
return 0;
Output:
If the content of the source.txt file is:
This is a sample text for file copying.
After running the program, the content of the destination.txt file will be:
14.d)Write a C program to merge two files into the third file using command-line
arguments.
Algorithm:
1. Start
2. Check if the correct number of command-line arguments are provided (3 file names).
4. If the first file opening is unsuccessful, display an error message and exit.
6. If the second file opening is unsuccessful, display an error message, close the first file, and exit.
8. If the merged file opening is unsuccessful, display an error message, close both the first and second
files, and exit.
9. Copy contents from the first file to the merged file using fgetc and fputc in a loop until EOF is
encountered.
10. Copy contents from the second file to the merged file using fgetc and fputc in a loop until EOF is
encountered.
13. End
Program:
#include <stdio.h>
#include <stdlib.h>
char ch;
if (argc != 4) {
return 1;
if (file1 == NULL) {
return 1;
if (file2 == NULL) {
fclose(file1);
return 1;
if (mergedFile == NULL) {
fclose(file1);
fclose(file2);
return 1;
fputc(ch, mergedFile);
fputc(ch, mergedFile);
fclose(file1);
fclose(file2);
fclose(mergedFile);
return 0;
Output:
Assuming the program is named merge_files:
$ ./merge_files file1.txt file2.txt merged_file.txt
FLowchart:
Algorithm:
1. Start
2. Declare a function countLinesWordsCharacters that takes a file pointer and three integer pointers
(lines, words, and characters).
4. Use a while loop to read characters from the file until EOF is encountered.
7. Check for space, tab, or newline characters to detect word boundaries and update the words count
accordingly.
9. End
Program:
#include <stdio.h>
char ch;
int inWord = 0;
(*characters)++;
if (ch == '\n') {
(*lines)++;
inWord = 0;
} else if (inWord == 0) {
inWord = 1;
(*words)++;
int main() {
FILE *file;
if (file == NULL) {
return 1;
fclose(file);
return 0;
Output:
Assuming the program is reading from a file named sample_text.txt with the following
content:
This is a sample text file.
Words: 15
Characters: 96
Flowchart:
Algorithm:
1. Start
3. Use fseek to move the file pointer to the end of the file (SEEK_END).
4. Use ftell to get the current position, which is the file size.
5. Move the file pointer to the start of the last n characters from the end of the file.
8. End
Program:
#include <stdio.h>
long fileSize = ftell(file); // Get the current position, which is the file size
if (fileSize == -1) {
return;
int ch = fgetc(file);
if (ch == EOF) {
break;
putchar(ch);
printf("\n");
int main() {
FILE *file;
int n;
if (file == NULL) {
return 1;
scanf("%d", &n);
printLastNCharacters(file, n);
fclose(file);
return 0;
Output:
Assuming the program is reading from a file named sample_text.txt with the following
content:
This is a sample text file.
Flowchart: