KEMBAR78
Internal Lab Exam Programs | PDF | Pointer (Computer Programming) | Matrix (Mathematics)
0% found this document useful (0 votes)
22 views21 pages

Internal Lab Exam Programs

Internal lab program

Uploaded by

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

Internal Lab Exam Programs

Internal lab program

Uploaded by

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

1.

CONVERSION OF FAHRENHEIT TO CELSIUS AND VICE VERSA

Fig. C program that converts temperature values between Fahrenheit and Celsius:
#include <stdio.h>
int main() {
int choice;
double temperature, convertedTemperature;
// Prompt the user for the conversion choice
printf("Temperature Conversion Menu:\n");
printf("1. Fahrenheit to Celsius\n");
printf("2. Celsius to Fahrenheit\n");
printf("Enter your choice (1/2): ");
scanf("%d", &choice);
// Check the user's choice and perform the corresponding conversion
if (choice == 1) {
// Fahrenheit to Celsius conversion
printf("Enter temperature in Fahrenheit: ");
scanf("%lf", &temperature);
convertedTemperature = (temperature - 32) * 5 / 9;
printf("Temperature in Celsius: %.2lf\n", convertedTemperature);
} else if (choice == 2) {
// Celsius to Fahrenheit conversion
Printf ("Enter temperature in Celsius: ");
scanf ("%lf", &temperature);
convertedTemperature = (temperature * 9 / 5) + 32;
printf ("Temperature in Fahrenheit: %.2lf\n", convertedTemperature);
} else {
// Invalid choice
printf ("Invalid choice. Please select 1 or 2.\n");
}
return 0;
}
In this program:
- We prompt the user to choose between two conversion options: Fahrenheit to Celsius or
Celsius to Fahrenheit.
- Based on the user's choice, we either convert from Fahrenheit to Celsius or from Celsius to
Fahrenheit.
- The conversion formulas are applied to calculate the converted temperature.
- Finally, we use `printf` to display the converted temperature with two decimal places.
- Compile and run the program, and it will allow you to convert temperature values between
Fahrenheit and Celsius as per your choice.
2. FIND THE MAXIMUM OF THREE NUMBERS USING CONDITIONAL
OPERATOR
#include <stdio.h>
int main() {

int num1, num2, num3, max;

printf("Enter three numbers: ");

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

max = (num1 > num2) ? ((num1 > num3) ? num1 : num3) : ((num2 > num3) ? num2 : num3);

printf("The maximum number is: %d\n", max);

return 0;
}

In this program,

we first read three numbers from the user. Then, we use the conditional operator to find the
maximum among the three numbers. The conditional operator evaluates the condition `(num1 >
num2)` first. If it's true, it returns `num1` if `(num1 > num3)` is true, and `num3` otherwise. If the
condition is false, it returns `num2` if `(num2 > num3)` is true, and `num3` otherwise. This way, we
obtain the maximum of the three numbers.
3. WRITE A C PROGRAM TO FIND THE ROOTS OF A QUADRATIC EQUATION

C program to find the roots of a quadratic equation using the quadratic formula. The
quadratic formula is used to find the roots (solutions) of a quadratic equation in the form of `ax^2 +
bx + c = 0`. Here's a simple C program to do that:
#include <stdio.h>
#include <math.h>
int main() {
double a, b, c;
double discriminant, root1, root2;
// Input the coefficients a, b, and c
printf("Enter the coefficients (a, b, c) of the quadratic equation:\n");
scanf("%lf %lf %lf", &a, &b, &c);
// Calculate the discriminant
discriminant = b * b - 4 * a * c;
// Check the discriminant for real roots
if (discriminant > 0) {
// Two real and distinct roots
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Root 1 = %.2lf\n", root1);
printf("Root 2 = %.2lf\n", root2);
} else if (discriminant == 0) {
// One real root (double root)
root1 = -b / (2 * a);
printf("Root 1 = Root 2 = %.2lf\n", root1);
} else {
// Complex roots
double realPart = -b / (2 * a);
double imaginaryPart = sqrt(-discriminant) / (2 * a);
printf("Root 1 = %.2lf + %.2lfi\n", realPart, imaginaryPart);
printf("Root 2 = %.2lf - %.2lfi\n", realPart, imaginaryPart);
}
return 0;
}
This program takes the coefficients `a`, `b`, and `c` as input, calculates the discriminate, and
then uses the discriminate to determine the nature of the roots. It handles cases of real and distinct
roots, a single real root (double root), and complex roots.
4. WRITE A C PROGRAM TO SIMULATE A CALCULATOR USING SWITCH
CASE

