0% found this document useful (0 votes)
3 views19 pages

C Programming Lab Report Complete

Uploaded by

dsd4dhhwz5
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)
3 views19 pages

C Programming Lab Report Complete

Uploaded by

dsd4dhhwz5
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

Computer Programming Laboratory

(PBC101)

Laboratory Assignment Report


Experiments 1-10

Internal Assessment: 30 Marks


Program 1: Data Types and Type Conversion
Objective
To demonstrate implicit and explicit type conversion between different data types (int,
float, char) and perform arithmetic operations.

Algorithm
1. Start
2. Declare variables of different data types: int, float, char
3. Demonstrate implicit type conversion:
a. Assign int to float (widening conversion)
b. Perform arithmetic operations between int and float
4. Demonstrate explicit type conversion (type casting):
a. Cast float to int (narrowing conversion)
b. Cast int to char
5. Display results of all conversions
6. Stop

C Program Code
/* Program 1: Data Types and Type Conversion */ #include <stdio.h> int main()
{ // Variable declarations int intVar = 10; float floatVar = 5.5;
char charVar = 'A'; printf("=== Data Types and Type Conversion Demo
===\n\n"); // Display original values printf("Original Values:\
n"); printf("Integer: %d\n", intVar); printf("Float: %.2f\n",
floatVar); printf("Character: %c (ASCII: %d)\n\n", charVar, charVar);
// Implicit type conversion (int to float) printf("Implicit Conversions:\
n"); float result1 = intVar; // int promoted to float printf("int %d
converted to float: %.2f\n", intVar, result1); // Arithmetic
operation causing implicit conversion float result2 = intVar + floatVar;
printf("int %d + float %.2f = %.2f (result is float)\n\n", intVar, floatVar,
result2); // Explicit type conversion (type casting)
printf("Explicit Conversions (Type Casting):\n"); int result3 =
(int)floatVar; // float cast to int printf("float %.2f cast to int: %d
(decimal part truncated)\n", floatVar, result3); char result4 =
(char)intVar; // int cast to char printf("int %d cast to char: %c (ASCII
value)\n\n", intVar, result4); // Division demonstration
printf("Division Operations:\n"); int a = 7, b = 2; printf("Integer
division: %d / %d = %d\n", a, b, a/b); printf("Float division: %d / %d =
%.2f (with casting)\n", a, b, (float)a/b); return 0; }

Expected Output
=== Data Types and Type Conversion Demo === Original Values: Integer: 10
Float: 5.50 Character: A (ASCII: 65) Implicit Conversions: int 10 converted
to float: 10.00 int 10 + float 5.50 = 15.50 (result is float) Explicit
Conversions (Type Casting): float 5.50 cast to int: 5 (decimal part truncated)
int 10 cast to char: (ASCII value) Division Operations: Integer division: 7
/ 2 = 3 Float division: 7 / 2 = 3.50 (with casting)

Outcome
Successfully demonstrated implicit and explicit type conversions in C. Learned how the
compiler automatically promotes smaller data types to larger ones during arithmetic
operations, and how type casting can be used to explicitly convert between data types
with potential data loss.
Program 2: Prime Number Checker
Objective
To develop a C program that checks whether a given integer entered by the user is a
prime number using conditional statements and loop constructs.

Algorithm
1. Start
2. Read an integer number from user
3. If number <= 1, it is not prime
4. If number == 2, it is prime
5. For numbers > 2:
a. Initialize flag = 1 (assume prime)
b. Loop from i = 2 to sqrt(number):
- If number % i == 0, set flag = 0 and break
6. If flag == 1, number is prime; else not prime
7. Display result
8. Stop

C Program Code
/* Program 2: Prime Number Checker */ #include <stdio.h> int main() { int
num, i, isPrime = 1; // Input number from user printf("Enter a
positive integer: "); scanf("%d", &num); // Handle special cases
if (num <= 1) { printf("%d is not a prime number.\n", num);
return 0; } if (num == 2) { printf("%d is a prime
number.\n", num); return 0; } // Check for divisibility
from 2 to num/2 for (i = 2; i <= num / 2; i++) { if (num % i == 0)
{ isPrime = 0; // Not prime if divisible break;
} } // Display result if (isPrime) printf("%d is a
prime number.\n", num); else printf("%d is not a prime number.\n",
num); return 0; }

Expected Output
Test Case 1: Enter a positive integer: 17 17 is a prime number. Test Case 2:
Enter a positive integer: 24 24 is not a prime number. Test Case 3: Enter a
positive integer: 2 2 is a prime number.

Outcome
Successfully implemented prime number checking logic using for loop and conditional
statements. Understood the concept of divisibility testing and optimized the checking
process by testing only up to num/2.
Program 3: Sum of Digits Using While Loop
Objective
To compute the sum of digits of a number using a while loop, reinforcing loop control
and arithmetic operations.

Algorithm
1. Start
2. Read a number from user
3. Initialize sum = 0
4. While number > 0:
a. Extract last digit: digit = number % 10
b. Add digit to sum: sum = sum + digit
c. Remove last digit: number = number / 10
5. Display sum
6. Stop

C Program Code
/* Program 3: Sum of Digits Using While Loop */ #include <stdio.h> int main()
{ int num, originalNum, digit, sum = 0; // Input number from user
printf("Enter a positive integer: "); scanf("%d", &num);
originalNum = num; // Store original number for display // Calculate
sum of digits using while loop while (num > 0) { digit = num % 10;
// Extract last digit sum = sum + digit; // Add to sum num
= num / 10; // Remove last digit } // Display result
printf("Sum of digits of %d = %d\n", originalNum, sum); return 0; }

Expected Output
Test Case 1: Enter a positive integer: 1234 Sum of digits of 1234 = 10 Test
Case 2: Enter a positive integer: 5678 Sum of digits of 5678 = 26

Outcome
Successfully practiced using while loops for digit extraction and summation. Learned the
modulo (%) and division (/) operators for processing individual digits of a number.
Program 4: String Length and Reverse
Objective
To find the length of a string and reverse it by manipulating characters in an array,
teaching string handling basics.

Algorithm
1. Start
2. Read a string from user
3. Calculate string length:
a. Initialize length = 0
b. Traverse string until null character
c. Increment length for each character
4. Reverse the string:
a. Use two pointers: start = 0, end = length - 1
b. While start < end:
- Swap characters at start and end positions
- Increment start, decrement end
5. Display length and reversed string
6. Stop

C Program Code
/* Program 4: String Length and Reverse */ #include <stdio.h> int main() {
char str[100]; int length = 0, i; char temp; // Input string
from user printf("Enter a string: "); scanf("%s", str); //
Calculate string length manually while (str[length] != '\0')
{ length++; } printf("\nOriginal String: %s\n", str);
printf("Length of string: %d\n", length); // Reverse the string using
two-pointer approach for (i = 0; i < length / 2; i++) { temp =
str[i]; str[i] = str[length - i - 1]; str[length - i - 1] =
temp; } printf("Reversed String: %s\n", str); return
0; }

Expected Output
Enter a string: HELLO Original String: HELLO Length of string: 5 Reversed
String: OLLEH

Outcome
Successfully learned string traversal and character manipulation. Understood how
strings are stored as character arrays with null terminator, and implemented the two-
pointer technique for in-place string reversal.
Program 5: Maximum and Minimum in Array
Objective
To read an array of integers and determine the minimum and maximum value by
traversing the array, demonstrating array operations and indexing.

Algorithm
1. Start
2. Read size of array from user
3. Read array elements from user
4. Initialize max = arr[0] and min = arr[0]
5. For i = 1 to n-1:
a. If arr[i] > max, update max = arr[i]
b. If arr[i] < min, update min = arr[i]
6. Display maximum and minimum values
7. Stop

C Program Code
/* Program 5: Find Maximum and Minimum in Array */ #include <stdio.h> int
main() { int arr[100], n, i; int max, min; // Input array
size printf("Enter number of elements: "); scanf("%d",
&n); // Input array elements printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) { printf("Element %d: ", i + 1);
scanf("%d", &arr[i]); } // Initialize max and min with first
element max = min = arr[0]; // Find maximum and minimum for
(i = 1; i < n; i++) { if (arr[i] > max) { max = arr[i];
} if (arr[i] < min) { min = arr[i]; } }
// Display results printf("\nArray elements: "); for (i = 0; i < n; i+
+) { printf("%d ", arr[i]); } printf("\n\nMaximum element: %d\
n", max); printf("Minimum element: %d\n", min); return 0; }

