0% found this document useful (0 votes)
22 views

C Practical Work

Uploaded by

Bhavya Vij
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)
22 views

C Practical Work

Uploaded by

Bhavya Vij
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/ 50

C PRACTICAL WORK

ANSWER 1:
#include<stdio.h>

int main(){

float celsius,fahrenheit;

printf("enter temperature in celsius:");

scanf("%f",&celsius);

fahrenheit=(celsius*9/5)+32;

printf("%f celsius=%f fahrenheit\n",celsius,fahrenheit);

return 0;

ANSWER 2:
#include <stdio.h>
int main() {

double n1, n2, n3;


printf("Enter three numbers: ");
scanf("%lf %lf %lf", &n1, &n2, &n3);

if (n1 >= n2 && n1 >= n3)


printf("%.2lf is the largest number.", n1);

else if (n2 >= n1 && n2 >= n3)

printf("%.2lf is the largest number.", n2);

else
printf("%.2lf is the largest number.", n3);

return 0;
}

ANSWER 3:
#include <stdio.h>
int main() {
int num, i;
printf("Enter a number: ");
scanf("%d", &num);

if (num <= 1) {
printf("%d is not a prime number.\n", num);
return 0;
}

for (i = 2; i < num; i++) {


if (num % i == 0) {
printf("%d is not a prime number.\n", num);
return 0;

}
}
printf("%d is a prime number.\n", num);
return 0;
}

ANSWER 3:
#include<stdio.h>
int main () {
int i,j,c,n;
c = 1;
printf("enter number of terms : ");
scanf("%d", &n);

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


for(j=1;j<=i;j++) {
printf("%d ",c);
c++;

}
printf("\n");
}
}

ANSWER 4:
#include <stdio.h>

int main() {
int marks[50];
int i;
float sum = 0;

// Input marks of 50 students

printf("Enter marks of 50 students:\n");


for (i = 0; i < 50; i++) {
printf("Student %d: ", i + 1);
scanf("%d", &marks[i]);

// Calculate the sum of marks


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

sum += marks[i];
}

// Calculate the average marks


float average = sum / 50;

// Display the average marks


printf("Average marks of the class: %.2f\n", average);

return 0;
}

OUTPUT:
ANSWER 5:
#include <stdio.h>

