PSC Lab Manual
PSC Lab Manual
Date: Functions
Aim:
To demonstrate call by reference by passing two integers to a function and swapping
the values.
Algorithm:
1. Start.
2. Input a, b.
3.Call the swap function with &a and &b.
4.Inside swap function:
a. Print values of *a and *b.
b. Temporary variable t used to swap values.
c. Print the new values of *a and *b.
d. Print the final values of *a and *b after swapping.
5.End.
Program:
#include <stdio.h>
void swap(int *a, int *b)
{
printf("Before swapping %d %d\n",a,b); int
t= *a;
*a=*b;
*b=t;
printf("After swapping %d %d\n",*a,*b);
}
int main()
{
int a,b;
scanf("%d %d",&a,&b);
swap(&a,&b);
printf(a,b);
}
Inferences:
● Pointer Basics: The program provides a simple example of how to use pointers
to directly manipulate variables in memory.
● Swapping Mechanism: It illustrates a common approach to swapping values
using a temporary variable to store one value while the other is moved.
● By Reference vs By Value: The use of pointers allows the function to alter the
values in the calling function (main), demonstrating the concept of passing by
reference in C.
● Correctness in Handling Data: Using a temporary variable ensures that no data
is lost during the swapping process.
Result:
Thus the implementation of call by reference was executed successfully.
Input:
10 20
Output:
Before Swapping 10 20
After Swapping 20 10
20 10
--------------------------------------------------------------
b) Write a C program to demonstrate value by passing two integers to a function and
swapping the values
Aim:
To demonstrate call by reference by passing two integers to a function and swapping
the values.
Algorithm:
● Start.
● Input a, b.
● Print the original values of a and b.
● Call the swap function with a and b.
● Inside swap function:
○ Print values of a and b.
○ Temporary variable t used to swap values.
○ Print the new values of a and b.
○ Print the final values of a and b after swapping.
● End.
Program:
#include <stdio.h>
void swap(int a, int b)
{
printf("Before swapping %d %d\n",a,b); int
t= a;
a=b;
b=t;
printf("After swapping %d %d\n",a,b);
}
int main()
{
int a,b;
scanf("%d %d",&a,&b); printf("Original
values %d %d\n",a,b); swap(a,b);
printf("Swapped values %d %d\n",a,b);
}
Inferences:
Copying Arguments:
● In this case, when the swap function is called, the actual values of a and b are
copied into the local variables a and b inside the swap function.
● These are local copies of the values, and the changes made to them inside
the function do not affect the original a and b in the main function.
Changes are Local:
● When the swap function modifies its local copies of a and b, the changes (like
the swap operation) only affect the local scope of the swap function.
● No effect on the original variables in main (because we are working on copies,
not references).
Output Behavior:
● The program will show the original values of a and b unchanged in the main
function after the swap function call.
● The swapped values will be printed within the swap function, but since they
only affect the local copies, they won’t persist outside of the function.
Result:
Thus the implementation of call by value was executed successfully.
Input:
56
Output:
Original values 5
6
Before Swapping 56
After Swapping 65
Swapped values 56
Exp no: 2
Date: Functions
a) Create C program using function to calculates the LCM of three numbers Aim:
To demonstrate LCM (Lowest Common Factor) of three numbers using a function.
Algorithm:
Step 1: Define a function LCM that calculates the LCM of three integers. Take one
temporary variable to store max product of all the three values because the lcm of three
numbers are less then or equal to max product value.
Step 2: Input three integers from the user in the main function.
Step 3: Call a function to find lcm of three numbers.
Step 4: Run a for loop for iterating starting to max product and check whether it is
completely divisible by all the three numbers if it is divisible then return that value.
Step 5: Display the LCM of the three integers.
Program:
#include <stdio.h>
void lcm(int a,int b,int c)
{
int i;
int max=a*b*c;
for(i=1;i<=max;i++)
{
if( i%a==0 && i%b==0 && i%c==0)
{
break;
}
}
printf("%d",i);
}
int main()
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
lcm(a,b,c);
return 0;
}
Inferences:
Initialization:
The program initializes the integers a, b, and c with user input and calculates the LCM
sequentially.
Calculation:
The program first finds out max product and based on the product iterating a loop up to
max value and finding LCM of three numbers.
Output:
The program displays the LCM of the three integers
Result:
Thus the implementation of LCM of three numbers was executed successfully.
Input:
248
Output:
2b)Create C program using function to find Greatest Common Divisor (GCD) Using
Euclid’s Algorithm
Aim:
To demonstrate Greatest common divisor (GCD) using Eculid’s Algorithm.
Algorithm:
1. Start.
2. Input: Read the integers a and b from the user.
3. Check if a or b is negative:
4. If a < 0, set a = -a.
5. If b < 0, set b = -b.
6. Loop (Euclidean Algorithm):
7. While b != 0:
a. Compute r = a % b (remainder when a is divided by b).
b. Set a = b and b = r (update a and b).
8. Output: Once b becomes 0, print the value of a (GCD).
9. End.
Program:
#include<stdio.h> int
GCD(int a,int b)
{
a=(a<0)?-a:a;
b=(b<0)?-b:b;
while(b!=0)
{
int r=a%b;
a=b;
b=r;
}
return a;
}
int main()
{
int a,b;
scanf("%d%d",&a,&b); int
res=GCD(a,b);
printf("%d",res);
}
Inferences:
● Efficiency: The program uses the Euclidean algorithm, which is an efficient
way to compute the GCD with a time complexity of O(log(min(a, b))).
● Negative Handling: The program ensures that negative inputs are
converted to positive values before proceeding with the GCD calculation.
Result:
Thus the implementation of Greatest Common Divisor Using Euclid’s Algorithm was
executed successfully.
Input:
84
Output:
4
Exp no: 3
Date: Functions
a)Aim: Create C program tokenizes a string based on a specified delimiter using function.
Algorithm :
1. Start
2. Input the string from the user.
3. Input the delimiter from the user.
4. Remove the newline character (if any) from both the string and the delimiter.
5. Initialize the tokenization process:
6. Use strtok() to extract the first token from the string.
7. Iterate through the string:
8. While there are more tokens:
9. Print the current token.
10. Get the next token using strtok().
11. End
Program:
#include <stdio.h>
#include <string.h>
void deli(char s[15],char d[10])
{
char *token=strtok(s,d);
while(token!=NULL)
{
printf("%s\n",token);
token=strtok(NULL,d);
}
}
int main()
{
char s[15];
scanf("%s",s);
char d[10];
scanf("%s",d);
deli(s,d);
return 0;
}
Inferences:
Initialization: Variables are initialized for the input string (str) and the delimiter (delimiter).
Another variable (token) is used to store each extracted part of the string during tokenization.
Input: The user provides an input string and specifies a delimiter. These inputs determine how
the string will be split into tokens.
Calculation: The strtok function is used to process the string. It iteratively splits the string into
smaller parts (tokens) based on the specified delimiter, updating the token variable with each
part.
Output: Each token extracted from the string is displayed to the user, clearly showing the
results of the tokenization process.
Sample Input:
Alli+ance+Univ+ersity
+
Sample Output:
Alli
ance
Univ
ersity
Sample Input:
Alliance-University
-
Sample Output:
Alliance
University
____________________________________________________________________________
EXP-3
Date:
b)Aim: Create C program removes duplicate characters from a function.
Algorithm:
1. Start
2. Input the string from the user.
3. Iterate through each character in the string:
4. For each character, initialize a flag = 1 (assume it is unique).
5. Compare the character with all other characters in the string:
6. If the same character is found at a different position, set flag = 0 and break the loop. Check
the if flag == 1, print the character (it is unique).
7. End
Program:
#include <string.h>
#include <stdio.h>
void removeduplicate(char s[20])
{
int n=strlen(s);
for(int i=0;i<n;i++)
{
int flag=1;
for(int j=0;j<i;j++)
{
if(s[i]==s[j])
{
flag=0;
break;
}
}
if(flag==1)
{
printf("%c",s[i]);
}
}
}
int main()
{
char s[20];
scanf("%s",s);
removeduplicate(s);
return 0;
}
Inferences:
Initialization: The input string and variables used for tracking unique characters are initialized
to process the input efficiently.
Input: The program takes a string as input, ensuring that it handles spaces and special
characters appropriately.
Calculation: Duplicate characters are identified and skipped, ensuring that only unique
characters remain in the resulting string.
Output: The resulting string, free of duplicate characters, is displayed to the user in a clear
format.
Sample Input:
Alliance
Sample Output:
Aiance
Sample Input:
ProblemSolvingUsingC
Sample Output:
PrbemSvUsC
Result: Thus the implementation of removing duplicated elements was executed successfully.
Exp-4
Date:
a) Aim: Create a C program to copy the string without strcpy function by using
pointers with the help of function.
Algorithm:
1.Start.
3.To accept the input from the user along with the space we are taking the character set up to
newline.
10. End
Program:
#include <stdio.h>
void stringcopy(char *s1,char *s2)
{
while(*s1!='\0')
{
*s2=*s1;
s1++;
s2++;
}
*s2='\0';
}
int main()
{
char s1[20];
scanf("%[^\n]",s1);
char s2[20];
stringcopy(s1,s2);
printf("After Copying: %s",s2);
}
Inferences:
Initialization: The source and destination character arrays are initialized to hold the strings.
Input: The user inputs the source string using scanf, which can include spaces.
Calculation: The stringCopy function uses pointer manipulation to copy each character from the
source string to the destination string.
Output: The copied string is printed, which is the same as the source string.
Sample Input:
AllianceUniversity
Sample Output:
Sample Input:
Hello World
Sample Output:
Result: Thus the implementation of copying one string to another string without using strcpy
was executed successfully.
____________________________________________________________________________
Exp-4
Date:
Algorithm:
1.Start.
2. Start Input the string from the user.
5.They didn’t mention anything about the characters so we can consider both uppercase and
lowercase letters.
9.End.
Program:
#include <string.h>
#include <ctype.h>
#include <stdio.h>
void countvowelsconsonants(char s[20])
{
int n=strlen(s);
int vowels=0,consonants=0;
for(int i=0;i<n;i++)
{
if(isalpha(s[i]))
{
if(s[i]=='a'||s[i]=='e'||s[i]=='o'||s[i]=='i'||s[i]=='u'||s[i]=='A'||s[i]=='E'||s[i]=='O'||s[i]=='I'||s[i]=='U')
{
vowels++;
}
else
{
consonanst++;
}
}
}
printf("Vowels: %d\nConsonants: %d",vowels,consonants);
}
int main()
{
char s[20];
scanf("%s",s);
count vowelsconsonants(s);
return 0;
}
Inferences:
Initialization:
char s[] is initialized to store input string from the user.
To count the vowels and consonants we initialize vowels=0 and consonants=0.
Calculation:
Output:
Result:
Thus the implementation of count vowels and consonants was executed successfully.
Sample Input:
AllianceUniversity
Sample Output:
Vowels: 8
Consonants: 8
Sample Input:
HelloWorld1
Sample Output:
Vowels: 3
Consonants: 7
Exp:5
Date:
Algorithm:
1.Start
8.Iterate each element from the entire array and add to the sum.
10.End.
Program:
#include<stdio.h>
void sumofarrayelements(int arr[], int n)
{
int sum=0;
for(int i=0;i<n;i++)
{
sum=sum+arr[i];
}
printf("%d",sum);
}
int main()
{
int n;
scanf("%d",&n);
int a[n];
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
sumofarrayelements(a,n);
}
Inferences:
Calculaction:
→The Program uses a for loop to traverse the entire array.
→Each element we are adding to the sum variable from the array.
→If we reached to last element then we have to stop iterating
Result: Thus the implementation of sum of the array elements was executed successfully.
Sample Input:
5
12345
Sample Output:
15
Sample Input:
5
13679
Sample Output:
26
____________________________________________________________________________
Exp:5
Date:
Algorithm:
1.Start
2.Declare a value to store the fixed size and declare the values.
6.Initialize a max=0 .
9.Return max.
10.End.
Program:
#include <stdarg.h>
#include <stdio.h>
int maxele(int n,...)
{
int f,max=0;
va_list arr;
va_start(arr,n);
for(int i=0;i<n;i++)
{
f=va_arg(arr,int);
if(max<f)
{
max=f;
}
}
return max;
va_end(arr);
}
int main()
{
int n;
scanf("%d",&n);
int a,b,c,d,e;
scanf("%d%d%d%d%d",&a,&b,&c,&d,&e);
printf("%d",maxele(n,a,b,c,d,e));
}
Inferences:
Initialization:Initialize a max=0.
Calculation:
Result: Thus the implementation of max of the list elements was executed successfully.
Sample Input:
5
12345
Sample Output:
5
Sample Input:
3
1 40 50
Sample Output:
50
Exp:6
Date:
Algorithm:
1.Start.
3. Define function display(int (*ptr)(int, int)) to pass the address of a function as a parameter.
5.End.
Program:
#include <stdio.h>
int sum(int a,int b)
{
return a+b;
}
void display(int (*ptr)(int,int))
{
ptr=∑
printf("%d",ptr(10,20));
}
int main()
{
display(sum);
}
Inferences:
Result:Thus the implementation of sum of two numbers by using callback was executed
successfully.
Output:
30
Exp:6
Date:
Algorithm:
1.Start.
● Compute x + y
● Return the sum
● Compute x * y
● Return the product
→Each element we have to pass to function by passing an element we have to add and
multiply the values.
8.End
Program:
#include <stdio.h>
int add(int x,int y)
{
return x+y;
}
int mul(int x,int y)
{
return x*y;
}
void display(int(*ptr)(int,int),int n,int a[],int (*ptr1)(int,int))
{
ptr=add;
ptr1=mul;
int res=a[0],res1=a[0];
for(int i=1;i<n;i++)
{
res=add(res,a[i]);
res1=mul(res1,a[i]);
}
printf("%d\n%d",res,res1);
}
int main()
{
int n;
scanf("%d",&n);
int a[n];
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
display(add,n,a,mul);
return 0;
}
Inferences:
Initialization:Initial the res=0 and res1=0 for adding and multiplying the values.
Input: Read the size of the array and elements from the user.
Calculation:
→The Program uses a for loop to traverse the entire array.
→Each element we are adding to the res and res1 variable from the array.
→If we reached to last element then we have to stop iterating
Output: The program displays the sum and multiplication of the array elements.
Result: Thus the implementation of sum and multiplication of the array elements was
executed successfully.
Sample Input:
5
12345
Sample Output:
15
120
Sample Input:
3
136
Sample Output:
10
18
__________________________________________________________________________
Exp:7
Date:
Algorithm:
1.Start.
4.Check the condition if n==0 return 0 ,if n==1 return 1 or add previous two values
fib(n-1)+fib(n-2).
5.If n==0 stop the process and return the value to where you are calling the function.
6.End.
Program:
#include <stdio.h>
int fib(int n)
{
if(n==0 )
{
return 0;
}
else if(n==1)
{
return 1;
}
else
return fib(n-1)+fib(n-2);
}
int main()
{
int n;
scanf("%d",&n);
printf("%d",fib(n));
return 0;
}
Inferences:
Calculation:
→Check the condition in a function until the base condition satisfies the recursive
condition will work.
→If the base condition satisfies it stops the program and returns the value as output.
Output: The program displays the fibonacci value of the nth term.
Result:Thus the implementation of the nth term of fibonacci number was implemented
successfully.
Sample Input:
Sample Output:
5
Sample Input:
Sample Output:
21
______________________________________________________________________
Exp:7
Date:
Algorithm:
1.Start.
5.If the condition is not satisfied it will come to a recursive statement up to n become
equal to 0 or 1.
6.End.
Program:
#include <stdio.h>
int fact(int n)
{
if(n==0 || n==1 )
{
return 1;
}
else
return n*fact(n-1);
}
int main()
{
int n;
scanf("%d",&n);
printf("%d",fact(n));
return 0;
}
Inferences:
Calculation: Until n becomes equal to one repeat the process if n is equal to 1 stop
iterating.
Sample Input:
Sample Output:
120
Sample Input:
Sample Output:
Exp:8
Date:
Algorithm:
1.Start
6.End program
Program:
#include <stdio.h>
void add();
inline void add(int a,int b)
{
printf("%d",a+b);
}
int main()
{
int a,b;
scanf("%d%d",&a,&b);
add(a,b);
return 0;
}
Inferences:
Input:Read two values as Input from the user to perform an addition operation.
Output: The program will print the sum of the two numbers by using an inline function.
Result: Thus the implementation of inline function macros was executed successfully.
Sample Input:
10 20
Sample Output:
30
Sample Input:
20 30
Sample Output:
50
______________________________________________________________________
Exp:8
Date:
b)Aim: Write a program to allocate memory dynamically for a matrix (2D array)
and demonstrate matrix multiplication operations in c.
Algorithm:
1.Start
2.Read Input form the user for rows (r) and columns (c).
5.Allocate a memory for matrix to store elements based on row and column position.
Program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int r,c;
scanf("%d%d",&r,&c);
int *a[r],*b[r],*res[r];
for(int i=0;i<c;i++)
{
a[i]=malloc(c*sizeof(int));
b[i]=malloc(c*sizeof(int));
res[i]=malloc(c*sizeof(int));
}
//reading input from the user for matrix b
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
//reading input from the user for matrix b
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
}
}
//for multiplying two matrices
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
for(int k=0;k<c;k++)
{
res[i][j] += a[i][k]*b[k][j];
}
}
}
//for printing result
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
printf("%d ",res[i][j]);
}
printf("\n");
}
return 0;
}
Inferences:
Input:
→Read row and column size as input from the user.
→Read 2 matrices from the user by using a nested loop.
Calculation:
→Multiply the first row from matrix a with entire columns in b matrix.
→Multiply the remaining rows from matrix a with all the columns present in matrix b.
→After multiplying, store the result in a res matrix.
Sample Input:
33
123
456
789
111
111
123
Sample Output:
6 9 12
15 21 27
24 33 42
Sample Input:
22
12
34
56
78
Sample output:
19 22
43 50
Exp:9
Date:
a)Aim:Write a program that allocates memory for an array dynamically and then
expands or shrinks the size of the array in c
Algorithm:
1.Start.
6.Initialize sum =0,mul=1 to store the result of addition and multiplication of array
elements.
7.By taking a for loop, find sum and multiplication values by iterating throughout the
array.
8.Once you reach the end of the array, stop the process and print output as sum of the
array and multiplication of array elements .
9.After completion of the process release the space that you allocated with the help of
free.
10.End.
Program:
#include<stdio.h>
#include <stdlib.h>
int main()
{
int n;
scanf("%d",&n);
int *a;
a=malloc(n*sizeof(int));//20
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
a=realloc(a,n*sizeof(int));//40
int mul=1,sum=0;
for(int i=0;i<n;i++)
{
mul=mul*a[i];
sum+=a[i];
}
printf("The product of the array is: %d",mul);
printf("\nThe sum of the array is: %d",sum);
free(a);
}
Inferences:
Calculation:
→By using a for loop, iterate each element in an array and find the sum and
multiplication of array elements of an array.
Output: Print the value of sum and multiplication along with the string.
Result: Thus the implementation of sum and product of the array elements by
performing realloc and free by using dynamic memory allocation was executed
Successfully.
Sample Input:
5
1 2 34 5
Sample Output:
Sample Input:
3
123
Sample Output:
_____________________________________________________________________
Exp: 9
Date:
Algorithm:
1.Start.
6.End.
Program:
Inferences:
Result: Thus the implementation of square of a number using macro was executed
successfully.
Sample Input:
Sample Output:
25
Sample Input:
Sample Output:
9
Exp: 10
Date:
a) Aim: Write a program that uses #define to create constants for mathematical
values (e.g., PI) and demonstrates their usage in calculations
Algorithm:
1.Start.
6.End.
Program:
#define pi 3.1415
#include <stdio.h>
int main()
{
int r;
scanf("%d",&r);
printf("Area of circle: %f",pi*r*r);
printf("\nCircumference of circle: %f",2*pi*r);
}
Inferences:
Sample Input:
Sample Output:
Sample Input:
Sample Output:
______________________________________________________________________
Exp: 10
Date:
b)Aim: Write a program that demonstrates the use of #if, #elif, #else, and #endif
for conditional compilation based on defined constants.
Algorithm:
o A constant MARKS is defined with a value (in this case, 85) using the
#define directive.
2. Conditional Compilation:
● The #if directive checks if the MARKS are between 90 and 100, and
prints "Excellent".
● The #elif directive checks if the MARKS are between 70 and 89, and
prints "Good".
● The next #elif checks if MARKS are between 40 and 69, and prints
"Average".
● The #else block will print "Fail" if none of the above conditions are
satisfied.
● The preprocessor checks these conditions before the code is compiled.
Program:
#include <stdio.h>
int main()
#else
#endif
return 0;
Inferences:
Calculation: Check the condition based on the constant macro name and print the
output.
Sample Input:
90
Sample Output:
Excellent
Sample Input:
10
Sample Output:
Fail
FILE PROCESSING
Exp:11
Date:
Aim: Create C program to perform New file, renaming, Write, read, Append
Operations
Algorithm:
1.Start.
7.Read content from a file by using “r” mode and print the content by using fgets and
printf functions.
9.End.
Program:
#include <stdio.h>
int main()
{
FILE *ptr;
ptr=fopen("new.txt","w");
fprintf(ptr,"hello ");
fclose(ptr);
ptr=fopen("new.txt","a");
fprintf(ptr," world ");
fclose(ptr);
ptr=fopen("new.txt","r");
char s[20];
fgets(s,20,ptr);
printf("%s",s);
fclose(ptr);
rename("new.txt","file.txt");
printf("\nSuccessfully Renamed");
return 0;
}
Inferences:
File Operations: Create a file,open a file,write content into a file ,read content from a
file.
→By using “w” mode we are checking whether a file exists or not. If a file does not exist
then only it will create a file.
Adding Content:
Reading Content:
→fgets(s, 20, ptr) reads up to 19 characters (leaving 1 for null terminator). If the file is
larger, it won't read the entire content unless done in a loop.
Rename a file:
Sample Output:
new.txt file.txt
hello world
Successfully Renamed
hello world
Successfully Renamed
FILE PROCESSING
Exp:12
Date:
Aim: Create C program to copies the contents of one file to another, Merge
Two Files
Algorithm:
1.Start.
3.Assign content to a file by using write mode with the help of a pointer.
4.Create two files (file1.txt , file2.txt) by using write mode and assign some content to a
file .
5.Create a third file(merge.txt) to merge the two files and store the result in that file.
6.Open a first file(fil1.txt) in read mode when a file is in read mode then only we can
read content from a file.
7.Create a variable (ch) to store the content which is present inside a first text
file(fil1.txt).
8.Here we are copying content from a file1.txt to a merge file in that format of character
by character with the help of a file pointer.
9.Close a file.txt.
10.Here we are copying content from a file2.txt to a merge file in that format of
character by character with the help of a file pointer.
12.End.
Program:
#include <stdio.h>
int main()
{
FILE *ptr1,*ptr2,*ptr3;
ptr1=fopen("file1.txt","w");
fprintf(ptr1,"hello");
fclose(ptr1);
ptr1=fopen("file1.txt","r");
ptr2=fopen("file2.txt","w");
char ch;
while((ch=fgetc(ptr1))!=EOF)
{
fputc(ch,ptr2);
}
fclose(ptr2);
ptr3=fopen("merge.txt","w");
ptr1=fopen("file1.txt","r");
ptr2=fopen("file2.txt","r");
while((ch=fgetc(ptr1))!=EOF)
{
fputc(ch,ptr3);
}
fclose(ptr1);
putc(' ',ptr3);
while((ch=fgetc(ptr2))!=EOF)
{
fputc(ch,ptr3);
}
fclose(ptr2);
fclose(ptr3);
ptr3=fopen("merge.txt","r");
char s[100];
fgets(s,100,ptr3);
printf("%s",s);
return 0;
}
Inferences:
File Creation and Writing: The program explains how to create multiple files and how
to add content to a file.
Reading and Writing: The program uses fgetc(),fputc() to read and write content into a
file by character by character format.
→A space ' ' is inserted between the contents of the two files to avoid merging them
directly without separation.
Result: Thus the implementation of copying a content of one file to another file and
merging two files was executed successfully.
Sample Output:
hello hello
____________________________________________________________________
FILE PROCESSING
Exp:13
Date:
Aim: Create C program to Word Count and Count the Number of Lines in a file
Algorithm:
1.Start.
4.Read each character by using fgetc() in a file until you reach the end of a file(EOF).
6.Check if the character is equal to ‘\t’ and space if it is equal then consider it as a word
and increment the count of a word.
7.End.
Program:
#include <stdio.h>
#include <ctype.h>
int main()
{
FILE *ptr;
ptr=fopen("newfile.txt","w");
fprintf(ptr,"hello\nWorld");//11
fputs(" welcome",ptr);
fclose(ptr);
int line=1,word=0;
ptr=fopen("newfile.txt","r");
char ch;
while((ch=fgetc(ptr))!=EOF)
{
if(ch=='\n')
{
line++;
}
if(ch=='\t' ||isspace(ch))
{
word++;
}
}
word++;
printf("Words count: %d",word);
printf("\nLines count: %d",line);
fclose(ptr);
return 0;
}
Inferences:
File Creation & Writing: Creating a file by using w mode and writing content to a file
by using w mode.
Reading content: By using “r” mode we are reading content from a file .
Result: Thus the implementation of count the number of lines and words in a file
executed successfully.
Sample Output:
main.c newfile.txt
hello
world welcome
Words count: 3
Lines count: 2
Exp:14
Date:
Algorithm:
1.Start.
4.Initialize a variable size=0 with long datatype to accept the size beyond the integer
range .
5.Declare a variable ch to store each character from a file up to the end of a file.
7. When you are reading each character, check whether the character is at the end of a
file or not. If it is not the end of a file increment the size variable.
8. If you reach the end of a file, stop the process and print the size value.
9.End.
Program:
#include <stdio.h>
int main()
{
FILE *ptr;
ptr=fopen("new.txt","w");
fprintf(ptr,"Hello ");
fclose(ptr);
ptr=fopen("new.txt","r");
char ch;
long size=0;
while(ch=fgetc(ptr)!=EOF)
{
size++;
}
printf("The size of the file is %ld bytes",size);
return 0;
}
Inferences:
→It reads the file character by character and counts how many characters (bytes) are
present.
→The value of size represents the total number of characters in the file, which is also
the file size in bytes.
→There is a bug in the while condition that causes incorrect counting. It must be
corrected to read actual characters.
→Once fixed, the code correctly calculates and displays the file size.
Result: Thus the implementation of calculating the size of a file was executed
successfully.
Sample Output:
main.c new.txt
Hello
Aim: Create a program that reads integers from a text file and calculates their
sum
Algorithm:
1.Start.
Program:
#include <stdio.h>
int main()
{
FILE *ptr;
ptr=fopen("newfile.txt","w");
fprintf(ptr,"10 20 30");
fclose(ptr);
ptr=fopen("newfile.txt","r");
int sum=0;
int n;
while(fscanf(ptr,"%d",&n)!=EOF)
{
sum=sum+n;
}
printf("Sum of the elements is %d",sum);
fclose(ptr);
return 0;
}
Inferences:
→The program demonstrates file handling using fopen(), fscanf(), and fprintf().
→The file newfile.txt is created and written with space-separated integers (10 20
30).
→ The use of fscanf(ptr, "%d", &n) allows reading integers one by one from the file.
→The condition fscanf(...) == 1 ensures the loop only continues while integers are
successfully read.
→ The final output of the program is the sum of the numbers read from the file.
Result: Thus the implementation of reading integers from a text file and their sum
was executed successfully.
Sample Output:
main.c newfile.txt
10 20 30