Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

C Programming Lab Manual

The document provides a comprehensive overview of the C programming language, covering essential topics such as keywords, data types, operators, memory allocation functions, and preprocessor directives. It includes practical examples demonstrating various algorithms and functions, including finding roots of quadratic equations, calculating GCD, generating Fibonacci numbers, and performing string manipulations. Additionally, it addresses array operations like searching, sorting, and element deletion.

Uploaded by

ankitkhedkar987
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

C Programming Lab Manual

The document provides a comprehensive overview of the C programming language, covering essential topics such as keywords, data types, operators, memory allocation functions, and preprocessor directives. It includes practical examples demonstrating various algorithms and functions, including finding roots of quadratic equations, calculating GCD, generating Fibonacci numbers, and performing string manipulations. Additionally, it addresses array operations like searching, sorting, and element deletion.

Uploaded by

ankitkhedkar987
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Introduction

1. C Keywords
• Purpose: These are reserved words in C, with predefined
meanings. They are essential in program structure and syntax.

C
• List of Common Keywords: int, char, return, void, if, else,
for, while, switch, case, break, continue, struct, etc.

2. Data Types
Primitive Data Types: int, char, float, double.
Derived Data Types: Arrays, pointers, structures (struct), and unions.

3. Operators
• Arithmetic Operators: +, -, *, /, %.
• Relational Operators: ==, !=, <, >, <=, >=.
• Logical Operators: && (AND), || (OR), ! (NOT).
• Assignment Operators: =, +=, -=, etc.

4. Memory Allocation Functions


• malloc(): Allocates a specified amount of memory.
• calloc(): Allocates memory for an array of elements, initializing all bytes to
zero.
• free(): Free allocated memory.
• realloc(): Resizes previously allocated memory.

5. Preprocessor Directives and Common Header Files


• #include: Includes libraries and files before compilation. Some common
libraries are:
o #include <stdio.h>: Standard I/O operations.
Functions like printf(), scanf(), fopen(), fclose()
o #include <stdlib.h>: General utilities and memory management.
Functions like malloc(), calloc(), free(), exit()
o #include <string.h>: String handling functions.
Functions like strlen(), strcpy(), strcmp().
o #include <math.h>: Mathematical computations.
Functions like sqrt(), pow(), sin()
o #include <ctype.h>: Character testing and conversion functions.
Functions like isalpha(), isdigit(), toupper(), tolower().
1. a. Find the all-possible roots of a quadratic equation.
#include <stdio.h>
#include <math.h>
#include <conio.h>
int main() {
float a, b, c, discriminant, root1, root2, realPart, imaginaryPart;

C
clrscr();
printf("Enter coefficients a, b, and c (non-zero values for a): ");
scanf("%f %f %f", &a, &b, &c);
if (a == 0 || b == 0 || c == 0) {
printf("Coefficients cannot be zero. Exiting the program.\n");
return 0;
}
discriminant = (b * b) - (4 * a * c);
if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
printf("Roots are real and equal: \n");
printf("Root1 = Root2 = %.2f\n", root1);
}
else if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Roots are real and distinct: \n");
printf("Root1 = %.2f\n", root1);
printf("Root2 = %.2f\n", root2);
}
else {
realPart = -b / (2 * a);
imaginaryPart = sqrt(-discriminant) / (2 * a);
printf("Roots are complex and distinct: \n");
printf("Root1 = %.2f + %.2fi\n", realPart, imaginaryPart);
printf("Root2 = %.2f - %.2fi\n", realPart, imaginaryPart);
}
getch();
return 0;
}

