2024-Updated As Per Rules-C Programming Lab Manual

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 58

Fundamentals of C Programming Lab Course Code: B24CS0108

SCHOOL
OF
COMPUTER SCIENCE
AND
ENGINEERING

Fundamentals of C Programming Lab


B24CI0110

First Semester
AY-2024-245

School of Computer Science and Engineering Page 1


Fundamentals of C Programming Lab Course Code: B24CS0108

INDEX
SL. No Contents Page. no

1 Lab Objectives 3

2 Lab Outcomes 3

3 Lab Requirements 3

4 Guidelines to Students 4

5 List of Lab Exercises 6

6 Lab Exercises’ Solutions: 7


LAB EXERCISES

Session – 1: Lab Exercise 7

Session – 2: Lab Exercise 10

Session – 3: Lab Exercise 13

Session – 4: Lab Exercise 15

Session – 5: Lab Exercise 17

Session – 6: Lab Exercise 19

Session – 7: Lab Exercise 23

Session – 8: Lab Exercise 25

Session – 9: Lab Exercise 26

Session – 10: Lab Exercise 31

Session – 11: Lab Exercise 35

Session – 12: Lab Exercise 38

School of Computer Science and Engineering Page 2


Fundamentals of C Programming Lab Course Code: B24CS0108

School of Computer Science and Engineering Page 3


Fundamentals of C Programming Lab Course Code: B24CS0108

1. Lab Objectives:

The objectives of this course are to


 Master in C programming fundamentals including syntax, data types, operators,
control flow statements, functions, and pointers.
 Implement and utilize fundamental data structures such as arrays, structures,
unions, linked lists, stacks, queues, and trees.
 Design and implement algorithms for searching, sorting, and other
computational problems.
 Develop programs that interact with users through input/output operations.
 Develop effective debugging strategies to identify and correct errors in C
programs.
 Develop applications that solve practical real world problems using C
programming

2. Lab Outcomes:

On successful completion of this course:

CO# Course Outcomes POs PSOs


1, 2, 3 1,3
CO1 Students will be able to analyze problems, design algorithms, and
implement solutions effectively using C programming.
Students will demonstrate proficiency in using C language features 1, 3 1,3
CO2 including data types, operators, control flow, functions, arrays,
pointers, structures, and unions.
Students will implement and apply various data structures like arrays 1, 2, 3 2,3
CO3 and algorithms (searching, sorting, etc.) to solve computational
problems
Students will be able to identify, locate, and correct errors in C 2,3,4 1,2
CO4 programs efficiently.
Students will be able to develop C programs to solve practical 1,2,3,5 1,2
CO5 problems in various domains and Students will demonstrate the
ability to translate real-world requirements into C code.

3. Lab Requirements:

The following are the required hardware and software for this lab.

Hardware Requirements: A standard personal computer or laptop with the following


minimum specifications:
1. Processor: Any modern multi-core processor (e.g., Intel Core i5 or AMD Ryzen
series).

School of Computer Science and Engineering Page 4


Fundamentals of C Programming Lab Course Code: B24CS0108

2. RAM: At least 4 GB of RAM for basic programs; 8 GB or more is


recommended for larger data structures and complex algorithms.
3. Storage: A few gigabytes of free disk space for the development environment
and program files.
4. Display: A monitor with a resolution of 1024x768 or higher is recommended for
comfortable coding.
5. Input Devices: Keyboard and mouse (or other input devices) for coding
and interacting with the development environment.

Software Requirements:

1. Operating System: You can develop and execute C programs for


Algorithms Lab on various operating systems, including Windows,
macOS, and Linux.
2. Text Editor or Integrated Development Environment (IDE):
 Text Editor: You can use a simple text editor like Notepad (Windows),
Nano (Linux/macOS), or any code-oriented text editor like Visual
Studio Code, Sublime Text, or Atom.
 IDE: Consider using a C/C++ integrated development environment
like Code: Blocks, Dev-C++, or Eclipse CDT for a more feature-rich
coding experience.
3. C - Compiler:
 To compile and execute C programs, you need a C compiler. GCC
(GNU Compiler Collection) is a popular choice for Linux and macOS.
 For Windows, you can use MinGW (Minimalist GNU for Windows)
with GCC or Visual C++ from Microsoft if you prefer a Microsoft
development environment.

4. Guidelines to Students:

 Equipment in the lab for the use of the student community. Students
need to maintain a proper decorum in the computer lab. Students must
use the equipment with care. Any damage caused is punishable.
 Students are required to carry their observation / programs book with
completed exercises while entering the lab.
 Students are supposed to occupy the machines allotted to them and are
not supposed to talk or make noise in the lab. The allocation is put up on
the lab notice board.
 The lab can be used in free time / lunch hours by the students who need
to use the systems should get prior permission from the lab in-charge.
 Lab records need to be submitted on or before the date of submission.

School of Computer Science and Engineering Page 5


Fundamentals of C Programming Lab Course Code: B24CS0108

 Students are not supposed to use flash drives.

School of Computer Science and Engineering Page 6


Fundamentals of C Programming Lab Course Code: B24CS0108

Practice
Here are some key activities involved in the design and analysis of algorithms:

 Problem Understanding: The first step is to clearly understand the


problem at hand. This involves identifying the input, output, constraints,
and any specific requirements.

 Algorithm Design: Once the problem is understood, the next step is to


design an algorithm to solve it. This involves creating a step-by-step
procedure or a set of rules that outlines how the problem can be solved.

 Algorithm Implementation: Once the algorithm design is finalized and its


correctness is established, the next step is to implement the algorithm in
a C Programming language. This involves translating the algorithm
into C Program code.

 Experimental Analysis: To validate the algorithm's performance in


practice, experimental analysis can be conducted. This involves running
the C Program code on various inputs and observe the corresponding
output by measuring its running time, memory usage, and other relevant
metrics. The results can be compared with the theoretical analysis to
verify the algorithm's efficiency.

School of Computer Science and Engineering Page 7


Fundamentals of C Programming Lab Course Code: B24CS0108

5. List of Lab Exercise:


Sl.N Program Pag
o e No
1 Write a C program using switch statement to design a basic calculator that 7
performs the basic operations such as addition, subtraction, multiplication,
and division.
2 A quadratic equation as an equation of degree 2, meaning that the highest 10
exponent of this function is 2. Write a C program to find the coefficients of a
quadratic equation and compute its roots.
3 Develop a C Program to find the largest among two and three different 13
numbers entered by the user.
4 A leap year is a calendar year that contains an additional day compared to a 15
common year. Design and develop C program to check whether the given
year is leap year (or) not.
5 A palindrome is a word, sentence, verse, or even number that reads the 17
same backward or forward. Write a C program to check if a given number is
a Palindrome.
6 Write a program to display the following pattern. 19

7 Consider student’s marks in Computer Test. Write a C Program to display 23


the grade obtained by a student in Computer Test based on range of marks.
8 If a four-digit number is input through the keyboard, write a program to 25
obtain the sum of the first and last digit of this number.
9 In computer-based applications, matrices play a vital role in the projection 26
of three-dimensional image into a two-dimensional screen, creating the
realistic seeming motions. Write a C program using 2-dimensional array to
check for compatibility of two matrices and perform matrix Multiplication.
10 Write a C program to implement bubble sort with appropriate input and 31
output.
11 Write a C program to implement binary search with appropriate input and 35
output.
12 Develop a program using pointers to compute the sum, mean and standard 38
deviation of all elements stored in an array of N real numbers.

School of Computer Science and Engineering Page 8


Fundamentals of C Programming Lab Course Code: B24CS0108

6. Lab Exercise Solutions:

1. Write a C program using switch statement to design a basic calculator


that performs the basic operations such as addition, subtraction,
multiplication, and division.

Problem Statement:

Develop a C program that can perform the four fundamental arithmetic


operations (addition, subtraction, multiplication, and division) based on
user input. The program should prompt the user to enter two numbers
and an operator, then display the corresponding result.

Solution Overview:
1. Input:
o Prompt the user to enter two numbers.
o Prompt the user to enter an operator (e.g., '+', '-', '*', '/').
2. Processing:
o Use a switch statement to evaluate the operator:
 If the operator is '+', perform addition.
 If the operator is '-', perform subtraction.
 If the operator is '*', perform multiplication.
 If the operator is '/', perform division.
 If the operator is invalid, display an error message.
3. Output:
o Display the result of the calculation.

