[go: up one dir, main page]

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

Student Manual 24es203 C Lab

The document outlines a series of programming exercises in C, covering various topics such as I/O statements, conditional constructs, looping constructs, arrays, and file operations. Each exercise includes an aim, algorithm, program code, and output examples to demonstrate the functionality. The exercises are designed to help learners understand fundamental programming concepts and practices.

Uploaded by

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

Student Manual 24es203 C Lab

The document outlines a series of programming exercises in C, covering various topics such as I/O statements, conditional constructs, looping constructs, arrays, and file operations. Each exercise includes an aim, algorithm, program code, and output examples to demonstrate the functionality. The exercises are designed to help learners understand fundamental programming concepts and practices.

Uploaded by

bharanibeast7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 34

TABLEOFCONTENTS

Ex.No. Date ExperimentName PageNo. Signature

1 I/O Statements and conditional constructs


1a Calculate total and average marks
1b Even or odd using Ternary operator
1c Find the year leap year or not
1d Biggest among given three integers using
nested if-else
1e Basic calculator operations –
addition, subtraction, multiplication, division
and square of a number using Switch case
2 Looping constructs: for, while and do-while
2a Generate Fibonacci series
2b Reverse a given number
2c Check a number for Palindrome
2d Check for Armstrong number
3 One dimensional array
3a Inserting an element after every ith position in an
array
3b Insertion sort
4 Multi dimensional arrays
4a Matrix Addition
4b Matrix multiplication
4c Transpose of a Matrix
5 Strings and their operations
5a Concatenation of strings
5b Extracting a substring
5c Checking for palindrome
5d Search for a given string using binary search
6 Functions with different parameter passing techniques
6a Swap two integers using Call by value
6b Swap two integers using Call by reference
6c Binary search using recursion
7 Demonstrate simple structure manipulations
7a Generating a transcript with CGPA and class
obtained
8 Demonstrate file operations
8a Count the number of characters
8b Count the number of words
8c Count the number of lines in a file
8d Replace a specific word with the given word in
the same file
EX 1(a)
PROGRAM TO FIND OUT THE AVERAGE OF 4 INTEGERS

DATE:

AIM:
To find average of 4 integers
ALGORITHM:

Step1.Start

Step2.Declare variables

Step3.Read the 4 numbers

Step4.Calculate avg=sum/n

Step 5. Display the output

Step6.Stop

PROGRAM:

#include<stdio.h>
void main()
{

int i,n=4,sum=0,nu[100];
float avg;
printf("\nEnter numbers\n");
for(i=1;i<5;i++)
{
scanf("%d",&nu[i]);
sum=sum + nu[i];
}

avg=sum/n;
printf("\nAverage is : %2f\n",avg);
}

OUTPUT:

Enter the enter the numbers

2 4 2 4

Average is: 3.000000

RESULT

Thus the Cprogram to find the average of 4numbers has been executed and verified.

EX.NO: 1(b) I/O Statements, Operators and Expressions

Even or odd using Ternary operator

Program:
#include <stdio.h>
int main()
{
int a,b;
printf("Enter value of a: \n");
scanf("%d",&a);
b=a%2==0?1:0;
if (b==0)
printf("The number is Odd");
else
printf("The number is Even");
return 0;
}
Output:

Enter value of a: 32
The number is even

EX 1(c) PROGRAM TO FIND WHETHER THE GIVEN YEAR IS LEAP


YEAR OR NOT
DATE:

AIM:
TowriteaCProgramtofindwhetherthegiven yearisleapyearornot.

ALGORITHM:
Step1:Start

Step2:Takeintegervariableyear

Step3:Checkifyearisdivisibleby400thenDISPLAY"isaleapyear"

Step4:Checkifyearis notdivisibleby100ANDdivisibleby4thenDISPLAY"isaleapyear"

Step5:Otherwise,DISPLAY"isnotaleapyear"Step

6:Stop

PROGRAM:
#include<stdio.h>
void main()
{
int year;
printf("Enter a year :\n");
scanf("%d",&year);
if((year% 400)==0)
{
printf("%disaleapyear\n",year);
}
else if((year%100)!=0&&(year%4)==0)
{
printf("%dis a leap year\n",year);
}
else
{
printf("%dis not a leapyear \n",year);
}
}