Outputs
Enter coefficients a, b, and c (non-zero values for a): Enter coefficients a, b, and c (non-zero values for a):
1 -2 1 125
Roots are real and equal: Roots are complex and distinct:
Root1 = Root2 = 1.00 Root1 = -1.00 + 2.00i
Root2 = -1.00 - 2.00i
Enter coefficients a, b, and c (non-zero values for a):
1 -3 2 Enter coefficients a, b, and c (non-zero values for a):
Roots are real and distinct: 025
Root1 = 2.00 Coefficients cannot be zero. Exiting the program
Root2 = 1.00
b. Find the reverse of an integer and check whether it is a palindrome or not.
#include <stdio.h>
#include <conio.h>
int main() {
int num, reversedNum = 0, remainder, originalNum;
clrscr();

C
printf("Enter an integer: ");
scanf("%d", &num);
originalNum = num;
while (num != 0) {
remainder = num % 10;
reversedNum = reversedNum * 10 + remainder;
num = num / 10;
}
printf("Reversed Number = %d\n", reversedNum);
if (originalNum == reversedNum) {
printf("The number is a palindrome.\n");
} else { printf("The number is not a palindrome.\n");
}
getch();
return 0;
}
Outputs
Enter an integer = 121 Enter an integer = 123
Reversed Number = 121 Reversed Number = 321
The number is a palindrome. The number is not a palindrome.

2. a. Find the GCD of two integers

#include<stdio.h>
#include<conio.h>
void main() {
int n, m;
clrscr();
printf("Input two numbers: ");
scanf("%d %d", &m, &n);
if (m <= 0 || n <= 0)
printf("Invalid Input\n");
else {
while (m != n) {
if (m > n)
m = m - n;
else
n = n - m;
}
printf("GCD = %d\n", n);
}
getch();
}
Outputs

Input two numbers: 36 60 Input two numbers: -5 20


GCD = 12 Invalid Input

C
b. Generate and print first N Fibonacci numbers using recursion.
#include <stdio.h>
#include <conio.h>
int fibonacci(int n) {
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int N, i;
clrscr();
printf("Enter the number of Fibonacci numbers to generate: ");
scanf("%d", &N);
printf("First %d Fibonacci numbers are:\n", N);
for (i = 0; i < N; i++) {
printf("%d ", fibonacci(i));
}
getch();
return 0;
}

Outputs
Enter the number of Fibonacci numbers to generate: 10
First 10 Fibonacci numbers are:
0 1 1 2 3 5 8 13 21 34

3. a. Compute Mean, Variance, and Standard Deviation of N real numbers.


#include<stdio.h>
#include<conio.h>
#include<math.h>
int main() {
int n, i;
float a[100], sum = 0, mean = 0, variance = 0, deviation = 0;
clrscr();
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter the numbers:\n");
for(i = 0; i < n; i++) {
scanf("%f", &a[i]);
sum = sum + a[i];
}
mean = sum / n;
printf("\nMean = %.2f", mean);
sum = 0;

C
for(i = 0; i < n; i++) {
sum = sum + (a[i] - mean) * (a[i] - mean);
}
variance = sum / n;
printf("\nVariance = %.2f", variance);
deviation = sqrt(variance);
printf("\nStandard Deviation = %.2f\n", deviation);
getch();
return 0;
}

Outputs
Enter the number of elements: 4 Enter the number of elements: 5
Enter the numbers: 2 4 4 6 Enter the numbers: 1 5 10 15 20

Mean = 4.00 Mean = 10.20


Variance = 2.00 Variance = 46.16
Standard Deviation = 1.41 Standard Deviation = 6.79

b. Search an element using linear search method.

#include<stdio.h>
#include<conio.h>
int main() {
int n, i, searchElement, found = 0;
int a[100];
clrscr();
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
printf("Enter the elements of the array:\n");
for(i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
printf("Enter the element to search: ");
scanf("%d", &searchElement);

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


if(a[i] == searchElement) {
printf("Element %d found at position %d.\n", searchElement, i + 1);
found = 1;
break;
}
}
if(!found) {
printf("Element %d not found in the array.\n", searchElement);
}
getch();
return 0;

C
}
Outputs
Enter the number of elements in the array 5 Enter the number of elements in the array: 5
Enter the elements of the array: Enter the elements of the array:
2 3 8 10 11 10 20 30 40 50
Enter the element to search: 10 Enter the element to search: 30
Element 10 found at position 4. Element 30 found at position 3.