C program that simulates a basic calculator using a switch-case statement. This program allows the
user to perform addition, subtraction, multiplication, and division operations on two numbers:
#include <stdio.h>
int main() {
int choice;
double num1, num2, result;
printf("Simple Calculator\n");
printf("1. Addition\n");
printf("2. Subtraction\n");
printf("3. Multiplication\n");
printf("4. Division\n");
printf("Enter your choice (1/2/3/4): ");
scanf("%d", &choice);
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
switch (choice) {
case 1:
result = num1 + num2;
printf("Result: %.2lf + %.2lf = %.2lf\n", num1, num2, result);
break;
case 2:
result = num1 - num2;
printf("Result: %.2lf - %.2lf = %.2lf\n", num1, num2, result);
break;
case 3:
result = num1 * num2;
printf("Result: %.2lf * %.2lf = %.2lf\n", num1, num2, result);
break;
case 4:
if (num2 != 0) {
result = num1 / num2;
printf("Result: %.2lf / %.2lf = %.2lf\n", num1, num2, result);
} else {
printf("Error: Division by zero is not allowed.\n");
}
break;
default:
printf("Invalid choice! Please select 1, 2, 3, or 4.\n");
}
return 0;
}
This program presents a menu to the user to choose an operation, accepts two numbers as
input, and then performs the selected operation using a switch-case statement. It also includes error
handling for division by zero.

5. FIND THE FACTORIAL OF A GIVEN NUMBER USING ANY LOOP


You can find the factorial of a given number using a loop, such as a `for` loop or a `while` loop.
Here's an example program using a `for` loop in C to find the factorial of a given number:
#include <stdio.h>
int main() {
int number;
unsigned long long factorial = 1;
printf("Enter a non-negative integer: ");
scanf("%d", &number);
if (number < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
for (int i = 1; i <= number; i++) {
factorial *= i;
}
printf("Factorial of %d = %llu\n", number, factorial);
}
return 0;
}
In this program, we use a `for` loop to calculate the factorial of a given non-negative integer.
The `factorial` variable is initialized to 1, and then we multiply it by each integer from 1 to the input
number. The result is stored in the `factorial` variable, and the final factorial value is printed. It also
includes a check for negative numbers because factorials are not defined for negative integers.
6. WRITE A C PROGRAM TO FIND THE GIVEN NUMBER IS A PRIME NUMBER
OR NOT

You can write a C program to determine whether a given number is prime or not. A prime
number is a positive integer greater than 1 that has no positive divisors other than 1 and itself.
Here's a C program to check for prime numbers:
#include <stdio.h>
#include <stdbool.h>
bool isPrime(int n) {
if (n <= 1) {
return false; // 0 and 1 are not prime numbers
}
if (n <= 3) {
return true; // 2 and 3 are prime
}
if (n % 2 == 0 || n % 3 == 0) {
return false; // Divisible by 2 or 3
}
// Check for divisors up to the square root of n
for (int i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0) {
return false; // Divisible by i or i + 2
}
}
return true;
}
int main() {
int number;
printf("Enter a positive integer: ");
scanf("%d", &number);

if (isPrime(number)) {
printf("%d is a prime number.\n", number);
} else {
printf("%d is not a prime number.\n", number);
}
return 0;
}
In this program, we define a function `isPrime` that checks whether a given number is
prime. The function returns `true` if the number is prime and `false` if it's not. The main part of the
program takes a positive integer as input, calls the `isPrime` function, and then prints whether the
number is prime or not.

7. WRITE A C PROGRAM TO COMPUTE SINE AND COS SERIES

