You are on page 1of 72

Computer Programming Lab

1. Text Editors/Integrated Development Environments (IDEs):


 Text Editors: Programs like Notepad (Windows), TextEdit (macOS), or nano/vi (Linux) are basic
text editors. They provide a simple environment for writing code.
 IDEs: Integrated Development Environments such as Visual Studio Code, PyCharm, or Eclipse
offer more advanced features. They often include code highlighting, debugging tools, and project
management.
2. Compilers and Interpreters:
 Compilers: Translate the entire source code into machine code or an intermediate code before
execution. Examples include GCC for C/C++ and Java's javac.
 Interpreters: Execute code line by line. Python, JavaScript, and Ruby use interpreters. Some
languages, like Java and Python, use a combination of compilation and interpretation.
3. Command-Line Interface (CLI):
 The CLI, accessed through a terminal or command prompt, allows you to interact with your
computer using text commands. You can compile and run programs, navigate files, and perform
various tasks.
4. Version Control Systems (VCS):
 Tools like Git help track changes in your code over time. Platforms like GitHub, GitLab, or
Bitbucket provide hosting services for repositories.
5. Package Managers:
 For languages like Python (pip), Node.js (npm), or Java (Maven), package managers simplify the
installation and management of external libraries and dependencies.
6. Virtual Environments:
 Tools like virtualenv (Python) or venv help create isolated environments for your projects. This
ensures that project-specific dependencies don't interfere with each other.
7. Debuggers:
 Integrated into IDEs, debuggers help identify and fix issues in your code. You can set breakpoints,
inspect variables, and step through code execution.
8. Documentation and Resources:
 Online documentation, forums (like Stack Overflow), and language-specific websites are valuable
resources for learning and problem-solving.
9. Build Tools:
 Tools like Apache Maven or Gradle (Java), Make (C/C++), or Webpack (JavaScript) automate the
build process, helping manage dependencies and compiling code.
10. Text-Based Terminals and Editors:
 Familiarity with using the command line, text-based terminals, and editors (like Vim or Emacs) is
valuable, especially in a Linux environment.
11. Coding Standards and Style Guides:
 Adhering to coding standards and style guides ensures consistent and readable code. Different
languages and communities often have their own conventions.
12. API Documentation:
 Understanding how to navigate and use API documentation is crucial for leveraging external
libraries and frameworks effectively.
13. Error Handling and Logging:
 Learn how to handle errors gracefully and use logging mechanisms to track and diagnose issues in
your code.
14. Learning and Staying Updated:
 Programming languages, tools, and best practices evolve. Regularly explore new features,
updates, and methodologies.
Computer Programming Lab
2. Displaying hexadecimal, decimal, octal number format of the entered numbers:

#include <stdio.h>

int main() {
int number;

printf("Enter a number: ");


scanf("%d", &number);

// Hexadecimal, Decimal, Octal formats


printf("Hexadecimal: %x\n", number);
printf("Decimal: %d\n", number);
printf("Octal: %o\n", number);

return 0;
}
OUTPUT
Computer Programming Lab
3. Displaying entered number with leading zeros and trailing zeros:

#include <stdio.h>

int main() {
int number;

printf("Enter a number: ");


scanf("%d", &number);

// Leading zeros
printf("With leading zeros: %05d\n", number); // Assuming a 5-digit number

// Trailing zeros (for floating-point numbers)


float floatNumber;
printf("Enter a floating-point number: ");
scanf("%f", &floatNumber);
printf("With trailing zeros: %.2f\n", floatNumber); // Assuming 2 decimal places

return 0;
}
OUTPUT
Computer Programming Lab

4. Displaying entered number with right and left justification:

#include <stdio.h>

int main() {
int number;

printf("Enter a number: ");


scanf("%d", &number);

// Right justification
printf("Right justified: %10d\n", number); // Assuming a field width of 10

// Left justification
printf("Left justified: %-10d\n", number); // Assuming a field width of 10

return 0;
}
OUTPUT
Computer Programming Lab
5.Displaying with different formatting specifiers:

#include <stdio.h>

int main() {
float number;

printf("Enter a floating-point number: ");


scanf("%f", &number);

// Different formatting specifiers


printf("Default: %f\n", number);
printf("2 decimal places: %.2f\n", number);
printf("Exponential format: %e\n", number);
printf("Percentage format: %.2f%%\n", number * 100);

return 0;
}
OUTPUT
Computer Programming Lab
6.To find the greatest / smallest of three numbers:

#include <stdio.h>

int main() {
int num1, num2, num3;

printf("Enter three numbers: ");


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

// Finding the greatest number


int greatest = (num1 > num2 && num1 > num3) ? num1 : (num2 > num3 ? num2 : num3);
printf("Greatest number: %d\n", greatest);

// Finding the smallest number


int smallest = (num1 < num2 && num1 < num3) ? num1 : (num2 < num3 ? num2 : num3);
printf("Smallest number: %d\n", smallest);

return 0;
}
OUTPUT
Computer Programming Lab
7.To display pass class, second-class, distinction according to the marks entered from the keyboard:

#include <stdio.h>