OUTPUT:
Enter a year:
2000
2000 is a leap year
Enter a year:
1900
1900 is not a leap year
RESULT:
Thus the C Program to find whether the given year is leap year or not has been
executed successfully and the output was verified.
1(d). Biggest among given three integers using nested if-else

Program:
#include<stdio.h>
void main()
{
int a, b, c;
printf("Enter three numbers\n");
scanf("%d %d %d", &a, &b, &c);
if(a > b)
{
if(a > c)
{
printf("a: %d is largest\n", a);
}
}
else if(b > c)
{
printf("b: %d is largest\n", b);
}
else
printf("c: %d is largest\n", c);
}
Output:
Enter three numbers
45
89
63
b: 89 is largest

EX 1(e) PROGRAM TO PERFORM THE CALCULATOR OPERATIONS,


DATE: NAMELY, ADDITION, SUBTRACTION, MULTIPLICATION, DIVISION
AND SQUARE OF A NUMBER

AIM:

To perform the Calculator operations, namely, addition, subtraction, multiplication,


division and square of anumber

ALGORITHM:

Step1: Start the program

Step 2 : Declare the functions

Step3: Get the input values

Step4:Perform the operations using functions

Step5:Printtheresults

Step6:Stop the program

PROGRAM:

#include<stdio.h>

// functions declaration
int add(int n1,int n2);
int subtract(int n1, int n2);
int multiply(int n1,int n2);
int divide(int n1,int n2);
int square(int n1);
/ / main function
int main()
{
int num1,num2;
printf("Enter two numbers:");
scanf("%d%d",&num1,&num2);
printf("%d + %d = %d\n", num1, num2, add(num1,num2));
printf("%d - %d = %d\n", num1, num2, subtract(num1, num2));
printf("%d * %d = %d\n", num1, num2, multiply(num1, num2));
printf("%d / %d = %d\n", num1, num2, divide(num1, num2));
printf(“%d^%d=%d\n”,num1,num1,square(num1));
return 0;
}
//function to add two integer numbers
int add(int n1,int n2)
{
int result;
result=n1+n2;
return result;
}

//function to subtract two integer numbers


int subtract(int n1,int n2)
{
int result;
result = n1 - n2;
return result;
}

//function to multiply two integer numbers


int multiply(int n1,int n2)
{
int result;
result = n1 * n2;
return result;
}

//function to divide two integer numbers


int divide(int n1,int n2)
{

int result;

result = n1 / n2;
return result;
}

//functionto find square of a number


int square(int n1)
{

int result;result = n1*n1;


return result;
}

OUTPUT:
Enter two numbers: 20 5
20+5=25
20–5=15
20*5=100
20/5=4
20^20=400
RESULT

Thus the C Program to perform the Calculator operations, namely, addition,


subtraction, multiplication, division and square of a number has been executed and results are
verified.

Ex.No: 2 Loops: for, while and do-while

2a. Generate Fibonacci series

Program:

#include <stdio.h>
int main()
{
int i, n;
int a = 0, b = 1,c;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci series: %d, %d, ", a, b);
for (i = 0; i <= n-3; ++i)
{
c = a + b;
a = b;
b = c;
printf("%d, ", c);
}
return 0;
}

Output:

Enter the number of terms: 6


Fibonacci series: 0, 1, 1, 2, 3, 5

Ex.No: 2 Loops: for, while and do-while

2b. Reverse a given number

Program:

#include <stdio.h>
int main()
{
int n, rev = 0, rem;
printf("Enter an integer: ");
scanf("%d", &n);
while (n != 0)
{
rem = n % 10;
rev = rev * 10 + rem;
n /= 10;
}
printf("Reversed number = %d", rev);
return 0;
}

Output:

Enter the integer: 1231


Reversed number: 1321
Ex.No: 2 Loops: for, while and do-while

2c. Check a number for Palindrome

Program:

#include <stdio.h>
int main()
{
int n, rev = 0, rem, a;
printf("Enter an integer: ");
scanf("%d", &n);
a = n;
while (n != 0)
{
rem = n % 10;
rev = rev * 10 + rem;
n /= 10;
}
if (a == rev)
printf("%d is a Palindrome.", a);
else
printf("%d is not a Palindrome.", a);
return 0;
}