To compute sine and cosine series in C, you can use the Taylor series expansion. Here's a
simple program that calculates the sine and cosine of an angle in radians using Taylor series:
#include <stdio.h>
#include <math.h>
double computeSine(double x, int terms) {
double result = 0.0;
int i;
for (i = 0; i < terms; i++) {
int sign = (i % 2 == 0) ? 1 : -1;
int power = 2 * i + 1;
result += (sign * pow(x, power)) / factorial(power);
}
return result;
}
double computeCosine(double x, int terms) {
double result = 1.0;
int i;
for (i = 1; i < terms; i++) {
int sign = (i % 2 == 0) ? 1 : -1;
int power = 2 * i;
result += (sign * pow(x, power)) / factorial(power);
}
return result;
}
double factorial(int n) {
if (n == 0) return 1.0;
return n * factorial(n - 1);
}
int main() {
double angle, radians;
int terms;
printf("Enter the angle in degrees: ");
scanf("%lf", &angle);
printf("Enter the number of terms: ");
scanf("%d", &terms);
// Convert degrees to radians
radians = angle * M_PI / 180.0;
double sine = computeSine(radians, terms);
double cosine = computeCosine(radians, terms);
printf("Sine(%lf) = %lf\n", angle, sine);
printf("Cosine(%lf) = %lf\n", angle, cosine);
return 0;
}
In this program, `computeSine` and `computeCosine` functions calculate the sine and cosine
values using the Taylor series with the specified number of terms. The `factorial` function
calculates the factorial of a number. The user inputs the angle in degrees and the number of terms to
approximate the sine and cosine functions. The program converts the angle to radians and then
calculates and prints the results.

8. WRITE A C PROGRAM TO CHECK WHETHER A NUMBER IS POLINDROME


OR NOT

To check if a number is a palindrome in C, you can reverse the number and compare it to the
original number. If they are the same, the number is a palindrome. Here's a C program to do that:
#include <stdio.h>
int main() {
int number, originalNumber, reversedNumber = 0, remainder;
printf("Enter an integer: ");
scanf("%d", &number);
originalNumber = number; // Store the original number
// Reverse the number
while (number > 0) {
remainder = number % 10;
reversedNumber = reversedNumber * 10 + remainder;
number /= 10;
}
if (originalNumber == reversedNumber) {
printf("%d is a palindrome number.\n", originalNumber);
} else {
printf("%d is not a palindrome number.\n", originalNumber);
}
return 0;
}
In this program, we take an integer as input and reverse it using a while loop. We store the
original number in `originalNumber` and then compare it to the reversed number. If they are the
same, the input number is a palindrome; otherwise, it is not.

9. WRITE A C PROGRAM FOR THE MULTIPLICATION OF TWO MATRICES

C program to multiply two matrices by following the standard matrix multiplication rules.
Here's a C program to do that:
#include <stdio.h>
int main() {
int rows1, cols1, rows2, cols2;
printf("Enter the number of rows and columns for the first matrix: ");
scanf("%d %d", &rows1, &cols1);
printf("Enter the number of rows and columns for the second matrix: ");
scanf("%d %d", &rows2, &cols2);
// Check if matrix multiplication is possible
if (cols1 != rows2) {
printf("Matrix multiplication is not possible. Columns of the first matrix must be equal to rows
of the second matrix.\n");
return 1;
}
int matrix1[rows1][cols1], matrix2[rows2][cols2], result[rows1][cols2];
// Input elements for the first matrix
printf("Enter elements for the first matrix:\n");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
scanf("%d", &matrix1[i][j]);
}
}
// Input elements for the second matrix
printf("Enter elements for the second matrix:\n");
for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
scanf("%d", &matrix2[i][j]);
}
}
// Initialize the result matrix with zeros
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
result[i][j] = 0;
}
}
// Multiply the two matrices
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
for (int k = 0; k < cols1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
// Display the result matrix
printf("Product of the two matrices:\n");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}
This program first takes the number of rows and columns for both matrices as input. It
checks if matrix multiplication is possible (the number of columns in the first matrix must be equal
to the number of rows in the second matrix). It then takes input for the elements of both matrices
and performs matrix multiplication to obtain the result matrix. Finally, it prints the product of the
two matrices as the output.

10. WRITE A RECURSIVE FUNCTION TO FIND THE FACTORIAL OF A NUMBER