int main() {
int marks;

printf("Enter the marks: ");


scanf("%d", &marks);

// Displaying pass class, second-class, distinction


if (marks >= 75) {
printf("Distinction\n");
} else if (marks >= 60) {
printf("First Class\n");
} else if (marks >= 50) {
printf("Second Class\n");
} else {
printf("Pass Class\n");
}

return 0;
}
OUTPUT
Computer Programming Lab
8.To find even or odd numbers:

#include <stdio.h>

int main() {
int num;

printf("Enter a number: ");


scanf("%d", &num);

// Checking even or odd


if (num % 2 == 0) {
printf("Even\n");
} else {
printf("Odd\n");
}

return 0;
}
OUTPUT
Computer Programming Lab
9.To display spellings of numbers 1-10 on entry:

#include <stdio.h>

int main() {
int num;

printf("Enter a number (1-10): ");


scanf("%d", &num);

// Displaying spellings
switch (num) {
case 1:
printf("One\n");
break;
case 2:
printf("Two\n");
break;
case 3:
printf("Three\n");
break;
case 4:
printf("Four\n");
break;
case 5:
printf("Five\n");
break;
case 6:
printf("Six\n");
break;
case 7:
printf("Seven\n");
Computer Programming Lab
break;
case 8:
printf("Eight\n");
break;
case 9:
printf("Nine\n");
break;
case 10:
printf("Ten\n");
break;
default:
printf("Invalid input\n");
}

return 0;
}
OUTPUT
Computer Programming Lab
10. Implementation and displaying the menu to execute 1. ADD, 2. SUBTRACT 3. MULTIPLICATION, 4.
DIVISION using switch case:

#include <stdio.h>

int main() {
int choice;
float num1, num2;

printf("Enter two numbers: ");


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

printf("Choose operation:\n");
printf("1. ADD\n");
printf("2. SUBTRACT\n");
printf("3. MULTIPLICATION\n");
printf("4. DIVISION\n");
printf("Enter your choice (1-4): ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Sum: %.2f\n", num1 + num2);
break;
case 2:
printf("Difference: %.2f\n", num1 - num2);
break;
case 3:
printf("Product: %.2f\n", num1 * num2);
break;
case 4:
if (num2 != 0) {
printf("Quotient: %.2f\n", num1 / num2);
Computer Programming Lab
} else {
printf("Division by zero is not allowed.\n");
}
break;
default:
printf("Invalid choice\n");
}

return 0;
}
OUTPUT
Computer Programming Lab
11.To check whether there exist real (float) roots of a quadratic equation and if exist find them:

#include <stdio.h>
#include <math.h>

int main() {
float a, b, c;
float discriminant, root1, root2;

printf("Enter coefficients a, b, and c: ");


scanf("%f %f %f", &a, &b, &c);

// Calculate discriminant
discriminant = b * b - 4 * a * c;

// Check if roots are real


if (discriminant >= 0) {
// Calculate roots
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);

// Display roots
printf("Root 1: %.2f\n", root1);
printf("Root 2: %.2f\n", root2);
} else {
printf("No real roots exist.\n");
}
return 0;
}
OUTPUT
Computer Programming Lab
12.To display our College name twenty times on the screen:

#include <stdio.h>

int main() {
int i;

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


printf("Our Collage Name\n");
}

return 0;
}
OUTPUT
Computer Programming Lab
13.To demonstrate Continue and Break statements within loop structure:

#include <stdio.h>

int main() {
int i;

// Continue statement
for (i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
printf("%d ", i);
}

printf("\n");

// Break statement
for (i = 1; i <= 10; i++) {
if (i == 6) {
break; // Exit loop when i is 6
}
printf("%d ", i);
}

return 0;
}
OUTPUT
Computer Programming Lab
14.To add first ‘n’ natural, even, odd numbers using different loop structures:

#include <stdio.h>
int main() {
int n, i, sum_n = 0, sum_even = 0, sum_odd = 0;
printf("Enter a value for n: ");
scanf("%d", &n);
// Using a for loop
for (i = 1; i <= n; i++) {
sum_n += i;
}
// Using a while loop for even numbers
i = 2;
while (i <= n) {
sum_even += i;
i += 2;
}
// Using a do-while loop for odd numbers
i = 1;
do {
sum_odd += i;
i += 2;
} while (i <= n);
printf("Sum of first %d natural numbers: %d\n", n, sum_n);
printf("Sum of first %d even numbers: %d\n", n, sum_even);
printf("Sum of first %d odd numbers: %d\n", n, sum_odd);
return 0;
}
OUTPUT
Computer Programming Lab
15.To find GCD, LCM of two integral numbers:

#include <stdio.h>

int findGCD(int a, int b) {


while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}

int findLCM(int a, int b) {


return (a * b) / findGCD(a, b);
}

int main() {
int num1, num2;

printf("Enter two numbers: ");


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

printf("GCD: %d\n", findGCD(num1, num2));


printf("LCM: %d\n", findLCM(num1, num2));

return 0;
}
OUTPUT
Computer Programming Lab
16.To generate a simple number triangle for n rows:

#include <stdio.h>

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

printf("Enter the number of rows: ");


scanf("%d", &n);

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


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