int main() {

int n, i, j, key, found = 0;

// Get the size of the array from the user


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

// Declare the array


int arr[n];

// Get the array elements from the user


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

// Get the key to be searched from the user


printf("Enter the number to be searched: ");
scanf("%d", &key);

// Sort the array in ascending order


for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {

if (arr[i] > arr[j]) {


int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}

// Search for the key in the array


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

if (arr[i] == key) {
found = 1;
break;
}

// Display the array in ascending order


printf("The array in ascending order is:\n");
for (i = 0; i < n; i++) {

printf("%d ", arr[i]);


}

// Display whether the key was found or not

if (found) {
printf("\nThe number %d is found at index %d.\n", key, i);
} else {
printf("\nThe number %d is not found in the array.\n", key);

return 0;
}
ANSWER 6:
) #include <stdio.h>
#include <string.h>

int isPalindrome(char str[]) {


int len = strlen(str);
for (int i = 0; i < len / 2; i++) {
if (str[i] != str[len - i - 1]) {

return 0; // Not a palindrome


}
}
return 1; // Palindrome
}

int main() {

char str[100];
printf("Enter a string: ");
scanf("%s", str);

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

return 0;
}

ANSWER 7:
#include <stdio.h>
int main() {
int num1, num2;
int *ptr1, *ptr2;

printf("Enter two numbers: ");


scanf("%d %d", &num1, &num2);

ptr1 = &num1;
ptr2 = &num2;

printf("Sum: %d\n", *ptr1 + *ptr2);

printf("Difference: %d\n", *ptr1 - *ptr2);


printf("Product: %d\n", *ptr1 * *ptr2);
printf("Quotient: %d\n", *ptr1 / *ptr2);

return 0;

}
ANSWER 8:
#include <stdio.h>
#include <string.h>

#define NUM_EMPLOYEES 10

// Define structure for Employee


struct Employee {
int id;

char name[50];
int age;
char address[100];
char department[50];

float salary;
};

// Function to input employee data

void inputEmployeeData(struct Employee *emp) {


printf("Enter Employee ID: ");
scanf("%d", &emp->id);
printf("Enter Employee Name: ");
scanf(" %[^\n]", emp->name);

printf("Enter Age: ");


scanf("%d", &emp->age);
printf("Enter Address: ");
scanf(" %[^\n]", emp->address);

printf("Enter Department: ");


scanf(" %[^\n]", emp->department);
printf("Enter Salary: ");
scanf("%f", &emp->salary);
}

// Function to display employee data


void displayEmployeeData(struct Employee emp) {
printf("\nEmployee ID: %d\n", emp.id);
printf("Employee Name: %s\n", emp.name);

printf("Age: %d\n", emp.age);


printf("Address: %s\n", emp.address);
printf("Department: %s\n", emp.department);
printf("Salary: %.2f\n", emp.salary);

int main() {
struct Employee employees[NUM_EMPLOYEES];
int i, searchId, found = 0;

printf("Enter details for %d employees:\n", NUM_EMPLOYEES);


for (i = 0; i < NUM_EMPLOYEES; i++) {
printf("\nEmployee %d:\n", i + 1);

inputEmployeeData(&employees[i]);
}

printf("\nEnter Employee ID to search: ");

scanf("%d", &searchId);

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


if (employees[i].id == searchId) {

displayEmployeeData(employees[i]);
found = 1;
break;
}

if (!found) {
printf("Employee with ID %d not found.\n", searchId);

return 0;
}

OUTPUT:
ANSWER 9:
#include <stdio.h>

int main() {

FILE *evenFile, *oddFile;


int num, i;

// Open files for writing


evenFile = fopen("EvenFile.txt", "w");

oddFile = fopen("OddFile.txt", "w");

if (evenFile == NULL || oddFile == NULL) {


printf("Error opening files.\n");

return 1;
}

printf("Enter 20 numbers:\n");

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


scanf("%d", &num);

// Check if number is even or odd


if (num % 2 == 0) {

fprintf(evenFile, "%d\n", num);


} else {
fprintf(oddFile, "%d\n", num);
}

// Close files
fclose(evenFile);
fclose(oddFile);

printf("Even numbers saved to EvenFile.txt\n");


printf("Odd numbers saved to OddFile.txt\n");

return 0;

OUTPUT:
ANSWER 10:
#include <stdio.h>

int main() {
char operator;
double num1, num2;

printf("Enter an operator (+, -, *, /, a, p): ");


scanf(" %c", &operator);

printf("Enter two numbers: ");

scanf("%lf %lf", &num1, &num2);

switch (operator) {
case '+':

printf("%.1lf + %.1lf = %.1lf\n", num1, num2, num1 + num2);


break;
case '-':
printf("%.1lf - %.1lf = %.1lf\n", num1, num2, num1 - num2);
break;

case '*':
printf("%.1lf * %.1lf = %.1lf\n", num1, num2, num1 * num2);
break;
case '/':

if (num2 == 0) {
printf("Error: Division by zero!\n");
} else {
printf("%.1lf / %.1lf = %.1lf\n", num1, num2, num1 / num2);

}
break;
case 'a':
printf("Average of %.1lf and %.1lf is %.1lf\n", num1, num2, (num1 + num2) / 2);
break;

case 'p':
printf("%.1lf%% of %.1lf is %.1lf\n", num1, num2, (num1 / 100) * num2);
break;
default:

printf("Error: Invalid operator!\n");


}

return 0;

}
ANSWER 11:
(i) #include <stdio.h>
#include <math.h>

int main() {
int n, i, num, originalNum, remainder, result = 0, count = 0;

printf("Enter the upper limit: ");

scanf("%d", &n);

printf("Armstrong numbers between 1 and %d are: \n", n);

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


num = i;
originalNum = i;
count = 0;
while (num != 0) {
count++;
num /= 10;

num = i;
result = 0;

while (num != 0) {
remainder = num % 10;
result += pow(remainder, count);

num /= 10;
}

if (result == originalNum) {
printf("%d ", originalNum);

}
}

printf("\n");

return 0;
}
(ii) #include <stdio.h>

int main() {
int n, i, j, isPrime;

printf("Enter the upper limit: ");


scanf("%d", &n);

printf("Prime numbers between 1 and %d are: \n", n);

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


isPrime = 1;

for (j = 2; j <= i / 2; j++) {


if (i % j == 0) {
isPrime = 0;
break;

}
}

if (isPrime) {
printf("%d ", i);

}
}

printf("\n");

return 0;
}
(iii) #include <stdio.h>

int main() {
int n, reverse = 0, remainder, original;

printf("Enter an integer: ");


scanf("%d", &n);

original = n;

while (n != 0) {

remainder = n % 10;
reverse = reverse * 10 + remainder;
n /= 10;
}

if (original % 10 == 0) {
printf("Reversed number = %d", reverse);
while (original % 10 == 0) {
printf("0");

original /= 10;
}
} else {
printf("Reversed number = %d", reverse);

return 0;
}

ANSWER 13:
#include <stdio.h>
#include <math.h>

int main() {
int decimalNum, i, remainder, binaryNum[100], j;

printf("Enter a hexadecimal number: ");

scanf("%x", &decimalNum);
// Convert hexadecimal to binary
j = 0;

while (decimalNum > 0) {


remainder = decimalNum % 2;
binaryNum[j] = remainder;
decimalNum /= 2;

j++;
}

// Print binary number

printf("Binary equivalent: ");


for (i = j - 1; i >= 0; i--) {
printf("%d", binaryNum[i]);
}
printf("\n");

return 0;
}
ANSWER 14:
#include <stdio.h>

// Function to calculate the factorial of a number using recursion

int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);

}
}

// Function to generate the Fibonacci series using recursion

void fibonacci(int n) {
int a = 0, b = 1, c;
for (int i = 0; i < n; i++) {
printf("%d ", a);

c = a + b;
a = b;
b = c;
}
printf("\n");

int main() {
int num, n;

printf("Enter a number: ");


scanf("%d", &num);
printf("Factorial of %d is %d\n", num, factorial(num));

printf("Enter the number of terms for the Fibonacci series: ");


scanf("%d", &n);

printf("Fibonacci series up to %d terms:\n", n);

fibonacci(n);

return 0;
}

ANSWER 15:
(i) #include <stdio.h>
int main() {
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter the number of rows (between 1 and 100): ");
scanf("%d", &r);

printf("Enter the number of columns (between 1 and 100): ");


scanf("%d", &c);
printf("\nEnter elements of 1st matrix:\n");
for (i = 0; i < r; ++i)

for (j = 0; j < c; ++j) {


printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}

printf("Enter elements of 2nd matrix:\n");


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {

printf("Enter element b%d%d: ", i + 1, j + 1);


scanf("%d", &b[i][j]);
}

// adding two matrices

for (i = 0; i < r; ++i)


for (j = 0; j < c; ++j) {
sum[i][j] = a[i][j] + b[i][j];
}

// printing the result


printf("\nSum of two matrices: \n");
for (i = 0; i < r; ++i)

for (j = 0; j < c; ++j) {


printf("%d ", sum[i][j]);
if (j == c - 1) {
printf("\n\n");

}
}

return 0;

OUTPUT:

(ii) #include <stdio.h>

int main() {

int m, n, p, q, i, j, k;

// Input dimensions for Matrix A

printf("Enter rows and columns for Matrix A: ");

scanf("%d %d", &m, &n);

// Input dimensions for Matrix B

printf("Enter rows and columns for Matrix B: ");

scanf("%d %d", &p, &q);


// Check if matrix multiplication is possible

if (n != p) {

printf("Matrix multiplication not possible. Columns of A must equal rows of B.\n");

return 1;

int A[m][n], B[p][q], C[m][q];

// Input elements for Matrix A

printf("Enter elements of Matrix A:\n");

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

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

printf("A[%d][%d]: ", i, j);

scanf("%d", &A[i][j]);

// Input elements for Matrix B

printf("Enter elements of Matrix B:\n");

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

for (j = 0; j < q; j++) {

printf("B[%d][%d]: ", i, j);

scanf("%d", &B[i][j]);

// Initialize result matrix C to zero

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

for (j = 0; j < q; j++) {

C[i][j] = 0;
}

// Perform matrix multiplication

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

for (j = 0; j < q; j++) {

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

C[i][j] += A[i][k] * B[k][j];

// Display the result matrix C

printf("Resultant Matrix C (Product of A and B):\n");

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

for (j = 0; j < q; j++) {

printf("%d ", C[i][j]);

printf("\n");

} OUTPUT:

return 0;

}
(iii) #include <stdio.h>
int main() {
int a[10][10], transpose[10][10], r, c;
printf("Enter rows and columns: ");

scanf("%d %d", &r, &c);

// asssigning elements to the matrix


printf("\nEnter matrix elements:\n");
for (int i = 0; i < r; ++i)

for (int j = 0; j < c; ++j) {


printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}

// printing the matrix a[][]


printf("\nEntered matrix: \n");
for (int i = 0; i < r; ++i)

for (int j = 0; j < c; ++j) {


printf("%d ", a[i][j]);
if (j == c - 1)
printf("\n");
}

// computing the transpose


for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {

transpose[j][i] = a[i][j];
}
// printing the transpose
printf("\nTranspose of the matrix:\n");
for (int i = 0; i < c; ++i)

for (int j = 0; j < r; ++j) {


printf("%d ", transpose[i][j]);
if (j == r - 1)
printf("\n");

}
return 0;
}

OUTPUT:
ANSWER 16:
#include <stdio.h>
#include <string.h>

// Structure for a student


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

};

// Structure for a class


struct Class {

struct Student students[100]; // Array of students as a structure data member


int num_students;
};

int main() {
// Create an array of structure variables
struct Student students[3];

// Input student details for the array of structure variables

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


printf("Enter details for student %d:\n", i + 1);
printf("Name: ");
scanf("%s", students[i].name);

printf("Roll No: ");


scanf("%d", &students[i].roll_no);
printf("Marks: ");
scanf("%f", &students[i].marks);
}

// Create a class structure


struct Class class1;

// Initialize the class structure

class1.num_students = 3;

// Input student details for the array inside the class structure
for (int i = 0; i < class1.num_students; i++) {

printf("Enter details for student %d in class:\n", i + 1);


printf("Name: ");
scanf("%s", class1.students[i].name);
printf("Roll No: ");
scanf("%d", &class1.students[i].roll_no);

printf("Marks: ");
scanf("%f", &class1.students[i].marks);
}

// Print details of students from the array of structure variables


printf("\nStudent details from array of structures:\n");
for (int i = 0; i < 3; i++) {
printf("Student %d:\n", i + 1);

printf("Name: %s\n", students[i].name);


printf("Roll No: %d\n", students[i].roll_no);
printf("Marks: %.2f\n", students[i].marks);
}
// Print details of students from the class structure
printf("\nStudent details from class structure:\n");
for (int i = 0; i < class1.num_students; i++) {

printf("Student %d:\n", i + 1);


printf("Name: %s\n", class1.students[i].name);
printf("Roll No: %d\n", class1.students[i].roll_no);
printf("Marks: %.2f\n", class1.students[i].marks);

return 0;
}
ANSWER 17:
#include <stdio.h>
#include <stdlib.h>

/* Function declaration */
int compareFile(FILE * fPtr1, FILE * fPtr2, int * line, int * col);

int main()

{
/* File pointer to hold reference of input file */
FILE * fPtr1;
FILE * fPtr2;

char path1[100];
char path2[100];

int diff;

int line, col;

/* Input path of files to compare */


printf("Enter path of first file: ");

scanf("%s", path1);
printf("Enter path of second file: ");
scanf("%s", path2);

/* Open all files to compare */


fPtr1 = fopen(path1, "r");
fPtr2 = fopen(path2, "r");

/* fopen() return NULL if unable to open file in given mode. */

if (fPtr1 == NULL || fPtr2 == NULL)


{
/* Unable to open file hence exit */
printf("\nUnable to open file.\n");

printf("Please check whether file exists and you have read privilege.\n");
exit(EXIT_FAILURE);
}

/* Call function to compare file */


diff = compareFile(fPtr1, fPtr2, &line, &col);

if (diff == 0)

{
printf("\nBoth files are equal.");
}
else

{
printf("\nFiles are not equal.\n");
printf("Line: %d, col: %d\n", line, col);
}

/* Finally close files to release resources */


fclose(fPtr1);

fclose(fPtr2);
return 0;
}

/**
* Function to compare two files.

* Returns 0 if both files are equivalent, otherwise returns


* -1 and sets line and col where both file differ.
*/
int compareFile(FILE * fPtr1, FILE * fPtr2, int * line, int * col)

{
char ch1, ch2;

*line = 1;
*col = 0;

do
{
// Input character from both files

ch1 = fgetc(fPtr1);
ch2 = fgetc(fPtr2);

// Increment line

if (ch1 == '\n')
{
*line += 1;
*col = 0;

}
// If characters are not same then return -1
if (ch1 != ch2)

return -1;

*col += 1;

} while (ch1 != EOF && ch2 != EOF);

/* If both files have reached end */

if (ch1 == EOF && ch2 == EOF)


return 0;
else
return -1;
}

OUTPUT:
ANSWER 18:
#include <stdio.h>
#include <stdlib.h>

int main() {
FILE *file;
int numbers[] = {10, 20, 30, 40, 50}; // Sample data to write into the file
int read_num;

// Open a binary file for writing


file = fopen("data.bin", "wb");
if (file == NULL) {
printf("Error opening file for writing.\n");

return 1;
}

// Write array of integers to the file

fwrite(numbers, sizeof(int), 5, file);


fclose(file);

// Reopen the file in read mode


file = fopen("data.bin", "rb");

if (file == NULL) {
printf("Error opening file for reading.\n");
return 1;
}

// Using fseek and ftell to navigate in the file


fseek(file, 0, SEEK_END); // Move to the end of the file
long end_position = ftell(file); // Get the current position (end position)
printf("End position in the file: %ld bytes\n", end_position);

rewind(file); // Go back to the beginning of the file


printf("Position after rewind: %ld bytes\n", ftell(file));

// Read and print values in the file using fseek

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


fseek(file, i * sizeof(int), SEEK_SET); // Move to the ith integer position
fread(&read_num, sizeof(int), 1, file); // Read the integer
printf("Number at position %d: %d\n", i, read_num);

fclose(file); // Close the file


return 0;
}

OUTPUT:
ANSWER 19:
#include <stdio.h>
#include <string.h>

int main() {
char str1[100], str2[100];
int choice, n;

do {

printf("\nMenu:\n");
printf("1. Calculate length of a string\n");
printf("2. Concatenate at the end of a given string\n");
printf("3. Copy one string to another\n");

printf("4. Compare contents of two strings\n");


printf("5. Copy nth character string to another\n");
printf("6. Exit\n");
printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter a string: ");

scanf("%s", str1);
printf("Length of the string: %lu\n", strlen(str1));
break;
case 2:

printf("Enter the first string: ");


scanf("%s", str1);
printf("Enter the second string: ");
scanf("%s", str2);
strcat(str1, str2);
printf("Concatenated string: %s\n", str1);

break;
case 3:
printf("Enter the source string: ");
scanf("%s", str1);

strcpy(str2, str1);
printf("Copied string: %s\n", str2);
break;
case 4:

printf("Enter the first string: ");


scanf("%s", str1);
printf("Enter the second string: ");
scanf("%s", str2);
if (strcmp(str1, str2) == 0) {

printf("The strings are equal.\n");


} else {
printf("The strings are not equal.\n");
}

break;
case 5:
printf("Enter the source string: ");
scanf("%s", str1);

printf("Enter the destination string: ");


scanf("%s", str2);
printf("Enter the nth character: ");
scanf("%d", &n);

str2[0] = str1[n - 1]; // Copy the nth character from str1 to str2
str2[1] = '\0'; // Null-terminate the destination string
printf("Copied character: %s\n", str2);
break;

case 6:
printf("Exiting the program.\n");
break;
default:

printf("Invalid choice. Please try again.\n");


}
} while (choice != 6);

return 0;
}
ANSWER 20:
#include <stdio.h>
#include <string.h>

#include <stdlib.h>
int main() {
char time_str[10];
int hours, minutes, seconds;

printf("Enter time in HH:MM:SS format: ");


scanf("%s", time_str);

// Check if the input string is in the correct format


if (strlen(time_str) != 8 || time_str[2] != ':' || time_str[5] != ':') {
printf("Invalid time format.\n");
return 1;

// Extract hours, minutes, and seconds


hours = atoi(time_str);
minutes = atoi(time_str + 3);

seconds = atoi(time_str + 6);

// Check if the time is valid


if (hours < 0 || hours > 23 || minutes < 0 || minutes > 59 || seconds < 0 || seconds > 59) {

printf("Invalid time.\n");
return 1;
}

// Print the extracted time


printf("Hours: %d\n", hours);
printf("Minutes: %d\n", minutes);
printf("Seconds: %d\n", seconds);
return 0;
}

You might also like