You can create a recursive function in C to find the factorial of a number. The factorial of a
non-negative integer `n`, denoted as `n!`, is the product of all positive integers from 1 to `n`. Here's
a C program with a recursive function to calculate the factorial:
#include <stdio.h>
// Recursive function to calculate the factorial of a number
unsigned long long factorial(int n) {
if (n == 0 || n == 1) {
return 1; // Base case: 0! and 1! are defined as 1
} else {
return n * factorial(n - 1);
}
}
int main() {
int n;
printf("Enter a non-negative integer: ");
scanf("%d", &n);
if (n < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
unsigned long long result = factorial(n);
printf("%d! = %llu\n", n, result);
}
return 0;
}
In this program, the `factorial` function is defined to calculate the factorial of a non-negative
integer using recursion. The base cases are when `n` is 0 or 1, and for all other values of `n`, it
recursively calls itself to compute `n! = n * (n-1)!`. The `main` function takes a non-negative
integer as input and then prints the factorial using the `factorial` function.

11. WRITE A C PROGRAM TO SWAP TWO NUMBERS USING CALL BY


REFERENCE
In C, you can swap two numbers using call by reference by passing the addresses of the
variables to a function. Here's a C program to demonstrate swapping two numbers using call by
reference:
#include <stdio.h>
// Function to swap two numbers using call by reference
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int num1, num2;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
printf("Before swapping: num1 = %d, num2 = %d\n", num1, num2);
// Call the swap function with the addresses of num1 and num2
swap(&num1, &num2);
printf("After swapping: num1 = %d, num2 = %d\n", num1, num2);
return 0;
}
In this program, the `swap` function takes two integer pointers (`int* a` and `int* b`) as
parameters. Inside the function, it uses the pointers to access the values of `num1` and `num2` and
swaps their values. When calling the `swap` function from `main`, you pass the addresses of `num1`
and `num2` using the `&` operator.

12. WRITE A C PROGRAM TO FIND NUMBER OF LOWER CASE, UPPER CASE,


DIGITS AND OTHER CHARACTERS USING POINTERS

You can write a C program to count the number of lowercase letters, uppercase letters,
digits, and other characters in a string using pointers. Here's a program that does this:
#include <stdio.h>
#include <ctype.h>
void countCharacterTypes(const char *str, int *lowercase, int *uppercase, int *digits, int *others) {
while (*str != '\0') {
if (islower(*str)) {
(*lowercase)++;
} else if (isupper(*str)) {
(*uppercase)++;
} else if (isdigit(*str)) {
(*digits)++;
} else {
(*others)++;
}
str++;
}
}
int main() {
char inputString[100];
int lowercaseCount = 0, uppercaseCount = 0, digitCount = 0, otherCount = 0;

printf("Enter a string: ");


gets(inputString); // You can use fgets for safer input handling
countCharacterTypes(inputString, &lowercaseCount, &uppercaseCount, &digitCount,
&otherCount);
printf("Lowercase letters: %d\n", lowercaseCount);
printf("Uppercase letters: %d\n", uppercaseCount);
printf("Digits: %d\n", digitCount);
printf("Other characters: %d\n", otherCount);
return 0;
}
In this program:
1. The `countCharacterTypes` function takes a string pointer (`const char *str`) and four
integer pointers (`int *lowercase`, `int *uppercase`, `int *digits`, `int *others`) as
parameters. It iterates through the characters of the string and checks their type using the
`islower`, `isupper`, and `isdigit` functions from the `ctype.h` library. Depending on the
character type, it increments the respective counters pointed to by the integer pointers.
2. In the `main` function, the user inputs a string using `gets` (you can use `fgets` for safer
input handling). Then, it calls the `countCharacterTypes` function to count the number of
lowercase letters, uppercase letters, digits, and other characters in the input string.
Finally, the program prints the counts of each character type.

13. CREATE AND DISPLAY A SINGLY LINKED LIST USING SELF REFERENTIAL
STRUCTURE

Creating and displaying a singly linked list using a self-referential structure in C is a