4. a. Interchange the largest and smallest number in the array.


#include <stdio.h>
#include <conio.h>
int main() {
int n, i, largestIndex = 0, smallestIndex = 0, temp;
int a[100];
clrscr();
printf("Enter the array size: ");
scanf("%d", &n);
printf("Enter the elements of array:\n");
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
printf("The array elements are: ");
for (i = 0; i < n; i++) {
printf("%d ", a[i]);
}
printf("\n");
for (i = 1; i < n; i++) {
if (a[i] > a[largestIndex]) {
largestIndex = i;
}
if (a[i] < a[smallestIndex]) {
smallestIndex = i;
} }
printf("Smallest number: =%d\n", a[smallestIndex]);
printf("Largest number: =%d\n", a[largestIndex]);
temp = a[largestIndex];
a[largestIndex] = a[smallestIndex];
a[smallestIndex] = temp;
printf("After interchanging largest & smallest values the array: \n");
for (i = 0; i < n; i++) {
printf("%d ", a[i]); }
getch();
return 0;
}
Outputs;
Enter the array size: 6
Enter the elements of array:
10 30 40 12 56 79
The array elements are: 10 30 40 12 56 79
Smallest number: =10

C
Largest number: =79
After interchanging largest & smallest values the array:
79 30 40 12 56 10

b. Search an element using binary search method


#include <stdio.h>
#include <conio.h>
int main() {
int n, i, key, low, high, mid;
int a[100];
clrscr();
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
printf("Enter the sorted elements of the array:\n");
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
printf("Enter the element to search: ");
scanf("%d", &key);
low = 0;
high = n - 1;
while (low <= high) {
mid = (low + high) / 2;

if (a[mid] == key) {
printf("Element found at position %d\n", mid + 1);
getch();
return 0;
} else if (a[mid] < key) {
low = mid + 1;
} else {
high = mid - 1;
}
}
printf("Element not found in the array.\n");
getch();
return 0;
}
Outputs;
Enter the number of elements in the array: 5
Enter the sorted elements of the array:
10 20 30 40 50
Enter the element to search: 30
Element found at position 3
5. a. To check whether a given string is palindrome or not without using library
functions
#include <stdio.h>
#include <conio.h>
int main() {
char str[100];

C
int start = 0, end = 0, flag = 1;
clrscr();
printf("Enter a string: ");
scanf("%s", str);
while (str[end] != '\0') {
end++;
}
end--;
while (start < end) {
if (str[start] != str[end]) {
flag = 0;
break;
}
start++;
end--;
}
if (flag == 1) {
printf("The string is a palindrome.\n");
} else {
printf("The string is not a palindrome.\n");
}
getch();
return 0;
}

Outputs
Enter a string: madam Enter a string: hello
The string is a palindrome. The string is not a palindrome

b. Find the number of vowels, constants, digits and white spaces in a string

#include <stdio.h>
#include <conio.h>
#include <ctype.h> // For tolower(), isdigit(), isspace()
int main() {
char str[100];
int vowels = 0, consonants = 0, digits = 0, spaces = 0, i = 0;
clrscr();
printf("Enter a string: ");
gets(str);
while (str[i] != '\0') {
char ch = tolower(str[i]);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
} else if ((ch >= 'a' && ch <= 'z')) {
consonants++;
} else if (isdigit(ch)) {
digits++;
} else if (isspace(ch)) {
spaces++;

C
}
i++;
}

printf("Number of Vowels: %d\n", vowels);


printf("Number of Consonants: %d\n", consonants);
printf("Number of Digits: %d\n", digits);
printf("Number of White spaces: %d\n", spaces);

getch();
return 0;
}

Output:
Enter a string: Hello World 123

Number of Vowels: 3
Number of Consonants: 7
Number of Digits: 3
Number of White spaces: 2

6. a. Delete an element from an array


b. Sort N elements of an array in ascending order using bubble sort
technique.