Expected Output
Enter number of elements: 5 Enter 5 elements: Element 1: 12 Element 2: 45
Element 3: 7 Element 4: 89 Element 5: 23 Array elements: 12 45 7 89 23
Maximum element: 89 Minimum element: 7

Outcome
Successfully gained experience in array traversal and comparison operations. Learned
how to efficiently find maximum and minimum values in a single pass through the array.
Program 6: Matrix Transpose Using 2D Arrays
Objective
To compute the transpose of a matrix using nested loops and two-dimensional arrays,
reinforcing multidimensional array concepts.

Algorithm
1. Start
2. Read matrix dimensions (rows and columns) from user
3. Read matrix elements using nested loops
4. Display original matrix
5. Compute transpose:
For i = 0 to rows-1:
For j = 0 to cols-1:
transpose[j][i] = matrix[i][j]
6. Display transpose matrix
7. Stop

C Program Code
/* Program 6: Matrix Transpose Using 2D Arrays */ #include <stdio.h> int
main() { int matrix[10][10], transpose[10][10]; int rows, cols, i, j;
// Input matrix dimensions printf("Enter number of rows: ");
scanf("%d", &rows); printf("Enter number of columns: "); scanf("%d",
&cols); // Input matrix elements printf("\nEnter matrix
elements:\n"); for (i = 0; i < rows; i++) { for (j = 0; j < cols;
j++) { printf("Element [%d][%d]: ", i, j); scanf("%d",
&matrix[i][j]); } } // Display original matrix
printf("\nOriginal Matrix (%dx%d):\n", rows, cols); for (i = 0; i < rows;
i++) { for (j = 0; j < cols; j++) { printf("%4d ",
matrix[i][j]); } printf("\n"); } // Compute
transpose for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++)
{ transpose[j][i] = matrix[i][j]; } } //
Display transpose matrix printf("\nTranspose Matrix (%dx%d):\n", cols,
rows); for (i = 0; i < cols; i++) { for (j = 0; j < rows; j++) {
printf("%4d ", transpose[i][j]); } printf("\n"); }
return 0; }