Output:

Enter an integer: 676


676 is a Palindrome.

Enter an integer: 123


123 is not a Palindrome.

Ex.No: 2 Loops: for, while and do-while

2d. Check for Armstrong number

Program:

#include <stdio.h>
int main()
{
int a,b,temp,sum=0;
printf(“Enter a three digit number: “);
scanf(“%d”,&a);
temp=a;
while(temp>0)
{
b=temp%10;
sum=sum+b*b*b;
temp/=10;
}
if(sum==a)
{
printf(“It’s an Armstrong number”);}
else
{
printf(“It’s not an Armstrong number “);}
return 0;
}
Output:

Enter a three digit Number: 371


It’s an Armstrong number

Enter a three digit Number: 123


It’s not an Armstrong number

Ex.no:3 3.a Inserting an element after every ith position in an array

#include <stdio.h>

void insertAfterIthPosition(int arr[], int *size, int elem, int i) {


int originalSize = *size;

// The new size of the array after inserting elements


*size = originalSize + (originalSize / i);

// Traverse the array and insert the element after every i-th position
int j = *size - 1; // Pointer for the last position of the new array
for (int k = originalSize - 1; k >= 0; k--) {
// If the current position is a multiple of i, insert the element
if ((k + 1) % i == 0) {
arr[j--] = elem; // Insert the element
}
arr[j--] = arr[k]; // Move the original element
}
}

int main() {
int n, i, elem;

// Input size of array


printf("Enter the size of the array: ");
scanf("%d", &n);

int arr[n + n / 2]; // The array size will be increased dynamically

// Input array elements


printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Input element to insert and the position interval


printf("Enter the element to insert: ");
scanf("%d", &elem);
printf("Enter the position after which to insert the element: ");
scanf("%d", &i);

// Call the function to insert element after every `i`th position


insertAfterIthPosition(arr, &n, elem, i);

// Print the modified array


printf("Modified array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}

return 0;
}

O/P:

Enter the size of the array: 5


Enter 5 elements:
12345
Enter the element to insert: 9
Enter the position after which to insert the element: 2

Modified array: 1 2 9 3 4 9 5

Ex.no:3 3.b Insertion sort


#include <stdio.h>

// Function to perform insertion sort on the array


void insertionSort(int arr[], int n) {
int i, key, j;

// Start from the second element (index 1)


for (i = 1; i < n; i++) {
key = arr[i]; // The element to be inserted
j = i - 1;

// Move elements of arr[0..i-1], that are greater than key,


// to one position ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key; // Insert the key at the correct position
}
}

// Function to print the array


void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int n;

// Input size of the array


printf("Enter the size of the array: ");
scanf("%d", &n);

int arr[n];

// Input array elements


printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Call the insertionSort function


insertionSort(arr, n);

// Print the sorted array


printf("Sorted array: ");
printArray(arr, n);

return 0;
}

O/P:
Enter the size of the array: 5
Enter 5 elements:
12 11 13 5 6

Sorted array: 5 6 11 12 13

Ex.No: 4 Arrays: 1D and 2D, Multi - dimensional arrays, traversal

4a. Matrix Addition

Program:

#include<stdio.h>
int main()
{
inti=0,j=0;
int g ,h;
printf(“enter row size”);
scanf(“%d”,&g);
printf(“enter column size”);
scanf(“%d”,&h);
int a[g][h];
int b[g][h];
printf(“Enter the First Matrix elements :”);
for (i=0;i<g;i++)
{
for(j=0;j<h;j++)
{
printf(“a[%d] [%d]=”,i,j);
scanf(“%d”,&a[i][j]);
}
}
printf(“First Matrix:”);
for(i=0;i<g;i++)
{
for(j=0;j<h;j++)
{
printf(“%d”,a[i][j]);
}
printf(“ ”);
printf(“Enter Second Matrix elements:” );
for(i=0;i<g;i++)
{
for(j=0;j<h;j++)
{
printf(“b[%d][%d]= ”,i,j);
scanf(“%d”,&b[i][j]);
}
}
printf( “Second Matrix: ”);
for(i=0;i<g;i++)
{
for(j=0;j<h;j++)
{
printf(“%d ”,b[i][j]);
}
printf(“ ”);
}
printf(“Addition of Two Matrix “);
for(i=0;i<g;i++)
{
for(j=0;j<h;j++)
{
printf(“%d ”,a[i][j]+b[i][j]);
}
printf(“ ” );
}
return 0;
}

Output:

Enter row size:3


Enter column size:3
Enter First Matrix elements:
a[0][0]=1
a[0][1]=2
a[0][2]=3
a[1][0]=4
a[1][1]=5
a[1][2]=6
a[2][0]=7
a[2][1]=8
a[2][2]=9
First Matrix:
1 2 3
4 5 6
7 8 9
Enter Second Matrix elements:
a[0][0]=1
a[0][1]=2
a[0][2]=3
a[1][0]=4
a[1][1]=5
a[1][2]=6
a[2][0]=7
a[2][1]=8
a[2][2]=9
Second Matrix:
1 2 3
4 5 6
7 8 9

Addition of Two Matrix:


2 4 9
8 10 12
14 16 18

Ex.No: 4 Arrays: 1D and 2D, Multi - dimensional arrays, traversal

4b. Matrix multiplication

Program:

#include<stdio.h>
int main()
{
int i=0,j=0;
int g ,h;
printf(“enter row size”);
scanf(“%d”,&g);
printf(“enter column size”);
scanf(“%d”,&h);
int a[g][h];
int b[g][h];
printf(“Enter the First Matrix elements :”);
for (i=0;i<g;i++)
{
for(j=0;j<h;j++)
{
printf(“a[%d] [%d]=i,j);
scanf(“%d”,&a[i][j]);
}
}
printf(“First Matrix:”);
for(i=0;i<g;i++)
{
for(j=0;j<h;j++)
{
printf(“%d”,a[i][j]);
}
printf(“ ”);
printf(“Enter Second Matrix elements:” );
for(i=0;i<g;i++)
{
for(j=0;j<h;j++)
{
printf(“b[%d][%d]= ”,i,j);
scanf(“%d”,&b[i][j]);
}
}
printf( “Second Matrix: ”);
for(i=0;i<g;i++)
{
for(j=0;j<h;j++)
{
printf(“%d ”,b[i][j]);
}
printf(“ ”);
}
printf(“Multiplication of Two Matrix:”);
for(i=0;i<g;i++)
{
for(j=0;j<h;j++)
{
int c=0;
for(int k=0;k<h;k++)
{
c=c+(a[i][j]*b[i][j]);
}
printf(“%d”,c);
printf(“ “);
}
printf(“ “);
}
return 0;
}

Output:

Enter row size:3


Enter column size:3
Enter First Matrix elements:
a[0][0]=1
a[0][1]=2
a[0][2]=3
a[1][0]=4
a[1][1]=5
a[1][2]=6
a[2][0]=7
a[2][1]=8
a[2][2]=9
First Matrix:
1 2 3
4 5 6
7 8 9
Enter Second Matrix elements:
a[0][0]=1
a[0][1]=2
a[0][2]=3
a[1][0]=4
a[1][1]=5
a[1][2]=6
a[2][0]=7
a[2][1]=8
a[2][2]=9
Second Matrix:
1 2 3
4 5 6
7 8 9
Multiplication of two matrix:
30 36 42
66 81 96
102 126 150

Ex.No: 4 Arrays: 1D and 2D, Multi - dimensional arrays, traversal

4c. Transpose of a Matrix

Program:

#include<stdio.h>
int main()
{
int i=0,j=0;
int g ,h;
printf(“enter row size”);
scanf(“%d”,&g);
printf(“enter column size”);
scanf(“%d”,&h);
int a[g][h];
int c[g][h];
printf(“Enter the First Matrix elements :”);
for (i=0;i<g;i++)
{
for(j=0;j<h;j++)
{
printf(“a[%d] [%d]=”,i,j);
scanf(“%d”,&a[i][j]);
}
}
printf(“First Matrix:”);
for(i=0;i<g;i++)
{
for(j=0;j<h;j++)
{
printf(“%d”,a[i][j]);
}
printf(“ “);
}
for(i=0;i<g;i++)
{
for(j=0;j<h;j++)
{
c[i][j]=a[i][j];
}
}
printf(“Transpose of Matrix:”);
for(i=0;i<g;i++)
{
for(j=0;j<h;j++)
{
printf( “%d”,c[i][j]);
}
printf(“ ”);
}
return 0;
}

Output:

Enter row size: 3


Enter column size: 3
Enter First Matrix elements:
a[0][0]=1
a[0][1]=2
a[0][2]=3
a[1][0]=4
a[1][1]=5
a[1][2]=6
a[2][0]=7
a[2][1]=8
a[2][2]=9

First Matrix:
1 2 3
4 5 6
7 8 9
Transpose of Matrix:
1 4 7
2 5 8
3 6 9

Ex.no:5 5.a Concatenation of strings


#include<stdio.h>
#include<string.h>
void main()
{
char string1[25],string2[25];
int l;
printf("**** Performing string concatenation ****\n");
printf("Enter two strings\n");
scanf("%s%s",string1,string2);
printf("The concatenated string is %s\n\n",strcat(string1,string2));
}

O/P:
**** Performing string concatenation ****
Enter two strings
Sara nathan
The concatenated string is Saranathan

Ex.no:5 5.b Extracting a substring


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

// Function to extract a substring


void extractSubstring(char source[], char result[], int start, int length) {
int i;

// Loop to copy the required part of the source string to the result string
for (i = 0; i < length && source[start + i] != '\0'; i++) {
result[i] = source[start + i];
}

// Null-terminate the result string


result[i] = '\0';
}

int main() {
char source[100], result[100];
int start, length;

// Input the source string


printf("Enter the source string: ");
fgets(source, sizeof(source), stdin);

// Remove the newline character if it's read by fgets


source[strcspn(source, "\n")] = '\0';

// Input the start index and the length of the substring


printf("Enter the start index: ");
scanf("%d", &start);

printf("Enter the length of the substring: ");


scanf("%d", &length);

// Extract the substring


extractSubstring(source, result, start, length);

// Output the extracted substring


printf("Extracted substring: %s\n", result);

return 0;
}

O/P:
Enter the source string: Hello, World!
Enter the start index: 7
Enter the length of the substring: 5

Extracted substring: World

Ex.no:5 5.c Checking for palindrome


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

// Function to check if a string is palindrome


int isPalindrome(char str[]) {
int start = 0;
int end = strlen(str) - 1;

// Check for palindrome by comparing characters from both ends


while (start < end) {
// Skip non-alphanumeric characters (optional, for phrases)
if (!isalnum(str[start])) {
start++;
} else if (!isalnum(str[end])) {
end--;
} else {
// Convert characters to lowercase for case-insensitive comparison
if (tolower(str[start]) != tolower(str[end])) {
return 0; // Not a palindrome
}
start++;
end--;
}
}
return 1; // The string is a palindrome
}

int main() {
char str[100];
// Input string
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);

// Remove the newline character if it's read by fgets


str[strcspn(str, "\n")] = '\0';

// Check if the string is a palindrome


if (isPalindrome(str)) {
printf("'%s' is a palindrome.\n", str);
} else {
printf("'%s' is not a palindrome.\n", str);
}

return 0;
}

O/P:
Enter a string: A man a plan a canal Panama

'A man a plan a canal Panama' is a palindrome.

Ex.no:5 5.d Search for a given string using binary search


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

// Function to perform binary search on sorted strings


int binarySearch(char arr[][100], int n, char target[]) {
int left = 0, right = n - 1;

while (left <= right) {


int mid = left + (right - left) / 2;

// Compare the target string with the middle element


int res = strcmp(arr[mid], target);

// If the target is found at the mid position


if (res == 0) {
return mid; // Return the index of the found string
}

// If target is smaller, ignore the right half


if (res > 0) {
right = mid - 1;
}
// If target is larger, ignore the left half
else {
left = mid + 1;
}
}

return -1; // If the string is not found


}
int main() {
int n;
char target[100];

// Input the number of strings


printf("Enter the number of strings: ");
scanf("%d", &n);

// Array to store the strings


char arr[n][100];

// Input strings
printf("Enter the strings (one per line):\n");
for (int i = 0; i < n; i++) {
scanf("%s", arr[i]);
}

// Sort the strings in lexicographical order (for binary search to work)


for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (strcmp(arr[i], arr[j]) > 0) {
// Swap the strings
char temp[100];
strcpy(temp, arr[i]);
strcpy(arr[i], arr[j]);
strcpy(arr[j], temp);
}
}
}