#include <stdio.h>
#include <conio.h>
int main()
{
int arr[100], n, i, j, temp, element, pos = -1;
clrscr();
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter the elements of the array:\n");
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
printf("Enter the element to delete: ");
scanf("%d", &element);

// Search for the element in the array


for (i = 0; i < n; i++)
{
if (arr[i] == element)
{
pos = i;
break;
}
}
// If the element was found, delete it by shifting elements

C
if (pos != -1)
{
for (i = pos; i < n - 1; i++)
{
arr[i] = arr[i + 1];
}
n--;
// Display the array after deletion
printf("Array after deletion:\n");
for (i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
else
{
printf("Element not found in the array.\n");
}
// Bubble Sort to sort the array in ascending order
for (i = 0; i < n - 1; i++)
{
for (j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// Display the sorted array after deletion
printf("Array after deletion and sorting:\n");
for (i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}

getch();
return 0;
}

Outputs:
Enter the number of elements: 5 Enter the number of elements: 6
Enter the elements of the array: Enter the elements of the array:
10 20 30 40 50 50 40 30 20 10 60
Enter the element to delete: 30 Enter the element to delete: 20
Array after deletion: Array after deletion:
10 20 40 50 50 40 30 10 60
Array after deletion and sorting: Array after deletion and sorting:
10 20 40 50 10 30 40 50 60
7. Read a matrix A of size MxN and find the following:
a) Sum of the elements of each row.
b) Sum of the elements of each column.
c) Sum of all the elements of the matrix.
d) Sum of both diagonals with suitable headings.

C
#include <stdio.h>
#include <conio.h>
int main()
{
int m, n, i, j;
int matrix[10][10];
int rowSum, colSum, totalSum = 0, diagonalSum = 0;
clrscr();
printf("Enter the order of the matrix (rows): ");
scanf("%d", &m);
printf("Enter the order of the matrix (columns): ");
scanf("%d", &n);
printf("Enter the elements of the matrix:\n");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
scanf("%d", &matrix[i][j]);
}
}
// Calculate row sums
for (i = 0; i < m; i++)
{
rowSum = 0;
for (j = 0; j < n; j++)
{
rowSum += matrix[i][j];
totalSum += matrix[i][j];
}
printf("Sum of row %d is = %d\n", i, rowSum);
}
printf("\n");
// Calculate column sums
for (j = 0; j < n; j++)
{
colSum = 0;
for (i = 0; i < m; i++)
{
colSum += matrix[i][j];
}
printf("Sum of column %d is = %d\n", j, colSum);
}
printf("\n");
// Calculate diagonal sum if matrix is square
if (m == n)
{
for (i = 0; i < m; i++)
{
diagonalSum += matrix[i][i]; // Only the main diagonal sum
}
printf("The Sum of the Diagonal Elements is = %d\n", diagonalSum);
}
// Display total sum
printf("\nSum of All elements of the matrix is = %d\n", totalSum);
getch();
return 0;
}

C
Outputs
Enter the order of the matrix (rows): 2 Enter the order of the matrix (rows): 2
Enter the order of the matrix (columns): 2 Enter the order of the matrix (columns): 3
Enter the elements of the matrix: Enter the elements of the matrix:
12 123
34 456

Sum of row 0 is = 3 Sum of row 0 is = 6


Sum of row 1 is = 7 Sum of row 1 is = 15

Sum of column 0 is = 4 Sum of column 0 is = 5


Sum of column 1 is = 6 Sum of column 1 is = 7
Sum of column 2 is = 9
The Sum of the Diagonal Elements is = 5
Sum of All elements of the matrix is = 21
Sum of All elements of the matrix is = 10

8. Input two matrices of size M x N and P x Q. Perform the following


operations:
a) Multiply the two matrices if they are compatible.
b) Compute the transpose of the resultant matrix after multiplication.