Expected Output
Enter number of rows: 2 Enter number of columns: 3 Enter matrix elements:
Element [0][0]: 1 Element [0][1]: 2 Element [0][2]: 3 Element [1][0]: 4
Element [1][1]: 5 Element [1][2]: 6 Original Matrix (2x3): 1 2 3
4 5 6 Transpose Matrix (3x2): 1 4 2 5 3 6
Outcome
Successfully learned multidimensional array representation and element indexing.
Understood how to perform matrix operations using nested loops and how rows become
columns in transpose.
Program 7: Employee Information Using Structures
Objective
To store and display employee information (ID, Name, Salary) using structures,
demonstrating how to organize related data.

Algorithm
1. Start
2. Define a structure 'Employee' with members: id, name, salary
3. Read number of employees from user
4. For each employee:
a. Read employee ID
b. Read employee name
c. Read employee salary
5. Display all employee information in tabular format
6. Stop

C Program Code
/* Program 7: Employee Information Using Structures */ #include <stdio.h>
#include <string.h> // Define Employee structure struct Employee { int
id; char name[50]; float salary; }; int main() { struct Employee
emp[50]; int n, i; // Input number of employees printf("Enter
number of employees: "); scanf("%d", &n); // Input employee
details printf("\nEnter employee details:\n"); for (i = 0; i < n; i++)
{ printf("\nEmployee %d:\n", i + 1); printf("Enter ID: ");
scanf("%d", &emp[i].id); printf("Enter Name: "); scanf("%s",
emp[i].name); printf("Enter Salary: "); scanf("%f",
&emp[i].salary); } // Display employee information printf("\
n\n========================================\n"); printf(" EMPLOYEE
INFORMATION\n"); printf("========================================\n");
printf("%-10s %-20s %-10s\n", "ID", "Name", "Salary");
printf("----------------------------------------\n"); for (i = 0; i <
n; i++) { printf("%-10d %-20s %.2f\n", emp[i].id,
emp[i].name, emp[i].salary); }
printf("========================================\n"); return 0; }

Expected Output
Enter number of employees: 3 Enter employee details: Employee 1: Enter ID:
101 Enter Name: John Enter Salary: 50000 Employee 2: Enter ID: 102 Enter
Name: Alice Enter Salary: 60000 Employee 3: Enter ID: 103 Enter Name: Bob
Enter Salary: 55000 ======================================== EMPLOYEE
INFORMATION ======================================== ID Name
Salary ---------------------------------------- 101 John
50000.00 102 Alice 60000.00 103 Bob
55000.00 ========================================
Outcome
Successfully understood how to organize related data using structures. Learned how to
access structure members using the dot operator and manage complex data in a
structured and readable manner.
Program 8: Fibonacci Series Using Function
Objective
To generate the first N terms of the Fibonacci series using a user-defined function,
demonstrating modular programming.

Algorithm
1. Start
2. Read number of terms (n) from user
3. Call fibonacci function with n as parameter
4. Inside fibonacci function:
a. Initialize first = 0, second = 1
b. Print first two terms
c. For i = 3 to n:
- Calculate next = first + second
- Print next term
- Update: first = second, second = next
5. Stop

C Program Code
/* Program 8: Fibonacci Series Using Function */ #include <stdio.h> //
Function to generate Fibonacci series void fibonacci(int n) { int first =
0, second = 1, next, i; printf("Fibonacci Series (%d terms):\n", n);
for (i = 1; i <= n; i++) { if (i == 1) { printf("%d ",
first); continue; } if (i == 2)
{ printf("%d ", second); continue; }
next = first + second; printf("%d ", next); first =
second; second = next; } printf("\n"); } int main() { int
n; // Input number of terms printf("Enter number of terms: ");
scanf("%d", &n); // Handle edge cases if (n <= 0)
{ printf("Please enter a positive number.\n"); } else { //
Call fibonacci function fibonacci(n); } return 0; }

Expected Output
Test Case 1: Enter number of terms: 10 Fibonacci Series (10 terms): 0 1 1 2 3
5 8 13 21 34 Test Case 2: Enter number of terms: 7 Fibonacci Series (7
terms): 0 1 1 2 3 5 8

Outcome
Successfully understood modular programming with functions. Learned how functions
help in code reuse, logical separation, and solving sequence generation problems
effectively.
Program 9: Count Vowels and Consonants
Objective
To count the number of vowels and consonants in a user-entered string, demonstrating
character-level operations.

Algorithm
1. Start
2. Read a string from user
3. Initialize vowels = 0, consonants = 0
4. For each character in string:
a. Convert character to lowercase
b. If character is alphabet:
- If character is a, e, i, o, u: increment vowels
- Else: increment consonants
5. Display vowel and consonant counts
6. Stop

