0% found this document useful (0 votes)
5 views49 pages

PSC Lab Manual

The document contains multiple C programming exercises demonstrating various concepts such as call by reference, call by value, calculating LCM and GCD, string tokenization, removing duplicate characters, string copying without using strcpy, and counting vowels and consonants. Each exercise includes an aim, algorithm, program code, inferences, and sample input/output. The implementations are successful and illustrate essential programming techniques in C.

Uploaded by

harshitgowda606
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)
5 views49 pages

PSC Lab Manual

The document contains multiple C programming exercises demonstrating various concepts such as call by reference, call by value, calculating LCM and GCD, string tokenization, removing duplicate characters, string copying without using strcpy, and counting vowels and consonants. Each exercise includes an aim, algorithm, program code, inferences, and sample input/output. The implementations are successful and illustrate essential programming techniques in C.

Uploaded by

harshitgowda606
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
You are on page 1/ 49

Exp no: 1

Date: ​Functions

1. a)Write a C program using a pointer to demonstrate call by reference 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:
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.

● Simple and Robust: It is a straightforward implementation of the Euclidean


algorithm, and it will correctly handle most cases, including negative inputs and zeros
(though the edge case of both inputs being zero is not explicitly handled).

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.

Requirements : Visual Studio or GCC Compiler.

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.

Result: Thus the implementation of String Tokenize was executed successfully.

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.

Requirements : Visual Studio or GCC Compiler.

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.

2. Input the string from the user into s1.

3.To accept the input from the user along with the space we are taking the character set up to
newline.

4.Initialize s2 as an empty character array.

5.Iterate through each character in s1.

6.Copy the current character of s1 to s2.

7. Move to the next character in both s1 and s2.

8.Terminate s2 with a null character (\0).

9.Print s2 to display the copied string.

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:

After Copying: AllianceUniversity

Sample Input:

Hello World

Sample Output:

After Copying: Hello World

Result: Thus the implementation of copying one string to another string without using strcpy
was executed successfully.

____________________________________________________________________________

Exp-4
Date:

b)Aim:Create C program to Count Vowels and Consonants using string function.

Algorithm:

1.Start.
2. Start Input the string from the user.

3.Input the string from the user.

4. Initialize count of the vowel= 0 and count of the consonant =0.

5.They didn’t mention anything about the characters so we can consider both uppercase and
lowercase letters.

6.Iterate through each character in the string .

7.Check the current character


If the character is a vowel(a,e,i,o,u), increment the count of the vowel .
If the character is not a vowel, come to else block and increment the count of the
consonant.

8.Print the count of the vowels and consonants.

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.

Input: We are using scanf to read input from the user.

Calculation:

→Here we are using a for loop to travel the entire string.


→To check whether it is character or not we are using isalpha() function
→If we find it is an alphabet then we are checking whether the current character is a vowel or
not.

Output:

The program displays the count of vowels and consonants.

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:

a)Aim: Create a c program to perform functions with arrays as parameters.

Algorithm:

1.Start

2.Take the size of the array as an input from the user.

3.To store elements based on the size we have to create an array.

4.Iterate through each element of an array.

5. Pass size,array as a parameter to function.

6.Create a function to perform the task.

7.Initialize a variable to store the sum of the array elements sum=0.

8.Iterate each element from the entire array and add to the sum.

9.Print the sum value.

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:

Initialization: Initialize size and array to store the multiple values.

Input: Use scanf to read input from the user.

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

Output: The program displays the sum of the array elements.

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:

b)Aim:Write a C program to demonstrate Variadic function to find the largest number.

Algorithm:

1.Start

2.Declare a value to store the fixed size and declare the values.

3.Read input from the user by using scanf.

4.Declare a function and pass size and elements as a parameters.

5.To accept the number of parameters use an arbitrary function.

6.Initialize a max=0 .

7.Initialize variable argument list using va_start.

8.Iterate each element by using for loop


→when you are iterating each element by using a for loop compare it with max.
→If the element is greater than the max update the max.

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.

Input: We have to read input from the user by using scanf.

Calculation:

→The Program uses a for loop to traverse the entire list.