#include <stdio.h>
#include <conio.h>
void displayMatrix(int matrix[10][10], int rows, int cols) {
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
void inputMatrix(int matrix[10][10], int rows, int cols) {
int i, j;
printf("Enter elements for a %dx%d matrix:\n", rows, cols);
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
scanf("%d", &matrix[i][j]);
}
}
}
int main() {

C
int m, n, p, q, i, j, k;
int matrix1[10][10], matrix2[10][10], result[10][10], transpose[10][10];
clrscr();
printf("Enter the order of the first matrix (rows and columns): ");
scanf("%d %d", &m, &n);
printf("Enter the order of the second matrix (rows and columns): ");
scanf("%d %d", &p, &q);
// Check if multiplication is possible
if (n != p) {
printf("Matrix multiplication is not possible.\n");
return 0;
}
// Input matrices
inputMatrix(matrix1, m, n);
inputMatrix(matrix2, p, q);
// Initialize result matrix to zero
for (i = 0; i < m; i++) {
for (j = 0; j < q; j++) {
result[i][j] = 0;
}
}
// Perform matrix multiplication
for (i = 0; i < m; i++) {
for (j = 0; j < q; j++) {
for (k = 0; k < n; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
// Display the resultant matrix
printf("Resultant matrix after multiplication:\n");
displayMatrix(result, m, q);
// Compute transpose of the resultant matrix
for (i = 0; i < q; i++) {
for (j = 0; j < m; j++) {
transpose[i][j] = result[j][i];
} }
// Display the transpose

C
printf("Transpose of the resultant matrix:\n");
displayMatrix(transpose, q, m);
getch();
return 0;
}
Outputs:
Enter the order of the first matrix (rows and columns): 2 3 Enter the order of the first matrix (rows and columns): 1 4
Enter the order of the second matrix (rows and columns): 3 2 Enter the order of the second matrix (rows and columns): 41
Enter elements for a 2x3 matrix: Enter elements for a 1x4 matrix:
1234
123
Enter elements for a 4x1 matrix:
456
5
Enter elements for a 3x2 matrix: 6
78 7
9 10 8
11 12 Resultant matrix after multiplication:
Resultant matrix after multiplication: 70
58 64 Transpose of the resultant matrix:
139 154 70
Transpose of the resultant matrix:
58 139 Enter the order of the first matrix (rows and columns): 2 3
64 154 Enter the order of the second matrix (rows and columns): 2 4

Matrix multiplication is not possible.

9. a. Swap the contents of two variables using pointers.

#include <stdio.h>
#include <conio.h>
int main()
{
int x, y, *a = &x, *b = &y, temp;
clrscr();
printf("Enter values for x and y: ");
scanf("%d%d", &x, &y);
printf("Before Swapping: x = %d, y = %d\n", x, y);
temp = *b;
*b = *a;
*a = temp;
printf("After Swapping: x = %d, y = %d\n", x, y);
getch();
return 0;
}
Outputs:
Enter values for x and y: 5 10 Enter values for x and y: -3 -7
Before Swapping: x = 5, y = 10 Before Swapping: x = -3, y = -7
After Swapping: x = 10, y = 5 After Swapping: x = -7, y = -3

C
b. Concatenate the contents of two files
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
FILE *fp1 = fopen("file1.txt", "a");
FILE *fp2 = fopen("file2.txt", "r");
char c;
if (!fp1 || !fp2)
{
puts("Could not open files");
exit(0);
}
while ((c = fgetc(fp2)) != EOF)
fputc(c, fp1);
fclose(fp1);
fclose(fp2);
printf("File1 and File2 merged. Please check file1.\n");
getch();
return 0;
}

Outputs:
file1.txt file2.txt

After Running Program:


10. Define a Structure called Employee with Emp ID, Emp-name and Salary
as its data members. Read details of N Employees and display the details
of employee whose salary is greater than ₹15000.

#include <stdio.h>

C
struct Employee {
int empID;
char empName[50];
float salary;
};

int main() {
int n, count = 0;
printf("Enter the number of employees: ");
scanf("%d", &n);

struct Employee employees[n];

// Read employee details


for (int i = 0; i < n; i++) {
printf("Enter details of Employee %d:\n", i + 1);
printf("Employee ID: ");
scanf("%d", &employees[i].empID);
printf("Employee Name: ");
scanf(" %[^\n]", employees[i].empName);
printf("Salary: ");
scanf("%f", &employees[i].salary);
}

// Display employees with salary > 15000


printf("\n------------------------\n");
printf("Employees with salary greater than 15000:\n");
printf("------------------------\n");
for (int i = 0; i < n; i++) {
if (employees[i].salary > 15000) {
printf("\n------------------------\n");
printf("Employee ID: %d\n", employees[i].empID);
printf("Employee Name: %s\n", employees[i].empName);
printf("Salary: %.2f\n", employees[i].salary);
printf("------------------------\n");
count++;
}
}

if (count == 0) {
printf("No employee has a salary greater than 15000.\n");
}

return 0;
}
Outputs:

Enter the number of employees: 3 Enter the number of employees: 4


Enter details of Employee 1: Enter details of Employee 1:
Employee ID: 101 Employee ID: 201
Employee Name: Alice Johnson Employee Name: David Lee

C
Salary: 20000 Salary: 14000
Enter details of Employee 2: Enter details of Employee 2:
Employee ID: 102 Employee ID: 202
Employee Name: Bob Smith Employee Name: Eva Miller
Salary: 12000 Salary: 16500
Enter details of Employee 3: Enter details of Employee 3:
Employee ID: 103 Employee ID: 203
Employee Name: Charlie Brown Employee Name: Frank Harris
Salary: 18000 Salary: 12500
Enter details of Employee 4:
------------------------ Employee ID: 204
Employees with salary greater than Employee Name: Grace Nguyen
15000: Salary: 13000
------------------------
------------------------
------------------------ Employees with salary greater than
Employee ID: 101 15000:
Employee Name: Alice Johnson ------------------------
Salary: 20000.00
------------------------ ------------------------
Employee ID: 202
------------------------ Employee Name: Eva Miller
Employee ID: 103 Salary: 16500.00
Employee Name: Charlie Brown -----------------------
Salary: 18000.00

11. Create a structure called student with the following members student
name, roll_no, marks in three tests. Write a C program to create N
records and
a) Search on roll_no and display all the records
b) Average marks in test
c) Highest in test.
#include <stdio.h>
#include <string.h>