// Input the target string to search


printf("Enter the string to search: ");
scanf("%s", target);

// Perform binary search


int result = binarySearch(arr, n, target);

// Output the result


if (result != -1) {
printf("The string '%s' was found at index %d.\n", target, result);
} else {
printf("The string '%s' was not found.\n", target);
}

return 0;
}

O/P:
Enter the number of strings: 5
Enter the strings (one per line):
apple
banana
grape
orange
kiwi
Enter the string to search: grape

The string 'grape' was found at index 2.

EX.No:6 Functions with different parameter passing techniques


6a. Swap two numbers using call by value

Program:

#include<stdio.h>
void swap(int,int);
void main( )
{
int n1,n2;
printf("Enter the two numbers to be swapped\n");
scanf("%d%d",&n1,&n2);
printf("\nThe values of n1 and n2 in the main function before calling the swap
function are n1=%d n2=%d",n1,n2);
swap(n1,n2);
printf("\nThe values of n1 and n2 in the main function after calling the swap
function are n1=%d n2=%d",n1,n2);
}
void swap(int n1,int n2)
{
int temp;
temp=n1;
n1=n2;
n2=temp;
printf("\nThe values of n1 and n2 in the swap function after swapping are n1=%d
n2=%d",n1,n2);
}

Output:

Enter the two numbers to be swapped


2 3
The values of n1 and n2 in the main function before calling the swap function
are n1=2 n2=3
The values of n1 and n2 in the swap function after swapping are n1=3 n2=2
The values of n1 and n2 in the main function after calling the swap function
are n1=3 n2=2

6b. Swap two numbers using call by reference

Program:

#include<stdio.h>
void swap(int *,int *);
void main( )
{
int n1,n2;
printf("Enter the two numbers to be swapped\n");
scanf("%d%d",&n1,&n2);
printf("\nThe values of n1 and n2 in the main function before calling the swap
function are n1=%d n2=%d",n1,n2);
swap(&n1,&n2);
printf("\nThe values of n1 and n2 in the main function after calling the swap
function are n1=%d n2=%d",n1,n2);
}
void swap(int *n1,int *n2)
{
int temp;
temp=*n1;
*n1=*n2;
*n2=temp;
printf("\nThe values of n1 and n2 in the swap function after swapping are n1=%d
n2=%d",*n1,*n2);
}

Output:

Enter the two numbers to be swapped


2 3
The values of n1 and n2 in the main function before calling the swap function
are n1=2 n2=3
The values of n1 and n2 in the swap function after swapping are n1=3 n2=2
The values of n1 and n2 in the main function after calling the swap function
are n1=3 n2=2

6c. Binary search using recursion

#include <stdio.h>

// Binary Search using Pass by Value


int binarySearchByValue(int arr[], int left, int right, int target) {
if (left <= right) {
int mid = left + (right - left) / 2;

// Check if target is present at mid


if (arr[mid] == target) {
return mid;
}

// If target is smaller, search the left half


if (arr[mid] > target) {
return binarySearchByValue(arr, left, mid - 1, target);
}

// Otherwise, search the right half


return binarySearchByValue(arr, mid + 1, right, target);
}
// Return -1 if the element is not found
return -1;
}

// Binary Search using Pass by Reference (using pointers)


int binarySearchByReference(int* arr, int left, int right, int target) {
if (left <= right) {
int mid = left + (right - left) / 2;

// Check if target is present at mid


if (*(arr + mid) == target) {
return mid;
}

// If target is smaller, search the left half


if (*(arr + mid) > target) {
return binarySearchByReference(arr, left, mid - 1, target);
}

// Otherwise, search the right half


return binarySearchByReference(arr, mid + 1, right, target);
}
// Return -1 if the element is not found
return -1;
}

int main() {
int n, target;

// Input number of elements in the array


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

int arr[n];

// Input the sorted elements in the array


printf("Enter %d sorted elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Input the target value to search


printf("Enter the target value to search: ");
scanf("%d", &target);

// Perform Binary Search using Pass by Value


int resultByValue = binarySearchByValue(arr, 0, n - 1, target);

if (resultByValue != -1) {
printf("Using Pass by Value: Element %d found at index %d.\n", target, resultByValue);
} else {
printf("Using Pass by Value: Element %d not found.\n", target);
}

// Perform Binary Search using Pass by Reference


int resultByReference = binarySearchByReference(arr, 0, n - 1, target);

if (resultByReference != -1) {
printf("Using Pass by Reference: Element %d found at index %d.\n", target, resultByReference);
} else {
printf("Using Pass by Reference: Element %d not found.\n", target);
}

return 0;
}

O/P:
Enter the number of elements in the array: 5
Enter 5 sorted elements:
10 20 30 40 50
Enter the target value to search: 30

Using Pass by Value: Element 30 found at index 2.


Using Pass by Reference: Element 30 found at index 2.

EX.NO:7 Generating a transcript with CGPA and GRADE


AIM:

To store student information in structure and display it

ALGORITHM:

Step 1: START
Step 2: Read student details like name,
mark1,2,3 Step 3: Calculate total, and
average
Step 4: Display the
grade Step 5: STOP

PROGRAM:
#include <stdio.h>

// Define the structure for a student


struct Student {
char name[50];
int roll_no;
float marks[5]; // Array to store marks for 5 subjects
float CGPA;
char grade;
};

// Function to calculate CGPA and grade


void calculateCGPAandGrade(struct Student* s) {
float total_marks = 0;

// Calculate total marks


for (int i = 0; i < 5; i++) {
total_marks += s->marks[i];
}

// Calculate CGPA (out of 10)


s->CGPA = total_marks / 50; // assuming each subject is out of 10

// Determine the grade based on CGPA


if (s->CGPA >= 9) {
s->grade = 'A';
} else if (s->CGPA >= 8) {
s->grade = 'B';
} else if (s->CGPA >= 7) {
s->grade = 'C';
} else if (s->CGPA >= 6) {
s->grade = 'D';
} else {
s->grade = 'F';
}
}

// Function to display the transcript


void displayTranscript(struct Student* s) {
printf("\n--- Transcript ---\n");
printf("Name: %s\n", s->name);
printf("Roll Number: %d\n", s->roll_no);
printf("Marks: ");
for (int i = 0; i < 5; i++) {
printf("%.2f ", s->marks[i]);
}
printf("\nCGPA: %.2f\n", s->CGPA);
printf("Grade: %c\n", s->grade);
}

int main() {
struct Student student;

// Input student details


printf("Enter the student's name: ");
fgets(student.name, sizeof(student.name), stdin);

// Remove newline character that fgets might have added


student.name[strcspn(student.name, "\n")] = '\0';

printf("Enter the student's roll number: ");


scanf("%d", &student.roll_no);

// Input marks for 5 subjects


printf("Enter marks for 5 subjects (out of 10): \n");
for (int i = 0; i < 5; i++) {
printf("Subject %d: ", i + 1);
scanf("%f", &student.marks[i]);
}

// Calculate CGPA and Grade


calculateCGPAandGrade(&student);

// Display the transcript


displayTranscript(&student);
return 0;
}

O/P:
Enter the student's name: John Doe
Enter the student's roll number: 101
Enter marks for 5 subjects (out of 10):
Subject 1: 8
Subject 2: 9
Subject 3: 7
Subject 4: 6
Subject 5: 8

--- Transcript ---


Name: John Doe
Roll Number: 101
Marks: 8.00 9.00 7.00 6.00 8.00
CGPA: 7.60
Grade: C

EX.NO:8 Demonstrate file operations


8a. Count number of characters in the file

Program:

#include<stdio.h>
#define MAX_FILE_NAME 100
int main()
{
FILE* fp;
int count = 0;
char filename[MAX_FILE_NAME];
char c;
printf("Enter file name: ");
scanf("%s", filename);
fp = fopen(filename, "r");
if (fp == NULL) {
printf("Could not open file %s",filename);
return 0;
}
for (c = getc(fp); c != EOF; c = getc(fp))
count = count + 1;
fclose(fp);
printf("The file %s has %d characters\n ",filename, count);
return 0;
}

Output:

Enter file name: Empdetails.txt


The file Empdetails.txt has 26 characters
(or)

8.a Count the number of character, words and lines in the file
#include <stdio.h>
#include <ctype.h>

void countFileDetails(FILE *file, int *charCount, int *wordCount, int *lineCount) {


char ch;
int inWord = 0; // Flag to check if we are inside a word

// Read the file character by character


while ((ch = fgetc(file)) != EOF) {
(*charCount)++; // Increment character count

// Count the number of words


if (isspace(ch)) {
if (inWord) {
(*wordCount)++; // End of a word
inWord = 0; // Reset the word flag
}
if (ch == '\n') {
(*lineCount)++; // Increment line count on newline character
}
} else {
inWord = 1; // Mark as inside a word
}
}

// If the file ends while inside a word, count the last word
if (inWord) {
(*wordCount)++;
}
}

int main() {
FILE *file;
char filename[100];
int charCount = 0, wordCount = 0, lineCount = 0;

// Input file name


printf("Enter the file name: ");
scanf("%s", filename);

// Open the file for reading


file = fopen(filename, "r");

// Check if file is opened successfully


if (file == NULL) {
printf("Could not open file %s\n", filename);
return 1; // Return with an error code
}

// Count characters, words, and lines


countFileDetails(file, &charCount, &wordCount, &lineCount);
// Output the results
printf("The number of characters in the file: %d\n", charCount);
printf("The number of words in the file: %d\n", wordCount);
printf("The number of lines in the file: %d\n", lineCount);

// Close the file


fclose(file);

return 0;
}

O/P:
Hello World! This is a test.
This is the second line.
And here is the third line.

Enter the file name: example.txt


The number of characters in the file: 91
The number of words in the file: 14
The number of lines in the file: 3

8b. Replace a specific word with the given word in the same file

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

#define MAX_LENGTH 1000

// Function to replace all occurrences of 'oldWord' with 'newWord' in a file


void replaceWordInFile(FILE *file, const char *oldWord, const char *newWord) {
FILE *tempFile;
char buffer[MAX_LENGTH];
char temp[MAX_LENGTH];
int i, j, found;

// Open a temporary file to store the modified content


tempFile = fopen("temp.txt", "w");
if (tempFile == NULL) {
printf("Unable to open temporary file.\n");
return;
}

// Read the content of the original file line by line


while (fgets(buffer, sizeof(buffer), file) != NULL) {
i = 0;
while (buffer[i] != '\0') {
found = 1;
j = 0;
// Check if the current part of the line matches the 'oldWord'
while (oldWord[j] != '\0' && buffer[i + j] == oldWord[j]) {
j++;
}
// If the 'oldWord' is found, replace it with the 'newWord'
if (oldWord[j] == '\0' && (buffer[i + j] == ' ' || buffer[i + j] == '\0' || buffer[i + j] == '\n')) {
// Copy new word to temp
fprintf(tempFile, "%s", newWord);
i += j; // Move past the old word
} else {
// Copy the current character from buffer to temp
fputc(buffer[i], tempFile);
i++;
}
}
}

// Close the temporary file


fclose(tempFile);

// Close the original file


fclose(file);

// Delete the original file


remove("input.txt");

// Rename the temporary file to the original file name


rename("temp.txt", "input.txt");

printf("The word replacement is done successfully.\n");


}

int main() {
FILE *file;
char filename[100];
char oldWord[100], newWord[100];

// Input file name, word to replace and new word


printf("Enter the filename: ");
scanf("%s", filename);
printf("Enter the word to be replaced: ");
scanf("%s", oldWord);
printf("Enter the new word: ");
scanf("%s", newWord);

// Open the file for reading


file = fopen(filename, "r");
if (file == NULL) {
printf("Could not open file %s\n", filename);
return 1;
}

// Replace the word in the file


replaceWordInFile(file, oldWord, newWord);

return 0;
}
O/P:
Hello world!
This is a test file. Hello again!

Hi world!
This is a test file. Hi again!

Enter the filename: input.txt


Enter the word to be replaced: Hello
Enter the new word: Hi

The word replacement is done successfully.

You might also like