return 0;
}
OUTPUT
Computer Programming Lab
17. To generate Pascal triangle for n rows:

#include <stdio.h>

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

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

printf("Enter the number of rows: ");


scanf("%d", &n);

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


for (j = 0; j <= i; j++) {
printf("%ld ", factorial(i) / (factorial(j) * factorial(i - j)));
}
printf("\n");
}

return 0;
}
OUTPUT
Computer Programming Lab
18. To add the series 1 + (1 + 2) + (1 + 2 + 3) + …+ (1 + 2 + 3 + … + n):

#include <stdio.h>

int main() {
int i, j, n, sum = 0;

printf("Enter the value of n: ");


scanf("%d", &n);

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


int innerSum = 0;
for (j = 1; j <= i; j++) {
innerSum += j;
}
sum += innerSum;
}

printf("Sum of the series: %d\n", sum);

return 0;
}
OUTPUT
Computer Programming Lab
19. To generate all prime numbers within the given range:

#include <stdio.h>

int isPrime(int num) {


if (num < 2) {
return 0; // Not prime
}
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return 0; // Not prime
}
}
return 1; // Prime
}

int main() {
int start, end;

printf("Enter the range (start and end): ");


scanf("%d %d", &start, &end);
printf("Prime numbers in the range [%d, %d]: ", start, end);
for (int i = start; i <= end; i++) {
if (isPrime(i)) {
printf("%d ", i);
}
}
return 0;
}
OUTPUT
Computer Programming Lab
20.To find all the Armstrong numbers within 100 to 1000.
#include <stdio.h>
#include <math.h>
int isArmstrong(int num) {
int originalNum, remainder, n = 0, result = 0;
originalNum = num;
while (originalNum != 0) {
originalNum /= 10;
++n;
}
originalNum = num;
// Check if the number is Armstrong
while (originalNum != 0) {
remainder = originalNum % 10;
result += pow(remainder, n);
originalNum /= 10;
}
return result == num;
}
int main() {
int start = 100, end = 1000;
printf("Armstrong numbers in the range [%d, %d]: ", start, end);
for (int i = start; i <= end; i++) {
if (isArmstrong(i)) {
printf("%d ", i);
}
}
return 0;
}
OUTPUT
Computer Programming Lab
21.Find the largest and smallest numbers from array elements:

#include <stdio.h>

void findMinMax(int arr[], int size, int *min, int *max) {


*min = *max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] < *min) {
*min = arr[i];
} else if (arr[i] > *max) {
*max = arr[i];
}
}
}

// Example usage:
int main() {
int arr[] = {4, 2, 8, 1, 6, 5};
int size = sizeof(arr) / sizeof(arr[0]);
int min, max;

findMinMax(arr, size, &min, &max);

printf("Minimum: %d\nMaximum: %d\n", min, max);

return 0;
}
OUTPUT
Computer Programming Lab
22.Sort array elements in ascending/descending order:

#include <stdio.h>

void swap(int *a, int *b) {


int temp = *a;
*a = *b;
*b = temp;
}

void bubbleSortAscending(int arr[], int size) {


for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(&arr[j], &arr[j + 1]);
}
}
}
}

void bubbleSortDescending(int arr[], int size) {


for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] < arr[j + 1]) {
swap(&arr[j], &arr[j + 1]);
}
}
}
}

// Example usage:
int main() {
Computer Programming Lab
int arr[] = {4, 2, 8, 1, 6, 5};
int size = sizeof(arr) / sizeof(arr[0]);

// Sorting in ascending order using Bubble Sort


bubbleSortAscending(arr, size);
printf("Ascending Order: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}

// Sorting in descending order using Bubble Sort


bubbleSortDescending(arr, size);
printf("\nDescending Order: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}

return 0;
}
OUTPUT
Computer Programming Lab
23.To enter elements for 3X3 matrix and display them.
#include <stdio.h>

// Function to enter elements for a 3x3 matrix


void enterMatrix(int matrix[3][3]) {
printf("Enter elements for the 3x3 matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("Enter element at position (%d, %d): ", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}
}

// Function to display a 3x3 matrix


void displayMatrix(int matrix[3][3]) {
printf("Matrix elements are:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
}

// Example usage:
int main() {
int matrix[3][3];

// Enter elements for the matrix


enterMatrix(matrix);
Computer Programming Lab

// Display the matrix


displayMatrix(matrix);

return 0;
}
OUTPUT
Computer Programming Lab
24.To calculate addition / subtraction of 2-dimensional matrix
#include <stdio.h>

// Function to calculate addition of two matrices


void addMatrices(int matA[3][3], int matB[3][3], int result[3][3]) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
result[i][j] = matA[i][j] + matB[i][j];
}
}
}

// Function to calculate subtraction of two matrices


void subtractMatrices(int matA[3][3], int matB[3][3], int result[3][3]) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
result[i][j] = matA[i][j] - matB[i][j];
}
}
}

// Function to display a 2-dimensional matrix