→Each element we are going to compare with the max variable from the list.
→If we reached to last element then we have to stop iterating

Output: The program displays the max of the list elements.

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:

a)Aim:Write a C program to demonstrate callback function by passing a function pointer


as an argument to another function

Algorithm:

1.Start.

2.Create one function sum to add two numbers.

3. Define function display(int (*ptr)(int, int)) to pass the address of a function as a parameter.

4.Print the result.

5.End.

Program:

#include <stdio.h>
int sum(int a,int b)
{
return a+b;
}
void display(int (*ptr)(int,int))
{
ptr=&sum;
printf("%d",ptr(10,20));
}
int main()
{
display(sum);
}

Inferences:

Calculation:We are passing the address of a function to another function.

Output: The program displays the sum of 2 numbers.

Result:Thus the implementation of sum of two numbers by using callback was executed
successfully.

Output:
30
Exp:6
Date:

b)Aim:Write C program to demonstrates higher-order functions by using function


pointers to perform operations like addition and multiplication on elements of an
array

Algorithm:

1.Start.

2.Take the size of the array as an input from the user.

3.To store elements based on the size we have to create an array.

4.Iterate through each element of an array.

5.Define function add(int x, int y)

●​ Compute x + y
●​ Return the sum

6.Define function mul(int x, int y)

●​ Compute x * y
●​ Return the product

7.Define function display(int(*ptr)(int, int), int n, int a[], int(*ptr1)(int, int))

●​ Assign ptr = add and ptr1 = mul


●​ Initialize res = a[0] for addition and res1 = a[0] for multiplication.
●​ Loop from i = 0 to n:

→Each element we have to pass to function by passing an element we have to add and
multiply the values.

●​ Print res and res1

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:

a)Aim:Create a program that demonstrates direct recursion by calculating the nth


Fibonacci number using a recursive function

Algorithm:

1.Start.

2.Read Input from the user.

3.Create one function and pass the input to that function.

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:

Input: Read n value from the user by using scanf.

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:

b)Aim:Write a program to calculate the factorial of a number using tail recursion


to demonstrate its efficiency

Algorithm:

1.Start.

2.Read the input from the user.

3.Create one function to find the factorial of a number.

4.The value of 1!=1 and 0!=1 so initialize the value.

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:

Input: Read n value from the user by using sacnf.

Calculation: Until n becomes equal to one repeat the process if n is equal to 1 stop
iterating.

Output: The program displays the factorial of a number by using recursion.

Result:Thus the implementation of factorial of a number by using recursion was


executed successfully.

Sample Input:

Sample Output:

120

Sample Input:

Sample Output:

Exp:8
Date:

a)Aim:Demonstrate Inline Function Using Macros

Algorithm:

1.Start​

2.Read Input from the user.​

3.Define inline add(int a, int b) to find addition of two numbers.

4.Call a function then the entire function will work .

5.Print the result.​

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.

Calculation : when you are calling a function it will be considered as a preprocessor


function before calling it. When you call a function then it will take a place and you will
get the result as an output.

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).​

3.Allocate memory dynamically for input matrices a and b.

4.Declare one matrix to store the result after multiplying.

5.Allocate a memory for matrix to store elements based on row and column position.​

6.Read input values for matrices a and b​

7.Perform matrix multiplication using nested loops​


8.Print the result matrix​

9.End

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.

Output: Print the resultant matrix by using nested for loop.

Result:Thus the implementation of matrix multiplication(2D Array)by using dynamic


memory allocation was executed successfully.

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.

2.Take size as an input from the user.

3.Create an array dynamically and allocate memory by using malloc or calloc.

4.Read array elements from the user by using a for loop.

5.Reallocate a memory by using realloc function.

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:

Input: Read size of the array from the user.

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:

The product of the array is: 120


The sum of the array is: 15

Sample Input:

3
123
Sample Output:

The product of the array is: 6


The sum of the array is: 6

_____________________________________________________________________

Exp: 9
Date:

b) Aim: Write C program to Calculate the Square of a Number Using a Macro

Algorithm:

1.Start.

2.Define a Macro function for square function.

3.Read input value from the user.

4.Call macro function by passing arguments .