struct Student {
char name[50];
int roll_no;

C
float marks[3];
};

// Function to search for and display a student's record by roll_no


void searchByRollNo(struct Student students[], int n, int roll_no) {
int found = 0;
printf("\nDisplaying Search Information:\n");
printf("Name\t\tRoll_No\tTest1\tTest2\tTest3\tAverage\tHighest Marks\n");
printf("---------------------------------------------------------------\n");

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


if (students[i].roll_no == roll_no) {
float avg = (students[i].marks[0] + students[i].marks[1] +
students[i].marks[2]) / 3;
float highest = students[i].marks[0];

for (int j = 1; j < 3; j++) {


if (students[i].marks[j] > highest) {
highest = students[i].marks[j];
}
}

printf("%s\t\t%d\t%.0f\t%.0f\t%.0f\t%.2f\t%.0f\n",
students[i].name, students[i].roll_no, students[i].marks[0],
students[i].marks[1], students[i].marks[2], avg, highest);

found = 1;
break;
}
}
if (!found) {
printf("No student found with Roll No: %d\n", roll_no);
}
}

// Function to display all student records with average and highest marks
void displayAllRecords(struct Student students[], int n) {
printf("\nDisplaying Information:\n");
printf("Name\t\tRoll_No\tTest1\tTest2\tTest3\tAverage\tHighest Marks\n");
printf("---------------------------------------------------------------\n");

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


float avg = (students[i].marks[0] + students[i].marks[1] +
students[i].marks[2]) / 3;
float highest = students[i].marks[0];
for (int j = 1; j < 3; j++) {
if (students[i].marks[j] > highest) {
highest = students[i].marks[j];
}
}

C
printf("%s\t\t%d\t%.0f\t%.0f\t%.0f\t%.2f\t%.0f\n",
students[i].name, students[i].roll_no,
students[i].marks[0], students[i].marks[1], students[i].marks[2],
avg, highest);
}
}