void displayMatrix(int matrix[3][3]) {
printf("Matrix elements are:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
}
Computer Programming Lab

// Example usage:
int main() {
int matrixA[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int matrixB[3][3] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int resultMatrixAdd[3][3], resultMatrixSubtract[3][3];

// Calculate and display the addition of matrices


addMatrices(matrixA, matrixB, resultMatrixAdd);
printf("Addition of matrices:\n");
displayMatrix(resultMatrixAdd);

// Calculate and display the subtraction of matrices


subtractMatrices(matrixA, matrixB, resultMatrixSubtract);
printf("\nSubtraction of matrices:\n");
displayMatrix(resultMatrixSubtract);

return 0;
}
OUTPUT
Computer Programming Lab
25. To calculate multiplication of 2-dimensional matrix.
#include <stdio.h>

// Function to calculate multiplication of two matrices


void multiplyMatrices(int matA[3][3], int matB[3][3], int result[3][3]) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
result[i][j] = 0;
for (int k = 0; k < 3; k++) {
result[i][j] += matA[i][k] * matB[k][j];
}
}
}
}

// Function to display a 2-dimensional matrix


void displayMatrix(int matrix[3][3]) {
printf("Matrix elements are:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
}

// Example usage:
int main() {
int matrixA[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int matrixB[3][3] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int resultMatrix[3][3];
Computer Programming Lab

// Calculate and display the multiplication of matrices


multiplyMatrices(matrixA, matrixB, resultMatrix);
printf("Multiplication of matrices:\n");
displayMatrix(resultMatrix);

return 0;
}
OUTPUT
Computer Programming Lab
26.To find the number of vowels and consonants in a string.
#include <stdio.h>
#include <ctype.h>

// Function to count vowels and consonants in a string


void countVowelsAndConsonants(char *str, int *vowelCount, int *consonantCount) {
*vowelCount = *consonantCount = 0;

while (*str) {
char currentChar = tolower(*str);

if ((currentChar >= 'a' && currentChar <= 'z')) {


if (currentChar == 'a' || currentChar == 'e' || currentChar == 'i' || currentChar == 'o' ||
currentChar == 'u') {
(*vowelCount)++;
} else {
(*consonantCount)++;
}
}

str++;
}
}

// Example usage:
int main() {
char inputString[100];
int vowelCount, consonantCount;

printf("Enter a string: ");


fgets(inputString, sizeof(inputString), stdin);
Computer Programming Lab
countVowelsAndConsonants(inputString, &vowelCount, &consonantCount);

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


printf("Number of consonants: %d\n", consonantCount);

return 0;
}
Output
Computer Programming Lab
27. Implementation of strlen(), strcpy(), strcat() and strcmp() functions.
#include <stdio.h>

// Function to calculate the length of a string


size_t strlen_custom(const char *str) {
size_t length = 0;
while (str[length] != '\0') {
length++;
}
return length;
}

// Function to copy a string


char *strcpy_custom(char *destination, const char *source) {
char *originalDestination = destination;
while ((*destination++ = *source++))
;
return originalDestination;
}

// Function to concatenate two strings


char *strcat_custom(char *destination, const char *source) {
char *originalDestination = destination;

while (*destination) {
destination++;
}

while ((*destination++ = *source++))


;
Computer Programming Lab
return originalDestination;
}

// Function to compare two strings


int strcmp_custom(const char *str1, const char *str2) {
while (*str1 && (*str1 == *str2)) {
str1++;
str2++;
}
return *(unsigned char *)str1 - *(unsigned char *)str2;
}

// Example usage:
int main() {
const char *str1 = "Hello";
const char *str2 = "World";
char buffer[20];

// strlen() example
printf("Length of '%s': %zu\n", str1, strlen_custom(str1));

// strcpy() example
strcpy_custom(buffer, str1);
printf("Copy of '%s': %s\n", str1, buffer);

// strcat() example
strcat_custom(buffer, " ");
strcat_custom(buffer, str2);
printf("Concatenation of '%s' and '%s': %s\n", str1, str2, buffer);

// strcmp() example
Computer Programming Lab
int compareResult = strcmp_custom(str1, str2);
printf("Comparison of '%s' and '%s': %d\n", str1, str2, compareResult);

return 0;
}
OUTPUT
Computer Programming Lab
28. To check whether a string is palindrome or not.
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
// Function to check if a string is a palindrome
bool isPalindrome(const char *str) {
int length = strlen(str);
for (int i = 0; i < length / 2; i++) {
if (str[i] != str[length - i - 1]) {
return false;
}
}
return true;
}
int main() {
char inputString[100];
printf("Enter a string: ");
fgets(inputString, sizeof(inputString), stdin);
// Remove the newline character from the input (if present)
inputString[strcspn(inputString, "\n")] = '\0';

if (isPalindrome(inputString)) {
printf("The string \"%s\" is a palindrome.\n", inputString);
} else {
printf("The string \"%s\" is not a palindrome.\n", inputString);
}
return 0;
}
OUTPUT
Computer Programming Lab
29. To replace a specific character/string by another character/string in a multiword string. C
#include <stdio.h>
#include <string.h>

// Function to replace a specific substring in a multiword string


void replaceSubstring(char *str, const char *oldSubstring, const char *newSubstring) {
char *pos = strstr(str, oldSubstring);

if (pos != NULL) {
int oldLength = strlen(oldSubstring);
int newLength = strlen(newSubstring);

// Shift the remaining characters to make space for the new substring
memmove(pos + newLength, pos + oldLength, strlen(pos + oldLength) + 1);

// Copy the new substring into the space


strncpy(pos, newSubstring, newLength);
}
}

// Example usage:
int main() {
char multiwordString[] = "This is a test string.";
char oldSubstr[] = "test";
char newSubstr[] = "example";

// Display the original string


printf("Original string: %s\n", multiwordString);

// Replace a substring in the multiword string


replaceSubstring(multiwordString, oldSubstr, newSubstr);
Computer Programming Lab

// Display the modified string


printf("Modified string: %s\n", multiwordString);

return 0;
}
OUTPUT
Computer Programming Lab
29. To make the abbreviated form of a multiword string.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
// Function to create an abbreviated form of a multiword string
void createAbbreviation(const char *inputString) {
if (inputString == NULL || *inputString == '\0') {
printf("Invalid input string.\n");
return;
}
// Print the first character of the first word in uppercase
printf("%c", toupper(inputString[0]));
// Iterate through the string to find spaces and print the next character after a space
for (int i = 0; i < strlen(inputString); i++) {
if (inputString[i] == ' ' && inputString[i + 1] != '\0') {
printf("%c", toupper(inputString[i + 1]));
}
}
printf("\n");
}
// Example usage:
int main() {
char multiwordString[] = "This is a multiword string";
printf("Original string: %s\n", multiwordString);
printf("Abbreviation: ");
createAbbreviation(multiwordString);
return 0;
}
OUTPUT
Computer Programming Lab
30. To calculate the value of nCr, n≥r using function:

#include <stdio.h>

// Function to calculate factorial


int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
// Function to calculate nCr
int nCr(int n, int r) {
if (n < r) {
return 0;
}
return factorial(n) / (factorial(r) * factorial(n - r));
}
// Example usage:
int main() {
int n, r;
printf("Enter values for n and r (n >= r): ");
scanf("%d %d", &n, &r);

printf("%dC%d = %d\n", n, r, nCr(n, r));

return 0;
}
OUTPUT
Computer Programming Lab
31. To find the sum of the series 1 + 1/2 + ⋯ for n ≥ 1, x ≥ 0 using function:
#include <stdio.h>
// Function to calculate factorial
double factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
// Function to calculate the sum of the series
double seriesSum(int n, double x) {
double sum = 0;
for (int i = 1; i <= n; i++) {
sum += 1.0 / (factorial(i) * x);
}
return sum;
}
// Example usage:
int main() {
int n;
double x;
printf("Enter values for n and x (n >= 1, x >= 0): ");
scanf("%d %lf", &n, &x);
printf("Sum of the series: %lf\n", seriesSum(n, x));

return 0;
}
OUTPUT
Computer Programming Lab
32.To interchange the biggest and smallest number in a one-dimensional array using function:

#include <stdio.h>
// Function to find the index of the smallest element in an array
int findMinIndex(int arr[], int size) {
int minIndex = 0;
for (int i = 1; i < size; i++) {
if (arr[i] < arr[minIndex]) {
minIndex = i;
}
}
return minIndex;
}
// Function to find the index of the largest element in an array
int findMaxIndex(int arr[], int size) {
int maxIndex = 0;
for (int i = 1; i < size; i++) {
if (arr[i] > arr[maxIndex]) {
maxIndex = i;
}
}
return maxIndex;
}
// Function to interchange the biggest and smallest numbers
void interchangeMinMax(int arr[], int size) {
int minIndex = findMinIndex(arr, size);
int maxIndex = findMaxIndex(arr, size);
// Interchange the values
int temp = arr[minIndex];
arr[minIndex] = arr[maxIndex];
arr[maxIndex] = temp;
}
Computer Programming Lab
// Function to display the array
void displayArray(int arr[], int size) {
printf("Array elements: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
// Example usage:
int main() {
int size;
printf("Enter the size of the array: ");
scanf("%d", &size);
int arr[size];
printf("Enter elements of the array:\n");
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
interchangeMinMax(arr, size);
printf("After interchange:\n");
displayArray(arr, size);

return 0;
}
OUTPUT
Computer Programming Lab
33. To calculate addition, subtraction, and multiplication of 2-dimensional matrix using function:

#include <stdio.h>

// Function to perform matrix addition


void matrixAddition(int matA[3][3], int matB[3][3], int result[3][3]) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
result[i][j] = matA[i][j] + matB[i][j];
}
}
}

// Function to perform matrix subtraction


void matrixSubtraction(int matA[3][3], int matB[3][3], int result[3][3]) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
result[i][j] = matA[i][j] - matB[i][j];
}
}
}

