0% found this document useful (0 votes)
139 views

Final Lab Manual CPPS

c programming manual

Uploaded by

Sanskriti Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
139 views

Final Lab Manual CPPS

c programming manual

Uploaded by

Sanskriti Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 92

PUNE INSTITUTE OF COMPUTER TECHNOLOGY,

DHANKAWADI, PUNE – 43.

ACADEMIC YEAR: 2024-25

LIST OF LAB EXPERIMENTS

DEPARTMENT: Basic Science and Engineering Date: 23/09/2024

CLASS: F.Y.B.Tech SEMESTER: I


SUBJECT: C Programming for Problem solving Lab(CPPSL)

Expt.
Problem Definition/Statement
No.
(Implement any 10)
Write a Program to convert Fahrenheit to Celsius.
1
Write a program to calculate simple and compound interests.
2
Write a program to develop an arithmetic calculator. Add the modulus (%) operator and
3 provision of negative numbers.

Write a program to calculate the electricity bill for the given MODULEs.
4
Write a program to check whether a triangle is valid or not, when the three angles of the
triangle are entered through the keyboard. A triangle is valid if the sum of all the three angles
5
is equal to 180 degrees.

Write a program to read the user given year as an input and determine whether it is a “leap”
6 year or not.

Write a program to accept a character from user and check whether entered character is:
1. alphabet (lower case or upper case)
2. vowel
7
3. digit
4. special character

Write a program to accept a suitable input from the user and count blanks, tabs and
8 newlines.

Write a program to print “mirrored half diamond star pattern”.


9
Write a program to print all prime numbers from 1 to n. (use nested loop, break and
10 continue)

Write a program to count the frequency of each element in an array.


11
Write a program to find the smallest and largest elements in an array using pointers and
12 then swap these elements and display the resultant array.

First Year Engineering 1 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Write a program to perform matrix operations - Add, transpose and multiplication.


13
Write a program to count the vowels & consonants in each string using pointers.
14
The instructor has a class of 20 students. Each student is identified by roll no from 1 to 20.
and name. The two test scores of each student are to be stored. The instructor would like to
15 enter student roll no, name and test score. Write a program to process this information, grade
each student and display the result in pleasing format.

Write a program in C to swap two numbers using a function. (use call by value and call by
16 reference)

Write a C program to accept a matrix of order m x n. Implement the following functions:


i)Find the sum of each row
17
ii) Find the sum of each column.
The sum should be printed in the main function only.
18 Develop a recursive C function to find the factorial of a given number.

First Year Engineering 2 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

PREFACE
INTRODUCTION
These laboratory exercises are designed with a dual purpose:
1. To provide the student with “hands-on” experience in the C Programming Language
through the implementation of several programs.
2. To provide an atmosphere where the student will be required to communicate, both in
written and oral form.
It is the responsibility of the student to perform required preparation for lab work.
These labs will require some preparation prior to arriving in the lab.
JOURNAL WRITING INSTRUCTIONS
1. Title
2. Date of Completion
3. Problem Statement
4. Objectives
5. Software & Hardware requirements
6. Theory- Concept
7. Pseudo code
8. Flowchart
9. Test Cases minimum 3
10. Conclusion

REQUIRED LABORATORY PROCEDURES


1. The implementation required of any program should be completed during the scheduled
lab timings.
2. All the students must report to the lab on time.
3. All the students must carry a lab notebook, without which students won’t be allowed to
enter the lab.
4. All programs should be properly documented, well indented & must use appropriate
Hungarian notation along with relevant comments wherever necessary.
5. Program should be tested for all valid data.
Failure to any of the above will result in a reduced grade.

To develop and run a program in:


1. C Compiler:
o You need a C compiler to translate your C code into machine-readable language
(executable code). Popular choices include:
▪ GCC (GNU Compiler Collection): Available on Linux distributions and also as part of
MinGW for Windows.
▪ Clang: Another widely used compiler, known for its strict adherence to standards and
helpful error messages.
▪ Microsoft Visual C++ Compiler: Specifically for Windows environments.
2. Integrated Development Environment (IDE) (optional but recommended):
o An IDE provides an integrated environment for writing, compiling, and debugging code.
Some popular options for C programming include:
▪ Visual Studio: Offers a comprehensive IDE with powerful debugging tools (Windows).
▪ Code::Blocks: A lightweight and open-source IDE that supports multiple compilers
(Windows, Linux, macOS).
▪ Eclipse: Widely used in various programming languages, including C/C++ (cross-
platform).

First Year Engineering 3 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
▪ Xcode: Apple's IDE for macOS and iOS development.
3. Text Editor:
o If you prefer not to use a full IDE, a text editor with syntax highlighting for C can
suffice. Examples include:
▪ Visual Studio Code: A lightweight editor with extensive plugin support (cross-
platform).
▪ Sublime Text: Known for its speed and flexibility (cross-platform).
▪ Atom: An open-source editor developed by GitHub (cross-platform).
▪ Notepad++: A simple and fast editor for Windows.
4. Operating System Compatibility:
o Most C compilers and IDEs are compatible with major operating systems like Windows,
macOS, and Linux. Ensure that your chosen development environment supports your operating
system.
5. Libraries (if needed):
o For basic calculations like those in simple and compound interest programs, standard
C libraries (like stdio.h for input/output operations) are typically sufficient. However, for more
advanced functionality, you might need additional libraries.

The hardware requirements for developing and running a C program

Processor (CPU):
o Any modern processor, such as Intel Core i3/i5/i7 or AMD Ryzen series, will suffice
for compiling and running C programs. Even older processors can handle C programs well due
to the language's efficiency.
2. Memory (RAM):
o A minimum of 2 GB of RAM is usually sufficient for compiling and running simple C
programs. However, having more RAM (4 GB or more) can improve overall performance,
especially when working with larger projects or multiple applications simultaneously.
3. Storage:
o C compilers and development environments require only a small amount of disk space
(typically less than 1 GB). However, ensure you have enough disk space for storing your source
code files, compiler executables, and any additional libraries or tools you might use.

Introduction to Programming

Software refers to a program or set of instructions that instructs a computer to perform some
task. Software can be divided into two major categories called system software and application
software. Systems software includes operating systems and various device drivers. Application
software are used to perform real-world tasks and solve specific problems.

First Year Engineering 4 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
A program is simply a set of instructions that tells a computer how to perform a particular task.
Programs are developed using programming languages. Computer programming is the art of
developing computer programs. Programming is rather like a recipe; a set of instructions that
tells a cook how to make a particular dish. It describes the ingredients (the data) and the
sequence of steps (the process) on how to mix those ingredients.
A programming language provides a set of rules to develop a program. A person who writes a
program using a programming language is called a programmer. His/her job is to convert a
solution to a problem (i.e. algorithm) into a set of instructions understood by a computer. The
programmer should also test the program to see whether it is working properly and corrective
actions should be taken if not.

Program Development

Developing a program involves a set of steps:

1. Define the problem


2. Outline the solution
3. Develop an algorithm1
4. Test the algorithm for correctness
5. Code the algorithm using a suitable programming language
6. Compile and correction of compile errors
7. Run the program on the computer
8. Test, document and maintain the program

Define the Problem


First of all the problem should be clearly defined. The problem can be divided into three
components:

• Inputs – what do you have?


• Outputs – what do you want to have?
• Processing – how do you go from inputs to outputs?

Programmers should clearly understand “what are the inputs to the program”, “what is
expected as output(s)” and “how to process inputs to generate necessary outputs”. Consider an
example where a computer program is to be written to calculate and display the circumference
and area of a circle when the radius.

• Inputs – the radius (r)


• Outputs – circumference (c) and area (a)
• Processing § c = 2pr, a = pr2

Outline the Solution


The programmer should define:

• The major steps required to solve the problem


• Any subtasks • the major variables and data structures
• The major control structures (e.g. sequence, selection, repetition loops)2 in the
algorithm
• The underlined logic
Consider the above-mentioned example. In order to calculate the circumference:

First Year Engineering 5 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
• Variables – radius (r), circumference (c)
• Calculation – c = 2pr0

In order to calculate the area:

• Variables – radius (r), area (a)


• Calculation – a = pr2

Develop the Algorithm

The next step is to develop an algorithm that will produce the desired result(s). An algorithm
is a segment of precise steps that describes exactly the tasks to be performed, and the order in
which they are to be carried out to solve a problem. Pseudocode (a structured form of the
English language) can be used to express an algorithm. A suitable algorithm for our example
would be:

Start
Input r
Calculate circumference
c = 2 * PI* r
Calculate area
a = PI* r^2
Output c & a
End

In here PI is a constant that represents the value of p.

Test the Algorithm


For Correctness The programmer must make sure that the algorithm is correct. The objective
is to identify major logic errors early, so that they may be easily corrected. Test data should be
applied to each step, to check whether the algorithm actually does what it is supposed to.
Our simple example can be quite easily check by submitting some values for radius (r) and
walking through the algorithm to see whether the resulting output is correct for each input.

Code the Algorithm


After all the design considerations have been met and when the algorithm is finalized code it
using a suitable programming language.

Compile:
The next step is to compile the program. While compiling syntax errors can be identified. When
the written program does not adhere to the programming language rules those are called syntax
errors. These errors occur mostly due to miss typed characters, symbols, missing punctuations,
etc. If there are no syntax errors the program gets compiled and it produces an executable
program.

Run the Program:

First Year Engineering 6 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
Executable program generated after compiling can then be executed. While the program is
running runtime errors and sometimes logic errors can be identified. Runtime errors occur
while executing the program and those are mostly due to incorrect inputs.
Test, Document and Maintain the Program
Test the running program using test data to make sure the program is producing correct
output(s).
During this phase logic errors can be found. Logic errors occur due to incorrect algorithms
(although you provide correct inputs you do not get the correct outputs). All the steps involved
in developing the program algorithm and code should be documented for future reference.
Programmers should also maintain and update the program according to new or
changing requirements.

Running a Program:
After a program is developed using a programming language, it should be executed by the
computer. Programmers write programmes in human readable languages called high-level
languages. However, the computer understands only 1’s and 0’s (referred as the machine
language3 or machine code). Therefore, we need to convert the human readable programs into
a machine language before executing. This conversion is achieved by a special set of programs
called compilers (or interpreters). These programs convert the high-level language program
into machine language programs.

Compilers translate a source program (human-readable) into an executable (machine- readable)