int main() {
int n, roll_no;

printf("Enter number of students: ");


scanf("%d", &n);

struct Student students[n];

// Input student records


for (int i = 0; i < n; i++) {
printf("\nEnter information of Student %d\n", i + 1);
printf("Name: ");
scanf(" %[^\n]", students[i].name);
printf("Roll No: ");
scanf("%d", &students[i].roll_no);
printf("Test1: ");
scanf("%f", &students[i].marks[0]);
printf("Test2: ");
scanf("%f", &students[i].marks[1]);
printf("Test3: ");
scanf("%f", &students[i].marks[2]);
}

// Display all records with average and highest marks


displayAllRecords(students, n);

// Search for a student by roll number and display their record


printf("\nEnter the student roll_no to be searched: ");
scanf("%d", &roll_no);
searchByRollNo(students, n, roll_no);

return 0;
}
Output

Enter number of students: 2

Enter information of Student 1

C
Name: Ganeshji
Roll No: 12
Test1: 65
Test2: 98
Test3: 78

Enter information of Student 2


Name: Sharmaji
Roll No: 15
Test1: 78
Test2: 45
Test3: 65

Displaying Information:
Name Roll_No Test1 Test2 Test3 Average Highest Marks
---------------------------------------------------------------
Ganeshji 12 65 98 78 80.00 98
Sharmaji 15 78 45 65 62.00 78

Enter the student roll_no to be searched: 15

Displaying Search Information:


Name Roll_No Test1 Test2 Test3 Average Highest Marks
---------------------------------------------------------------
Sharmaji 15 78 45 65 62.00 78
12: a. Store a character string in a block of memory space created by malloc()
ㅤㅤㅤand then modify the same to store a large string.

#include <stdio.h>
#include <stdlib.h>

C
#include <string.h>

int main() {
char *buffer;

/* Allocating memory */
if ((buffer = (char *)malloc(6)) == NULL) {
printf("malloc failed.\n");
exit(1);
}
printf("Buffer of size 6 created \n");

/* Storing initial string */


strcpy(buffer, "MYSORE");
printf("Buffer contains: %s\n", buffer);

/* Reallocation */
if ((buffer = (char *)realloc(buffer, 25)) == NULL) {
printf("Reallocation failed.\n");
exit(1);
}
printf("\nBuffer size modified.\n");
printf("Modified Buffer size is 25\n");

/* Checking buffer contents after reallocation */


printf("Buffer still contains: %s\n", buffer);

/* Modifying buffer content */


strcpy(buffer, "BENGALURU");
printf("Buffer now contains: %s\n", buffer);

/* Freeing memory */
free(buffer);

return 0;
}

Output
Buffer of size 6 created
Buffer contains: MYSORE

Buffer size modified.


Modified Buffer size is 25
Buffer still contains: MYSORE
Buffer now contains: BENGALURU
b. Reverse the elements of an array using pointers

#include <stdio.h>
int main() {
int n;

C
// Step 1: Get the number of elements in the array
printf("Enter the number of elements: ");
scanf("%d", &n);

int arr[n]; // Declare array


int *ptr1 = arr; // Pointer to the beginning of the array
int *ptr2 = arr + n - 1; // Pointer to the end of the array

// Step 2: Take array elements as input from the user


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

// Step 3: Reverse the array using pointers


while (ptr1 < ptr2) {
// Swap the values pointed by ptr1 and ptr2
int temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;

// Move the pointers towards each other


ptr1++;
ptr2--;
}

// Step 4: Display the reversed array


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

return 0;
}

Outputs
Enter the number of elements: 5 Enter the number of elements: 6
Enter 5 elements: Enter 6 elements:
12345 10 20 30 40 50 60
Reversed array: Reversed array:
54321 60 50 40 30 20 10

You might also like