common programming task. Here's a simple example of how you can do it:
#include <stdio.h>
#include <stdlib.h>
// Define the self-referential structure for a linked list node
struct Node {
int data;
struct Node* next;
};
// Function to create a new node and return a pointer to it
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to insert a new node at the end of the linked list
void insertAtEnd(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
// Function to display the linked list
void displayList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}
int main() {
struct Node* head = NULL;
// Insert elements into the linked list
insertAtEnd(&head, 1);
insertAtEnd(&head, 2);
insertAtEnd(&head, 3);
insertAtEnd(&head, 4);
// Display the linked list
printf("Linked List: ");
displayList(head);
// Free the allocated memory
struct Node* current = head;
while (current != NULL) {
struct Node* temp = current;
current = current->next;
free(temp);
}
return 0;
}
In this example, we have defined a self-referential structure `struct Node` which represents
each node in the linked list. The structure contains an integer `data` and a pointer `next` that points
to the next node in the list.
The `createNode` function is used to create a new node, the `insertAtEnd` function inserts a
new node at the end of the list, and the `displayList` function prints the elements of the linked list.
In the `main` function, we demonstrate how to create a linked list, insert elements into it,
display the linked list, and finally, free the allocated memory to prevent memory leaks.
Finally, it frees the dynamically allocated memory using `free()`.
This program demonstrates how `realloc()` can be used to resize dynamically allocated memory.

14. WRITE A C PROGRAM TO COPY THE CONTENTS OF ONE FILE INTO


ANOTHER FILE

To copy the contents of one file into another file in C, you can use the following program. In
this example, we will copy the contents of one text file to another.
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *sourceFile, *destinationFile;
char ch;
// Open the source file for reading
sourceFile = fopen("source.txt", "r");
if (sourceFile == NULL) {
perror("Error opening the source file");
return 1;
}
// Open the destination file for writing
destinationFile = fopen("destination.txt", "w");
if (destinationFile == NULL) {
perror("Error opening the destination file");
fclose(sourceFile);
return 1;
}
// Copy contents from source to destination
while ((ch = fgetc(sourceFile)) != EOF) {
fputc(ch, destinationFile);
}
// Close both files
fclose(sourceFile);
fclose(destinationFile);
printf("File copied successfully.\n");
return 0;
}
In this program:
 We open the source file ("source.txt") for reading using `fopen` with the "r" mode.
 We open the destination file ("destination.txt") for writing using `fopen` with the "w" mode.
If the destination file does not exist, it will be created. If it already exists, its content will be
overwritten.
 We use a `while` loop to read characters from the source file using `fgetc` and write them to
the destination file using `fputc` until we reach the end of the source file (EOF).
 Finally, we close both the source and destination files using `fclose`.
 After running the program, the contents of the "source.txt" file will be copied to the
"destination.txt" file.
15. WRITE A C PROGRAM TO PRINT LAST n CHARACTERS OF A GIVEN FILE

To print the last `n` characters of a given file using a C program, you can use the following
code. This program reads the file in reverse order and prints the last `n` characters.
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *file;
char fileName[100];
char ch;
long long int fileSize, currentPosition;
printf("Enter the name of the file: ");
scanf("%s", fileName);
file = fopen(fileName, "r");
if (file == NULL) {
perror("Error opening the file");
return 1;
}
// Find the file size
fseek(file, 0, SEEK_END);
fileSize = ftell(file);
if (fileSize == -1) {
perror("Error getting file size");
fclose(file);
return 1;
}
// Determine the number of characters to read (n)
long long int n;
printf("Enter the number of characters to print (n): ");
scanf("%lld", &n);
if (n <= 0) {
printf("Invalid value of n.\n");
fclose(file);
return 1;
}
if (n > fileSize) {
n = fileSize;
}
// Calculate the position from where to start reading
currentPosition = fileSize - n;
// Seek to the calculated position
fseek(file, currentPosition, SEEK_SET);
// Print the last n characters
while ((ch = fgetc(file)) != EOF) {
putchar(ch);
}
fclose(file);
return 0;
}
In this program:
 We prompt the user to enter the name of the file they want to read.
 We open the file in read mode using `fopen`.
 We use `fseek` and `ftell` to find the file size.
 The user is prompted to enter the number of characters to print (`n`).
 We calculate the starting position for reading as `fileSize - n`.
 We use `fseek` to move the file pointer to the calculated position.
 We then read and print the last `n` characters from the file using `fgetc` and `putchar`.
Compile and run this program, and it will print the last `n` characters of the specified file.

You might also like