// Function to perform matrix multiplication


void matrixMultiplication(int matA[3][3], int matB[3][3], int result[3][3]) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
result[i][j] = 0;
for (int k = 0; k < 3; k++) {
result[i][j] += matA[i][k] * matB[k][j];
}
}
}
Computer Programming Lab
}

// Function to display the matrix


void displayMatrix(int matrix[3][3]) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
}

// Example usage:
int main() {
int matA[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int matB[3][3] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int resultMatrix[3][3];

printf("Matrix A:\n");
displayMatrix(matA);

printf("\nMatrix B:\n");
displayMatrix(matB);

// Addition
matrixAddition(matA, matB, resultMatrix);
printf("\nAddition of matrices:\n");
displayMatrix(resultMatrix);

// Subtraction
matrixSubtraction(matA, matB, resultMatrix);
Computer Programming Lab
printf("\nSubtraction of matrices:\n");
displayMatrix(resultMatrix);

// Multiplication
matrixMultiplication(matA, matB, resultMatrix);
printf("\nMultiplication of matrices:\n");
displayMatrix(resultMatrix);

return 0;
}
OUTPUT
Computer Programming Lab
34. Write a program in C to find GCD of two numbers using recursion:

#include <stdio.h>

// Function to find the GCD of two numbers using recursion


int findGCD(int a, int b) {
if (b == 0) {
return a;
} else {
return findGCD(b, a % b);
}
}

// Example usage:
int main() {
int num1, num2;

printf("Enter two numbers: ");


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

printf("GCD of %d and %d is %d\n", num1, num2, findGCD(num1, num2));

return 0;
}
OUTPUT
Computer Programming Lab
35. To calculate factorial of any given number using recursion:

#include <stdio.h>

// Function to calculate factorial using recursion


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

// Example usage:
int main() {
int num;

printf("Enter a number: ");


scanf("%d", &num);

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

return 0;
}
OUTPUT
Computer Programming Lab
36. To demonstrate call by reference, call by value:

#include <stdio.h>

// Function to demonstrate call by value


void callByValue(int x) {
printf("Inside callByValue function\n");
printf("Before modification, x = %d\n", x);
x = 20;
printf("After modification, x = %d\n", x);
}

// Function to demonstrate call by reference


void callByReference(int *y) {
printf("Inside callByReference function\n");
printf("Before modification, *y = %d\n", *y);
*y = 30;
printf("After modification, *y = %d\n", *y);
}

// Example usage:
int main() {
int a = 10, b = 15;

printf("Call by Value:\n");
printf("Before function call, a = %d\n", a);
callByValue(a);
printf("After function call, a = %d\n", a);

printf("\nCall by Reference:\n");
printf("Before function call, b = %d\n", b);
callByReference(&b);
Computer Programming Lab
printf("After function call, b = %d\n", b);

return 0;
}
OUTPUT
Computer Programming Lab
37. To read and display an integer array using pointer:

#include <stdio.h>

// Function to read and display an integer array using pointer


void readAndDisplayArray(int *arr, int size) {
printf("Enter %d elements:\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", arr + i);
}

printf("Array elements are:\n");


for (int i = 0; i < size; i++) {
printf("%d ", *(arr + i));
}
printf("\n");
}
// Example usage:
int main() {
int size;
printf("Enter the size of the array: ");
scanf("%d", &size);
int arr[size];
readAndDisplayArray(arr, size);
return 0;
}
OUTPUT
Computer Programming Lab
38. To read and display a text using a character pointer to a string. Also count the number of characters,
words, and lines in the text:

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