program (. Executable machine code produced by a compiler can be saved in a file (referred as
the executable file) and used whenever necessary. Since the source program is already
compiled, no compilation is needed again unless the source program is modified. The saving
on the compilation time is an advantage that is gain from compiling and therefore these
programs run much faster. Programs written in programming languages such as FORTRAN,
COBOL, C, C++ and Pascal must be compiled before executing.

Compiling And executing a programs

First Year Engineering 7 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Interpretation of a program

Overview of C
“C’ seems a strange name for a programming language but it is one of the most widely used
languages in the world. C was introduced by Dennis Ritchie in 1972 at Bell Laboratories as a
successor of the language called B (Basic Combined Programming Language – BCPL). Since
C was developed along with the UNIX operating system it is strongly associated with UNIX.
UNIX was developed at Bell Laboratories and it was written almost entirely in C.
For many years, C was used mainly in academic environments. However with the release of C
compilers for commercial use and increasing popularity of UNIX, it began to gain wide- spread
interest among computer professionals. Various languages such as C++, Visual C++, Java and
C# have branched away from C by adding object-orientation and GUI features.
Today C compilers are available for a number of operating systems including all flavors of
UNIX, Linux, MS-DOS, Windows and Apple Mac. C is a robust language whose rich set of
built-in functions and operations can be used to write
any complex program. C is well suited to write both commercial applications and system
software since it incorporates features of high-level languages and Assembly language.
Programs written in C are efficient and fast. Most C programs are fairly portable; that is with
little or no modification and compiling, C programs can be executed on different operating
systems.
The syntax and coding style of C is simple and well structured. Due to this reason most of the
modern languages such as C++, Java and C# inherit C coding style. Therefore it is one of the
best languages to learn the art of programming. C is also suitable for many complex engineering
applications.

Steps in Developing a Program in C


The compilation of a C program is infact a three stages process; preprocessing, compiling and
linking.

First Year Engineering 8 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

An Example C Program

/* Program - My First Program */

#include <stdio.h>
int main()
{
printf(“Hello World!”);
return 0;
}

The C language is built from functions like printf that execute different tasks. The functions
must be used in a framework which starts with the word main( ) , followed by the block
containing the function(s) which is marked by braces ({ } ). The main() is a special function
that is required in every C program. The keyword int indicates that the main () function returns
an integer value. Because function main () returns an integer value, there must be a statement
that indicates what this value is. The statement “return 0;”
The first line starting with characters / * and ending with characters * / is a comment.
Comments are used by programmers to add remarks and explanations within the program. It is
always a good practice to comment on your code whenever possible. Comments are of two
types; single line comments and block comments. Single line comments start with two slashes
{/ /} and all the text until the end of the line is considered a comment. Block comments start
with characters / * and end with

First Year Engineering 9 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
characters * /. Any text between those characters is considered a block of comments.
Lines that start with a pound (# ) symbols are called directives for the preprocessor. A
directive is not a part of the actual program; it is used as a command to the preprocessor to
direct the translation of the program. The directive # include appears
in all programs as it refers to the standard input output header file (stdio.h). Here, the
header file stdio.h includes information about the printf( ) function. When using more
then one directive each must appear on a separate line.
The function printf is embedded into a statement whose end is marked by a semicolon (;).
Semicolon indicates the end of a statement to the compiler. The C language is case sensitive
and all C programs are generally written in lowercase letters. Some of the special words may
be written in uppercase letters. Use your favorite text editor in Linux and type the above
program. Save it as HelloWorld.c (all C source files are saved with the extension .c). Then use
the shell and go to the directory that you have saved your source file. Use the command gcc
HelloWorld.c to compile your program. If there are no errors an executable file will be created
in the same location with the default file name a.out. To execute the program at the prompt
type./ a.out (i.e. to execute the a.out file in current directory). When you execute your program,
it should display “Hello World!” on the screen.

$ vim HelloWorld.c
$ gcc HelloWorld.c
$ ./a.out
Hello World! $

However, you will see the prompt ($) appearing just after the message “Hello World!” you can
avoid this by adding the new line character (\ n) to the end of the message. Then your modified
program should look like the following:

/* Program - My First Program */


#include<stdio.h>
int main ()
{
printf(“Hello World!\n”);
return 0;
}

Assignment No – 1

First Year Engineering 10 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Problem Write a C program to convert a temperature value from Fahrenheit to


Statement: Celsius

Objective :
By the end of this experiment, students will be able to:

● Understand how to perform arithmetic operations in C.


● Apply mathematical formulas in a C program.
● Design and develop a C program that integrates user input and
output functionalities.

Requirements: OS : Linux
Processor: 32/64 bit
Theory Concepts: Program Structure:
A C program typically includes:
● Header Files: Include necessary libraries (e.g., #include <stdio.h>).
● Main Function: The entry point of the program where execution
begins (int main()).
● Statements and Expressions: The code that performs operations
and controls program flow.
Input and Output:
● printf: Displays output to the user.
● scanf: Reads input from the user.
Variables:
● Definition: Variables are used to store data that can be used and
manipulated within a program. Each variable has a specific type that
determines the size and layout of the variable's memory.
● Types: Common types include int (integer), float (floating-point),
char (character), and double (double-precision floating-point).
● Declaration: Variables must be declared before they are used. The
declaration specifies the variable's type and name.

int age; // Declaration of an integer variable


float salary; // Declaration of a floating-point variable

Data Types:
● Primitive Types: Basic data types provided by C, such as int, float,
char, and double.
○ int: Used for integer values.
○ float: Used for single-precision floating-point numbers.
○ char: Used for single characters.
○ double: Used for double-precision floating-point numbers.
● Derived Types: Include arrays, pointers, structures, and unions.
Operators:
● Arithmetic Operators: Used to perform basic mathematical
operations.
○ Addition (+): Adds two values.
○ Subtraction (-): Subtracts one value from another.
○ Multiplication (*): Multiplies two values.
○ Division (/): Divides one value by another.

First Year Engineering 11 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
○ Modulus (%): Finds the remainder after division.
Unary Increment Operators: ++ - -
var++ increment "post" variant
++var increment "pre" variant

var-- decrement "post" variant


--var decrement "pre" variant
Other Operators:
+=, -= Increment or decrement by RHS
*=, /= Multiply or divide by RHS
%= Mod by RHS
>>= Bitwise right shift by RHS (divide by power of 2)
<<= Bitwise left shift RHS (multiply by power of 2)
&=, |=, ^= Bitwise and, or, xor by RHS
Temperature Conversion:
Temperature conversion between Fahrenheit and Celsius involves
converting a temperature reading from one scale to another. The relationship
between these two temperature scales is linear, and the conversion is
achieved through a specific formula.
Pseudo Code: Start
Input F
C = (F - 32) * (5 / 9)
Print C
Stop
Flowchart:

Conclusion:
This experiment successfully demonstrates how to convert a temperature
from Fahrenheit to Celsius using a C program. The exercise reinforces the
application of arithmetic operations and user interaction within a program.

First Year Engineering 12 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
By implementing the conversion formula, students gain practical experience
in using mathematical expressions in C programming.

Test Case:
Test Test case description Expected Output Actual Output Test Status
Case no
1 32 0.00 0.00 Pass
2 112 44.4444 44.4444 Pass
3 98.6 37.00 37.00 Pass
4 0 -17.78 -17.78 Pass

Questions:
1. What is the formula for converting Celsius to Fahrenheit?
2. What data types should I use for the variables in a Celsius to Fahrenheit conversion
program?
3. How does the use of floating-point numbers in C affect the accuracy of temperature
conversions?
4. Which data types in C are best suited for handling temperature values, and why?
5. How can you handle user input in C to ensure valid temperature values are entered?

Extra Practice Assignments: -

1. Create a program that converts temperatures from Fahrenheit to Celsius and also from
Celsius to Fahrenheit.
2. Implement a C program to display a conversion table from Fahrenheit to Celsius for
temperatures ranging from -50°F to 100°F, with increments of 10°F.
3. Design a C program that calculates the average of multiple temperature readings in
Fahrenheit and then converts the average to Celsius.
4. Write a program to determine the state of water (solid, liquid, or gas) based on a given
temperature in Fahrenheit after converting it to Celsius.
5. The distance between two cities (in km.) is input through the keyboard. Write a program
to convert and print this distance in meters, feet, inches and centimeters.
6. Write a program that converts speed from kilometers per hour (km/h) to miles per hour
(mph).
7. Create a program that converts an amount of money from one currency to another based
on the provided exchange rate.
8. Design a program that converts a distance from kilometers to miles.
9. Create a program that converts an amount in US Dollars (USD) to Euros (EUR) using
a predefined exchange rate.
10. Write a program that converts fuel efficiency from miles per gallon (mpg) to liters per
100 kilometers (L/100 km).
11. Ramesh’s basic salary is input through the keyboard. His dearness allowance is 40% of
basic salary, and house rent allowance is 20% of basic salary. Write a program to calculate his
gross salary.

First Year Engineering 13 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
12. If the marks obtained by a student in five different subjects are input through the
keyboard, find out the aggregate marks and percentage marks obtained by the student. Assume
that the maximum marks that can be obtained by a student in each subject is 100.
13. A cashier has currency notes of denominations 10, 50 and 100. If the amount to be
withdrawn is input through the keyboard in hundreds, find the total number of currency notes
of each denomination the cashier will have to give to the withdrawer.
14. If the total selling price of 15 items and the total profit earned on them is input through
the keyboard, write a program to find the cost price of one item.

Assignment No – 2

Problem Write a program to develop an arithmetic calculator. Add the modulus (%)
Statement: operator and provision of negative numbers.

First Year Engineering 14 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Objective :
By the end of this experiment, students will be able to:

● Apply arithmetic operators in C to perform basic calculations.


● Analyze user input, including negative numbers, and output the
correct result.
● Implement a modular approach to building a basic calculator in C.

Requirements: OS : Linux
Processor: 32/64 bit
Theory Concepts:
● Key Components of the Program

1. Operators and Syntax: Arithmetic operators in C are used to


perform operations on operands. For an arithmetic calculator, we need to
handle the following operators:
○ Addition (+): Adds two numbers.
○ Subtraction (-): Subtracts the second number from the first.
○ Multiplication (*): Multiplies two numbers.
○ Division (/): Divides the first number by the second. Care must be
taken to handle division by zero.
○ Modulus (%): Returns the remainder of the division of the first
number by the second. Only applicable for integer types.

The modulus operator, denoted as %, returns the remainder when one


number (the dividend) is divided by another number (the divisor).
Modulus of Positive Numbers
A remainder is least positive integer that should be subtracted from a to
make it divisible by b (mathematically if, a = q*b + r then 0 ? r < |b|), where
a is dividend, b is divisor, q is quotient and r is remainder.
modulus of the operation.
● Syntax of Modulus Operator
If x and y are integers, then the expression:
x % y;
pronounced as “x mod y”. For example, 10 % 2 will be pronounced as ” Ten
mod Two”.
Return Value of Modulo Operator
● If y completely divides x, the result of the expression is 0.
● If x is not completely divisible by y, then the result will be the
remainder in the range [0, y-1]
● (x % y) < (x / 2) ………if (x >= y)
● (x % y) = x ……… if (x < y)
● If y is 0, then division by zero is a compile-time error.

The modulo operator has few restrictions or limitations on it. The %


modulus operator cannot be applied to floating-point numbers i.e. float or
double. If you try to use the modulo operator with floating-point constants
or variables, the compiler will produce an error.

First Year Engineering 15 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

3. if Statement
The if in C is the most simple decision-making statement. It consists of the
test condition and if block or body. If the given condition is true only then
the if block will be executed.

Syntax:
if(condition)
{
// if body
// Statements to execute if condition is true
}

if-else Statement:

The if-else statement is used to make decisions based on conditions. It


executes a block of code if a specified condition is true and optionally
executes another block of code if the condition is false.

Syntax:

if (condition) {

// Code to execute if condition is true

} else {

// Code to execute if condition is false

4. if else if ladder
if else if ladder in C programming is used to test a series of conditions
sequentially. Furthermore, if a condition is tested only when all previous if
conditions in the if-else ladder are false. If any of the conditional
expressions evaluate to be true, the appropriate code block will be
executed, and the entire if-else ladder will be terminated.
Syntax:

// any if-else ladder starts with an if statement only


if(condition) {

}
else if(condition) {
// this else if will be executed when condition in if is false and
// the condition of this else if is true
}
.... // once if-else ladder can have multiple else if
else { // at the end we put else

First Year Engineering 16 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

}
Nested if-else Statements:

nested if-else statements involve placing one if-else statement inside


another if-else statement. This allows for more complex decision-making
where multiple conditions need to be evaluated.

Syntax:

if (condition1) {
// Code to execute if condition1 is true
if (condition2) {
// Code to execute if condition1 and condition2 are true
} else {
// Code to execute if condition1 is true and condition2 is false
}
} else {
// Code to execute if condition1 is false
}

switch-case Statement:

The switch-case statement is used for multi-way branching. It allows you


to select one of many code blocks to execute based on the value of an
expression.

Syntax:

switch (expression) {
case value1:
// Code to execute if expression equals value1
break;
case value2:
// Code to execute if expression equals value2
break;
// More cases...
default:
// Code to execute if expression does not match any case
}
for Loop:
The for loop is used for iterating over a block of code a specific number of
times. It is typically used when the number of iterations is known
beforehand.

Syntax:
for (initialization; condition; increment/decrement) {
// Code to execute on each iteration
}

First Year Engineering 17 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

while Loop:

The while loop is used for iterating as long as a condition is true. It is


typically used when the number of iterations is not known beforehand and
is determined by a condition evaluated before each iteration.

Syntax:

while (condition) {
// Code to execute while condition is true
// Update control variable to eventually break the loop
}

goto Statement:

The goto statement transfers control to another part of the program. It is


generally discouraged because it can make code harder to read and
maintain. Use it with caution.

Syntax:

goto label;

...

label:
// Code to execute

continue Statement:

The continue statement is used to skip the rest of the code in the current
loop iteration and proceed to the next iteration of the loop.

Syntax:

for (initialization; condition; increment) {


if (condition) {
continue; // Skip to next iteration
}
// More code
}

while (condition) {
if (condition) {
continue; // Skip to next iteration
}
// More code
}

First Year Engineering 18 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Pseudo Code: START

FUNCTION main()
// Initialize variables
DECLARE choice AS INTEGER
DECLARE a, b, c AS DOUBLE
DECLARE continueCalc AS CHARACTER

// Display the menu options


PRINT "Calculator Menu:"
PRINT "1. Addition"
PRINT "2. Subtraction"
PRINT "3. Multiplication"
PRINT "4. Division"
PRINT "5. Modulus"
PRINT "Enter your choice (1-5):"
INPUT choice

// Ask the user to input two numbers


PRINT "Enter two numbers:"
INPUT a, b

// Perform the selected operation based on user choice


SWITCH(choice)
CASE 1:
// Addition
c=a+b
PRINT "Result: ", c
BREAK
CASE 2:
// Subtraction
c=a-b
PRINT "Result: ", c
BREAK
CASE 3:
// Multiplication
c=a*b
PRINT "Result: ", c
BREAK
CASE 4:
// Division
IF b != 0 THEN
c=a/b
PRINT "Result: ", c
ELSE
PRINT "Error: Division by zero is not allowed."
END IF
BREAK
CASE 5:

First Year Engineering 19 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
// Modulus
IF (INTEGER(b) != 0) THEN
c = INTEGER(a) % INTEGER(b)
PRINT "Result: ", c
ELSE
PRINT "Error: Modulus by zero is not allowed."
END IF
BREAK
DEFAULT:
PRINT "Invalid choice! Please enter a number between 1 and 5."
END SWITCH

// Ask if the user wants to perform another calculation


PRINT "Do you want to perform another calculation? (y/n):"
INPUT continueCalc

// Check if the user wants to continue


IF continueCalc == 'y' OR continueCalc == 'Y' THEN
CALL main() // Recursively call main() to repeat the process
ELSE
PRINT "Program ended."
END IF
END FUNCTION

END

Flowchart:

Menu:
Addition
Substractin

Input

Conclusion This experiment successfully demonstrates the implementation of a basic


arithmetic calculator in C, covering all primary arithmetic operations and
handling of negative numbers. Through this exercise, students gain practical
experience in using arithmetic operators, managing user input, and

First Year Engineering 20 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
structuring a C program to solve real-world problems. This foundational
knowledge is essential for more advanced programming concepts.

Test Case:
Test Choice Enter two Expected Output Actual Output Test
Case numbers Status
no
1 6 - Invalid Choice Invalid choice Pass
2 4 a=7,b=3 2.33 2.33 Pass
3 5 a=7,b=3 1 1 Pass

Questions:
1. What is the modulus operator (%), and how does it differ from other arithmetic
operators?
2. How do you handle division by zero in an arithmetic calculator program?
3. How can a calculator program be designed to accept and correctly process negative
numbers?
4. What is an arithmetic calculator, and what basic operations should it support?

Extra Practice Assignments: -


1. If a five-digit number is input through the keyboard, write a program to calculate the
sum of its digits. (Hint: Use the modulus operator ‘%’)
2. Implement a C program to calculate the power of a number using a custom function,
allowing the user to choose the base and exponent.
3. Write a C program that can calculate the power of a number and the square root of a
number, in addition to performing basic arithmetic operations.
4. Write a program that calculates the result of an arithmetic expression that includes
multiple operations, following the correct order of operations (BODMAS).
5. Develop a calculator program that accepts a single string input in the form of an
arithmetic expression (e.g., 5 + 3) and outputs the result.
6. Create a C program that continuously accepts user input for operations until the user
decides to exit.
7. Write a program to handle division by zero and provide an appropriate error message
to the user.
8. If a five-digit number is input through the keyboard, write a program to reverse the
number.
9. 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.
10. In a town, the percentage of men is 52. The percentage of total literacy is 48. If the
total percentage of literate men is 35% of the total population, write a program to find the
total number.of illiterate men and women if the population of the town is 80,000.
11. If a five-digit number is input through the keyboard, write a program to print a new
number by adding one to each of its digits. For example if the number that is input is 12391
then the output should be displayed as 23402.
12. According to a study, the approximate level of intelligence of a person can be
calculated using the following formula:

First Year Engineering 21 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
Write a program, which will produce a table of values of i, y and x, where y varies from 1 to
6, and, for each value of y, x varies from 5.5 to 12.5 in steps of 0.5.
13. When interest compounds q times per year at an annual rate of r % for n years, the
principle p compounds to an amount a as per the following formula

Write a program to read 10 sets of p, r, n & q and calculate


the corresponding as.

14. The natural logarithm can be approximated by the following series.

If x is input through the keyboard, write a program to calculate the sum of first seven terms of
this series.

Assignment No – 3

Problem Write a program to calculate the electricity bill for the given MODULEs.
Statement:
Objective :
By the end of this experiment, students will be able to:

● Understand how to use functions in C to create modular code.


● Apply conditional statements to handle different tariff slabs.
● Implement a user-friendly program that accurately calculates the
electricity bill based on units consumed.

Requirements: OS : Linux
Processor: 32/64 bit
Theory Concepts:
Electricity billing is a standard problem involving the calculation of the
cost of electricity consumed by a user. The cost depends on the number of
units consumed and the applicable tariff rates. The calculation typically
involves the following steps:

1. Units Consumed: The amount of electricity used, measured in


kilowatt-hours (kWh).

First Year Engineering 22 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
2. Tariff Slabs: Different rates are applied to different ranges of units
consumed. For example, the rate may be lower for initial units and higher
for subsequent units.
3. Total Bill Calculation: Based on the units consumed and the
corresponding rates, the total bill is computed.

Modular Programming in C:

● Modular programming involves breaking down a program into


smaller, manageable functions, each responsible for a specific task. This
approach improves code readability, maintainability, and reusability.
● In this program, we will use separate functions (modules) for
input, calculation, and display. Each function will handle a specific aspect
of the program, allowing for easier debugging and updates.

What is a Function:A function is a self-contained block of statements


that perform a coherent task of some kind.

Syntax:

1. Function Declaration (Prototype):

return_type function_name(parameter_list);

2. Function Definition:

return_type function_name(parameter_list) {

// Function body: code to be executed

return value; // Optional: only if return_type is not void

3. Function Call:

function_name(arguments);

First Year Engineering 23 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Fig:Function Call in same Program

Fig: Function call in other programs.

Tariff Rates:Let's assume the following tariff rates for simplicity:

● First 100 units: ₹4.29 per unit


● Next 300 units: ₹7.34 per unit (101 to 300)
● Next 500 units: ₹10.28 per unit(301 to 500)
● Beyond 500 units: ₹11.83 per unit

First Year Engineering 24 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
● Minimum charges should be ₹120

Pseudo Code: START

FUNCTION input()
DECLARE units AS INTEGER
PRINT "Enter units: "
INPUT units
RETURN units
END FUNCTION

FUNCTION calculate_bill(units)
DECLARE bill AS DOUBLE
IF units <= 150 THEN
bill = units * 2.75
ELSE
bill = 150 * 2.75 + ((units - 150) * 5.25)
END IF
RETURN bill
END FUNCTION

FUNCTION display_bill(bill)
PRINT "Bill is: ", bill
END FUNCTION

FUNCTION main()
DECLARE units AS INTEGER
DECLARE bill AS DOUBLE

// Call input function and store units


units = input()

// Call calculate_bill with units and get the bill


bill = calculate_bill(units)

// Call display_bill with the calculated bill


display_bill(bill)

RETURN 0
END FUNCTION

END

First Year Engineering 25 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Flowchart:

if amount=unit*1.50

else if amount=(100*1.50)+((

else amount=(100*1.50)+(2

Conclusion
This experiment successfully demonstrates the use of modular
programming in C to develop a basic electricity bill calculator. The
program handles user input, calculates the bill based on different tariff
slabs, and displays the result effectively. This modular approach not only
makes the program easy to understand and maintain but also highlights the
importance of structured programming techniques in solving real-world
problems.

Test Case:
Test Units consumed Expected Bill Actual Output Test Status
Case no calculated
1 0 150 150 Pass
2 50 75 75 Pass
3 350 450 450 Pass

Questions:
1. Define mod.
2. What is mod arithmetic?
3. What is the difference between modulus and divide operator?
4. What are the typical components of an electricity bill?
5. How is energy consumption usually measured and billed?
6. What are usage slabs or MODULEs, and why are they used in electricity billing?
7. How can conditional statements be used in C to calculate electricity bills based on
different MODULEs?

First Year Engineering 26 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Extra Practice Assignments: -


1. Extend the above program to apply a 5% tax on the total bill amount after calculating
the electricity charges.
2. Write a program to calculate the electricity bill, including a peak hour surcharge
3. Write a C program to calculate a taxi fare based on the distance traveled in kilometers.
4. Write a C program to calculate income tax based on a graduated tax system.
5. Create a C program to calculate toll fees for a highway based on distance traveled and
vehicle type.
6. Create a C program to calculate hotel bills with tiered room rates and additional
service charges
7. Write a program to add first seven terms of the following
8. Write a program to print all prime numbers from 1 to 300.
9. series using a for loop:

10. Write a program to generate all combinations of 1, 2 and 3 using a for loop.
11. Write a program to produce the following output:

12. A machine is purchased which will produce an earning of Rs. 1000 per year while it
lasts. The machine costs Rs. 6000 and will have a salvage of Rs. 2000 when it is condemned.
If 12 percent per annum can be earned on alternative investments what would be the
minimum life of the machine to make it a more attractive investment compared to alternative
investment?

First Year Engineering 27 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Assignment No – 4

Problem Write a program to check whether a triangle is valid or not, when the three
Statement: angles of the triangle are entered through the keyboard. A triangle is valid if
the sum of all the three angles is equal to 180 degrees.

Objective : By the end of this experiment, students will be able to:

● Understand the concept of triangle validity based on angles.


● Implement a simple conditional check in a C program.
● Take user input and display output using C programming.

Requirements: OS : Linux
Processor: 32/64 bit
Theory Concepts: A triangle is a polygon with three edges and three vertices. The most
important property of a triangle is that the sum of its internal angles is always

First Year Engineering 28 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
equal to 180 degrees. This property can be used to verify if three given angles
can form a triangle.
● Basic Concepts in C Programming:

● Variables: Used to store data that can be used and manipulated


within the program.
● Input/Output: scanf and printf are used to read input from the user
and print output to the console, respectively.
● Conditional Statements: if statements are used to perform different
actions based on different conditions. In this program, we use if to check if
the sum of the angles equals 180.
● Operators:
○ Arithmetic Operators: Used for mathematical calculations (+, -,
etc.).
○ Relational Operators: Used to compare values (==, !=, <, >, etc.).

Pseudo Code: START


DECLARE three INTEGER variables: angle1, angle2, angle3
PRINT "Enter the three angles of the triangle: "
INPUT angle1, angle2, angle3
CALCULATE sum = angle1 + angle2 + angle3
IF sum EQUALS 180 THEN
PRINT "The triangle is valid."
ELSE
PRINT "The triangle is not valid."
END

First Year Engineering 29 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Flowchart:
Start

Read
ang1,ang2,and3

sum=ang1+ang2+ang3

If Triangle is not
sum==180 valid

Triangle is valid

Stop

Conclusion This experiment demonstrates how to use basic input, output, and conditional
logic in C to solve a real-world problem. By checking the sum of the three
angles, we can determine whether a given set of angles can form a valid
triangle. The experiment also reinforces the understanding of using relational
operators and conditional statements in programming.

Test Case:
Test Angle 1 Angle2 Angle3 Expected Actual Test
Case Output Output Status
no
1 60 60 60 Triangle is Triangle is Pass
valid valid
2 90 45 45 Triangle is Triangle is Pass
valid valid
3 12 30 25 Triangle is Triangle is Pass
not valid not valid

First Year Engineering 30 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Questions:
1. What are the potential types of triangles based on their angles, and how can they be
identified?
2. What are some real-world applications where validating the angles of a triangle is
necessary?

Extra Practice Assignments: -


1. Write a program in which user input be validated in C to ensure the program only
accepts valid angles?
2. Modify the above program to also check if the triangle is a right triangle, an acute
triangle, or an obtuse triangle.
3. Develop a C program that repeatedly asks the user for three angles until a valid
triangle is entered.
4. Create a program that takes input for three angles and outputs whether they form a
valid triangle and, if so, calculates the possible lengths of sides assuming a unit radius
circumcircle
5. Write a C program to calculate the area and perimeter of a rectangle.
6. Write a C program to calculate the volume and surface area of a cylinder
7. Create a C program to calculate the area of a regular polygon.

8. Create a C program to calculate the area of a triangle given its three sides. The
program should use Heron's formula:

9. Write a program to print the multiplication table of the number entered by the user.
The table should get displayed in the following form.

10. Write a program to produce the following output:

11. Write a program to produce the following output:

First Year Engineering 31 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

First Year Engineering 32 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Assignment No – 5

Problem Write a program to accept a suitable input from the user and count blanks,
Statement: tabs and newlines.
Objective : By the end of this experiment, students will be able to:

● Understand how to read and process character input in C.


● Implement loops and conditional statements to analyze and count
specific characters.
● Develop skills in handling text input and managing program flow
based on user input.

Requirements: OS : Linux
Processor: 32/64 bit
Theory Concepts: In text processing, characters such as blanks (spaces), tabs, and newlines are
used for formatting. These characters are part of the control characters in
ASCII:

● Blanks (Spaces): Represented by ' ' in C, they separate words and


sentences.
● Tabs: Represented by '\t' in C, they are used for indentation or
aligning text in a tabular format.
● Newlines: Represented by '\n' in C, they mark the end of a line and
move the cursor to the beginning of the next line.

Strings:
Strings are used for storing text/characters.

For example,
"Hello World" is a string of characters.

Unlike many other programming languages, C does not have a String type
to easily create string variables. Instead, you must use the char type and
create an array of characters to make a string in C
Note that you have to use double quotes ("").

To output the string, you can use the printf() function together with
the format specifier %s to tell C that we are now working with strings:

Example:

First Year Engineering 33 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
char greetings[] = "Hello World!";

printf("%s", greetings);

Access Strings:
Since strings are actually arrays in C, you can access a string by referring
to its index number inside square brackets [].

This example prints the first character (0) in greetings.

Example:

char greetings[] = "Hello World!";

printf("%c", greetings[0]);

Modify Strings:
To change the value of a specific character in a string, refer to the index
number, and use single quotes.

Example:

char greetings[] = "Hello World!";


greetings[0] = 'J';
printf("%s", greetings);
// Outputs Jello World! instead of Hello World!

Loop Through a String:

You can also loop through the characters of a string, using a for loop.

Example:

char carName[] = "Volvo";


int i;

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


printf("%c\n", carName[i]);
}

Another Way Of Creating Strings:


In the examples above, we used a "string literal" to create a string variable.
This is the easiest way to create a string in C.

You should also note that you can create a string with a set of characters.

Example:

First Year Engineering 34 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
char greetings[] = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0'};
printf("%s", greetings);

5. C String Functions:
C also has many useful string functions, which can be used to perform
certain operations on strings.
To use them, you must include the <string.h> header file

#include <string.h>

String Length

For example, to get the length of a string, you can use the strlen() function.

Example:
char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
printf("%d", strlen(alphabet));

In the Strings chapter, we used sizeof to get the size of a string/array. Note
that sizeof and strlen behaves differently, as sizeof also includes the \0
character when counting

Example:

char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";


printf("%d", strlen(alphabet)); // 26
printf("%d", sizeof(alphabet)); // 27

Concatenate Strings

To concatenate (combine) two strings, you can use the strcat() function

Example:

char str1[20] = "Hello ";


char str2[] = "World!";

// Concatenate str2 to str1 (result is stored in str1)


strcat(str1, str2);

// Print str1
printf("%s", str1);

Copy Strings

To copy the value of one string to another, you can use the strcpy()
function
char str1[20] = "Hello World!";
char str2[20];

First Year Engineering 35 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
// Copy str1 to str2
strcpy(str2, str1);

// Print str2
printf("%s", str2);

Compare Strings

To compare two strings, you can use the strcmp() function.


It returns 0 if the two strings are equal, otherwise a value that is not 0.
char str1[] = "Hello";
char str2[] = "Hello";
char str3[] = "Hi";

// Compare str1 and str2, and print the result


printf("%d\n", strcmp(str1, str2)); // Returns 0 (the strings are equal)

// Compare str1 and str3, and print the result


printf("%d\n", strcmp(str1, str3)); // Returns -4 (the strings are not equal)

In C, the getchar() function is used to read characters one by one from the
standard input (keyboard). This function reads input until the end-of-file
(EOF) is reached, which allows processing of all characters entered by the
user. By counting each occurrence of blanks, tabs, and newlines, the
program can provide useful statistics about the input text.
Pseudo Code: START

DECLARE INTEGER variables: blanks, tabs, newlines, initialized to 0


DECLARE CHARACTER variable: ch

PRINT "Enter text (press Ctrl+D to end input on Unix/Linux or Ctrl+Z on


Windows):"

WHILE character ch = getchar() IS NOT EOF


a. IF ch IS EQUAL TO ' ' (blank)
i. INCREMENT blanks
b. ELSE IF ch IS EQUAL TO '\t' (tab)
i. INCREMENT tabs
c. ELSE IF ch IS EQUAL TO '\n' (newline)
i. INCREMENT newlines
d. END IF
END WHILE

PRINT "Blanks: ", blanks


PRINT "Tabs: ", tabs
PRINT "Newlines: ", newlines

END

First Year Engineering 36 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Flowchart:

Initialize

Read

++blan_ch ++tab_ch ++new_ch

printf(“blank=%d,tab%d,newline%d”,blan

Conclusion
This experiment demonstrates how to use basic input functions in C to read
and process character data. It reinforces understanding of character control
structures like loops and conditional statements. By counting pecific types
of characters (blanks, tabs, and newlines), students gain insight into text
processing and control flow in programming.

Test Case:

Test Test case description Expected Output Actual Output Test


Case no Status
1 "Hello World\tGood\n" Blanks: 2, Tabs: 1, Blanks: 2, Tabs: 1, Pass
Newlines: 1 Newlines: 1
2 "Test\nTest\tTest" Blanks: 0, Tabs: 1, Blanks: 0, Tabs: 1, Pass
Newlines: 1 Newlines: 1
3 "ThisIsALongStringWit Blanks: 0, Tabs: 0, Blanks: 0, Tabs: 0, Pass
houtAnySpacesOrTabs Newlines: 0 Newlines: 0
OrNewlines"

Questions:
1. What is the purpose of the program that counts blanks, tabs, and newlines?
2. Explain the difference between a blank, a tab, and a newline character.
3. How does the getchar() function work, and why is it used in this program?
4. What is ASCII, and why is it important in programming?
5. How are characters represented in C using ASCII values?
6. What functions or operators in C can be used to work with ASCII values?

First Year Engineering 37 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
7. What is the ASCII value of the null character, and why is it significant in C
programming?

Extra Practice Assignments: -


1. Write a program to fill the entire screen with a smiling face. The smiling face has an
ASCII value 1.
2. Write a program to fill the entire screen with diamond and heart alternatively. The
ASCII value for the heart is 3 and that of diamond is 4.
3. Write a program to convert an uppercase letter to lowercase using ASCII values.
4. Write a C program to print the ASCII values of all characters from 'A' to 'Z'.
5. Develop a C program to read a string from the user and print the ASCII values of each
character in the string.
6. Create a C program that takes a character as input from the user and displays its
ASCII value.

First Year Engineering 38 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Assignment No – 6

Problem Write a program to print “mirrored half diamond star pattern”.


Statement:
Objective :
The objective of this C program is to generate a specific type of text-based
visual pattern using stars (*) and spaces. This pattern involves creating a
half-diamond shape where the upper part of the diamond grows outward
and the lower part shrinks inward, creating a mirrored effect.

Requirements:
OS : Linux
Processor: 32/64 bit
Theory Concepts:
The for loop in C is the most general looping construct. The loop header
contains three parts: an initialization, a continuation condition, and an
action.

for (initialization; condition;increment/decrement operator)

//block of code

The initialization is executed once before the body of the loop is entered.
The loop continues to run as long as the continuation condition remains true.
After every execution of the loop, the action is executed. Output

○ The expression represents the initialization of the loop variable.

○ We can initialize more than one variable in Expression 1.

○ Expression 1 is optional.

○ In C, we can not declare the variables in Expression 1. However, It


can be an exception in some compilers.

○ Expression 2 is a conditional expression. It checks for a specific


condition to be satisfied. If it is not, the loop is terminated.

First Year Engineering 39 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

○ Expression 2 can have more than one condition. However, the loop
will iterate until the last condition becomes false. Other conditions will be
treated as statements.

○ Expression 2 is optional.

○ Expression 2 can perform the task of expression 1 and expression


3. That is, we can initialize the variable as well as update the loop variable
in expression 2 itself.

○ We can pass zero or non-zero values in expression 2. However, in


C, any non-zero value is true, and zero is false by default.

Infinitive for loop in C

To make a for loop infinite, we need not give any expression in the syntax.
Instead of that, we need to provide two semicolons to validate the syntax
of the for loop. This will work as an infinite for loop.

Nested for loop

The nested for loop means any type of loop which is defined inside the
'for' loop.

1. for (initialization; condition; update) {


2. for(initialization; condition; update) {
3. // inner loop statements.
4. }
5. // outer loop statements.
6. }

1. Understand the Pattern:

● The mirrored half diamond star pattern consists of two parts: an


upper part that increases in width and a lower part that decreases.
● The pattern is symmetrical along its central vertical axis.

2.Pattern Characteristics:

The number of rows in the pattern is twice the size minus one (i.e., 2*size
- 1).

● For the upper part (first size rows):

First Year Engineering 40 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
○ The number of stars in each row starts from 1 and increases by 2
for each subsequent row.
○ The number of leading spaces starts from size-1 and decreases by 1
each row.
● For the lower part (last size-1 rows):
○ The number of stars starts from 2*size-3 and decreases by 2 each
row.
○ The number of leading spaces starts from 1 and increases by 1
each row.

3.Program Logic:

● Use nested loops to generate the pattern:


○ First Loop: For the upper part of the pattern.
■ Inner loops to handle spaces and stars.
○ Second Loop: For the lower part of the pattern.
■ Inner loops to handle spaces and stars.

4. Handling Different Sizes:

● Ensure the pattern adjusts according to the input size.


● Handle edge cases where size is less than 1 gracefully.

To Print “mirrored half diamond star pattern” required minimum 2


rows.
Pseudo Code:
Function printMirroredHalfDiamondPattern(n):

// n is the number of rows in the upper half of the diamond

// Print the upper half of the pattern

For i from 1 to n:

// Print leading spaces

For j from 1 to (n - i):

Print " "

End For

// Print stars

For k from 1 to i:

Print "*"

End For

// Move to the next line

First Year Engineering 41 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Print newline

End For

// Print the lower half of the pattern

For i from (n - 1) down to 1:

// Print leading spaces

For j from 1 to (n - i):

Print " "

End For

// Print stars

For k from 1 to i:

Print "*"

End For

// Move to the next line

Print newline

End For

End Function

First Year Engineering 42 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Flowchart

Start

Take Input

Initialize i=1

Top Half Loop


Print (n - i)
spaces

Initialize i=n-1

Bottom Half Loop


Print (n - i) spaces End

Conclusion This program effectively provides an excellent way to practice and solidify
your understanding of fundamental programming concepts such as loops,
conditional statements, and output formatting.

Test Case:
Test Test case description Expected Output Actual Output Test Status
Case no
1 Numbers of rows=1 * * Pass

2 Numbers of rows=2 * * Pass

First Year Engineering 43 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

** **
* *
3 Numbers of rows=6 * * Pass
** **
*** ***
**** ****
***** *****
****** ******
***** *****
**** ****
*** ***
** **
* *

Questions:

1.Explain For loop


2.Explain working of Nested For loop
3.What is the role of leading spaces in the mirrored half-diamond pattern?
4.How would you modify the code if the pattern needed to be printed in a different character,
such as # instead of *?

5.What would be the output of the following programs:


main( )
{
int i = 0 ;
for ( ; i ; )
printf ( "\nHere is some mail for you" ) ;
}
6. What would be the output of the following programs:
main( )
{

First Year Engineering 44 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
int i ;
for ( i = 1 ; i <= 5 ;
printf ( "\n%d", i ) ) ;
i++ ; }

7. What would be the output of the following programs:


main( ) {
int i = 1 ;
for ( ; i <= 10 ; ) {
printf ( "%d\n", i ) ;
i=i+1;
}}
8. What would be the output of the following programs:
main( )
{ int r, c, sum ;
for ( r = 1 ; r <= 3 ; r++ ) /* outer loop */
{ for ( c = 1 ; c <= 2 ; c++ ) /* inner loop */
{ sum = r + c ;
printf ( "r = %d c = %d sum = %d\n", r, c, sum ) ;
}}}
9. The three parts of the loop expression in the for loop are: the ____________ expression the
____________ expression the ____________ expression

10. What would be the output of the following programs:


main( ) {
int i ;
for ( i = 0 ; ++i <= 10 ; )
printf ( "%d\n", i ) ;
}

Extra Practice Assignments:-


1. Write a program to produce the following output
1
2 3
4 5 6
7 8 9 10

2. Write a program to produce the following output


First Year Engineering 45 P:F:-LTL-UG/03/R1
PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

3. Write a program to produce the following output


*
* *
* * *
* * * *
* * * * *
4. Write a program to produce the following output

*
* * *
* * * * *
* * * * * * *
5. Write a program to print “Hollow Diamond Star Pattern”.

*
* *
* *
* *
*

6. Write a program to generate all combinations of 1, 2 and 3 using a for loop.


7. Write a program to Calculate simple interest for 3 sets of p, n and r.
8. Write a program to produce the following output:
A B C D E F G F E D C B A
A B C D E F F E D C B A
A B C D E E DC B A
A B C D D C B A
A B C C B A
A B B A
A A
9. Write a program in C to display the cube of the number up to an integer.
10. Write a program in C to display the multiplier table vertically from 1 to n.

First Year Engineering 46 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Assignment No –07

Problem Write a program to count the frequency of each element in an array.


Statement:
Objective : To determine how many times each distinct value appears in the array.
This is useful in various scenarios such as:
1. Data Analysis: To understand the distribution of values in a dataset.
2. Frequency Analysis: To identify the most common or least
common elements in a dataset.
3. Data Validation: To check for duplicates or validate the integrity of
data.

Requirements: OS : Linux
Processor: 32/64 bit
Theory Concepts: 1. Basic Concepts
Array
An array is defined as the collection of similar types of data items stored at
contiguous memory locations. Arrays are the derived data type in C
programming language which can store the primitive type of data such as
int, char, double, float, etc
Each element of an array is of the same data type and carries the same size,
i.e., int = 4 bytes.
Elements of the array are stored at contiguous memory locations where the
first element is stored at the smallest memory location.
Elements of the array can be randomly accessed since we can calculate the
address of each element of the array with the given base address and the size
of the data element.

● Declaration of C Array
We can declare an array in the c language in the following way.
1. data_type array_name[array_size];
Now, let us see the example to declare the array.
1. int marks[5];
Here, int is the data_type, marks are the array_name, and 5 is the
array_size.

● Initialization of C Array
The simplest way to initialize an array is by using the index of each
element. We can initialize each element of the array by using the index.
Consider the following example.
marks[0]=80;//initialization of array

First Year Engineering 47 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

marks[1]=60;

marks[2]=70;

marks[3]=85;

marks[4]=75;

● C Array: Declaration with Initialization


We can initialize the c array at the time of declaration. Let's see the code.

nt marks[5]={20,30,40,50,60};

In such a case, there is no requirement to define the size. So it may also be


written as the following code.

int marks[]={20,30,40,50,60};

Array Elements in Memory

Consider the following array declaration:

int arr[6] ; //considering int size as 4 bytes

Bounds Checking

In C there is no check to see if the subscript used for an array exceeds the
size of the array. Data entered with a subscript exceeding the array size
will simply be placed in memory outside the array; probably on top of
other data, or on the program itself. This will lead to unpredictable results,

First Year Engineering 48 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
to say the least, and there will be no error message to warn you that you
are going beyond the array size. In some cases the computer may just
hang.

Thus, the following program may turn out to be suicidal.

main( ) {

int num[40], i ;

for ( i = 0 ; i <= 100 ; i++ )

num[i] = i ; }

Thus, to see to it that we do not reach beyond the array size is entirely the
programmer’s botheration and not the compiler’s.

● Frequency: Frequency refers to the number of times an element


appears in a dataset.

Pseudo Code: BEGIN // Initialize the array with values array

arr = {1, 2, 8, 3, 2, 2, 2, 5, 1}

// Calculate the length of the array

length = size of arr / size of an element in arr

// Create an array fr to store frequencies of elements

arrayfr[length]

// Define a constant to mark visited elements

visited = -1

// Loop through each element of the array

FOR i FROM 0 TO length-1

// Initialize count for the current element

count = 1

// Loop through remaining elements to count occurrences

FOR j FROM i+1 TO length-1

IF arr[i] == arr[j]

First Year Engineering 49 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Increment count

// Mark element as visited

fr[j] = visited

END IF

END FOR

// Store the count in the frequency array if not visited

IF fr[i] != visited

fr[i] = count

END IF

END FOR

// Display the frequency of each element

PRINT "---------------------"

PRINT " Element | Frequency"

PRINT "---------------------"

FOR i FROM 0 TO length-1

IF fr[i] != visited

PRINT arr[i], "|", fr[i]

END IF

END FOR

PRINT "---------------------"

END

First Year Engineering 50 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Flowchart:
start

Initialize
variables:

ye
i freq[i] i++
i=0

ye ctr=1 j fr
i
ye
i++ ye
Print freq[i]
arr

i f Print ye
ye i++
ye Cnt+

Conclusion By understanding the principles behind this program, you can adapt the
approach for more complex data structures , maintaining its effectiveness
across various scenarios.

Test Case:
Test Test case description Expected Output Actual Output Test Status
Case no
1 Input array elements: The array is The array is Pass
empty. empty.
int arr[] = {};

2 Input array elements: Frequency of 1 = Frequency of 1 Pass


int arr[9]={1, 2, 8, 3, 2, 2 =2
2, 2, 5, 1} Frequency of 2 = Frequency of 2
4 =4

First Year Engineering 51 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Frequency of 3 = Frequency of 3
1 =1
Frequency of 5 = Frequency of 5
1 =1
Frequency of 8 = Frequency of 8
1 =1

3 Input array elements: You might get a You might get a Pass
int arr[9]={1, 2, 8, 3, 2, random value, the random value,
2, 2, 5, 1,10,11} program might the program
crash with a might crash
segmentation with a
fault, or it might segmentation
behave fault, or it might
unpredictably in behave
other ways. unpredictably in
other ways.

Questions:

1. Define Array
2. What is meant by Frequency of elements
3. What are some efficient algorithms to count element frequencies in a large dataset?
4. How can I modify the program to count the frequency of elements in a
multidimensional array?
5. How can I implement a program to find the most frequent element in an array?
6. How can I handle and count the frequency of elements in an array with duplicate
values?
7. what will be the output of following code
main( ) {
int num[ ] = { 24, 34, 12, 44, 56, 17 } ;
int i ;
for ( i = 0 ; i <= 5 ; i++ ) {

First Year Engineering 52 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
printf ( "\n element no. %d ", i ) ;
printf ( "address = %u", &num[i] ) ;
}}
8. what will be the output of following code
main( ) {
int num[ ] = { 24, 34, 12, 44, 56, 17 } ;
int i ;
for ( i = 0 ; i <= 5 ; i++ ) {
printf ( "\naddress = %u ", &num[i] ) ;
printf ( "element = %d", num[i] ) ;
}}
9. what will be the output of following code
main( ) {
int num[ ] = { 24, 34, 12, 44, 56, 17 } ;
int i, *j ;
j = &num[0] ; /* assign address of zeroth element */
for ( i = 0 ; i <= 5 ; i++ ) {
printf ( "\naddress = %u ", j ) ;
printf ( "element = %d", *j ) ;
j++ ; /* increment pointer to point to next location */
}}
10. what will be the output of following code
main( ) {
int num[ ] = { 24, 34, 12, 44, 56, 17 } ;
int i ;
for ( i = 0 ; i <= 5 ; i++ ) {
printf ( "\naddress = %u ", &num[i] ) ;
printf ( "element = %d %d ", num[i], *( num + i ) ) ;
printf ( "%d %d", *( i + num ), i[num] ) ;
}}

Extra Practice Assignments:-


1. Write a program to count the frequency of each character in a string
2. Write a program to count frequencies and then sort the elements by their
frequencies in descending order?
3. Write a program to find the most frequent element in an array?
4. Write a program to count the frequency of digits in number.

First Year Engineering 53 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
5.Write a C program to enter a number and print it in words.
6.Print all array elements having frequencies equal to powers of K in ascending order
7.Find a peak element which is not smaller than its neighbors
8.Move all the negative elements to one side of the array
9.Write a program to reverse the array
10.Write a program to sort the given array

First Year Engineering 54 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Assignment No – 08

Problem Write a program to find the smallest and largest elements in an array
using pointers and then swap these elements and display the resultant
Statement:
array.

Objective : The objective of the program is to use pointers to find and swap the smallest
and largest elements in an array. It demonstrates pointer arithmetic and
dereferencing to efficiently manipulate array elements. Finally, it verifies
the operation by displaying the modified array.
Requirements: OS : Linux
Processor: 32/64 bit
Theory Concepts: ● C Pointers

The pointer in C language is a variable which stores the address of another


variable. This variable can be of type int, char, array, function, or any other
pointer. The size of the pointer depends on the architecture. However, in 32-
bit architecture the size of a pointer is 2 byte.

Consider the following example to define a pointer which stores the address
of an integer.

1. int n = 10;
2. int* p = &n; // Variable p of type pointer is pointing to the address
of the variable n of type integer.

● Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol). It is


also known as an indirection pointer used to dereference a pointer.

int *a;//pointer to int

char *c;//pointer to char

Pointer Example

First Year Engineering 55 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

As you can see in the above figure, pointer variable stores the address of
number variable, i.e., fff4. The value of number variable is 50. But the
address of pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer


variable p.

● Pointer to array
1. int arr[10];
2. int *p[10]=&arr; // Variable p of type pointer is pointing to the
address of an integer array arr.

● Pointer to a function
1. void show (int);
2. void(*p)(int) = &display; // Pointer p is pointing to the address of a
function

● Pointer to structure
1. struct st {
2. int i;
3. float f;
4. }ref;
5. struct st *p = &ref;

First Year Engineering 56 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

● Address Of (&) Operator

The address of operator '&' returns the address of a variable. But, we need
to use %u to display the address of a variable.

● NULL Pointer

A pointer that is not assigned any value but NULL is known as the NULL
pointer. If you don't have any address to be specified in the pointer at the
time of declaration, you can assign a NULL value. It will provide a better
approach.

int *p=NULL;

● Reading complex pointers

There are several things which must be taken into consideration while
reading the complex pointers in C. Lets see the precedence and associativity
of the operators which are used regarding pointers.

○ (): This operator is a bracket operator used to declare and define


the function.

○ []: This operator is an array subscript operator

○ * : This operator is a pointer operator.

○ Identifier: It is the name of the pointer. The priority will always be


assigned to this.

○ Data type: Data type is the type of the variable to which the pointer
is intended to point. It also includes the modifier like signed int, long, etc).

C Double Pointer (Pointer to Pointer)

First Year Engineering 57 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

The syntax of declaring a double pointer is given below.


int **p; // pointer to a pointer which is pointing to an integer.

● Dynamic memory allocation

The concept of dynamic memory allocation in c language enables


the C programmer to allocate memory at runtime. Dynamic memory
allocation in c language is possible by 4 functions of stdlib.h header
file.
1. malloc()

2. calloc()

3. realloc()

4. free()

● malloc() function in C

The malloc() function allocates a single block of requested memory.It


doesn't initialize memory at execution time, so it has garbage value
initially.It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

ptr=(cast-type*)malloc(byte-size)

● calloc() function in C
The calloc() function allocates multiple blocks of requested memory.It
initially initializes all bytes to zero.It returns NULL if memory is not
sufficient.

First Year Engineering 58 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

The syntax of calloc() function is given below:

ptr=(cast-type*)calloc(number, byte-size)

● realloc() function in C

If memory is not sufficient for malloc() or calloc(), you can reallocate the
memory by realloc() function. In short, it changes the memory size.

Let's see the syntax of realloc() function.

ptr=realloc(ptr, new-size)

● free() function in C

The memory occupied by malloc() or calloc() functions must be released by


calling free() function. Otherwise, it will consume memory until the
program exits. Let's see the syntax of free() function.

free(ptr)

Pseudo Code: Start


// Input the size of the array
PRINT "Enter the number of elements in the array:"
READ size
// Initialize the array
DECLARE array[size]
// Input elements of the array
PRINT "Enter the elements:"
FOR i FROM 0 TO size - 1
READ array[i]
END FOR
// Display the original array
PRINT "Original array:"
FOR i FROM 0 TO size - 1
PRINT array[i]
END FOR
// Initialize pointers for smallest and largest
DECLARE smallest POINTER TO array[0]
DECLARE largest POINTER TO array[0]
// Find smallest and largest elements
FOR i FROM 1 TO size - 1
IF array[i] < *smallest THEN
smallest = POINTER TO array[i]
END IF
IF array[i] > *largest THEN
largest = POINTER TO array[i]
First Year Engineering 59 P:F:-LTL-UG/03/R1
PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

END IF
END FOR
// Swap smallest and largest elements if they are different
IF smallest != largest THEN
temp = *smallest
*smallest = *largest
*largest = temp
END IF
// Display the resultant array
PRINT "Array after swapping smallest and largest elements:"
FOR i FROM 0 TO size - 1
PRINT array[i]
END FOR
End
Flowchart
Start

Initialize
Array

Set Pointers for


Array,Traversal
& Initialize ,

Traverse Array:
Compare each
element to ,
current smallest

Swap Smallest
and Largest, Display End
Conclusion This method leverages pointers for direct access and modification of array
elements, demonstrating a practical application of pointer arithmetic and
array manipulation techniques.

Test Case:

First Year Engineering 60 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Test Test case description Expected Output Actual Output Test Status
Case no
1 Enter 2 integers: 2 ,5 , After interchange After interchange Pass
array elements array elements
are:5,2 are:5,2

2 Enter 7 integers: 2 ,5 ,4, After interchange After interchange Pass


1 ,3,10,8 array elements array elements
are:2,5,4,10,3,1,8 are:2,5,4,10,3,1,8

3 Enter 5 integers: After interchange After interchange pass


10,10,10,10,10, array elements array elements
are:10,10,10,10,10 are:10,10,10,10,10

Questions:

1.Describe the usage of pointers in C.

2.What is an array of pointers?

3.How many pointers can point to the same address?

4.What is a Null Pointer?

5. What will be the output of following code


main( ) {
int i = 3 ;
printf ( "\nAddress of i = %u", &i ) ;
printf ( "\nValue of i = %d", i ) ; }

6. What will be the output of following code


main( ) {
int i = 3 ;
printf ( "\nAddress of i = %u", &i ) ;
printf ( "\nValue of i = %d", i ) ;
printf ( "\nValue of i = %d", *( &i ) ) ;
}

7.What will be the output of following code

main( ) {

First Year Engineering 61 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
int i = 3 ;

int *j ;

j = &i ;

printf ( "\nAddress of i = %u", &i ) ;

printf ( "\nAddress of i = %u", j ) ;

printf ( "\nAddress of j = %u", &j ) ;

printf ( "\nValue of j = %u", j ) ;

printf ( "\nValue of i = %d", i ) ;

printf ( "\nValue of i = %d", *( &i ) ) ;

printf ( "\nValue of i = %d", *j ) ;

8. What will be the output of the following program?

#include<stdio.h>

void main () {

int a[10] = {100, 206, 300, 409, 509, 601};

int *p[] = {a, a+1, a+2, a+3, a+4, a+5};

int **pp = p;

pp++;

printf("%d %d %d\n",pp-p,*pp - a,**pp);

*pp++;

printf("%d %d %d\n",pp-p,*pp - a,**pp);

++*pp;

printf("%d %d %d\n",pp-p,*pp - a,**pp);

++**pp;

printf("%d %d %d\n",pp-p,*pp - a,**pp); }

First Year Engineering 62 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
9. What will be the output of the following program?

#include<stdio.h>
void main () {
int a = 10;
int *p;
int **pp;
p = &a;
pp = &p;
printf("address of a: %x\n",p);
printf("address of p: %x\n",pp); /
printf("value stored at p: %d\n",*p);
printf("value stored at pp: %d\n",**pp); }

10. What will be the output of the following program?


#include<stdio.h>

int main(){

int a=10,b=20,*p1=&a,*p2=&b;

printf("Before swap: *p1=%d *p2=%d",*p1,*p2);

*p1=*p1+*p2;

*p2=*p1-*p2;

*p1=*p1-*p2;

printf("\nAfter swap: *p1=%d *p2=%d",*p1,*p2);

return 0;

Extra Practice Assignments:-


1.Find the Second Smallest and Second Largest Elements in an array using pointer

2.Write a program in C to store n elements in an array and print the elements using a pointer.
3.Write a Program to Create a dynamic array of pointers, allocate memory for each pointer,
and initialize each pointer to point to an integer. Then, display the values.
4.Write a program in C to count the number of vowels and consonants in a string using a
pointer.

First Year Engineering 63 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
5.Write a program to sort an array using pointers.
6.Write a program to Print the Length of a String using Pointers
7.Write a Program to Compare Two Strings Using Pointers
8.Write a program in C to find the maximum number between two numbers using a pointer.
9.Write a program in C to print all permutations of a given string using pointers.
10.Write a program in C to find the factorial of a given number using pointers.

Assignment No – 09

Problem Write a program to perform matrix operations - Add, transpose and


Statement: multiplication.

Objective : The objective of the matrix operations program is to provide fundamental


matrix manipulations-addition, transposition, and multiplication. These
operations are essential for various mathematical, engineering, and data
processing tasks, enabling efficient data transformation and analysis.
Requirements: OS : Linux
Processor: 32/64 bit
Theory Concepts: 1.Matrix Addition:

● Concept: Adding two matrices involves summing corresponding


elements from each matrix. This operation requires both matrices to have
identical dimensions.
● Application: Used in combining data sets, aggregating results, and
performing element-wise operations in various fields.

2.Matrix Transposition:

● Concept: Transposition of a matrix involves swapping its rows


with its columns, resulting in a new matrix where the element at position
(i,j)(i, j)(i,j) in the original matrix moves to position (j,i)(j, i)(j,i) in the
transposed matrix.
● Application: Useful for data reorientation, aligning data structures,
and in algorithms where row-wise operations are needed as column-wise.

3.Matrix Multiplication:

First Year Engineering 64 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
● Concept: Multiplying two matrices involves computing the dot
product of rows from the first matrix with columns from the second
matrix. This operation is only defined when the number of columns in the
first matrix equals the number of rows in the second matrix.
● Application: Crucial for linear transformations, solving systems of
linear equations, and in machine learning for operations involving weight
matrices and transformations.

Pseudo Code:
● 1. Matrix Addition
function AddMatrices(Matrix1, Matrix2):
// Ensure both matrices have the same dimensions
If dimensions of Matrix1 != dimensions of Matrix2:
Raise error "Matrices must have the same dimensions for addition."
Initialize ResultMatrix with same dimensions as Matrix1
For each row index i from 0 to number of rows in Matrix1 - 1:
For each column index j from 0 to number of columns in Matrix1 - 1:
ResultMatrix[i][j] = Matrix1[i][j] + Matrix2[i][j]
Return ResultMatrix

2. Matrix Transposition

Function TransposeMatrix(Matrix):
// Get the dimensions of the original matrix
NumberOfRows = number of rows in Matrix
NumberOfColumns = number of columns in Matrix
Initialize TransposedMatrix with dimensions (NumberOfColumns,
NumberOfRows)
For each row index i from 0 to NumberOfRows - 1:
For each column index j from 0 to NumberOfColumns - 1:
TransposedMatrix[j][i] = Matrix[i][j]
Return TransposedMatrix

3. Matrix Multiplication

Function MultiplyMatrices(Matrix1, Matrix2):


// Ensure the number of columns in Matrix1 equals the number of rows in
Matrix2
If number of columns in Matrix1 != number of rows in Matrix2:
Raise error "Number of columns in the first matrix must be equal to
the number of rows in the second matrix."
Initialize ResultMatrix with dimensions (number of rows in Matrix1,
number of columns in Matrix2)
For each row index i from 0 to number of rows in Matrix1 - 1:
For each column index j from 0 to number of columns in Matrix2 - 1:
ResultMatrix[i][j] = 0
For each index k from 0 to number of columns in Matrix1 - 1:
ResultMatrix[i][j] = ResultMatrix[i][j] + (Matrix1[i][k] *
Matrix2[k][j])
Return ResultMatrix

First Year Engineering 65 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Flowchart
1. Flowchart for addition

start

Declare
A[r][c],B[r][c
], C[r][c]

Read
r,c,p A[]

i=0,j=0

C[i][j]=A[i][j]+
i j<
B[i][j]

Print c
i=i+1 j=j+1

2. Flowchart for Multiplication

First Year Engineering 66 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

start

Read m,n,p,q

False
If

Read Multiplicat
a[m,p],b[p,q] ion not

For

c[i][j]+a[i][k]*b[k][ print+c[m] End

3. Flowchart for Transpose

First Year Engineering 67 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Declare

Read
matrix

initialise

i< j< b[i][j]=a[j][i]


n m j=j+1

Print
matrix i=i+1

Conclusion
Matrix addition allows for combining data from matrices of the same
dimensions, matrix transposition facilitates the rearrangement of data, and
matrix multiplication enables complex linear transformations and
computations.

Test Case:
Test Test case description Expected Output Actual Output Test
Case no Status1
1 Enter no of rows and Result of matrix Result of matrix Pass
column in matrix A: 1,1 Addition: 5 Addition: 5
Enter no of rows and Result of matrix Result of matrix
column in matrix B: 1,1 multiplication:6 multiplication:6
Enter elements of matrix Transpose of Transpose of
A: 2 Matrix A :2 Matrix A :2
Enter elements of matrix B: Transpose of Transpose of
3 Matrix B :3 Matrix B :3

First Year Engineering 68 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

2 Enter no of rows and Result of matrix Result of matrix Pass


column in matrix A: 3 3 Addition: Addition:
Enter no of rows and 333 333
column in matrix B: 3 3 444 444
Enter elements of matrix 555 555
A: Result of matrix Result of matrix
111 multiplication multiplication
222 6 6 6 6 6 6
333 12 12 12 12 12 12
Enter elements of matrix B: 18 18 18 18 18 18
222 Transpose of Transpose of
222 Matrix A Matrix A
222 123 123
123 123
123 123

3 Enter no. of rows and Result of matrix Result of matrix pass


columns in matrix A: 4 3 Addition:Matrix Addition:Matrix
Enter no. of rows and addition requires addition requires
columns in matrix B: 3 4 both matrices to both matrices to
Enter elements of matrix have the same have the same
A: 1 1 1 dimensions. Since dimensions. Since
222 Matrix A is 4x3 and Matrix A is 4x3
333 Matrix B is 3x4, and Matrix B is
444 they are not 3x4, they are not
Enter elements of matrix B: compatible for compatible for
2223 addition. Therefore, addition.
2223 addition is not Therefore,
2223 possible in this case addition is not
Result of matrix possible in this
multiplication case
6669 Result of matrix
12 12 12 18 multiplication

First Year Engineering 69 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

18 18 18 27 6669
24 24 24 36 12 12 12 18
Transpose of 18 18 18 27
Matrix A 24 24 24 36
1234 Transpose of
1234 Matrix A
1234 1234
Transpose of 1234
Matrix B: 1234
222 Transpose of
222 Matrix B:
222 222
333 222
222
333

Questions:

1.What are the basic operations you need to implement for matrices?
2. What are the dimensional requirements for matrix addition and multiplication?
3.How do you handle matrices of different sizes in addition?
4.What is the transpose of a matrix?
5.How do you implement the transpose operation?
6.What are the rules for matrix multiplication?
7. What would be the output of the following programs:
main( )
{ int n[3][3] = { 2, 4, 3, 6, 8, 5, 3, 5, 1 } ;
printf ( "\n%d %d %d", *n, n[3][3], n[2][2] ) ; }

8. What would be the output of the following programs:


main( ) {
int n[3][3] = { 2, 4, 3, 6, 8, 5, 3, 5, 1 } ;
int i, j ;
for ( i = 0 ; i <= 2 ; i++ )
First Year Engineering 70 P:F:-LTL-UG/03/R1
PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
for ( j = 0 ; j <= 2 ; j++ )
printf ( "\n%d %d", n[i][j], *( *( n + i ) + j ) ) ; }
9. Point out the errors, if any, in the following programs:
main( ) {
int twod[ ][ ] = { 2, 4, 6, 8 } ;
printf ( "\n%d", twod ) ;
}
10.Point out the errors, if any, in the following programs:
main( ) {
int three[3][ ] = { 2, 4, 3, 6, 8, 2, 2, 3 ,1 } ;
printf ( "\n%d", three[1][1] ) ; }

Extra Practice Assignments:-


1.Write a program to obtain the transpose of a 4 x 4 matrix. The transpose of a matrix is
obtained by exchanging the elements of each row with the elements of the corresponding
column
2.Write a program to multiply any two 3 x 3 matrices
3.Write a program to add two 3 x 3 matrices.
4.Write a program to sort all the elements of a 3 x 3 matrix
5.Write a program to obtain the determinant value of a 2 x 2 matrix.
6.Write a program to find if a square matrix
7.Write a function to find the norm of a matrix. The norm is defined as the square root of the
sum of squares of all elements in the matrix.
8.A 6 x 6 matrix is entered through the keyboard and stored in a 2-dimensional array
mat[7][7]. Write a program to obtain the Determinant values of this matrix.

Assignment No – 10

First Year Engineering 71 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Problem The instructor has a class of 20 students. Each student is identified by roll
no from 1 to 20. and name. The two test scores of each student are to be
Statement:
stored. The instructor would like to enter student roll no, name and test
score. Write a program to process this information, grade each student and
display the result in pleasing format.
Objective :
The objective of the program is to manage and process student information
by:

1. Collecting: Inputting each student's roll number, name, and test scores.

2. Processing: Calculating grades based on the test scores.

3. Displaying: Presenting the student information and their grades in a


clear and organized format.
Requirements: OS : Linux
Processor: 32/64 bit
Theory Concepts:
1.Loops
Iteration: Employing loops (e.g., for, while) to process multiple students
and their scores efficiently, allowing repetitive tasks such as input
collection and result display.

2.What is Structure
Structure in c is a user-defined data type that enables us to store the
collection of different data types. Each element of a structure is called a
member.The ,struct keyword is used to define the structure.

Syntax

structure in c.
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};

Declaring structure variable


We can declare a variable for the structure so that we can access the member
of the structure
easily. There are two ways to declare structure variable:

1. By struct keyword within main() function


Now write given code inside the main() function.
struct employee e1, e2;

First Year Engineering 72 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
The variables e1 and e2 can be used to access the values stored in the
structure. Here, e1 and
e2 can be treated in the same way as the objects in C++ and Java.
2.By declaring a variable at the time of defining the structure.

struct employee
{ int id;
char name[50];
float salary;
}e1,e2;

Accessing members of the structure


There are two ways to access structure members:
1. By . (member or dot operator)
2. By -> (structure pointer operator)

Let's see the code to access the id member of p1 variable by . (member)


operator.
1. p1.id

Let's see the code to access the id member of p1 variable by ->(member)


operator.

1..p1->id

Pseudo Code: BEGIN


FUNCTION get_student_data()
INITIALIZE empty list students
FOR roll_no FROM 1 TO 20
PROMPT user to enter student name for roll_no
STORE name
PROMPT user to enter test score 1 for roll_no
STORE score1
PROMPT user to enter test score 2 for roll_no
STORE score2
ADD student record (roll_no, name, [score1, score2]) TO students
RETURN students
END FUNCTION
FUNCTION calculate_grade(average_score)
IF average_score >= 90 THEN
RETURN 'A'
ELSE IF average_score >= 80 THEN
RETURN 'B'
ELSE IF average_score >= 70 THEN
RETURN 'C'
ELSE IF average_score >= 60 THEN
RETURN 'D'
ELSE RETURN 'F'
END IF
END FUNCTION

First Year Engineering 73 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

FUNCTION display_results(students)
PRINT header row: "Roll No | Name | Test 1 | Test 2 | Average | Grade"
PRINT separator line
FOR EACH student IN students
CALCULATE average_score = (score1 + score2) / 2
GET grade = calculate_grade(average_score)
PRINT student details: roll_no, name, score1, score2, average_score, grade
END FOR
END FUNCTION
// Main program flow
students = get_student_data()
display_results(students)
END
Flowchart

Declare

F Ent Calc Dis


er ulate

Pe Dis

Dis P Dis

Conclusion The program not only supports essential academic record-keeping and
grading functions but also exemplifies fundamental programming concepts
such as data structures, loops, conditionals, and formatted output. This
structured approach ensures that the program can be adapted to various
educational contexts or extended with additional features as needed.

Test Case:

First Year Engineering 74 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Test Test case description Expected Output Actual Output Test


Case Status
no

1 Enter roll number :1 Enter student Results: student Results: Pass


student name: Alice Roll No Name Test 1 Roll No Name Test 1
Enter test score 1: 88 Enter 1 Alice 88 1 Alice 88
test score 2: 92 Enter roll 2 Bob 75 2 Bob 75
number :2 Enter student 3 Charlie 55 3 Charlie 55
name: Bob Enter test score 1: Tes2 Average Score Tes2 AverageScore Grade
75 Enter test score 2: 80 Grade 92 90.00 A
Enter roll number:3 Enter 92 90.00 A 80 77.50 B
student name: Charlie 80 77.50 B 60 57.50 B
Enter test score 1: 55 Enter 60 57.50 B ----------
test score 2: 60 ----------
----------
2 Enter roll number : 1 student Results: student Results: Pass
Enter student name: David Roll No Name Test 1 Roll No Name Test 1
Enter test1: 85 1 David 85 1 David 85
Enter test2: 90 2 Emma 78 2 Emma 78
Enter roll number : 2 3 Fiona 62 3 Fiona 62
Enter student name: Emma Tes2 Average Score Tes2 Average Score Grade
Enter test1: 78 Grade 90 87.50 A
Enter test2: 82 90 87.50 A 82 80.00 A
Enter roll number: 3 82 80.00 A 64 63.00 A
Enter student name: Fiona 64 63.00 A ----------
Enter test1: 62 ----------
Enter test2: 64
----------
3 Enter roll number : 1 student Results: student Results: Pass
Enter student name: Greg Roll No Name Test 1 Roll No Name Test 1
Enter test score 1: 0 1 Greg 0 1 Greg 0
Enter test score 2: 0 2 Ian 100 2 Ian 100
Enter roll number : 2 21 Kyle 75 21 Kyle 75

First Year Engineering 75 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Enter student name: Ian Enter Tes2 Average Score Tes2 Average Score Grade
test score 1: 100 Grade 0 0.00 no grade
Enter test score 2: 100 0 0.00 no 100 100.00 A
Enter roll number : 21 grade Invalid roll number. Please enter
Enter student name: Kyle 100 100.00 A a number between 1 and 20.
Enter test score 1: 75 Invalid roll number. Please ----------
Enter test score 2: 85 enter a number between 1
---------- and 20.
----------

Questions:
1. What inputs does the program require?
2. How many students should the program handle?
3. How is the average score calculated?
4. How does the program handle invalid roll numbers?
5. What happens if non-numeric input is provided for test scores?
6. How does the program perform with the maximum number of students?

Extra Practice Assignments:-

1. Company XYZ is a growing organization with a team of 30 employees.Each


employee is identified by emp id.Write a program to process emp id ,emp salary,emp mobile
and display the result in pleasing format.

2. Write a menu driven program that depicts the working of a library. The menu options
should be:
1. Add book information
2. Display book information
3. List all books of given author
4. List the title of specified book
5. List the count of books in the library
6. List the books in the order of accession number
7. Exit
3. A record contains the name of a cricketer, his age, number of test matches that he has
played and the average runs that he has scored in each test match. Create an array of structure
to hold records of 20 such cricketer and then write a program to read these records and
arrange them in ascending order by average runs

4. Create a structure to specify data on students given below: Roll number, Name,
Department, Course, Year of joining Assume that there are not more than 450 students in the
college.
(a) Write a function to print names of all students who joined in a particular year.

First Year Engineering 76 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
(b) Write a function to print the data of a student whose roll number is given.

5. Create a structure to specify data of customers in a bank. The data to be stored is:
Account number, Name, Balance in account. Assume a maximum of 200 customers in the
bank. Write a function to print the Account number and name of each customer with balance
below Rs. 100.

Assignment No – 11

Problem Write a program in C to swap two numbers using a function. (use call by
Statement: value and call by reference)

First Year Engineering 77 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Objective : By the end of this experiment, students will be able to:


Understand the difference between Call by Value and Call by Reference.
● Implement functions in C that modify variables directly and
indirectly.
● Effectively use pointers in C programming.
Requirements: OS : Linux
Processor: 32/64 bit
Theory Concepts:
In C programming, a function is a block of code that performs a specific
task. Functions are used to modularize code, making it easier to understand,
maintain, and reuse. A function can take inputs, perform operations, and
return a result. Functions allow for code reusability and help in organizing
complex programs.

Syntax:

return_type function_name(parameter_list) {

// function body

// code to perform a specific task

return value; // optional, based on return_type

Components of a Function:

1. Return Type:
○ The return type specifies the data type of the value the function
returns.
○ Common return types are:
■ int: Returns an integer value.
■ float: Returns a floating-point value.
■ void: If no value is returned by the function.
2. Example: int, float, void
3. Function Name:
○ The function name is an identifier used to uniquely name a
function.
○ It follows the same naming rules as variables.
4. Example: add, multiply
5. Parameter List:
○ The parameter list (also called arguments) contains variables (with
their types) that are passed to the function.
○ These parameters act as inputs to the function.
○ If no parameters are required, the function uses void in the
parameter list.
6. Example: (int a, int b) or (void)
7. Function Body:
○ The function body contains the code to perform the desired task.

First Year Engineering 78 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
○ This can include variables, loops, conditionals, and function calls.
8. Return Statement:
○ The return statement is used to return a value from the function.
○ If the return type is void, no value is returned.

Call by Value and Call by Reference. These two approaches differ in how
data is passed to a function and how the function interacts with the data.

1. Call by Value:

In Call by Value, the actual value of the argument is passed to the function.
This means that a copy of the variable is made, and any changes made to
this copy inside the function do not affect the original variable in the calling
function. The function works with the copied value, leaving the original
variables unchanged.

● How it works:
○ A copy of the variable is created and passed to the function.
○ The function operates on this copy, without modifying the original
values.
○ Once the function ends, the original variables remain the same.

void swap_by_value(int a, int b) {

int temp;

temp = a; // Store the value of 'a' in a temporary variable

a = b; // Assign the value of 'b' to 'a'

b = temp; // Assign the value of 'temp' (original 'a') to 'b'

}
● 2. Call by Reference:

In Call by Reference, instead of passing copies of the values, the memory


address (reference) of the variable is passed to the function. This allows the
function to directly access and modify the original variables in memory,
making any changes permanent in the calling function.

● How it works:
○ A pointer to the memory location of the variable is passed to the
function.
○ The function operates on the original data stored at this memory
address.
○ Once the function ends, the changes made to the variables persist.

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

int temp;

First Year Engineering 79 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
temp = *a; // Store the value pointed to by 'a' in a temporary variable

*a = *b; // Assign the value pointed to by 'b' to 'a'

*b = temp; // Assign the value of 'temp' to 'b'

Pointers and Memory Addressing:

The Call by Reference approach relies on the concept of pointers, which


are variables that store the memory address of another variable. In C, the
following symbols are used:

● & (Address-of Operator): Retrieves the memory address of a


variable.
● * (Dereference Operator): Accesses the value stored at a given
memory address.

Pseudo Code: START

Function swapByValue(num1, num2)


temp = num1
num1 = num2
num2 = temp
PRINT "Inside swapByValue, num1:", num1, "num2:", num2
END Function

Function swapByReference(&num1, &num2)


temp = *num1
*num1 = *num2
*num2 = temp
PRINT "Inside swapByReference, num1:", *num1, "num2:", *num2
END Function

Main Function:
INPUT num1, num2

PRINT "Before swapping - num1:", num1, "num2:", num2

CALL swapByValue(num1, num2)


PRINT "After swapByValue - num1:", num1, "num2:", num2

CALL swapByReference(&num1, &num2)


PRINT "After swapByReference - num1:", num1, "num2:", num2

END

First Year Engineering 80 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Flowchart:
Start

Read a
Read b

swap(a,b) swap(int a,int b)


Uses original Uses copy of
variable original variable

temp=a
End a=b
b=temp

print a
print b

Return
Conclusion In this experiment, the differences between Call by Value and Call by
Reference were demonstrated. Using Call by Reference, the values of the
variables were successfully swapped in the calling function. This
experiment shows how functions and pointers are used to manipulate data
directly in C programming.

Test Case:

Test Test case description Expected Output Actual Output Test


Case no Status
1 a=10,b=20 a=20,b=10 a=20,b=10 Pass
2 a=0,b=0 a=0,b=0 a=0,b=0 Pass
3 a=5,b=5 a=5,b=5 a=5,b=5 Pass

Questions:
1. What is the difference between call by value and call by reference?
2. What happens when you pass variables using call by value?
3. How does swapping work using call by reference?
4. Why is the temporary variable necessary in the swapping process?

First Year Engineering 81 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
5. What are the advantages of using call by reference in a C program?
6. If both numbers are zero, how will the program behave in both call by value and call
by reference?
7. What potential errors could occur when implementing call by reference, and how
would you debug them?
8. Explain what would happen if you forgot to pass the address of the variables in call by
reference. How would you resolve it?
9. How can you modify the program to handle both integer and floating-point numbers
using the same function for swapping?

Extra Practice Assignments: -


1. Modify the program to swap three numbers instead of two. How will this change the
function definitions?
2. How would you handle swapping of floating-point numbers in this program?
3. Write a C program to swap two numbers, where one number is positive and the other
is negative, using both call by value and call by reference.
4. Write a program in C to swap two large numbers (greater than 1 million) using call by
value and call by reference. Ensure that your program handles large values without any
overflow or error.
5. Given three variables x, y, z write a function to circularly shift their values to right. In
other words if x = 5, y = 8, z = 10 after circular shift y = 5, z = 8, x =10 after circular shift y =
5, z = 8 and x = 10. Call the function with variables a, b, c to circularly shift values.
6. Write a function to find the binary equivalent of a given decimal integer and display
it.
7. If the lengths of the sides of a triangle are denoted by a, b, and c, then area of triangle
is given by

8. Write a function to compute the distance between two points and use it to develop
another function that will compute the area of the triangle whose vertices are A(x1, y1), B(x2,
y2), and C(x3, y3). Use these functions to develop a function which returns a value 1 if the
point (x, y) lines inside the triangle ABC, otherwise a value 0.
9. Write a function to compute the greatest common divisor given by Euclid’s algorithm,
exemplified for J = 1980, K = 1617

Assignment No – 12

Problem Write a C program to accept a matrix of order m x n. Implement the


Statement: following functions:
i. Find the sum of each row
ii. Find the sum of each column.
The sum should be printed in the main function only.
Objective : By the end of this experiment, students will be able to:
● Understand matrix manipulation in C.
● Learn to implement functions to compute sums of rows and
columns.
● Gain experience in handling user input and output in matrix
operations.

First Year Engineering 82 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Requirements: OS : Linux
Processor: 32/64 bit
Theory Concepts:
Matrix Representation:

A matrix in C is represented as a 2D array, where the number of rows is m


and the number of columns is n. Each element of the matrix can be
accessed using indices like matrix[i][j], where i represents the row
index and j represents the column index.

Syntax:

int matrix[i][j];

Matrix Input:

The matrix is populated by user input using nested loops.

Syntax for accepting user input for matrix elements:

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

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

scanf("%d", &matrix[i][j]); // input element at row i and column j

Functions in C:

● Function Definition: Functions are blocks of code that perform


specific tasks. In this problem, two functions will be written: one to
compute the sum of each row and another to compute the sum of each
column.
● Function Prototype: Declares the function's return type and
parameters before the main() function to ensure that the compiler knows
about the function before its actual implementation.

Functions to Compute Sums:

The row and column sums are calculated using two separate functions.

void sum_of_rows(int matrix[][j], int m, int n, int row_sum[]);

void sum_of_columns(int matrix[][j], int m, int n, int col_sum[]);

First Year Engineering 83 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Row Sum Calculation:

For each row i, sum all elements in that row (matrix[i][j] where j
varies from 0 to n-1).

Syntax for calculating row sums:

void sum_of_rows(int matrix[][j], int m, int n, int row_sum[]) {

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

row_sum[i] = 0; // Initialize row sum

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

row_sum[i] += matrix[i][j]; // Add elements of row i

Column Sum Calculation:

For each column j, sum all elements in that column (matrix[i][j]


where i varies from 0 to m-1).

Syntax for calculating column sums:

void sum_of_columns(int matrix[][j], int m, int n, int col_sum[]) {

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

col_sum[j] = 0; // Initialize column sum

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

col_sum[j] += matrix[i][j]; // Add elements of column j

Display Results in main():

After computing the sums, display the sum of each row and column using
loops.

First Year Engineering 84 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Syntax for displaying results:

printf("Sum of each row:\n");

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

printf("Row %d: %d\n", i + 1, row_sum[i]);

printf("Sum of each column:\n");

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

printf("Column %d: %d\n", j + 1, col_sum[j]);

Pseudo Code: START


READ matrix dimensions m and n
Allocate memory for an m x n matrix

READ matrix elements from the user


Initialize arrays for row sums and column sums

COMPUTE row sums:


For each row i:
INITIALIZE row_sum to 0
For each column j:
Add matrix[i][j] to row_sum
Store row_sum in row_sums[i]
COMPUTE column sums:
For each column j:
INITIALIZE column_sum to 0
For each row i:
Add matrix[i][j] to column_sum
Store column_sum in column_sums[j]
PRINT row sums
PRINT column sums
END

First Year Engineering 85 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Flowchart:

Read

Allocate

Read

Initialise Initialise

Compute Compute

Print row Print

Conclusion
This lab exercise helps in understanding matrix operations in C. It provides
practical experience in working with two-dimensional arrays, handling user
input, and implementing functions to compute sums. The exercise
reinforces key concepts such as iteration and memory management.

Test Case:

Test Test case description Expected Row Expected Column Test


Case no Sum Sum Status
1 m = 2, n = 2 Row 1: 3 Column 1: 4 Pass
12 Row 2: 7 Column 2: 6
34
2 m = 4, n = 3 Row 1: 2 Column 1: 7 Pass
5 0 -3 Row 2: 9 Column 2: 8
7 -2 4 Row 3: 0 Column 3: 0
0 1 -1 Row 4: 4
-5 9 0
3 m = 3, n = 4 Row 1: 6 Column 1: 5 Pass
1023 Row 2: 0 Column 2: 5
0000 Row 3: 15 Column 3: 8
4560 Column 4: 3

Questions:
1. What is a matrix in the context of computer programming?
2. What are the dimensions of a matrix?

First Year Engineering 86 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
3. How do you input and store a 2D matrix in C?
4. What is the purpose of calculating the sum of rows and columns in a matrix?
5. Explain the algorithm for calculating the sum of each row in a matrix.
6. Explain the algorithm for calculating the sum of each column in a matrix.
7. What challenges might you face when handling matrices of larger sizes (e.g.,
100x100)?
8. In what scenarios can matrix row and column sum operations be applied?

Extra Practice Assignments: -


1. Write a C program to accept a matrix of order m x n and find the maximum element
in each row and each column.
2. Write a C program to accept two matrices A of order m x n and B of order n x p
and calculate their product matrix C of order m x p. Display the resulting matrix.
3. Write a C program to accept a matrix of order m x n and calculate the sum of all the
boundary elements (elements in the first row, last row, first column, and last column) of the
matrix.
4. Write a C program to accept a matrix of order m x n and display the elements in spiral
order (i.e., starting from the top-left corner and traversing the matrix in a spiral manner).
Enter the number of rows and columns: 3 3
Enter the elements of the matrix:
123
456
789
Spiral order of the matrix: 1 2 3 6 9 8 7 4 5
5. A 6 x 6 matrix is entered through the keyboard and stored in a 2-dimensional array
mat[7][7]. Write a program to obtain the Determinant values of this matrix.
6. Write a function to find the norm of a matrix. The norm is defined as the square root of
the sum of squares of all elements in the matrix.
7. Write a program to find if a square matrix is symmetric.

Assignment No – 13

Problem Develop a recursive C function to find the factorial of a given number.

First Year Engineering 87 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Statement:
Objective :
The objective of the recursive factorial function is to provide a clear
example of recursion, compute factorials, and demonstrate how problems
can be divided into simpler sub problems.

Requirements:
OS : Linux
Processor: 32/64 bit
Theory Concepts:
1. Recursive Concept:

● Recursion is a method where a function calls itself to solve a smaller


instance of the same problem.
● A recursive function must have:
● Base Case: A condition under which the function returns a result
directly without further recursion.
● Recursive Case: A condition where the function calls itself with a
modified argument to reduce the problem size, moving towards the base
case.

2. Factorial Definition:

The factorial of a non-negative integer n (denoted as n!) is the product of


all positive integers less than or equal to n.

Mathematically: n!= { 1 if n=0 or n=1

n×(n−1)! If n>1

3.Recursive Factorial Function:

Base Case: For factorial, the base case is when n is 0 or 1.

By definition, 0!=1 and 1!=1.

● Recursive Case: For any n>1, the factorial can be


computed as n×(n−1)!. The function multiplies n by the
result of the factorial of n−1.
4. Example:To compute 4!
1. Function Call: factorial(4)
Recursive Case: 4×factorial(3)

2. Function Call: factorial(3)

Recursive Case: 3×factorial(2)

First Year Engineering 88 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
3. Function Call: factorial(2)

Recursive Case: 2×factorial(1)

4. Function Call: factorial(1)

Base Case: Returns 1

● Combining the results:


factorial(2) = 2 \times 1 = 2
factorial(3) = 3 \times 2 = 6
factorial(4) = 4 \times 6 = 24

5.Code Example:

int factorial(int n)
{
return (n <= 1) ? 1 : n * factorial(n - 1);
}

Pseudo Code: FUNCTION factorial(n)


IF n <= 1 THEN
RETURN 1
ELSE
RETURN n * factorial(n - 1)
END IF
END FUNCTION

First Year Engineering 89 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

Flowchart
Start

Read n

i=1,fact=1

i< Ye Print
=n fact

Stop
i=i+1 fact=fact*i

Conclusion The recursive factorial function elegantly breaks


down the problem of computing n! by reducing it to
simpler subproblems, relying on the base case of n≤1
to terminate recursion. This approach demonstrates
the power of recursion in solving problems that can be
divided into smaller, similar tasks.

Test Case:
Test Test case description Expected Output Actual Output Test Status
Case no
1 Enter number n=0 1 1 Pass
2 Enter number n=5 120 120 Pass

First Year Engineering 90 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.

3 Enter number n=10 3628800 3628800 Pass

Questions:

1.What is the time complexity of the recursive factorial function?


2.What is the space complexity of the recursive factorial function?
3.How does the base case in the recursive factorial function prevent infinite recursion?
4.What are the limitations of using recursion to compute factorials for very large
values of n?
5.How would you modify the recursive factorial function to handle very large values
of n more efficiently?
6.How can you test the recursive factorial function to ensure its correctness?
7.What changes would you make if the factorial function needed to handle very large
integers that exceed standard data type limits?
8.What is the difference between the factorial function and the Gamma function, and
how does it relate to the factorial calculation?
9.What changes would you make if the factorial function were required to work with
floating-point numbers?
10.How can you ensure the recursive factorial function performs correctly across
different programming environments or compilers?

Extra Practice Assignments:-

1.Find the last digit when factorial of A divides factorial of B


2. Golang Program to Count Trailing Zeros in Factorial of a Number
3.Check if a given number is factorial of any number
4.One line function for factorial of a number
5.find First digit in factorial of a number
6.Number of digits in N factorial to the power N
7.Last digit of a number raised to last digit of N factorial
8.Factorial of a number without using multiplication
9.Find the last two digits of Factorial of a given Number
10.Find maximum power of a number that divides a factorial

First Year Engineering 91 P:F:-LTL-UG/03/R1


PUNE INSTITUTE OF COMPUTER TECHNOLOGY,
DHANKAWADI, PUNE – 43.
11.Count trailing zeroes in factorial of a number.

First Year Engineering 92 P:F:-LTL-UG/03/R1

You might also like