Intuition:

 The switch statement is a control flow structure that allows you to


execute different code blocks based on the value of an expression.
 By comparing the entered operator to different cases within the switch
statement, you can determine the appropriate arithmetic operation to
perform.

Algorithm:
Read input:
- Prompt the user to enter the first number (num1).
- Prompt the user to enter the operation code (operator).
- Prompt the user to enter the second number (num2).
Perform the operation using a switch statement:

School of Computer Science and Engineering Page 9


Fundamentals of C Programming Lab Course Code: B24CS0108

- Use a switch statement with `operator` as the controlling expression.


- For each case (+, -, *, /):
- Calculate the result based on the selected operation.
- Display the result.
Handle division by zero:
- For the division operation:
- Check if `num2` is not equal to zero.
- If true, perform the division and display the result.
- If false, display an error message for division by zero.

Code Implementation:
#include <stdio.h>
int main()
{
float num1, num2, result;
char operator;
printf("Enter two integer numbers: \n");
scanf("%f%f", &num1, &num2);
printf("Enter the operation (+, -, *, /): ");
scanf(" %c", &operator);

switch (operator)
{
case '+':
result = num1 + num2;
printf("Sum: %f\n", result);
break;
case '-':
result = num1 - num2;
printf("Difference: %f\n", result);
break;

School of Computer Science and Engineering Page 10


Fundamentals of C Programming Lab Course Code: B24CS0108

case '*':
result = num1 * num2;
printf("Product: %.2f\n", result);
break;

case '/':
// Check for division by zero
if (num2 != 0)
{
result = num1 / num2;
printf("Result: %.2f\n", result);
}
else
printf("Division by zero is not allowed.\n");

break;
default:
printf("Invalid operator\n");
break;
}
return 0;
}

Output:
Enter two integer numbers:
12
2
Enter the operation (+, -, *, /): +
Sum: 14.000000

School of Computer Science and Engineering Page 11


Fundamentals of C Programming Lab Course Code: B24CS0108

Enter two integer numbers:


10
0
Enter the operation (+, -, *, /): /
Division by zero is not allowed.

Enter two integer numbers:


12
4
Enter the operation (+, -, *, /): &
Invalid operator

Outcome of the Exercise:


This program provides a basic calculator functionality, allowing users to perform
addition, subtraction, multiplication, and division operations on two numbers. It also
handles the case of division by zero and provides appropriate error messages.

Viva questions and Answers:

1. What is the purpose of using a switch statement in this program?


 The switch statement is used to select different code blocks based on the
value of the operator entered by the user.
2. How does the switch statement work?
 The switch statement compares the expression (operator) with different
cases. If a match is found, the corresponding code block is executed.
3. What happens if the operator entered by the user is not one of the valid
cases?
 The default case is executed, which typically displays an error message.
4. How does the program handle division by zero?
 The division case should include a check for division by zero. If the
denominator is zero, an error message should be displayed.
5. Can you modify the program to handle more operators, such as
exponentiation or modulus?
 Yes, you can add more cases to the switch statement to handle additional
operators.
6. How can you make the program more user-friendly?
 You can provide clear prompts for user input, include error handling for
invalid input, and display informative messages.
7. What is the importance of operator precedence in this program?
 Operator precedence determines the order in which operations are
performed. If necessary, parentheses can be used to override the default
precedence.
8. Can you explain the concept of a switch statement in simpler terms?

School of Computer Science and Engineering Page 12


Fundamentals of C Programming Lab Course Code: B24CS0108

 A switch statement is like a decision-making structure that allows you to


choose between different options based on a given condition.
9. What are the advantages of using a switch statement over if-else statements
in this context?
 A switch statement can often be more readable and efficient than nested
if-else statements, especially when dealing with multiple comparison
cases.
10. Can you modify the program to handle floating-point numbers instead of
integers?
 Yes, you can modify the data types used in the program to handle floating-point
numbers.

2. A quadratic equation as an equation of degree 2, meaning that the


highest exponent of this function is 2. Write a C program to find the
coefficients of a quadratic equation and compute its roots. Write a C
program to find the coefficients of a quadratic equation and compute
its roots.
Problem Statement:
Write a C program to find the coefficients of a quadratic equation and
compute its roots. A quadratic equation is of the form ax^2 + bx + c = 0,
where a, b, and c are coefficients, and x is the unknown variable.

Solution Overview:

1. Input Coefficients:
 Prompt the user to enter the values for a, b, and c.
 Ensure that a is not zero, as it would result in a linear equation.
2. Calculate Discriminant:
 Compute the discriminant D using the formula D = b^2 - 4ac.
 The discriminant determines the nature of the roots:
 If D > 0, there are two distinct real roots.
 If D = 0, there is one repeated real root.
 If D < 0, there are two complex conjugate roots.
3. Compute Roots:
 Based on the discriminant's value, calculate the roots using the
appropriate formula:
 If D > 0:
 x1 = (-b + sqrt(D)) / (2a)
 x2 = (-b - sqrt(D)) / (2a)
 If D = 0:
 x1 = x2 = -b / (2a)

School of Computer Science and Engineering Page 13


Fundamentals of C Programming Lab Course Code: B24CS0108

 If D < 0:
 x1 = (-b + sqrt(-D)) / (2a)
 x2 = (-b - sqrt(-D)) / (2a) (Note: The imaginary part
is sqrt(-D) / (2a))
4. Output Results:
 Print the calculated roots, appropriately formatted based on their
type (real or complex).
Intuition:
 The discriminant is a crucial factor in determining the nature of the roots.
 The quadratic formula provides a general solution for finding the roots of a
quadratic equation.
 The imaginary unit i is used to represent complex numbers.

Algorithm:
Read coefficients from the user.
- Prompt the user to enter coefficients `a`, ‘b’ and ‘c’
Calculate discriminant.
- Calculate the discriminant using the formula ‘discriminant = b2- 4ac`.
Check discriminant.
- If `discriminant` is greater than 0:
- Calculate real and different roots using the quadratic formula:
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
- Display the roots.
- If `discriminant` is equal to 0:
- Calculate real and equal roots using the quadratic formula:
root1 = -b / (2 * a);
- Display the roots.
- If `discriminant` is less than 0:
- Calculate complex and different roots using the quadratic formula:
realPart = -b / (2 * a);
imaginaryPart = sqrt(-discriminant) / (2 * a);

School of Computer Science and Engineering Page 14


Fundamentals of C Programming Lab Course Code: B24CS0108

- Display the roots.

Program:
#include <stdio.h>
#include <math.h>
int main()
{
float a, b, c, discriminant, root1, root2;
printf("Enter coefficients a, b, and c: ");
scanf("%f%f%f", &a, &b, &c);

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

if (discriminant > 0)
{
// Roots are real and different
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);

printf("Roots are real and different.\n");


printf("Root 1 = %.2f\n", root1);
printf("Root 2 = %.2f\n", root2);
} else if (discriminant == 0)
{
// Roots are real and equal
root1 = -b / (2 * a);

printf("Roots are real and equal.\n");


printf("Root 1 = Root 2 = %.2f\n", root1);
} else {

School of Computer Science and Engineering Page 15


Fundamentals of C Programming Lab Course Code: B24CS0108

// Roots are complex and different


float realPart = -b / (2 * a);
float imaginaryPart = sqrt(-discriminant) / (2 * a);

printf("Roots are complex and different.\n");


printf("Root 1 = %.2f + %.2fi\n", realPart, imaginaryPart);
printf("Root 2 = %.2f - %.2fi\n", realPart, imaginaryPart);
}
return 0;
}

Output:
Enter coefficients a, b, and c: 1 4 1
Roots are real and different.
Root 1 = -0.27
Root 2 = -3.73

Enter coefficients a, b, and c: 2 4 2


Roots are real and equal.
Root 1 = Root 2 = -1.00

Enter coefficients a, b, and c: 2 2 3


Roots are complex and different.
Root 1 = -0.50 + 1.12i
Root 2 = -0.50 - 1.12i

Outcome of the Exercise:


The program will successfully compute and display the roots of the given quadratic
equation. The output will vary depending on the values of a, b, and c, and the nature of
the roots (real, repeated, or complex).

School of Computer Science and Engineering Page 16


Fundamentals of C Programming Lab Course Code: B24CS0108

Viva Questions and Answers:

1. What is a quadratic equation?


 A quadratic equation is a polynomial equation of degree 2.
2. How do you determine the nature of the roots of a quadratic equation?
 The discriminant, calculated as b^2 - 4ac, determines the nature of the roots.
3. What is the quadratic formula?
 The quadratic formula is x = (-b ± √(b² - 4ac)) / (2a).
4. What happens if the discriminant is negative?
 If the discriminant is negative, the roots are complex conjugate numbers.
5. How do you handle division by zero in the quadratic formula?
 The program should check if a is zero before applying the quadratic formula.
If a is zero, the equation is not quadratic, and an error message should be
displayed.
6. Can you explain the concept of complex numbers?
 Complex numbers are numbers that can be expressed in the form a + bi,
where a and b are real numbers, and i is the imaginary unit (√-1).
7. What is the purpose of the sqrt function in the program?
 The sqrt function is used to calculate the square root of a number.
8. How can you improve the readability and maintainability of the program?
 You can use meaningful variable names, comments, and proper indentation
to enhance code clarity.
9. Can you modify the program to handle different data types for the coefficients?
 Yes, you can modify the data types used for a, b, and c to handle different
ranges of values.
10. What are some potential errors or exceptions that might occur in the program?

 Potential errors include division by zero, invalid input, and numerical overflow.
The program should handle these errors appropriately.

3. Develop a C Program to find the largest among two and three different
numbers entered by the user.

Problem Statement:

Write a C program to find the largest number among two or three numbers entered
by the user.

Solution Overview:

1. Input Numbers:
 Prompt the user to enter the first number.
 Prompt the user to enter the second number.
 Optionally, prompt the user to enter the third number if desired.
2. Compare Numbers:
 Compare the first two numbers and determine the larger one.

School of Computer Science and Engineering Page 17


Fundamentals of C Programming Lab Course Code: B24CS0108

If a third number is entered, compare the larger of the first two



with the third number and determine the overall largest number.
3. Output Result:
 Print the largest number found.

Intuition:

 The program uses conditional statements (if-else) to compare the numbers


and determine the largest one.
 The comparison is done pairwise, starting with the first two numbers and
then comparing the larger result with the third number (if provided).

Algorithm

Read input:

- Prompt the user to enter two or three numbers.


Calculate the largest among two or three different numbers
- if the user enters only two integer numbers, then it finds the largest
between number1 and number2 and stores the result in largest variable.

- If the user enters a three-integer numbers, then it finds the largest


between number1 and number2 using find_largest function, then
compares that result with number3 to find the largest number using
find_largest function again, and stores the final result in largest variable.

- Display the Results

Program:
#include <stdio.h>

int find_largest (int a, int b) {


return (a > b) ? a : b;
}

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

School of Computer Science and Engineering Page 18


Fundamentals of C Programming Lab Course Code: B24CS0108

printf("Enter two or three numbers: ");


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

// Check if a third number is entered


if (scanf("%d", &num3) == 1) {
largest = find_largest (find_largest (num1, num2), num3);
} else {
largest = find_largest (num1, num2);
}
printf("The largest number is: %d\n", largest);
return 0;
}

Output:
Enter three numbers: 10 25
The largest number is: 25

Enter three numbers: 45 15 8


The largest number is: 45

Enter three numbers: 30 30 23


The largest number is: 30

Outcome of the Exercise:

The program will successfully identify and display the largest number among the
given inputs.

Viva Question and Answers:


1. How can you make the program more user-friendly?
 To enhance user-friendliness:
o Provide clear and informative prompts for user input.

School of Computer Science and Engineering Page 19


Fundamentals of C Programming Lab Course Code: B24CS0108

o Include error handling to gracefully handle invalid inputs (e.g., non-


numeric values).
o Consider adding a feature to allow the user to repeat the process multiple
times without having to restart the program.
2. What if you need to find both the largest and smallest numbers?
 To find both the largest and smallest numbers:
o Initialize two variables, largest and smallest, to the first input value.
o Compare each subsequent input with both largest and smallest, updating
them accordingly.
o At the end, largest will hold the maximum value, and smallest will hold
the minimum value.
3. Can you implement this program using functions?
 Yes, using functions can improve code organization and reusability. You could
create separate functions for:
o Taking input from the user

o Comparing and finding the largest number

o Printing the result

4. How does the program handle negative numbers?


 The program can handle both positive and negative numbers. The
comparison logic will correctly identify the largest number regardless of
their signs.
5. What happens if the user enters the same number for all inputs?
 In this case, the program will display any of the repeated numbers as the
largest, since they are all equal.
6. Can the program be modified to handle more than three numbers?
 Yes, the program can be easily modified to handle any number of inputs
by using a loop (like a for loop) to iterate through the numbers and
compare them.
7. How does the program handle non-numeric input?
 If the user enters non-numeric input, the program may encounter errors
or unexpected behavior. To prevent this, input validation can be
implemented to ensure that only valid numbers are entered.

School of Computer Science and Engineering Page 20


Fundamentals of C Programming Lab Course Code: B24CS0108

8. What is the time complexity of the algorithm?


 The time complexity of the algorithm is O(n), where n is the number of
inputs. This means that the program's running time increases linearly with
the number of inputs.
9. Can the program be optimized for performance?
 While the current algorithm is relatively efficient, further optimizations
can be explored. For example, if the number of inputs is large, using a
more efficient sorting algorithm followed by selecting the last element
could potentially improve performance.
10. What are the potential limitations or drawbacks of this approach?
 One potential limitation is that the program is specific to finding the largest
number. If the goal is to find the smallest number or other specific values, the
comparison logic would need to be adjusted accordingly. Additionally, for very
large datasets, more efficient algorithms might be required to handle the
comparison process effectively.

4. A leap year is a calendar year that contains an additional day compared to


a common year. Design and develop C program to check whether the
given year is leap year (or) not.

Problem Statement:
Write a C program to determine whether a given year is a leap year or not. A leap
year is a year that is divisible by 4, but not divisible by 100 unless it's also divisible by
400.
Solution Overview:
1. Input Year: Prompt the user to enter the year to be checked.
2. Check Divisibility:
o If the year is divisible by 400, it's a leap year.
o If the year is divisible by 100 but not by 400, it's not a leap year.
o If the year is divisible by 4 but not by 100, it's a leap year.
o Otherwise, it's not a leap year.
3. Output Result: Print whether the given year is a leap year or not.

Intuition:
The logic behind leap years is based on the Gregorian calendar. The extra day
(February 29th) is added to ensure that the average length of a year aligns closely
with the Earth's orbital period around the Sun.

School of Computer Science and Engineering Page 21


Fundamentals of C Programming Lab Course Code: B24CS0108

Algorithm:
Read input:
- Prompt the user to enter the year as an integer.
Check Divisibility:
- If the year is divisible by 400, it is a leap year.
- Else if the year is divisible by 100, it is not a leap year.
- Else if the year is divisible by 4, it is a leap year.
- Otherwise, it is not a leap year.
- Print whether the year is a leap year or not.
Program:

#include <stdio.h>
int main()
{
int year;
printf("Enter a year: ");
scanf("%d", &year);
if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100! = 0)))
{
printf("%d is a leap year\n", year);
}
else
{
printf("%d is not a leap year\n", year);
}
return 0;
}
Output:
Enter a year: 2024
2024 is a leap year

Enter a year: 1900


1900 is not a leap year

School of Computer Science and Engineering Page 22


Fundamentals of C Programming Lab Course Code: B24CS0108

Enter a year: 2000


2000 is a leap year

Outcome of the Exercise:


The program will accurately determine whether the input year is a leap year or not
based on the specified criteria.

Viva Question and Answers:

1. What is the purpose of a leap year?


 To maintain the alignment between the calendar year and the Earth's orbital
period.
2. What are the conditions for a year to be a leap year?
 A year is a leap year if it is divisible by 4, but not divisible by 100 unless it's
also divisible by 400.
3. How does your program implement the leap year logic?
 The program uses conditional statements (if-else) to check the divisibility
conditions and determine if the year is a leap year.
4. Can you explain the use of the modulo operator (%) in your code?
 The modulo operator is used to check if a number is divisible by another
number. If the remainder is 0, it means the first number is divisible by the
second.
5. What happens if the user enters a non-integer value for the year?
 The program may encounter errors or unexpected behaviour if the input is not
an integer. Input validation can be implemented to prevent this.
6. Can you explain the significance of the year 1700, 1800, and 1900?
 These years are examples of years that are divisible by 4 and 100 but not by
400, making them non-leap years.
7. How can you make the program more user-friendly?
 Add error handling to handle invalid input, provide clear prompts, and
consider adding a loop to allow the user to check multiple years.
8. Can you explain the time complexity of your program?
 The time complexity is O (1), as the program performs a constant number of
operations regardless of the input year.
9. What are the potential limitations of this approach?
 The program is specific to the Gregorian calendar and may not be applicable
to other calendars.
10. Can you modify the program to handle other calendar systems?
 Yes, the program can be adapted to handle other calendars by adjusting the leap
year criteria accordingly.

School of Computer Science and Engineering Page 23


Fundamentals of C Programming Lab Course Code: B24CS0108

5. A palindrome is a word, sentence, verse, or even number that reads


the same backward or forward. Write a C program to check if a given
number is a Palindrome.

Problem Statement:

Write a C program to determine if a given integer is a palindrome. A


palindrome number reads the same backward as forward.

Solution Overview:

1. Input Number:
 Prompt the user to enter an integer.
2. Reverse Number:
 Create a temporary variable to store the reversed number.
 While the original number is not zero:
 Extract the last digit of the original number using the modulo
operator (%).
 Append the extracted digit to the reversed number (multiply
the reversed number by 10 and add the extracted digit).
 Divide the original number by 10 to remove the last digit.
3. Compare Original and Reversed:
 Compare the original number with the reversed number.
 If they are equal, the number is a palindrome. Otherwise, it is not.
4. Output Result:
 Print whether the number is a palindrome or not.

Intuition:

 A palindrome number remains unchanged when its digits are reversed.

 The program uses a simple algorithm to reverse the number and then
compares it with the original.

Algorithm:
- Read the input number from the user and store it in a variable (num).
- Initialize variables originalNum to store the original number and reversed
Num to store the reversed number to 0.
- Save the original number by setting originalNum equal to num.
- Repeat until num is not equal to 0:
a. Calculate the remainder (remainder) when num is divided by 10.
b. Multiply reversedNum by 10 and add the remainder to it.
c. Divide num by 10.

School of Computer Science and Engineering Page 24


Fundamentals of C Programming Lab Course Code: B24CS0108

Check if originalNum is equal to reversedNum.


a. If true, print that the number is a palindrome.
b. If false, print that the number is not a palindrome.

Program:
#include <stdio.h>
int main()
{
int num, originalNum, reversedNum = 0, remainder;
printf("Enter an integer: \n");
scanf("%d", &num);
// Save the original number
originalNum = num;
// Reverse the number
while (num != 0)
{
remainder = num % 10;
reversedNum = reversedNum * 10 + remainder;
num /= 10;
}

// Check if the original number is equal to its reverse


if (originalNum == reversedNum)
printf("%d is a palindrome.\n", originalNum);
else
printf("%d is not a palindrome.\n", originalNum);
return 0;
}

School of Computer Science and Engineering Page 25


Fundamentals of C Programming Lab Course Code: B24CS0108

Output:
Enter an integer:
1234
1234 is not a palindrome.

Enter an integer:
1221
1221 is a palindrome.

Outcome of the Exercise:


The program will successfully determine if the given integer is a palindrome or not.
The output will be a message indicating whether the number is a palindrome.

Viva question and Answers:

1. What is a palindrome number?


 A palindrome number reads the same backward as forward.
2. How does the program reverse the number?
 The program extracts the last digit of the number repeatedly, appends it to a
reversed number, and removes the last digit from the original number until the
original number becomes zero.
3. Why is the modulo operator (%) used to extract the last digit?
 The modulo operator gives the remainder when a number is divided by
another. In this case, dividing by 10 gives the last digit.
4. Can the program handle negative numbers?
 Yes, the program can handle negative numbers. However, negative numbers
are generally not considered palindromes in the mathematical sense.
5. What happens if the user enters a number with leading zeros?
 Leading zeros are ignored when determining if a number is a palindrome.
6. Can the program be optimized for larger numbers?
 For very large numbers, more efficient methods like converting the number to
a string and comparing the characters might be considered.
7. How can you make the program more user-friendly?
 You can add input validation to ensure that the user enters a valid integer. You
can also provide clear prompts and informative messages.
8. Can the program be extended to handle other types of palindromes, such as
strings or words?
 Yes, the basic principle of comparing the original and reversed values can be
applied to other types of palindromes. However, the implementation details
might differ.
9. What is the time complexity of the algorithm?

School of Computer Science and Engineering Page 26


Fundamentals of C Programming Lab Course Code: B24CS0108

 The time complexity of the algorithm is O(log n), where n is the number of
digits in the input number. This is because the number of iterations in the loop
is proportional to the number of digits.
10. Can the program be made more efficient for numbers with a large number of
digits?

 For very large numbers, more efficient algorithms might be considered, such as
comparing the first half of the number with the second half in reverse order.

6. Design and Develop a C Program to print the following pattern using


Looping concepts.
a. first pattern

b. second pattern

Problem Statement:

Design and Develop a C Program to print the following pattern using


Looping concepts.
a. first pattern

School of Computer Science and Engineering Page 27


Fundamentals of C Programming Lab Course Code: B24CS0108

Solution Overview:

1. Initialize Variables:
o Create variables rows and cols to store the number of rows and columns in the
pattern.
o In this case, rows will be 6 and cols will be 6.
2. Outer Loop:
o Iterate from rows down to 1 using a for loop.
3. Inner Loop:
o Iterate from 1 to the current outer loop value using a for loop.
o Print the characters 'A' to 'Z' (or the desired starting character) based on the
current inner loop value and the outer loop value.
4. Newline:
o After the inner loop, print a newline character to move to the next row.

Intuition:

 The pattern consists of decreasing rows of characters.


 Nested loops are used to control the number of characters printed in each row and
the specific characters to be printed.
 The outer loop determines the number of rows, while the inner loop determines the
number of characters in each row.

Algorithm for first pattern :


- Read number of rows. In this case, rows = 6.
- Use a nested loop structure:

 The outer loop iterates through each row, starting from 1 to rows.
 The inner loop iterates through each character in the current row,
starting from 'A' and incrementing until the desired number of
characters for that row.

- Print the characters in each row.


- After printing each row, move to the next line.
- Repeat the process as many number of rows that user specifies

School of Computer Science and Engineering Page 28


Fundamentals of C Programming Lab Course Code: B24CS0108

Program for first pattern :


#include <stdio.h>
int main() {
int rows, i, j;

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


scanf("%d", &rows);

for (i = rows - 1; i >= 0; i--) {


for (j = 0; j <= (rows - i - 2); j++) {
printf(" ");
}
for (j = 0; j <= i; j++) {
printf("%c ", 'A' + j);
}
printf("\n");
}
return 0;
}

Output:

Enter number of rows: 6


ABCDEF
ABCDE
ABCD
ABC
AB
A

School of Computer Science and Engineering Page 29


Fundamentals of C Programming Lab Course Code: B24CS0108

Outcome of the Exercise:


The program will successfully print the specified pattern, displaying the desired
arrangement of characters.

Problem Statement:

Design and Develop a C Program to print the following pattern using


Looping concepts.
b. second pattern

Solution Overview:

1. Initialize Variables:
o Create a variable rows to store the number of rows in the pattern.
o In this case, rows will be 5.
2. Outer Loop:
o Iterate from rows down to 1 using a for loop.
3. Inner Loop:
o Iterate from 1 to the current outer loop value using a for loop.
o Print an asterisk in each iteration.
4. Newline:
o After the inner loop, print a newline character to move to the next row.

Intuition:

 The pattern consists of decreasing rows of asterisks.


 Nested loops are used to control the number of asterisks printed in each row.
 The outer loop determines the number of rows, while the inner loop determines the
number of asterisks in each row.

School of Computer Science and Engineering Page 30


Fundamentals of C Programming Lab Course Code: B24CS0108

Algorithm for Second pattern :


- Read number of rows. In this case, rows = 6.
- Use a nested loop structure:

a. The outer loop iterates through each row, starting from 1 to rows.
b. The inner loop iterates through each * in the current row and
incrementing until the desired number of * for that row.

- Print the * in each row.


- After printing each row, move to the next line.
- Repeat the process as many number of rows that user specifies

Program for second pattern :


#include <stdio.h>
int main() {
int rows, i, j;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = rows - 1; i >= 0; i--) {
for (j = 0; j <= (rows - i - 2); j++) {
printf(" ");
}
for (j = 0; j <= i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}

School of Computer Science and Engineering Page 31


Fundamentals of C Programming Lab Course Code: B24CS0108

Output:
Enter the number of rows: 6
******
*****
****
***
**
*

Outcome of the Exercise:


The program will successfully print the specified patterns, displaying the desired
arrangement of asterisks.

Viva questions and Answers:

1. What is the purpose of nested loops in this program?


 Nested loops are used to create the triangular shape of the patterns. The
outer loop controls the number of rows, while the inner loop determines
the number of asterisks or spaces printed within each row.
2. How do you control the number of spaces printed in Pattern B?
 The number of spaces printed in Pattern B is calculated by subtracting the
current row number from the total number of rows. This ensures that the
pattern is centered.
3. Can you modify the program to print a different number of rows for each
pattern?
 Yes, you can modify the rows variable in each pattern to print a different
number of rows.
4. How can you make the program more flexible to accommodate different
patterns?
 You can use more complex nested loops and conditional statements to
create more intricate patterns. For example, you could introduce
variations in the number of asterisks or spaces printed in each row.
5. What is the time complexity of the program?
 The time complexity of the program is O(n^2), where n is the number of
rows. This is because the nested loops iterate through n^2 elements.
6. Can you explain the role of the newline character ('\n') in the program?

School of Computer Science and Engineering Page 32


Fundamentals of C Programming Lab Course Code: B24CS0108

 The newline character is used to move the cursor to the next line after
each row of the pattern is printed.
7. How can you modify the program to print the patterns in reverse order?
 To print the patterns in reverse order, you can modify the outer loop to
iterate from rows down to 1 instead of from 1 to rows.
8. Can you create a more general pattern-printing function that can be used to
generate different patterns?
 Yes, you can create a function that takes the desired number of rows and
a pattern specification as input, and then uses nested loops and
conditional statements to generate the corresponding pattern.
9. How can you add color or other formatting to the printed patterns?
 Depending on the programming environment, you can use escape
sequences or specific library functions to add color, bold, or other
formatting to the printed characters.
10. Can you modify the program to print the patterns in a different orientation
(e.g., rotated or inverted)?

 Yes, by adjusting the loop conditions and the placement of asterisks and
spaces, you can create different orientations for the patterns.

7. Consider student’s marks in Computer Test. Write a C Program to


display the grade obtained by a student in Computer Test based on
range of marks.
Problem Statement:
Write a C program to determine and display the grade obtained by a student
in a Computer Test based on the range of marks.

Solution Overview:
1. Input Marks:
 Prompt the user to enter the student's marks obtained in the
Computer Test.
2. Check Grade:
 Use conditional statements (if-else) to compare the marks with
predefined grade ranges.
 Based on the comparison, assign the appropriate grade (e.g., 'A',
'B', 'C', 'D', 'F').
3. Display Grade:
 Print the assigned grade.

Intuition:
 The program uses conditional statements to categorize the marks into
different grade ranges.

School of Computer Science and Engineering Page 33


Fundamentals of C Programming Lab Course Code: B24CS0108

 The grade assignment is based on predefined criteria.

Algorithm:
- Accept the user's input for the grade.
- Check the value of grade using a series of if-else statements:
- If grade is equal to 10, print "Grade: O, Performance: Outstanding."
- Else, if grade is greater than or equal to 9, print "Grade: A+, Performance:
Excellent."
- Else, if grade is greater than or equal to 8, print "Grade: A, Performance: Very
Good."
- Else, if grade is greater than or equal to 7, print "Grade: B+, Performance:
Good."
- Else, if grade is greater than or equal to 6, print "Grade: B, Performance:
Above Average."
- Else, if grade is greater than or equal to 5.5, print "Grade: C+, Performance:
Average."
- Else, if grade is greater than or equal to 5, print "Grade: C, Performance:
Satisfactory."
- Else, print "Grade: F, Performance: Fail."

Program:
# include <stdio.h>
int main ()
{
float grade;
printf ("Enter your grade (0 to 10)\n");
scanf ("%f", &grade);
if (grade == 10)
printf ("Grade:O, Performance: Outstanding");
else if (grade >= 9)
printf ("Grade:A+, Performance: Excellent");
else if (grade >= 8)
printf ("Grade:A, Performance: Very Good");
else if (grade >= 7)
printf ("Grade:B+, Performance: Good");

School of Computer Science and Engineering Page 34


Fundamentals of C Programming Lab Course Code: B24CS0108

else if (grade >= 6)


printf ("Grade:B, Performance: Above Average");
else if (grade >= 5.5)
printf ("Grade:C+, Performance: Average");
else if (grade >= 5)
printf ("Grade:C, Performance: Satisfactory");
else
printf ("Grade:F, Performance: Fail");
}

Output:
Enter your grade (0 to 10)
7
Grade: B+, Performance: Good

Enter your grade (0 to 10)


1.2
Grade: F, Performance: Fail

Enter your grade (0 to 10)


5
Grade: C, Performance: Satisfactory

Outcome of the Exercise:


The program will successfully determine and display the grade obtained by
the student based on the input marks.

Viva Question and Answers:

1. What are the typical grade ranges used in Computer Tests?


 The grade ranges can vary depending on the educational institution
or specific course. Common ranges might include:
 A: 90-100
 B: 80-89

School of Computer Science and Engineering Page 35


Fundamentals of C Programming Lab Course Code: B24CS0108

 C: 70-79
 D: 60-69
 F: 0-59
2. How does the program handle marks outside the defined ranges?
 The program can include additional checks to handle marks outside
the defined ranges. For example, if the marks are below 0 or above
100, an error message can be displayed.
3. Can the program be modified to handle different grading systems?
 Yes, the program can be adapted to different grading systems by
modifying the grade ranges and the corresponding letter grades.
4. How can the program be made more user-friendly?
 You can provide clear prompts for user input, include error
handling for invalid inputs, and use informative messages to
display the results.
5. What is the time complexity of the algorithm?
 The time complexity of the algorithm is O(1) as it involves a
constant number of comparisons.
6. Can the program be extended to handle multiple subjects and
calculate an overall grade?
 Yes, the program can be extended to handle multiple subjects by
prompting the user to enter marks for each subject and calculating
an overall average or weighted average.
7. How can the program be made more robust to handle different input
formats?
 You can implement input validation to ensure that the user enters a
valid numeric value for the marks.
8. Can the program be adapted to use a different programming
language?
 Yes, the basic logic and structure of the program can be adapted to
other programming languages like Python, Java, or C++.
9. How can the program be made more efficient for large datasets?
 For large datasets, you might consider using more efficient data
structures or algorithms, but in this simple case, the current
approach is sufficient.
10. Can the program be integrated with other systems or applications?

 Yes, the program can be integrated with other systems or


applications through APIs or data exchange mechanisms. For
example, it could be integrated with a student management system
to automatically record and process student grades.

8. If a four-digit number is input through the keyboard, write a program


to obtain the sum of the first and last digit of this number

School of Computer Science and Engineering Page 36


Fundamentals of C Programming Lab Course Code: B24CS0108

Problem Statement:

Write a C program to find the sum of the first and last digits of a four-digit
number entered by the user.

Solution Overview:

1. Input Number:
 Prompt the user to enter a four-digit number.
2. Extract First and Last Digits:
 Extract the first digit by dividing the number by 1000 and taking the
integer part.
 Extract the last digit by taking the remainder of the number divided by 10.
3. Calculate Sum:
 Add the first and last digits together.
4. Output Result:
 Print the calculated sum.

Intuition:

 The first digit of a four-digit number can be obtained by dividing the number by
1000 and taking the integer part.
 The last digit can be obtained by taking the remainder of the number divided by
10.

Algorithm:
- Input: Prompt the user to enter four-digit number.
- Extract last digit: Calculate the remainder of the number when divided by 10.
- Extract first digit: Divide the number by 1000 to get the first digit.
- Calculate sum: Add the first and last digits.
- Output: Print the calculated sum.

Program:
#include <stdio.h>
int main()
{
int number, first_digit, last_digit, sum;
printf("Enter a four-digit number: ");
scanf("%d", &number);

// Extract last digit


last_digit = number % 10;

School of Computer Science and Engineering Page 37


Fundamentals of C Programming Lab Course Code: B24CS0108

// Extract first digit


first_digit = number / 1000;

// Calculate sum
sum = first_digit + last_digit;

printf("Sum of first and last digit: %d\n", sum);


return 0;
}

Output:
Enter a four-digit number:1234
Sum of first and last digit: 5

Enter a four-digit number:9876


Sum of first and last digit:15

Outcome of the Excercise:


The program will successfully calculate and display the sum of the first and last digits
of the entered four-digit number.

Viva Question and Answers:

1. What is the purpose of the program?


 To calculate the sum of the first and last digits of a four-digit number.
2. How do you extract the first digit of a number?
 Divide the number by 1000 and take the integer part.
3. How do you extract the last digit of a number?
 Take the remainder of the number divided by 10.
4. Can the program handle numbers with more or fewer than four digits?
 The program is specifically designed for four-digit numbers. It might not
produce accurate results for numbers with different lengths.
5. What happens if the user enters a non-integer value?
 The program might encounter errors or produce unexpected results if the input
is not an integer.
6. Can the program be modified to handle numbers with different lengths?
 Yes, the program can be modified to handle numbers with different lengths by
adjusting the division and remainder operations accordingly.
7. What is the time complexity of the algorithm?
 The time complexity of the algorithm is O(1) as it involves a constant number
of operations regardless of the input value.

School of Computer Science and Engineering Page 38


Fundamentals of C Programming Lab Course Code: B24CS0108

8. Can the program be optimized for performance?


 While the current algorithm is relatively efficient, further optimizations might
be possible for very large numbers.
9. How can you make the program more user-friendly?
 You can add input validation to ensure that the user enters a valid four-digit
number. You can also provide clear prompts and informative messages.
10. Can the program be extended to handle other arithmetic operations on the digits
of a number?
 Yes, the program can be extended to perform other operations, such as finding
the product, difference, or average of the digits.

9. In computer-based applications, matrices play a vital role in the


projection of three-dimensional image into a two-dimensional screen,
creating the realistic seeming motions. Write a C program using 2-
dimensional array to check for compatibility of two matrices and
perform matrix Multiplication.

Problem Statement:

Write a C program to check the compatibility of two matrices and perform matrix
multiplication using 2D arrays. Two matrices are compatible for multiplication if the
number of columns in the first matrix is equal to the number of rows in the second
matrix.

Solution Overview:

1. Input Matrices:
 Prompt the user to enter the dimensions of the two matrices (rows and
columns).
 Create two 2D arrays to store the elements of the matrices.
 Read the elements of the matrices from the user.
2. Check Compatibility:
 Verify if the number of columns in the first matrix is equal to the number
of rows in the second matrix. If not, the matrices are incompatible for
multiplication.
3. Matrix Multiplication:
 If the matrices are compatible, create a new 2D array to store the result
of the multiplication.
 Iterate through each element of the resulting matrix and calculate its
value by multiplying the corresponding elements of the first and second
matrices and summing the products.
4. Output Result:
 Print the resulting matrix.

Intuition:

School of Computer Science and Engineering Page 39


Fundamentals of C Programming Lab Course Code: B24CS0108

 Matrix multiplication involves multiplying corresponding elements of two


matrices and summing the products.
 The compatibility of matrices for multiplication depends on their dimensions.
 2D arrays are used to represent matrices in C.

Algorithm:
- Input dimensions of the first matrix (matrix A):
- Read the number of rows and columns for matrix A from the user.
- Input dimensions of the second matrix (matrix B):
- Read the number of rows and columns for matrix B from the user.
- Check for compatibility for matrix multiplication:
- If the number of columns in matrix A is not equal to the number of rows in
matrix B, print an error message and exit with an error code.
- Input elements of matrix A.
- Input elements of matrix B.
- Perform matrix multiplication.
- Print matrix A, matrix B, and the result matrix.
- Return 0 to indicate successful execution.

Program:
#include <stdio.h>
int main() {
int rowsA, colsA, rowsB, colsB;

// Input dimensions of the first matrix


printf("Enter the number of rows for matrix A: ");
scanf("%d", &rowsA);
printf("Enter the number of columns for matrix A: ");
scanf("%d", &colsA);

// Input dimensions of the second matrix


printf("Enter the number of rows for matrix B: ");
scanf("%d", &rowsB);
printf("Enter the number of columns for matrix B: ");
scanf("%d", &colsB);

School of Computer Science and Engineering Page 40


Fundamentals of C Programming Lab Course Code: B24CS0108

// Check for compatibility for matrix multiplication


if (colsA != rowsB) {
printf("Matrix multiplication is not possible due to incompatible
dimensions.\n");
return 1; // Exit with an error code
}

int matrixA[rowsA][colsA];
int matrixB[rowsB][colsB];
int result[rowsA][colsB];

// Input elements of the matrices A and B


printf("Enter the elements of matrix A:\n");
for (int i = 0; i < rowsA; ++i) {
for (int j = 0; j < colsA; ++j) {
printf("Enter element at position (%d, %d): ", i + 1, j + 1);
scanf("%d", &matrixA[i][j]);
}
}

printf("Enter the elements of matrix B:\n");


for (int i = 0; i < rowsB; ++i) {
for (int j = 0; j < colsB; ++j) {
printf("Enter element at position (%d, %d): ", i + 1, j + 1);
scanf("%d", &matrixB[i][j]);
}
}

// Perform matrix multiplication

School of Computer Science and Engineering Page 41


Fundamentals of C Programming Lab Course Code: B24CS0108

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


for (int j = 0; j < colsB; ++j) {
result[i][j] = 0;
for (int k = 0; k < colsA; ++k) {
result[i][j] += matrixA[i][k] * matrixB[k][j];
}
}
}
// Display matrices and the result
printf("\nMatrix A:\n");
for (int i = 0; i < rowsA; ++i) {
for (int j = 0; j < colsA; ++j) {
printf("%d\t", matrixA[i][j]);
}
printf("\n");
}
printf("\nMatrix B:\n");
for (int i = 0; i < rowsB; ++i) {
for (int j = 0; j < colsB; ++j) {
printf("%d\t", matrixB[i][j]);
}
printf("\n");
}
printf("\nResultant Matrix (A * B):\n");
for (int i = 0; i < rowsA; ++i) {
for (int j = 0; j < colsB; ++j) {
printf("%d\t", result[i][j]);
}
printf("\n");

School of Computer Science and Engineering Page 42


Fundamentals of C Programming Lab Course Code: B24CS0108

}
return 0; // Exit successfully
}

Output:
Enter the number of rows for matrix A: 2
Enter the number of columns for matrix A: 2
Enter the number of rows for matrix B: 2
Enter the number of columns for matrix B: 2
Enter the elements of matrix A:
Enter element at position (1, 1): 1
Enter element at position (1, 2): 2
Enter element at position (2, 1): 3
Enter element at position (2, 2): 4
Enter the elements of matrix B:
Enter element at position (1, 1): 5
Enter element at position (1, 2): 6
Enter element at position (2, 1): 7
Enter element at position (2, 2): 8

Matrix A:
1 2
3 4

Matrix B:
5 6
7 8

Resultant Matrix (A * B):


19 22

School of Computer Science and Engineering Page 43


Fundamentals of C Programming Lab Course Code: B24CS0108

43 50

Enter the number of rows for matrix A: 2


Enter the number of columns for matrix A: 3
Enter the number of rows for matrix B: 2
Enter the number of columns for matrix B: 3
Matrix multiplication is not possible due to incompatible dimensions.

Outcome of the Excercise:


The program will determine if two matrices are compatible for multiplication. If they
are, it will perform the multiplication and print the resulting matrix. If they are not
compatible, it will display an error message.

Viva Question and Answers:

1. What is the condition for two matrices to be compatible for multiplication?


 The number of columns in the first matrix must be equal to the number of
rows in the second matrix.
2. How is matrix multiplication performed?
 Matrix multiplication involves multiplying corresponding elements of the two
matrices and summing the products.
3. Why is it important to check matrix compatibility before multiplication?
 If the matrices are not compatible, the multiplication operation will be
undefined and may lead to incorrect results or errors.
4. How are matrices represented in C using 2D arrays?
 Each element of a matrix is stored in a corresponding element of a 2D array.
The rows and columns of the matrix correspond to the rows and columns of
the array.
5. What is the time complexity of matrix multiplication?
 The time complexity of matrix multiplication is O(n^3), where n is the number
of rows or columns in the matrices.
6. Can you explain the role of nested loops in matrix multiplication?
 Nested loops are used to iterate through the elements of the two matrices and
calculate the corresponding products.
7. How can you handle cases where the matrices have different dimensions?
 If the matrices have different dimensions, the program should display an error
message indicating that they are not compatible for multiplication.
8. Can you optimize the matrix multiplication algorithm for larger matrices?
 There are various optimization techniques that can be used to improve the
performance of matrix multiplication for larger matrices, such as Strassen's
algorithm or using parallel processing.

School of Computer Science and Engineering Page 44


Fundamentals of C Programming Lab Course Code: B24CS0108

9. What are some common applications of matrix multiplication in computer


graphics?
 Matrix multiplication is used for various operations in computer graphics,
such as transforming points, rotating objects, and projecting 3D scenes onto
2D screens.
10. How can you handle cases where the matrices contain non-numeric elements?
 If the matrices contain non-numeric elements, the program should handle them
appropriately, either by converting them to numeric values or by displaying an
error message.

10.Write a C program to implement bubble sort with appropriate input


and output.

Problem Statement:

Write a C program to implement bubble sort, an algorithm used to sort an


array of elements in ascending order.

Solution Overview:

1. Input Array:
o Prompt the user to enter the size of the array.
o Create an array of the specified size.
o Read the elements of the array from the user.
2. Outer Loop:
o Iterate from the last index to the second index (index 0 is already
sorted).
3. Inner Loop:
o Iterate from the first index to the current outer loop index.
o Compare adjacent elements:
 If the current element is greater than the next element, swap
them.
4. Output Sorted Array:
o Print the sorted array elements.

Intuition:

 Bubble sort works by repeatedly swapping adjacent elements if they are in


the wrong order.
 The largest element "bubbles up" to the end of the array in each pass of the
outer loop.
 The outer loop ensures that the elements from the end to the beginning are
sorted.

School of Computer Science and Engineering Page 45


Fundamentals of C Programming Lab Course Code: B24CS0108

Algorithm:
- Input the size of the array.
- Input elements into the array.
- Use nested loops to iterate over the array elements and perform the bubble
sort algorithm:
- Iterate over the array elements from the beginning to the second-to-last
element.
- Within the above loop, iterate over the array elements from the beginning to
size - i - 2.
- Swap adjacent elements if they are in the wrong order.
- Display the sorted array:

Program:
#include <stdio.h>
// Function to perform bubble sort on an array
void bubbleSort(int arr[], int size)
{
for (int i = 0; i < size - 1; ++i)
{
for (int j = 0; j < size - i - 1; ++j)
{
// Swap if the element found is greater than the next element
if (arr[j] > arr[j + 1])
{
// Swap the elements using a temporary variable
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

School of Computer Science and Engineering Page 46


Fundamentals of C Programming Lab Course Code: B24CS0108

// Function to input elements into an array


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

// Function to display elements of an array


void displayArray(int arr[], int size)
{
printf("Sorted Array:\n");
for (int i = 0; i < size; ++i)
printf("%d ", arr[i]);
printf("\n");
}

int main()
{
int size;
// Input the size of the array
printf("Enter the size of the array: ");
scanf("%d", &size);
int arr[size];
// Input elements into the array
inputArray(arr, size);

// Perform bubble sort

School of Computer Science and Engineering Page 47


Fundamentals of C Programming Lab Course Code: B24CS0108

bubbleSort(arr, size);
// Display the sorted array
displayArray(arr, size);
return 0;
// Exit successfully
}

Output:
Enter the size of the array: 10
Enter 10 elements:
12
21
43
32
11
56
54
87
76
65
Sorted Array:
11 12 21 32 43 54 56 65 76 87

Enter the size of the array: 5


Enter 5 elements:
67
65
54
43
32

School of Computer Science and Engineering Page 48


Fundamentals of C Programming Lab Course Code: B24CS0108

Sorted Array:
32 43 54 65 67

Outcome of the Exercise:


The program will successfully sort the given array of elements in ascending order and
print the sorted array.

Viva Question and Answers:

1. What is bubble sort?


o Bubble sort is a simple sorting algorithm that repeatedly swaps adjacent
elements if they are in the wrong order.
2. How does bubble sort work?
o Bubble sort compares adjacent elements and swaps them if the current
element is greater than the next element. This process is repeated until the
array is sorted.
3. What is the time complexity of bubble sort?
o The worst-case time complexity of bubble sort is O(n^2), where n is the
size of the array. This occurs when the array is already sorted in
descending order.
4. Is bubble sort a stable sorting algorithm?
o Yes, bubble sort is a stable sorting algorithm, meaning that it preserves the
relative order of elements with equal values.
5. Can you explain the role of the outer and inner loops in bubble sort?
o The outer loop iterates from the last index to the second index, ensuring
that elements from the end to the beginning are sorted. The inner loop
iterates from the first index to the current outer loop index, comparing and
swapping adjacent elements.
6. How can you optimize bubble sort for better performance?
o One optimization is to use a flag to determine if any swaps were made in a
pass. If no swaps were made, the array is already sorted, and the outer loop
can terminate early.
7. What are the advantages and disadvantages of bubble sort?
o Advantages: Simple to implement, stable.
o Disadvantages: Inefficient for large arrays, O(n^2) worst-case time
complexity.
8. Can you compare bubble sort with other sorting algorithms?
o Bubble sort is generally less efficient than algorithms like quicksort,
mergesort, or heapsort, especially for large arrays.
9. How can you handle duplicate elements in bubble sort?
o Bubble sort handles duplicate elements correctly. If two elements are
equal, they will remain in their original relative order.
10. Can you implement bubble sort using a different programming language?
 Yes, bubble sort can be implemented in various programming languages,
including Python, Java, C++, etc. The basic logic and steps remain the same,
although the syntax may differ.

School of Computer Science and Engineering Page 49


Fundamentals of C Programming Lab Course Code: B24CS0108

11.Write a C program to implement binary search with appropriate input


and output.

Problem Statement:

Write a C program to implement binary search on a sorted array of elements.


The program should take an array, a target value, and the array size as input,
and return the index of the target value in the array if found, or -1 if not
found.

Solution Overview:

1. Input:
o Read the array size, elements of the array, and the target value from
the user.
2. Sort the Array:
o Ensure the array is sorted in ascending order using a suitable sorting
algorithm (e.g., quicksort, mergesort).
3. Binary Search:
o Initialize left and right pointers to the first and last indices of the
array, respectively.
o While left is less than or equal to right:
 Calculate the middle index mid = (left + right) / 2.
 If the element at mid is equal to the target, return mid.
 If the element at mid is less than the target, update left to mid
+ 1.
 If the element at mid is greater than the target, update right to
mid - 1.
4. Output:
o If the target is found, print its index.
o If the target is not found, print -1.

Intuition:

 Binary search is a divide-and-conquer algorithm that efficiently searches for a


target value in a sorted array.
 It works by repeatedly dividing the search interval in half until the target is
found or the interval becomes empty.
 The key idea is to compare the target with the middle element of the array
and adjust the search interval accordingly.

Algorithm:
- Input the size of the array (size).

School of Computer Science and Engineering Page 50


Fundamentals of C Programming Lab Course Code: B24CS0108

- Input the sorted array elements into the array.


- Input the element to be searched (key).
- Call the binarySearch function with the array, low index as 0, high index as
size - 1, and the key.
- Initialize a while loop with the condition low <= high.
- Calculate the middle index mid using the formula mid = low + (high - low) / 2.
- Check if the element at index mid is equal to the key.
- If yes, return mid (element found).
- If no, check if the key is smaller than the element at index mid.
- If yes, update high = mid - 1 (ignore the right half).
- If no, update low = mid + 1 (ignore the left half).
- If the while loop exits, return -1 (element not found).

Program:
#include <stdio.h>
// Function to perform binary search
int binarySearch(int arr[], int low, int high, int key)
{
while (low <= high) {
int mid = low + (high - low) / 2;

// Check if the key is present at the middle


if (arr[mid] == key)
return mid;

// If the key is smaller, ignore the right half


else if (arr[mid] > key)
high = mid - 1;
// If the key is larger, ignore the left half
else
low = mid + 1;
}

// Key not present in the array


return -1;

School of Computer Science and Engineering Page 51


Fundamentals of C Programming Lab Course Code: B24CS0108

int main() {
int size, key, result;
// Input the size of the array
printf("Enter the size of the array: ");
scanf("%d", &size);
int arr[size];
// Input array elements in sorted order
printf("Enter the sorted array elements:\n");
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
// Input the element to be searched
printf("Enter the element to be searched: ");
scanf("%d", &key);
// Perform binary search
result = binarySearch(arr, 0, size - 1, key);
// Output the result
if (result != -1)
printf("Element %d found at index %d\n", key, result+1);
else
printf("Element %d not found in the array\n", key);

return 0;
}

Output:
Enter the size of the array: 6
Enter the sorted array elements:

School of Computer Science and Engineering Page 52


Fundamentals of C Programming Lab Course Code: B24CS0108

12
23
34
45
56
67
Enter the element to be searched: 56
Element 56 found at index 5

Enter the size of the array: 5


Enter the sorted array elements:
12
23
34
45
56
Enter the element to be searched: 78
Element 78 not found in the array

Outcome of the Excercise:


The program will effectively implement binary search and return the index of
the target value if found, or -1 if not found.

Viva Questions and Answers:

1. What is binary search?


 Binary search is an efficient algorithm for finding a target value in a sorted
array.
2. Why is binary search efficient?
 Binary search has a time complexity of O(log n), which is significantly
faster than linear search for large arrays.
3. What are the preconditions for binary search?
 The array must be sorted in ascending order.
4. How does binary search work?
 Binary search repeatedly divides the search interval in half until the target
is found or the interval becomes empty.
5. What is the time complexity of binary search?
 The time complexity of binary search is O(log n).

School of Computer Science and Engineering Page 53


Fundamentals of C Programming Lab Course Code: B24CS0108

6. Can binary search be used on unsorted arrays?


 No, binary search requires the array to be sorted.
7. What happens if the target value is not present in the array?
 The program will return -1 to indicate that the target value is not found.
8. How can you handle duplicate elements in the array?
 Binary search can handle duplicate elements. If the target value is found,
the program will return the index of the first occurrence.
9. Can binary search be implemented recursively?
 Yes, binary search can be implemented recursively.
10. What are some common applications of binary search?

 Binary search is used in various applications, including searching for elements in


sorted arrays, finding the square root of a number, and implementing data
structures like binary search trees.

12.Develop a program using pointers to compute the sum, mean and


standard deviation of all elements stored in an array of N real numbers.

Problem Statement:

Write a C program using pointers to compute the sum, mean, and standard
deviation of an array of N real numbers.

Solution Overview:

1. Input:
o Read the value of N (the number of elements in the array).
o Dynamically allocate memory for an array of N real numbers using malloc.
o Read the elements of the array from the user.
2. Pointer Operations:
o Use a pointer to iterate through the array elements.
o Calculate the sum of the elements.
o Calculate the mean by dividing the sum by the number of elements.
o Calculate the variance by subtracting the mean from each element,
squaring the difference, summing the squared differences, and dividing
by the number of elements.
o Calculate the standard deviation by taking the square root of the
variance.
3. Output:
o Print the calculated sum, mean, and standard deviation.

Intuition:

 Pointers provide a flexible way to access and manipulate array elements.

School of Computer Science and Engineering Page 54


Fundamentals of C Programming Lab Course Code: B24CS0108

 By using a pointer, you can iterate through the array and perform calculations on
each element.
 The formulas for sum, mean, and standard deviation are used to compute the
desired values.

Algorithm:
1. Input:
 Read the number of elements, N.
 Allocate memory dynamically for an array of N real numbers using malloc.
 Read the N elements from the user and store them in the array.
2. Calculate sum:
 Initialize a variable sum to 0.
 Iterate through the array using a pointer, adding each element to sum.
3. Calculate mean:
 Calculate the mean by dividing sum by N.
4. Calculate standard deviation:
 Initialize a variable sd to 0.
 Iterate through the array again, calculating the difference between each element
and the mean, squaring it, and adding it to sd.
 Divide sd by N-1 to get the variance.
 Calculate the standard deviation as the square root of the variance.
5. Output:
 Print the sum, mean, and standard deviation.

Program:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main()
{
int N;
float *arr, sum = 0, mean, sd = 0;
printf("Enter the number of elements: ");

School of Computer Science and Engineering Page 55


Fundamentals of C Programming Lab Course Code: B24CS0108

scanf("%d", &N);
// Dynamically allocate memory for the array
arr = (float*)malloc(N * sizeof(float));
if (arr == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
printf("Enter the elements:\n");
for (int i = 0; i < N; i++) {
scanf("%f", arr + i);
sum += *(arr + i);
}
mean = sum / N;
for (int i = 0; i < N; i++)
{
sd += pow(*(arr + i) - mean, 2);
}
sd = sqrt(sd / (N - 1));
printf("Sum: %.2f\n", sum);
printf("Mean: %.2f\n", mean);
printf("Standard deviation: %.2f\n", sd);
// Free the allocated memory
free(arr);
return 0;
}

Output:
Enter the number of elements: 5
Enter the elements:
1.0 2.5 3.0 4.5 5.0
Sum: 16.00
Mean: 3.20
Standard deviation: 1.41

Enter the number of elements: 4


Enter the elements:
2.0 4.0 6.0 8.0
Sum: 20.00

School of Computer Science and Engineering Page 56


Fundamentals of C Programming Lab Course Code: B24CS0108

Mean: 5.00
Standard deviation: 2.45

Outcomeof the Exercise:

The program will successfully compute and print the sum, mean, and standard
deviation of the given array of real numbers using pointers.

Viva Questions and Answers

1. What is the purpose of using pointers in this program?


 Pointers allow you to dynamically allocate memory for the array and
efficiently access and manipulate its elements.
2. How is memory allocated for the array?
 The malloc function is used to allocate memory for the array based on the
specified number of elements.
3. What are the steps involved in calculating the mean and standard deviation?
 The mean is calculated by summing the elements and dividing by the
number of elements. The standard deviation is calculated by finding the
square root of the variance, which is the average squared difference
between each element and the mean.
4. Why is it important to use a pointer to iterate through the array?
 Using a pointer allows you to access and modify the array elements
directly, without having to copy the entire array.
5. Can you explain the concept of dynamic memory allocation?
 Dynamic memory allocation allows you to allocate memory at runtime
based on the program's needs, rather than allocating a fixed amount of
memory at compile time.
6. What are the advantages of using pointers in this program?
 Pointers provide flexibility, efficiency, and dynamic memory management,
making them well-suited for tasks like array manipulation and
calculations.
7. How can you handle potential errors or exceptions in the program?
 You can use error checking to ensure that the malloc function succeeds
and that the array is properly allocated. You can also handle cases where
the input might be invalid or unexpected.
8. Can you modify the program to handle arrays of different data types?
 Yes, you can modify the program to handle arrays of different data types
by changing the data type of the pointer and the elements in the array.
9. What is the time complexity of the program?
 The time complexity of the program is O(n), where n is the number of
elements in the array. This is because the calculations involve iterating
through the array once.
10. Can you explain the significance of standard deviation in statistics?

 Standard deviation measures the dispersion or spread of data points around the
mean. It provides insights into how much the data varies from the average
value.

School of Computer Science and Engineering Page 57


Fundamentals of C Programming Lab Course Code: B24CS0108

7. Learning Resources:
TEXT BOOKS:
1. B.W. Kernighan & D.M. Ritchie, "C Programming Language", 2nd Edition,
PRENTICE HALL
2. SOFTWARE SERIES, 2005.
3. Herbert Schildt, “C: The Complete Reference”, 4th edition, TATA McGraw
Hill,2000.
4. B.S. Anami, S.A. Angadi and S. S. Manvi, “Computer Concepts and C Programming”
5. Holistic Approach”, second edition, PHI,2008.

REFERENCE BOOKS:
1. Balaguruswamy,” Programming in ANSI C”, 4th edition, TATA MCGRAW Hill, 2008.
2. Donald Hearn, Pauline Baker, “Computer Graphics C Version”,
second edition, Pearson Education, 2004

Web Based Resources and E-books:


1.http://cslabcms.nju.edu.cn/problem_solving/images/c/cc/
The_C_Programming_Language_%282nd_Edition_Ritchie_Kernighan%29.pdf

2.http://pdvpmtasgaon.edu.in/uploads/dptcomputer/Let%20us%20c%20-
%20yashwantkanetkar.pdf

3.https://karadev.net/uroci/filespdf/files/head-first-c-o-reilly-david-grifffiths-dawn-
griffiths.pdf

School of Computer Science and Engineering Page 58

You might also like