C Program Code
/* Program 9: Count Vowels and Consonants in String */ #include <stdio.h>
#include <ctype.h> int main() { char str[100]; int i, vowels = 0,
consonants = 0; char ch; // Input string from user
printf("Enter a string: "); fgets(str, sizeof(str), stdin); //
Count vowels and consonants for (i = 0; str[i] != '\0'; i++) { ch
= tolower(str[i]); // Convert to lowercase // Check if
character is an alphabet if ((ch >= 'a' && ch <= 'z'))
{ // Check if vowel if (ch == 'a' || ch == 'e' || ch
== 'i' || ch == 'o' || ch == 'u') { vowels++;
} else { consonants+
+; } } } // Display results printf("\
nString: %s", str); printf("Number of vowels: %d\n", vowels);
printf("Number of consonants: %d\n", consonants); return 0; }

Expected Output
Test Case 1: Enter a string: Hello World String: Hello World Number of
vowels: 3 Number of consonants: 7 Test Case 2: Enter a string: Programming
String: Programming Number of vowels: 3 Number of consonants: 8

Outcome
Successfully gained practice in string traversal and character checking using conditions.
Understood basic text processing and how to classify characters in C.
Program 10: Count Characters, Words, and Lines in File
Objective
To read a text file and count the total number of characters, words, and lines,
demonstrating file reading and data analysis.

Algorithm
1. Start
2. Read filename from user
3. Open file in read mode
4. If file cannot be opened, display error and exit
5. Initialize characters = 0, words = 0, lines = 0
6. Read file character by character:
a. Increment character count
b. If newline character, increment line count
c. If space/tab/newline after non-space, increment word count
7. Close file
8. Display character, word, and line counts
9. Stop

C Program Code
/* Program 10: Count Characters, Words, Lines in File */ #include <stdio.h>
int main() { FILE *file; char filename[100]; char ch; int
characters = 0, words = 0, lines = 0; int inWord = 0; // Flag to track if
inside a word // Input filename from user printf("Enter the
filename: "); scanf("%s", filename); // Open file in read mode
file = fopen(filename, "r"); // Check if file opened successfully
if (file == NULL) { printf("Error: Could not open file %s\n",
filename); return 1; } // Read file character by
character while ((ch = fgetc(file)) != EOF) { characters++;
// Count lines if (ch == '\n') { lines++; }
// Count words if (ch == ' ' || ch == '\t' || ch == '\n') {
if (inWord) { words++; inWord = 0;
} } else { inWord = 1; } } // Count
last word if file doesn't end with whitespace if (inWord) { words+
+; } // If file has content but no newline at end, count as one
line if (characters > 0) { lines++; } // Close file
fclose(file); // Display results printf("\n===== File Statistics
=====\n"); printf("Filename: %s\n", filename); printf("Characters: %d\
n", characters); printf("Words: %d\n", words); printf("Lines: %d\n",
lines); printf("==========================\n"); return 0; }
Sample Input File ([Link])
This is a sample file. It contains multiple lines. Used for testing the
program.

Expected Output
Enter the filename: [Link] ===== File Statistics ===== Filename: [Link]
Characters: 83 Words: 13 Lines: 3 ==========================

Outcome
Successfully gained experience in file handling operations in C. Learned how to open,
read, and close files, and how to process text data by analyzing characters, words, and
lines.
Conclusion
This laboratory assignment report successfully documents all 10 programming
experiments for the Computer Programming Laboratory (PBC101) course. Through
these experiments, the following key concepts and skills were developed:
1. Understanding of fundamental data types and type conversion mechanisms in C
2. Implementation of control structures including loops and conditional statements
3. Proficiency in string manipulation and character-level operations
4. Working with single and multidimensional arrays
5. Understanding and implementation of user-defined structures
6. Modular programming using functions
7. File handling operations for reading and analyzing text data
Each program was implemented with proper algorithms, well-commented code, and
verified outputs. The experiments provided hands-on experience in solving real-world
programming problems and laid a strong foundation for advanced programming
concepts.

--- End of Report ---

You might also like