5.Print the result as an output.

6.End.

Program:

#define square(r) (r*r)


#include <stdio.h>
int main()
{
int r;
scanf("%d",&r);
printf("%d",square(r));
return 0;
}

Inferences:

Input: Read r value as an input from the user.


Calculation: Call a function by passing an argument to a function.

Output: Print the square of a number.

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.

2.Define a Macro constant for pi.

3.Read input value from the user.

4.Perform some mathematical operations by using a constant pi value .

5.Print the result as an output.

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:

Input: Read r value as an input from the user.

Output: Find area and circumference of a circle and print as an output.


Result: Thus the implementation of creating constant pi value and performing
operations was executed successfully.

Sample Input:

Sample Output:

Area of circle: 78.537500


Circumference of circle: 31.415000

Sample Input:

Sample Output:

Area of circle: 28.273500


Circumference of circle: 18.849000

______________________________________________________________________

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:

1. ​ Define the Marks:

o A constant MARKS is defined with a value (in this case, 85) using the
#define directive.

2. ​ Conditional Compilation:

o The program uses preprocessor directives to check the value of MARKS


and classify it into one of the four categories (Excellent, Good, Average, or
Fail):

●​ 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.

3. ​ Output the Result:

o Based on the value of MARKS, the corresponding message


("Excellent", "Good", "Average", or "Fail") is printed.

4. ​ End the Program:

o The program returns 0 to indicate successful execution.

Program:

#include <stdio.h>

#define MARKS 90 // Define the marks value

int main()

// Conditional compilation based on the value of MARKS

#if MARKS >= 90 && MARKS <= 100

printf("Excellent"); // Marks between 90 and 100

#elif MARKS >= 70 && MARKS <= 89

printf("Good"); // Marks between 70 and 89

#elif MARKS >= 40 && MARKS <= 69

printf("Average"); // Marks between 40 and 69

#else

printf("Fail"); // Marks less than 40

#endif
return 0;

Inferences:

Calculation: Check the condition based on the constant macro name and print the
output.

Output: Print the result as an 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.

2.Create a FILE pointer to perform operations with a file.

3.Creates a file by using “w” mode .

4.Give the name of a file .

5.Write content to a file by using “w” mode.

6.Append content to a file by using “a” mode.

7.Read content from a file by using “r” mode and print the content by using fgets and
printf functions.

8.Rename a file by using the rename function.

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:

→By using append mode we are updating content in a file.

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:

→By using the rename function we are changing a file name.

Result: Thus the implementation of file creation,write,read,append and rename a file


was executed successfully.

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.

2.Create and open a file by using “w” mode .

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.

11.Print the content from a merge file.

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:

file1.txt file2.txt merge.txt

hello hello Hello hello

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.

2.Create a file pointer.

3.Create a file and write content into a file.

4.Read each character by using fgetc() in a file until you reach the end of a file(EOF).

5.Check if the character is equal to ‘\n’ increment the count of a line.

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 .

Initializing a Variables: Initialize word=0,line=1 and ch to store each character from a


file to count the number of lines and words from a file when file is in read mode.
→By using fgetc() we are checking if each charcater is space(‘ ‘) ,tab space(‘\t’) or
newline(‘\n’).

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:

Aim: Create a C Program to calculate the size of a file.

Algorithm:

1.Start.

2.Create a file and add content to a file.

3.Open a file in read mode to calculate the size of a file.

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.

6.By using fgetc() reach each character from 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:

→The program writes "Hello " to a file (new.txt).​

→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

The size of the file is 6 bytes.


Exp:15
Date:

Aim: Create a program that reads integers from a text file and calculates their
sum

Algorithm:

1.Start.

2.Declare a file pointer ptr.​

3.Open a file "newfile.txt" in write mode using fopen().​

4.Write numbers 10 20 30 into the file using fprintf().​

5.Close the file.​

6.Reopen the same file in read mode.​

7.Initialize sum = 0.​

8.Read integers from the file using fscanf() in a loop:​


For each integer read, add it to the sum.​

9.After reading all numbers, print the total sum.​

10.Close the file.

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

Sum of the elements is 60.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy