0% found this document useful (0 votes)
16 views43 pages

Lab Manual Computer Programming Lab (1)

Thats it anthe ra huka
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
16 views43 pages

Lab Manual Computer Programming Lab (1)

Thats it anthe ra huka
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 43

L T P C

0 0 3 1.5

COMPUTER PROGRAMMING LAB


(Common to All branches of Engineering)

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 2: Problem-solving using Algorithms and Flow charts.
Lab 1: Converting algorithms/flow charts into C Source code.
Developing the algorithms/flowcharts for the following sample programs
i) Sum and average of 3 numbers
#include <stdio.h>
#include <conio.h>
void main() {
8
ii) Conversion of Fahrenheit to Celsius and vice versa
#include <stdio.h>
#include<conio.h>
void main() {
float fahrenheit, celsius;
clrscr();
// Input Fahrenheit temperature
printf("Enter temperature in Fahrenheit: ");
scanf("%f", &fahrenheit);
// Convert Fahrenheit to Celsius
celsius = (fahrenheit - 32.0) * 5.0 / 9.0;
// Output Celsius temperature
printf("Temperature in Celsius: %.2f\n", celsius);
// Convert Celsius back to Fahrenheit
fahrenheit = (celsius * 9.0 / 5.0) + 32.0;
// Output Fahrenheit temperature
printf("Temperature in Fahrenheit: %.2f\n", fahrenheit);
return 0;
}

iii) Simple interest calculation


#include <stdio.h>
#include <conio,h>
void main() {
float principal, rate, time, interest;
clrscr();
// Input principal amount, rate, and time
printf("Enter principal amount (in dollars): ");
scanf("%f", &principal);
printf("Enter annual interest rate (as a percentage): ");
scanf("%f", &rate);
printf("Enter time (in years): ");
scanf("%f", &time);
// Calculate simple interest
interest = (principal * rate * time) / 100.0;
// Output the result
printf("Simple Interest: $%.2f\n", interest);
}
WEEK 3
Objective: Learn how to define variables with the desired data-type, initialize them with
appropriate values and how arithmetic operators can be used with variables and constants.

Suggested Experiments/Activities:
Tutorial 3: Variable types and type conversions:

Lab 3: Simple computational problems using arithmetic expressions.


i) Finding the square root of a given number

#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);

printf("Enter rate: ");


scanf("%lf", &rate);

printf("Enter time (in years): ");


scanf("%lf", &time);

// Calculate compound interest


amount = principal * pow((1 + rate / 100), time);
compound_interest = amount - principal;

// Output the result


printf("Compound Interest: %.6lf\n", compound_interest);

}
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));

printf("Area of the triangle: %.6f\n", area);

iv) Distance travelled by an object


#include <stdio.h>
#include <math.h>
#include <conio.h>
void main() {
float u, t, a, s;
clrscr();
printf("Enter initial velocity (u): ");
scanf("%f", &u);

printf("Enter time taken (t): ");


scanf("%f", &t);

printf("Enter acceleration (a): ");


scanf("%f", &a);

// Calculate the distance traveled


s = u * t + 0.5 * a * pow(t, 2);

printf("Distance traveled: %.6f\n", s);

}
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:

Tutorial4: Operators and the precedence and as associativity:


Lab4: Simple computational problems using the operator’ precedence and associativity
i) Evaluate the following expressions.
a. A+B*C+(D*E) + F*G
b. A/B*C-B+A*D/3
c. A+++B---A
d. J= (i++) + (++i)
#include <stdio.h>
#include <conio.h>
void main() {
float a,b,c,d,e,f,g,res;
clrscr();
printf("\nEnter a, b, c, d, e, f, g values");
scanf("%f%f%f%f%f%f%f",&a,&b,&c,&d,&e,&f,&g);
res=a+b*c+(d*e)+f*g;
printf("\nresult of expression = %f",res);
res=a/b*c-b+a*d/3;
printf("\nresult of expression = %f",res);
res=a+++b---a;
printf("\nresult of expression = %f",res);
res=(a++) + (++a);
printf("\nresult of expression = %f",res);

}
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

// 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)
cosx += term; // Positive term
else
cosx -= term; // Negative term
}
// Displaying the results
printf("Sine(%lf) using series: %lf\n", x, sinx);
printf("Cosine(%lf) using series: %lf\n", x, cosx);
// Comparing with built-in sin() and cos() functions from math.h
printf("Sine(%lf) using built-in function: %lf\n", x, sin(x));
printf("Cosine(%lf) using built-in function: %lf\n", x, cos(x));
}
iv) Checking a number palindrome
#include <stdio.h>
#include <conio.h>
void main() {
int num, originalNum, reversedNum = 0, remainder;
clrscr();
// Taking input for the number
printf("Enter an integer: ");
scanf("%d", &num);
originalNum = num; // Store the original number
// Reversing the number
while (num != 0) {
remainder = num % 10; // Get the last digit
reversedNum = reversedNum * 10 + remainder; // Append last digit to
reversedNum
num /= 10; // Remove the last digit from num
}
// Checking if the original number is equal to the reversed number
if (originalNum == reversedNum) {
printf("%d is a palindrome.\n", originalNum);
} else {
printf("%d is not a palindrome.\n", originalNum);
}
}
v) Construct a pyramid of numbers.
#include <stdio.h>
#include <conio.h>
void main() {
int i, j, k, levels;
// Taking input for the number of levels
printf("Enter the number of levels for the pyramid: ");
scanf("%d", &levels);
// Constructing the pyramid
for (i = 1; i <= levels; i++) {
// Print leading spaces
for (j = i; j < levels; j++) {
printf(" ");
}
// Print numbers in increasing order
for (k = 1; k <= i; k++) {
printf("%d ", k);
}
// Move to the next line
printf("\n");
}
}
vi) Construct a pascals triangle .
#include <stdio.h>
#include <conio.h>
void main() {
int rows;
clrscr();
// Taking input for the number of rows
printf("Enter the number of rows for Pascal's Triangle: ");
scanf("%d", &rows);
// Constructing Pascal's Triangle
for (int i = 0; i < rows; i++) {
// Print leading spaces for formatting
for (int j = 0; j < rows - i - 1; j++) {
printf(" ");
}
// Calculate and print numbers in the current row
int value = 1; // Initialize value for the first element in the row
for (int j = 0; j <= i; j++) {
printf("%d ", value);
// Update value to the next binomial coefficient
// value = value * (i - j) / (j + 1);
value = value * (i - j) / (j + 1);
}
// Move to the next line
printf("\n");
}
}
UNIT III

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.

i) Find the min and max of a 1-D integer array.


#include <stdio.h>

int main() {
int arr[] = {4, 7, 1, 9, 3};
int n = sizeof(arr) / sizeof(arr[0]);
int min = arr[0], max = arr[0];

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


if (arr[i] < min) {
min = arr[i];
}
if (arr[i] > max) {
max = arr[i];
}
}

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


printf("Maximum: %d\n", max);

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;

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


if (arr[i] == search) {
printf("Element %d found at index %d\n", search, i);
found = 1;
break;
}
}

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]);

printf("Original array: ");


for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}

// Reverse the array


for (int i = 0; i < n / 2; i++) {
int temp = arr[i];
arr[i] = arr[n - i - 1];
arr[n - i - 1] = temp;
}

printf("\nReversed array: ");


for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}

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;

// Invert the bits (1's complement)


for (int i = 0; i < n; i++) {
binary[i] = binary[i] == 0 ? 1 : 0;
}

// Add 1 to find the 2's complement


for (int i = n - 1; i >= 0; i--) {
if (binary[i] == 0 && carry == 1) {
binary[i] = 1;
carry = 0;
break;
} else if (binary[i] == 1 && carry == 1) {
binary[i] = 0;
}
}

printf("2's complement: ");


for (int i = 0; i < n; i++) {
printf("%d", binary[i]);
}
printf("\n");

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;

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


int is_duplicate = 0;
for (int j = 0; j < result_size; j++) {
if (arr[i] == result[j]) {
is_duplicate = 1;
break;
}
}
if (!is_duplicate) {
result[result_size++] = arr[i];
}
}

printf("Array after removing duplicates: ");


for (int i = 0; i < result_size; i++) {
printf("%d ", result[i]);
}
printf("\n");

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];

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


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

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};

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


for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
product[i][j] += a[i][k] * b[k][j];
}
}
}

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]);

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


for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}

printf("Sorted array: ");


for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");

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;

// Move to the end of str1


while (str1[i] != '\0') {
i++;
}

// Concatenate str2 to str1


while (str2[j] != '\0') {
str1[i] = str2[j];
i++;
j++;
}
str1[i] = '\0';

printf("Concatenated string: %s\n", str1);

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;

// Find the length of the string


while (str[n] != '\0') {
n++;
}

// Reverse the string


for (int i = 0; i < n / 2; i++) {
char temp = str[i];
str[i] = str[n - i - 1];
str[n - i - 1] = temp;
}

printf("Reversed string: %s\n", str);

return 0;
}
UNIT IV

WEEK9:
Objective: Explore pointers to manage a dynamic array of integers, including memory
allocation &amp; 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));

// Check if memory allocation was successful


if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
// Input elements into the array
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Calculate the sum of the array elements


for (i = 0; i < n; i++) {
sum += arr[i];
}
// Display the sum
printf("The sum of the array elements is: %d\n", sum);

// Free the allocated memory


free(arr);
}
ii) Write a C program to find the total, average of n students using structures
#include <stdio.h>

// Define a structure to hold student data


struct Student {
char name[50];
int marks;
};
void main() {
int n, i;
float total = 0, average;

// Prompt the user for the number of students


printf("Enter the number of students: ");
scanf("%d", &n);

// Declare an array of structures to hold data for all students


struct Student students[n];

// Input student details


for (i = 0; i < n; i++) {
printf("\nEnter details for student %d:\n", i + 1);
printf("Name: ");
scanf(" %[^\n]s", students[i].name); // Read string with spaces
printf("Marks: ");
scanf("%d", &students[i].marks);

// Add marks to the total


total += students[i].marks;
}

// Calculate the average


average = total / n;

// Output the total and average


printf("\nTotal Marks: %.2f\n", total);
printf("Average Marks: %.2f\n", average);

// Display student details


printf("\nStudent Details:\n");
for (i = 0; i < n; i++) {
printf("Name: %s, Marks: %d\n", students[i].name, students[i].marks);
}
}
iii) Enter n students data using calloc() and display failed students list
#include <stdio.h>
#include <stdlib.h>
// Define a structure to hold student data
struct Student {
char name[50];
int marks;
};
void main() {
int n, i;
struct Student *students;
// Prompt the user for the number of students
printf("Enter the number of students: ");
scanf("%d", &n);
// Allocate memory for students using calloc
students = (struct Student *)calloc(n, sizeof(struct Student));
// Check if memory allocation was successful
if (students == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
// Input student details
for (i = 0; i < n; i++) {
printf("\nEnter details for student %d:\n", i + 1);
printf("Name: ");
scanf(" %[^\n]s", students[i].name); // Read string with spaces
printf("Marks: ");
scanf("%d", &students[i].marks);
}
// Display failed students
printf("\nList of failed students (marks < 40):\n");
int failedCount = 0;
for (i = 0; i < n; i++) {
if (students[i].marks < 40) {
printf("Name: %s, Marks: %d\n", students[i].name, students[i].marks);
failedCount++;
}
}
if (failedCount == 0) {
printf("No students have failed.\n");
}

// Free the allocated memory


free(students);
}
iv) Read student name and marks from the command line and display the student details along with
the total.
#include <stdio.h>
#include <stdlib.h>

void main(int argc, char *argv[]) {


if (argc < 3 || (argc - 1) % 2 != 0) {
printf("Usage: %s <name1> <marks1> <name2> <marks2> ...\n", argv[0]);
return 1;
}

int n = (argc - 1) / 2; // Number of students


int total = 0;

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

printf("Name: %s, Marks: %d\n", name, marks);


total += marks;
}

printf("\nTotal Marks: %d\n", total);

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>

// Define the structure for a node


struct Node {
int data;
struct Node *next; // Self-referential pointer
};
// Function to create a new node
struct Node *createNode(int data) {
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed!\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to display the linked list
void displayList(struct Node *head) {
struct Node *current = head;
printf("Linked List: ");
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}
int main() {
struct Node *head = NULL, *temp = NULL, *newNode = NULL;
int n, i, data;

// Input the number of nodes


printf("Enter the number of nodes: ");
scanf("%d", &n);
// Create the linked list
for (i = 0; i < n; i++) {
printf("Enter data for node %d: ", i + 1);
scanf("%d", &data);
// Create a new node
newNode = createNode(data);
// Link the new node to the list
if (head == NULL) {
head = newNode; // First node
} else {
temp->next = newNode; // Append to the last node
}
temp = newNode; // Move temp to the new node
}
// Display the linked list
displayList(head);
return 0;
}
ii) Demonstrate the differences between structures and unions using a C program.
#include <stdio.h>
#include <string.h>
// Define a structure
struct Student {
char name[20];
int age;
float marks;
};
// Define a union
union Data {
char name[20];
int age;
float marks;
};
void main() {
// Declare and initialize a structure
struct Student s;
strcpy(s.name, "Alice");
s.age = 20;
s.marks = 85.5;
// Declare and initialize a union
union Data d;
strcpy(d.name, "Alice");
d.age = 20;
d.marks = 85.5;
// Display structure data
printf("Structure:\n");
printf("Name: %s\n", s.name);
printf("Age: %d\n", s.age);
printf("Marks: %.2f\n", s.marks);
// Display union data
printf("\nUnion:\n");
strcpy(d.name, "Alice");
printf("Name: %s\n", d.name);
d.age = 20; // Overwrites previous data
printf("Age: %d\n", d.age);
d.marks = 85.5; // Overwrites previous data
printf("Marks: %.2f\n", d.marks);
printf("\nSize of Structure: %lu bytes\n", sizeof(s));
printf("Size of Union: %lu bytes\n", sizeof(d));
}
iii) Write a C program to copy one structure variable to another structure of the same type.
#include <stdio.h>
#include <string.h>
// Define a structure
struct Student {
char name[50];
int age;
float marks;
};
void main() {
// Declare and initialize a structure variable
struct Student student1, student2;
// Input data for student1
printf("Enter the details of student1:\n");
printf("Name: ");
scanf(" %[^\n]s", student1.name);
printf("Age: ");
scanf("%d", &student1.age);
printf("Marks: ");
scanf("%f", &student1.marks);
// Copy the contents of student1 to student2
student2 = student1;
// Display the data of student2
printf("\nDetails of student2 (copied from student1):\n");
printf("Name: %s\n", student2.name);
printf("Age: %d\n", student2.age);
printf("Marks: %.2f\n", student2.marks);
}
UNIT V

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&#39; 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

You might also like