Lab Manual Computer Programming Lab (1)
Lab Manual Computer Programming Lab (1)
0 0 3 1.5
Course Objectives:
The course aims to give students hands – on experience and train them on the concepts of the C-
programming language.
Course Outcomes:
CO1: Read, understand, and trace the execution of programs written in C language.
CO2: Select the right control structure for solving the problem.
CO3: Develop C programs which utilize memory efficiently using programming constructs like
pointers.
CO4: Develop, Debug and Execute programs to demonstrate the applications of arrays,
functions, basic concepts of pointers in C.
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO1 PSO1 PSO2 PSO3
2
CO1 1 1 1 1 1 1
CO2 1 2 1 1 1
CO3 2 2 1 1 1
CO4 2 1 1 1 1
CO5 2 2 1 1 1
UNIT I
WEEK 1
Objective: Getting familiar with the programming environment on the computer and writing the
first program.
Suggested Experiments/Activities:
Tutorial 1: Problem-solving using Computers.
Lab1: Familiarization with programming environment
i) Exposure to Turbo C, gcc
ii) Writing simple programs using printf(), scanf()
WEEK 2
Objective: Getting familiar with how to formally describe a solution to a problem in a series
of finite steps both using textual notation and graphic notation.
Suggested Experiments/Activities:
Tutorial 3: Variable types and type conversions:
#include <stdio.h>
#include <conio.h>
#include <math.h>
void main ()
{
// declaration of the int, float and double variables
float x, res;
clrscr();
printf(“enter x value : “);
scanf(“%f”,&x);
// use the sqrt() function to return integer values
res = sqrt(x);
printf (" The square root of %d is: %d", x, res);
}
ii) Finding compound interest
#include <stdio.h>
#include <conio.h>
#include <math.h>
void main() {
double principal, rate, time, amount, compound_interest;
clrscr();
// Input principal, rate, and time
printf("Enter principal (amount): ");
scanf("%lf", &principal);
}
iii) Area of a triangle using heron’s formulae
#include <stdio.h>
#include <math.h>
#include <conio.h>
void main() {
float a, b, c;
clrscr();
printf("Enter the three sides of the triangle: ");
scanf("%f %f %f", &a, &b, &c);
float s = (a + b + c) / 2.0;
float area = sqrt(s * (s - a) * (s - b) * (s - c));
}
UNIT II
WEEK 4
Objective: Explore the full scope of expressions, type-compatibility of variables &
constants and operators used in the expression and how operator precedence works.
Suggested Experiments/Activities:
}
ii) Find the maximum of three numbers using conditional operator
#include <stdio.h>
#include <conio.h>
void main() {
float a, b, c, max;
clrscr();
printf("Enter three numbers: ");
scanf("%f %f %f", &a, &b, &c);
// Using the conditional operator to find the maximum
max = (a > b && a > c) ? a : ((b > c) ? b : c);
printf("Maximum number: %.2f\n", max);
iii) Take marks of 5 subjects in integers, and find the total, average in float
#include <stdio.h>
void main() {
int mark1, mark2, mark3, mark4, mark5; // Variables for 5 subject marks
int total; // Variable to store the total marks
float average; // Variable to store the average
// Taking input for each subject's marks
clrscr();
printf("Enter marks for 5 subjects:\n");
printf("Subject 1: ");
scanf("%d", &mark1);
printf("Subject 2: ");
scanf("%d", &mark2);
printf("Subject 3: ");
scanf("%d", &mark3);
printf("Subject 4: ");
scanf("%d", &mark4);
printf("Subject 5: ");
scanf("%d", &mark5);
// Calculating total
total = mark1 + mark2 + mark3 + mark4 + mark5;
// Calculating average
average = total / 5.0; // Ensuring float division by using 5.0
// Displaying the results
printf("Total Marks: %d\n", total);
printf("Average Marks: %.2f\n", average);
}
WEEK 5
Objective: Explore the full scope of different variants of “if construct” namely if-else, null-
else, if-else if*-else, switch and nested-if including in what scenario each one of them can
be used and how to use them. Explore all relational and logical operators while writing
conditionals for “if construct”.
Suggested Experiments/Activities:
Tutorial 5: Branching and logical expressions:
Lab 5: Problems involving if-then-else structures.
i) Write a C program to find the max and min of four numbers using if-else.
#include <stdio.h>
#nclude <conio.h>
void main() {
int num1, num2, num3, num4;
int max, min;
clrscr();
// Taking input for 4 numbers
printf("Enter four numbers:\n");
printf("Number 1: ");
scanf("%d", &num1);
printf("Number 2: ");
scanf("%d", &num2);
printf("Number 3: ");
scanf("%d", &num3);
printf("Number 4: ");
scanf("%d", &num4);
// Finding the maximum using if-else
max = num1; // Assume num1 is the max initially
if (num2 > max) {
max = num2;
}
if (num3 > max) {
max = num3;
}
if (num4 > max) {
max = num4;
}
// Finding the minimum using if-else
min = num1; // Assume num1 is the min initially
if (num2 < min) {
min = num2;
}
if (num3 < min) {
min = num3;
}
if (num4 < min) {
min = num4;
}
// Displaying the results
printf("Maximum number: %d\n", max);
printf("Minimum number: %d\n", min);
}
ii) Write a C program to generate electricity bill.
#include <stdio.h>
#nclude <conio.h>
void main() {
int units;
float bill = 0.0;
const float meter_charge = 50.0; // Fixed meter charge
clrscr();
// Taking input for the number of units consumed
printf("Enter the number of units consumed: ");
scanf("%d", &units);
// Calculating the bill according to the tariff slab
if (units <= 100) {
bill = units * 1.50; // For the first 100 units
} else if (units <= 200) {
bill = (100 * 1.50) + ((units - 100) * 2.00); // For the next 100 units
} else if (units <= 300) {
bill = (100 * 1.50) + (100 * 2.00) + ((units - 200) * 3.00); // For the next 100 units
} else {
bill = (100 * 1.50) + (100 * 2.00) + (100 * 3.00) + ((units - 300) * 5.00); // Above
300 units
}
// Adding the fixed meter charge
bill += meter_charge;
// Displaying the total bill
printf("Electricity Bill: ₹%.2f\n", bill);
}
iii) Find the roots of the quadratic equation.
#include <stdio.h>
#nclude <conio.h>
#include <math.h> // For sqrt() function
void main() {
float a, b, c;
float discriminant, root1, root2, realPart, imaginaryPart;
clrscr();
// Taking input for coefficients a, b, and c
printf("Enter coefficients a, b, and c: ");
scanf("%f %f %f", &a, &b, &c);
// Calculating discriminant
discriminant = b * b - 4 * a * c;
// Checking the nature of the roots using the discriminant
if (discriminant > 0) {
// Real and distinct roots
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Roots are real and distinct.\n");
printf("Root 1 = %.2f\n", root1);
printf("Root 2 = %.2f\n", root2);
} else if (discriminant == 0) {
// Real and equal roots
root1 = -b / (2 * a);
printf("Roots are real and equal.\n");
printf("Root 1 = Root 2 = %.2f\n", root1);
} else {
// Complex roots
realPart = -b / (2 * a);
imaginaryPart = sqrt(-discriminant) / (2 * a);
printf("Roots are complex and imaginary.\n");
printf("Root 1 = %.2f + %.2fi\n", realPart, imaginaryPart);
printf("Root 2 = %.2f - %.2fi\n", realPart, imaginaryPart);
}
}
iv) Write a C program to simulate a calculator using switch case.
#include <stdio.h>
#nclude <conio.h>
void main() {
char operator;
float num1, num2, result;
clrscr():
// Taking input for the operator and two numbers
printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &operator);
printf("Enter two numbers: ");
scanf("%f %f", &num1, &num2);
// Switch case to perform the operation
switch (operator) {
case '+':
result = num1 + num2;
printf("%.2f + %.2f = %.2f\n", num1, num2, result);
break;
case '-':
result = num1 - num2;
printf("%.2f - %.2f = %.2f\n", num1, num2, result);
break;
case '*':
result = num1 * num2;
printf("%.2f * %.2f = %.2f\n", num1, num2, result);
break;
case '/':
if (num2 != 0) { // Check for division by zero
result = num1 / num2;
printf("%.2f / %.2f = %.2f\n", num1, num2, result);
} else {
printf("Error! Division by zero is not allowed.\n");
}
break;
default:
printf("Error! Invalid operator.\n");
}
}
v) Write a C program to find the given year is a leap year or not.
#include <stdio.h>
#nclude <conio.h>
void main() {
int year;
clrscr();
// Taking input for the year
printf("Enter a year: ");
scanf("%d", &year);
// Checking if the year is a leap year
if (year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0) {
printf("%d is a leap year.\n", year); // Divisible by 400, so it's a leap year
} else {
printf("%d is not a leap year.\n", year); // Divisible by 100 but not by 400
}
} else {
printf("%d is a leap year.\n", year); // Divisible by 4 but not by 100
}
} else {
printf("%d is not a leap year.\n", year); // Not divisible by 4
}
}
WEEK 6
Objective: Explore the full scope of iterative constructs namely while loop, do-while loop
and for loop in addition to structured jump constructs like break and continue including
when each of these statements is more appropriate to use.
Suggested Experiments/Activities:
Tutorial 6: Loops, while and for loops
Lab 6: Iterative problems e.g., the sum of series
i) Find the factorial of given number using any loop.
#include <stdio.h>
#include<conio.h>
void main() {
int num, i;
unsigned long long factorial = 1; // Using unsigned long long to handle large factorials
clrscr();
// Taking input for the number
printf("Enter a number: ");
scanf("%d", &num);
// Factorial is not defined for negative numbers
if (num < 0) {
printf("Factorial of a negative number is not defined.\n");
} else {
// Calculating factorial using for loop
for (i = 1; i <= num; ++i) {
factorial *= i; // Multiply each number from 1 to num
}
// Displaying the result
printf("Factorial of %d = %llu\n", num, factorial);
}
}
ii) Find the given number is a prime or not.
#include <stdio.h>
#include <conio.h>
void main() {
int num, i, isPrime = 1; // isPrime is used as a flag variable
clrscr();
// Taking input for the number
printf("Enter a number: ");
scanf("%d", &num);
// Prime number check
if (num <= 1) {
// Numbers less than or equal to 1 are not prime
printf("%d is not a prime number.\n", num);
} else {
// Check divisibility from 2 to sqrt(num) (optimization)
for (i = 2; i * i <= num; i++) {
if (num % i == 0) {
isPrime = 0; // Set flag to 0 if number is divisible by i
break;
}
}
// Output result based on the flag
if (isPrime) {
printf("%d is a prime number.\n", num);
} else {
printf("%d is not a prime number.\n", num);
}
}
}
iii) Compute sine and cos series (Taylor Series Expansion)
#include <stdio.h>
#include <math.h> // For pow() and comparison with built-in functions
#include <conio.h>
void main() {
double x; // Angle in radians
int terms, i, j, power; // Number of terms in the series
double sinx = 0.0, cosx = 0.0; // Results
double term; // Intermediate term value
unsigned long long fact = 1; // Factorial value
// Taking input for the angle in radians and number of terms
printf("Enter the angle in radians: ");
scanf("%lf", &x);
printf("Enter the number of terms for the series: ");
scanf("%d", &terms);
// Calculate sine using Taylor series
for (int i = 0; i < terms; i++) {
power = 2 * i + 1; // Powers of x: 1, 3, 5, 7, ...
fact = 1; // Reset factorial for each term
// Compute factorial for the current term
for (j = 1; j <= power; j++) {
fact *= j;
}
term = pow(x, power) / fact; // x^power / power!
if (i % 2 == 0)
sinx += term; // Positive term
else
sinx -= term; // Negative term
}
// Calculate cosine using Taylor series
for (i = 0; i < terms; i++) {
power = 2 * i; // Powers of x: 0, 2, 4, 6, ...
fact = 1; // Reset factorial for each term
WEEK 7:
Objective: Explore the full scope of Arrays construct namely defining and initializing 1-D and
2-D and more generically n-D arrays and referencing individual array elements from the defined
array. Using integer 1-D arrays, explore search solution linear search.
Suggested Experiments/Activities:
Tutorial 7: 1 D Arrays: searching.
Lab 7:1D Array manipulation, linear search
i) Find the min and max of a 1-D integer array.
ii) Perform linear search on 1D array.
iii) The reverse of a 1D integer array
iv) Find 2’s complement of the given binary number.
v) Eliminate duplicate elements in an array.
int main() {
int arr[] = {4, 7, 1, 9, 3};
int n = sizeof(arr) / sizeof(arr[0]);
int min = arr[0], max = arr[0];
return 0;
}
ii) Perform linear search on 1D array.
#include <stdio.h>
int main() {
int arr[] = {4, 7, 1, 9, 3};
int n = sizeof(arr) / sizeof(arr[0]);
int search = 7;
int found = 0;
if (!found) {
printf("Element not found\n");
}
return 0;
}
iii) The reverse of a 1D integer array
#include <stdio.h>
int main() {
int arr[] = {4, 7, 1, 9, 3};
int n = sizeof(arr) / sizeof(arr[0]);
return 0;
}
iv) Find 2’s complement of the given binary number.
#include <stdio.h>
int main() {
int binary[] = {1, 0, 1, 0}; // Example binary number 1010
int n = sizeof(binary) / sizeof(binary[0]);
int carry = 1;
return 0;
}
v) Eliminate duplicate elements in an array.
#include <stdio.h>
int main() {
int arr[] = {4, 7, 1, 9, 4, 1};
int n = sizeof(arr) / sizeof(arr[0]);
int result[n];
int result_size = 0;
return 0;
}
WEEK 8:
Objective: Explore the difference between other arrays and character arrays that can be used as
Strings by using null character and get comfortable with string by doing experiments that will
reverse a string and concatenate two strings. Explore sorting solution bubble sort using integer
arrays.
Suggested Experiments/Activities:
Tutorial 8: 2 D arrays, sorting and Strings.
Lab 8: Matrix problems, String operations, Bubble sort
i) Addition of two matrices
#include <stdio.h>
int main() {
int a[2][2] = {{1, 2}, {3, 4}};
int b[2][2] = {{5, 6}, {7, 8}};
int sum[2][2];
printf("Sum of matrices:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", sum[i][j]);
}
printf("\n");
}
return 0;
}
ii) Multiplication two matrices
#include <stdio.h>
int main() {
int a[2][2] = {{1, 2}, {3, 4}};
int b[2][2] = {{5, 6}, {7, 8}};
int product[2][2] = {0};
printf("Product of matrices:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", product[i][j]);
}
printf("\n");
}
return 0;
}
iii) Sort array elements using bubble sort
#include <stdio.h>
int main() {
int arr[] = {5, 1, 4, 2, 8};
int n = sizeof(arr) / sizeof(arr[0]);
return 0;
}
iv) Concatenate two strings without built-in functions
#include <stdio.h>
int main() {
char str1[50] = "Hello, ";
char str2[] = "World!";
int i = 0, j = 0;
return 0;
}
v) Reverse a string using built-in and without built-in string functions
#include <stdio.h>
int main() {
char str[] = "Hello";
int n = 0;
return 0;
}
UNIT IV
WEEK9:
Objective: Explore pointers to manage a dynamic array of integers, including memory
allocation & value initialization, resizing changing and reordering the contents of an array
and memory de-allocation using malloc (), calloc (), realloc () and free () functions. Gain
experience processing command-line arguments received by C
Suggested Experiments/Activities:
Tutorial 9: Pointers, structures and dynamic memory allocation
Lab 9: Pointers and structures, memory dereference.
i) Write a C program to find the sum of a 1D array using malloc()
#include <stdio.h>
#include <stdlib.h>
void main() {
int n, i;
int *arr;
int sum = 0;
// Prompt user for the number of elements
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
// Allocate memory for the array using malloc
arr = (int *)malloc(n * sizeof(int));
printf("Student Details:\n");
for (int i = 0; i < n; i++) {
char *name = argv[1 + 2 * i];
int marks = atoi(argv[2 + 2 * i]); // Convert marks to integer
return 0;
}
v) Write a C program to implement realloc()
#include <stdio.h>
#include <stdlib.h>
void main() {
int *arr;
int initialSize, newSize, i;
// Input the initial size of the array
printf("Enter the initial size of the array: ");
scanf("%d", &initialSize);
// Allocate memory using malloc
arr = (int *)malloc(initialSize * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
// Input elements into the array
printf("Enter %d elements:\n", initialSize);
for (i = 0; i < initialSize; i++) {
scanf("%d", &arr[i]);
}
// Display the current elements
printf("Elements in the array: ");
for (i = 0; i < initialSize; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// Input the new size of the array
printf("Enter the new size of the array: ");
scanf("%d", &newSize);
// Reallocate memory using realloc
arr = (int *)realloc(arr, newSize * sizeof(int));
if (arr == NULL) {
printf("Memory reallocation failed!\n");
return 1;
}
// If the array size is increased, input new elements
if (newSize > initialSize) {
printf("Enter %d more elements:\n", newSize - initialSize);
for (i = initialSize; i < newSize; i++) {
scanf("%d", &arr[i]);
}
}
// Display the updated array
printf("Updated array elements: ");
for (i = 0; i < newSize; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// Free the allocated memory
free(arr);
}
WEEK 10:
Objective: Experiment with C Structures, Unions, bit fields and self-referential structures
(Singly linked lists) and nested structures
Suggested Experiments/Activities:
Tutorial 10: Bitfields, Self-Referential Structures, Linked lists
Lab10 : Bitfields, linked lists
Read and print a date using dd/mm/yyyy format using bit-fields and differentiate the same
without using bit- fields
i) Create and display a singly linked list using self-referential structure.
#include <stdio.h>
#include <stdlib.h>
WEEK 11:
Objective: Explore the Functions, sub-routines, scope and extent of variables, doing some
experiments by parameter passing using call by value. Basic methods of numerical integration
Suggested Experiments/Activities:
Tutorial 11: Functions, call by value, scope and extent,
Lab 11: Simple functions using call by value, solving differential equations using Eulers
theorem.
i) Write a C function to calculate NCR value.
ii) Write a C function to find the length of a string.
iii) Write a C function to transpose of a matrix.
iv) Write a C function to demonstrate numerical integration of differential equations using Euler’s
method
WEEK 12:
Objective: Explore how recursive solutions can be programmed by writing recursive functions
that can be invoked from the main by programming at-least five distinct problems that have
naturally recursive solutions.
Suggested Experiments/Activities:
Tutorial 12: Recursion, the structure of recursive calls
Lab 12: Recursive functions
i) Write a recursive function to generate Fibonacci series.
ii) Write a recursive function to find the lcm of two numbers.
iii) Write a recursive function to find the factorial of a number.
iv) Write a C Program to implement Ackermann function using recursion.
v) Write a recursive function to find the sum of series.
WEEK 13:
Objective: Explore the basic difference between normal and pointer variables, Arithmetic
operations using pointers and passing variables to functions using pointers
Suggested Experiments/Activities:
Tutorial 13: Call by reference, dangling pointers
Lab 13: Simple functions using Call by reference, Dangling pointers.
i) Write a C program to swap two numbers using call by reference.
ii) Demonstrate Dangling pointer problem using a C program.
iii) Write a C program to copy one string into another using pointer.
iv) Write a C program to find no of lowercase, uppercase, digits and other
characters using pointers.
WEEK14:
Objective: To understand data files and file handling with various file I/O functions. Explore the
differences between text and binary files.
Suggested Experiments/Activities:
Tutorial 14: File handling
Lab 14: File operations
i) Write a C program to write and read text into a file.
ii) Write a C program to write and read text into a binary file using fread() and
fwrite()
iii) Copy the contents of one file to another file.
iv) Write a C program to merge two files into the third file using command-line
arguments.
v) Find no. of lines, words and characters in a file
vi) Write a C program to print last n characters of a given file.
Textbooks:
1. Ajay Mittal, Programming in C: A practical approach, Pearson.
2. Byron Gottfried, Schaum' s Outline of Programming with C, McGraw Hill
Reference Books:
1. Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, Prentice-
Hall of India
2. C Programming, A Problem-Solving Approach, Forouzan, Gilberg, Prasad, CENGAGE