void processText(char *text) {

int charCount = 0, wordCount = 0, lineCount = 0;

int inWord = 0; // Flag to track if the current character is part of a word

// Iterate through each character in the text

for (int i = 0; text[i] != '\0'; i++) {

// Increment character count for each non-space character

if (text[i] != ' ' && text[i] != '\t' && text[i] != '\n') {

charCount++;

// If the current character is the beginning of a word, increment word count

if (!inWord) {

inWord = 1;

wordCount++;

} else {

// If the current character is a space, tab, or newline, set the inWord flag to 0

inWord = 0;

// Increment line count for newline characters


Computer Programming Lab
if (text[i] == '\n') {

lineCount++;

// Display the text

printf("Text:\n%s\n", text);

// Display counts

printf("\nCharacter Count: %d\n", charCount);

printf("Word Count: %d\n", wordCount);

printf("Line Count: %d\n", lineCount);

int main() {

char *text;

size_t bufferSize = 1024; // Adjust the buffer size as needed

// Allocate memory for the text buffer

text = (char*)malloc(bufferSize * sizeof(char));

if (text == NULL) {

fprintf(stderr, "Memory allocation failed\n");

return 1;

}
Computer Programming Lab
// Prompt user to enter text

printf("Enter text (Ctrl+D to end input on Unix-like systems, Ctrl+Z on Windows):\n");

// Read text from standard input

if (getline(&text, &bufferSize, stdin) == -1) {

fprintf(stderr, "Error reading input\n");

free(text);

return 1;

// Process and display the text

processText(text);

// Free allocated memory

free(text);

return 0;

OUTPUT
Computer Programming Lab
39. To read, display, add, and subtract two times defined using hour, minutes, and values of seconds:

#include <stdio.h>

// Structure to represent time


struct Time {
int hours;
int minutes;
int seconds;
};

// Function to read and display time


void readAndDisplayTime(struct Time *t) {
printf("Enter hours, minutes, and seconds:\n");
scanf("%d %d %d", &(t->hours), &(t->minutes), &(t->seconds));

printf("Time entered: %02d:%02d:%02d\n", t->hours, t->minutes, t->seconds);


}

// Function to add two times


struct Time addTimes(struct Time t1, struct Time t2) {
struct Time result;

result.seconds = t1.seconds + t2.seconds;


result.minutes = t1.minutes + t2.minutes + result.seconds / 60;
result.hours = t1.hours + t2.hours + result.minutes / 60;

result.seconds %= 60;
result.minutes %= 60;

return result;
}
Computer Programming Lab

// Function to subtract two times


struct Time subtractTimes(struct Time t1, struct Time t2) {
struct Time result;

result.seconds = t1.seconds - t2.seconds;


result.minutes = t1.minutes - t2.minutes;
result.hours = t1.hours - t2.hours;

if (result.seconds < 0) {
result.seconds += 60;
result.minutes--;
}
if (result.minutes < 0) {
result.minutes += 60;
result.hours--;
}

return result;
}

// Example usage:
int main() {
struct Time time1, time2, sum, difference;

printf("Enter the first time:\n");


readAndDisplayTime(&time1);

printf("\nEnter the second time:\n");


readAndDisplayTime(&time2);
Computer Programming Lab
// Addition
sum = addTimes(time1, time2);
printf("\nSum of times: %02d:%02d:%02d\n", sum.hours, sum.minutes, sum.seconds);

// Subtraction
difference = subtractTimes(time1, time2);
printf("Difference of times: %02d:%02d:%02d\n", difference.hours, difference.minutes,
difference.seconds);

return 0;
}
OUTPUT

40. To read and display the contents of a structure variable using a pointer to a structure:

#include <stdio.h>
// Structure to represent a student
struct Student {
char name[50];
int rollNumber;
float marks;
};
// Function to read and display student information using a pointer to a structure
void readAndDisplayStudent(struct Student *s) {
printf("Enter student details:\n");
printf("Name: ");
scanf("%s", s->name);
Computer Programming Lab
printf("Roll Number: ");
scanf("%d", &(s->rollNumber));
printf("Marks: ");
scanf("%f", &(s->marks));

printf("\nStudent Details:\n");
printf("Name: %s\n", s->name);
printf("Roll Number: %d\n", s->rollNumber);
printf("Marks: %.2f\n", s->marks);
}

// Example usage:
int main() {
struct Student student;
readAndDisplayStudent(&student);
return 0;
}
OUTPUT
Computer Programming Lab
41. Write a program in C to create a singly linked list of n nodes and display it in reverse order:

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

// Node structure
struct Node {
int data;
struct Node *next;
};

// Function to create a linked list of n nodes


struct Node *createLinkedList(int n) {
struct Node *head = NULL;
struct Node *temp, *newNode;

printf("Enter the elements for the linked list:\n");

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


newNode = (struct Node *)malloc(sizeof(struct Node));

if (newNode == NULL) {
printf("Memory allocation failed!\n");
exit(1);
}
scanf("%d", &(newNode->data));
newNode->next = NULL;
if (head == NULL) {
head = newNode;
temp = newNode;
} else {
temp->next = newNode;
Computer Programming Lab
temp = newNode;
}
}
return head;
}
// Function to display linked list in reverse order
void displayReverse(struct Node *head) {
if (head == NULL) {
return;
}
displayReverse(head->next);
printf("%d ", head->data);
}
// Example usage:
int main() {
int n;
struct Node *head;
printf("Enter the number of nodes: ");
scanf("%d", &n);
head = createLinkedList(n);
printf("Linked list in reverse order: ");
displayReverse(head);
printf("\n");
return 0;
}
OUTPUT
Computer Programming Lab
42. Write a program in C to insert a new node to a Singly Linked List after a desired node and display the
list:

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

// Node structure
struct Node {
int data;
struct Node *next;
};

// Function to insert a new node after a desired node


void insertAfter(struct Node *prevNode, int newData) {
if (prevNode == NULL) {
printf("Previous node cannot be NULL.\n");
return;
}

struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));


if (newNode == NULL) {
printf("Memory allocation failed!\n");
exit(1);
}

newNode->data = newData;
newNode->next = prevNode->next;
prevNode->next = newNode;
}

// Function to display a linked list


void displayList(struct Node *head) {
while (head != NULL) {
Computer Programming Lab
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}

// Example usage:
int main() {
struct Node *head = NULL;
struct Node *first = (struct Node *)malloc(sizeof(struct Node));
struct Node *second = (struct Node *)malloc(sizeof(struct Node));

if (first == NULL || second == NULL) {


printf("Memory allocation failed!\n");
exit(1);
}
first->data = 1;
first->next = second;
second->data = 3;
second->next = NULL;
head = first;
printf("Original linked list: ");
displayList(head);
insertAfter(first, 2);
printf("Linked list after insertion: ");
displayList(head);
return 0;
}
OUTPUT
Computer Programming Lab
43. Write a program in C to delete a node from a Singly Linked List after/before a desired node and
display the list:

#include <stdio.h>
#include <stdlib.h>
// Node structure
struct Node {
int data;
struct Node *next;
};

// Function to insert a new node after a desired node


void insertAfter(struct Node *prevNode, int newData) {
if (prevNode == NULL) {
printf("Previous node cannot be NULL.\n");
return;
}
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed!\n");
exit(1);
}
newNode->data = newData;
newNode->next = prevNode->next;
prevNode->next = newNode;
}

// Function to delete a node after a desired node


void deleteAfter(struct Node *prevNode) {
if (prevNode == NULL || prevNode->next == NULL) {
printf("Node cannot be deleted.\n");
return;
}
Computer Programming Lab

struct Node *temp = prevNode->next;


prevNode->next = temp->next;
free(temp);
}

// Function to display a linked list


void displayList(struct Node *head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}

// Example usage:
int main() {
struct Node *head = NULL;
struct Node *first = (struct Node *)malloc(sizeof(struct Node));
struct Node *second = (struct Node *)malloc(sizeof(struct Node));
struct Node *third = (struct Node *)malloc(sizeof(struct Node));

if (first == NULL || second == NULL || third == NULL) {


printf("Memory allocation failed!\n");
exit(1);
}

first->data = 1;
first->next = second;

second->data = 2;
Computer Programming Lab
second->next = third;

third->data = 3;
third->next = NULL;

head = first;

printf("Original linked list: ");


displayList(head);

// Insert a new node after the first node


insertAfter(first, 4);
printf("Linked list after insertion: ");
displayList(head);

// Delete the node after the first node


deleteAfter(first);
printf("Linked list after deletion: ");
displayList(head);

return 0;
}
OUTPUT
Computer Programming Lab
44. Implement Stack and Queue data structure using dynamic memory allocation:

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

typedef struct {
int *array;
int capacity;
int top;
} Stack;

// Function to initialize a stack with a given capacity


Stack* createStack(int capacity) {
Stack *stack = (Stack*)malloc(sizeof(Stack));
stack->capacity = capacity;
stack->top = -1;
stack->array = (int*)malloc(capacity * sizeof(int));
return stack;
}

// Function to check if the stack is empty


int isEmpty(Stack *stack) {
return stack->top == -1;
}

// Function to check if the stack is full


int isFull(Stack *stack) {
return stack->top == stack->capacity - 1;
}

// Function to push an element onto the stack


void push(Stack *stack, int item) {
Computer Programming Lab
if (isFull(stack)) {
printf("Stack Overflow\n");
return;
}
stack->array[++stack->top] = item;
}

// Function to pop an element from the stack


int pop(Stack *stack) {
if (isEmpty(stack)) {
printf("Stack Underflow\n");
return -1;
}
return stack->array[stack->top--];
}

// Function to get the top element of the stack without removing it


int peek(Stack *stack) {
if (isEmpty(stack)) {
printf("Stack is empty\n");
return -1;
}
return stack->array[stack->top];
}

// Function to free the memory allocated for the stack


void freeStack(Stack *stack) {
free(stack->array);
free(stack);
}
Computer Programming Lab
int main() {
Stack *stack = createStack(5);

push(stack, 1);
push(stack, 2);
push(stack, 3);

printf("Top element: %d\n", peek(stack));

printf("Popped element: %d\n", pop(stack));


printf("Popped element: %d\n", pop(stack));

printf("Is stack empty? %s\n", isEmpty(stack) ? "Yes" : "No");

freeStack(stack);

return 0;
}
OUTPUT
Computer Programming Lab
#include <stdio.h>
#include <stdlib.h>

typedef struct {
int *array;
int capacity;
int front;
int rear;
int size;
} Queue;

// Function to initialize a queue with a given capacity


Queue* createQueue(int capacity) {
Queue *queue = (Queue*)malloc(sizeof(Queue));
queue->capacity = capacity;
queue->front = 0;
queue->rear = -1;
queue->size = 0;
queue->array = (int*)malloc(capacity * sizeof(int));
return queue;
}

// Function to check if the queue is empty


int isEmpty(Queue *queue) {
return queue->size == 0;
}

// Function to check if the queue is full


int isFull(Queue *queue) {
return queue->size == queue->capacity;
}
Computer Programming Lab

// Function to enqueue an element into the queue


void enqueue(Queue *queue, int item) {
if (isFull(queue)) {
printf("Queue is full\n");
return;
}
queue->rear = (queue->rear + 1) % queue->capacity;
queue->array[queue->rear] = item;
queue->size++;
}

// Function to dequeue an element from the queue


int dequeue(Queue *queue) {
if (isEmpty(queue)) {
printf("Queue is empty\n");
return -1;
}
int item = queue->array[queue->front];
queue->front = (queue->front + 1) % queue->capacity;
queue->size--;
return item;
}

// Function to free the memory allocated for the queue


void freeQueue(Queue *queue) {
free(queue->array);
free(queue);
}

int main() {
Computer Programming Lab
Queue *queue = createQueue(5);

enqueue(queue, 1);
enqueue(queue, 2);
enqueue(queue, 3);

printf("Dequeued element: %d\n", dequeue(queue));


printf("Dequeued element: %d\n", dequeue(queue));

printf("Is queue empty? %s\n", isEmpty(queue) ? "Yes" : "No");

freeQueue(queue);

return 0;
}
OUTPUT

You might also like