You are on page 1of 320

Week1

Prelab:
1. Define an algorithm and explain its significance in computer programming. How
does an algorithm differ from a flowchart?
Ans:
An algorithm is a step-by-step procedure or set of rules that describes how to solve
a specific problem or perform a specific task. It is a fundamental concept in computer
programming and plays a crucial role in the development of software applications. The
significance of algorithms in computer programming lies in their ability to provide a
systematic approach to problem-solving whereas the flowchart is represented geometric
patterns and actions.
2. Describe the purpose of flowcharts in visualizing and representing algorithms.
What are the common symbols used in flowcharts, and what do they represent?
Ans:
The purpose of flowcharts in visualizing and representing algorithms is to provide a
graphical representation of the logical flow and structure of the algorithm. Some common
symbols used in flowchart.
 Terminal or start/End Symbol: It usually appears as an oval shape.
 Process Symbol: It represents a process or operation to be performed. Rectangle
with rounded corners.
 Input/output Symbol: It performs Input and output operations. Parallelogram.
 Decision Symbol: It is a condition to be evaluated. Diamond shape.
 Connector Symbol: It is used to connect different parts of a flowchart that are split
over multiple pages. Circle or Square.
 Flow Arrows/Directional Arrows: connect different symbols and indicate.

3. Explain the concept of sequential execution in the context of algorithms. How


does the order of instructions in an algorithm affect the outcome of a program?
Ans:
Sequential execution in the context of algorithms refers to the idea that instructions or
operations are executed in a specific order. The order of instructions in an algorithm has a
significant impact on the outcome of a program.
4. Discuss the importance of using clear and concise variable names in algorithms.
How does choosing appropriate variable names contribute to the readability and
maintainability of code?
Ans:
Using the clear and concise variable names in algorithm in crucial for improving the
readability and maintainability.
Readability: It becomes easier for programmers to understand the intention and logic of the
algorithm reducing the time and effort required to understand the code.
Maintainability: It becomes easier to make modifications or enhancements to the code.
Reducing the chances of introducing bugs or unintended consequences
LAB:
1. You are designing a flowchart and algorithm for a distance and speed calculator.
Theflowchart should prompt the user to input the distance travel and the time
taken, andcalculatethespeedusingtheformulaSpeed=Distance/Time.

Algorithm:
1. Start the algorithm.
2. Prompt the user to input the distance traveled and assign it to a variable called "distance".
3. Prompt the user to input the time taken and assign it to a variable called "time".
4. Calculate the speed using the formula: "speed = distance / time".
5. Display the calculated speed.
6. End the algorithm.

Flowchart:
Start

"Enter Distance:"
GET Distance

"Enter Time:"
GET TIme

Speed ← Distance / Time

PUT Speed¶

End
2. You are developing an algorithm and flow chart and algorithm for a circle area
calculator. The flowchart should prompt the user to input the radius of a circle
and calculate the area using the formula Area =π * ( Radius ^ 2).

Algorithm:
Step 1: Start the algorithm.
Step 2: Prompt the user to input the radius of the circle and assign it to a variable called
"radius".
Step 3: Calculate the area of the circle using the formula: "area = π *
(radius^2)". Note: π (pi) is a mathematical constant approximately equal to
3.14159.
Step 4: Display the calculated area of the
circle. Step 5: End the algorithm.

Flowchart:

Start

"Enter Radius:" GET Radius

Area ← 3.14 * Radius * Radius

PUT Area¶

End
3. You are designing an algorithm and flowchart for a fuel efficiency calculat or for a
carrental app. The flowchart should prompt the user to input the distance
traveled and the amount of fuel consumed , and calculate the fuel efficiency in
miles pergallon (MPG) using the formula MPG = Distance / Fuel Consumption.

Algorithm:
Step 1: Start the algorithm.
Step 2: Prompt the user to input the distance traveled and assign it to a variable called
"distance".
Step 3: Prompt the user to input the amount of fuel consumed and assign it to a variable
called "fuel_consumption".
Step 4: Calculate the fuel efficiency in miles per gallon (MPG) using the formula: "mpg =
distance / fuel_consumption".
Step 5: Display the calculated fuel efficiency
(MPG). Step 6: End the algorithm.

Flowchart:

Start

"Enter Distance: :" GET Distance

"Enter Fuel Consumption" GET FuelConsumption

MPG ← Distance / FuelConsumption

PUT MPG¶

End
4. You are developing an algorithm and flowchart for a discount calculator for an
onlineshopping app. The flowchart should prompt the user to input the original
price and the discount percentage, and calculate the discounted price using the
formula. Discounted Price = Original Price - (Original Price * Discount Percentage).

Algorithm:
Step 1: Start the algorithm.
Step 2: Prompt the user to input the original price and assign it to a variable
called "original_price".
Step 3: Prompt the user to input the discount percentage and assign it to a variable called
"discount_percentage".
Step 4: Calculate the discounted price using the formula: "discounted_price = original_price -
(original_price * discount_percentage / 100)".
Step 5: Display the calculated discounted
price. Step 6: End the algorithm.

Flowchart:
Start

"Enter Original Price: :" GET OriginalPrice

"Enter Discount Percentage" GET DiscountPerc

DiscountPrice ← OriginalPrice - (OriginalPrice * DiscountPercentag

PUT DiscountPrice¶

End
Post-Lab

1. Farmer Thimmayya bought some mules at Rs. 50 each, sheep at Rs. 40 each, goats at
Rs. 25 each, and pigs at Rs. 10 each. The average price of the animals per head
worked to Rs. 30.What is the minimum number of animals of each kind did he buy?

Algorithm and Flowchart


1. A Matter of Rupees and Paise

I have money pouch containing Rs.700. There are equal number of 25 paise coins, 50 paise coins
and1 rupee coins. How many of each are there?

Algorithm and Flowchart

Start

Total ← 0.25 + 0.50 + 1

X ← 700 / Total

PUT "Total Number of 0.25 Paise Coins " + X¶

PUT "Total Number of 0.50 Paise Coins " +X¶

PUT "Total Number of one rupee Coins " +X¶

End
Skill:
1. You are developing a flowchart and algorithm for a monthly budget tracker. The
flowchart should prompt the user to input their in come and expenses and
calculate the total savings using the formula Total Savings = Income – Total
Expenses.

Algorithm:
Step 1: Start the algorithm.
Step 2: Prompt the user to input their income and assign it to a variable called
"income". Step 3: Initialize a variable called "total_expenses" to 0.
Step 4: Repeat the following steps until the user indicates they have no more expenses:
a. Prompt the user to input an expense and assign it to a variable called "expense".
b. Add the expense to the total_expenses: "total_expenses = total_expenses + expense".
Step 5: Calculate the total savings using the formula:
"total_savings = income - total_expenses".
Step 6: Display the calculated total
savings. Step 7: End the algorithm.

Flowchart:
2. You are designing a flowchart for a loan amortization calculator. The flowchart
should prompt the user to input the loan amount, interest rate, and duration, and
calculate the monthly payment using the formula Monthly Payment = (LoanAmount *
InterestRate * (1 + InterestRate) ^ Duration) / ((1+InterestRate) ^ Duration-1).
CTSD WorkBook Skill Week 1 Problem 2
------------------------------------
In the context of Week 1 Skill Problem-2 (Page No:9), a minor correction is
necessary for the formula. The correct formula is as follows:
MonthlyPayment = (LoanAmount * InterestRate * (1 + InterestRate)^Duration) /
((1 + InterestRate)^Duration - 1).
For example, when using a 5.6% annual interest rate in the formula, it's crucial to
note that the formula operates on a monthly basis, not annually. Therefore, the
rate you enter should be 1/12th of the annual rate (for 5.6% annually, you should
input 0.00466666).
The refined formula is as follows:
MonthlyPayment = (LoanAmount * InterestRate/12 * (1 +
InterestRate/12)^Duration) / ((1 + InterestRate/12)^Duration - 1)

Algorithmic Solution Example for the Given Problem:


----------------------------------------------------------
1) Start
2) Prompt the user for input:
Enter the loan amount (loanAmount).
Enter the annual interest rate (annualInterestRate).
Enter the duration of the loan in months (durationMonths).
3) Calculate the monthly interest rate:
monthlyInterestRate = annualInterestRate / 12
4) Calculate the monthly payment using the formula:
monthlyPayment = (loanAmount * monthlyInterestRate * (1 +
monthlyInterestRate)^durationMonths) / ((1 +
monthlyInterestRate)^durationMonths - 1)
5) Display the calculated monthly payment:
Print "Your monthly payment is: Rs."+ monthlyPayment
6) Stop
Algorithm:
Step 1: Start the algorithm.
Step 2: Prompt the user to input the loan amount and assign it to a variable called
"loan_amount".
Step 3: Prompt the user to input the interest rate and assign it to a variable called
"interest_rate".
Step 4:Prompt the user to input the duration of the loan in months and assign it to a
variable called "duration".
Step 5: Calculate the monthly interest rate by dividing the annual interest rate by 12:
"monthly_interest_rate = interest_rate / 12".
Step 6: Calculate the monthly payment using the formula:
"monthly_payment = (loan_amount * monthly_interest_rate * pow(1 +
monthly_interest_rate, duration)) / (pow(1 + monthly_interest_rate, duration) - 1)".
Note: The "pow" function is used to raise a number to a
power. Step 7. Display the calculated monthly payment.
Step 8. End the algorithm.
Flowchart:

Start

"Enter Loan Amount: :" GET LoanAmount

"Enter Duration :" GET Duration

"Enter Intrest Rate" GET IntrestRate

IntrestRate ← IntrestRate / 100

MonthlyPayment ← (LoanAmount * IntrestRate


* (1 + IntrestRate) ^ Duration) / ((1 + IntrestRate)
^ Duration - 1)

PUT MonthlyPayment¶

End
3. You are designing a flow chart for a construction materials calculator.The flowchart
should prompt the user to input the length, width, and height of a room, and
calculate the amount of paint needed using the formula Surface Area = 2 *
(Length
* Width + Length * Height + Width * Height).

Algorithm:
Step 1: Start the algorithm.
Step 2: Prompt the user to input the length of the room and assign it to a variable called
"length".
Step 3: Prompt the user to input the width of the room and assign it to a variable called
"width".
Step 4. Prompt the user to input the height of the room and assign it to a variable called
"height".
Step 5: Calculate the surface area using the formula:
"surface_area = 2 * (length * width + length * height + width * height)".
Step 6: Display the calculated surface area.
Step 7: End the algorithm.
Flowchart:

Start

"Enter Length: :" GET Length

"Enter Width :" GET Width

"Enter Height: " GET Height

SurfaceArea ← 2 * (Length
* Width + Length * Height
+ Width * Height)

PUT SurfaceArea¶

End
4. Develop a flowchart and algorithm to convert a given time in hours and minutes to
minutes only. Prompt the user to input the time in hours and minutes and display
the converted time in minutes.

Algorithm:
Step 1: Start the algorithm.
Step 2: Prompt the user to input the time in hours and assign it to a variable called "hours".
Step 3: Prompt the user to input the time in minutes and assign it to a variable called
"minutes".
Step 4: Calculate the total time in minutes by multiplying the hours by 60 and adding the
minutes: "total_minutes = (hours * 60) + minutes".
Step 5: Display the total time in
minutes. Step 6: End the algorithm.

Flowchart:
5. Develop an algorithm and flowchart that prompts the user to input the initial
velocity, acceleration, and time. Calculate and display the final velocity using the
formula Final Velocity = Initial Velocity + (Acceleration * Time).

Algorithm:
Step 1: Start the algorithm.
Step 2: Read the initial velocity and assign it to a variable called
"initial_velocity". Step 3: Read the acceleration and assign it to a variable called
"acceleration".
Step 4: Read the time and assign it to a variable called "time".
Step 5: Calculate the final velocity using the formula:
"final_velocity = initial_velocity + (acceleration * time)".
Step 6: Display the calculated final
velocity. Step 7: End the algorithm.

Flowchart:
6. Develop an algorithm and flowchart that prompts the user to input the lengths of
the three sides of a triangle. Calculate and display the area of the triangle using
Heron's formula: Area = √(s * (s - Side1) * (s - Side2) * (s - Side3)), where
s=(Side1+Side2+Side3)/2.

Algorithm:
Step 1: Start the algorithm.
Step 2: Read the length of Side1 and assign it to a variable called
"side1". Step 3: Read the length of Side2 and assign it to a variable
called "side2". Step 4: Read the length of Side3 and assign it to a
variable called "side3".
Step 5: Calculate the semi-perimeter (s) of the triangle by adding side1, side2, and side3
and dividing it by 2: "s = (side1 + side2 + side3) / 2".
Step 6. Calculate the area of the triangle using Heron's formula:
"area = √(s * (s - side1) * (s - side2) * (s - side3))".
Step 7: Display the calculated area of the
triangle. Step 8: End the algorithm.
Flowchart:
Week2
Prelab:
1. Analyze the importance of flowcharts in software development and justify
their use in the planning and design stages.
Ans: Flowcharts are a tool that business users and programmers rely on for various
purposes. In software development, a programmer may create a flowchart or process
map to help a stakeholder visualize how data enters a program, different
transformations within the program, and how the data converts to an output. One reason
for the popularity of flowcharts is that they make it easier for users to communicate
how they plan to implement business requirements for a new application. They also
help you analyze a process from start to finish. When designing and planning a process,
flowcharts can help you identify its essential steps and simultaneously offer the bigger
picture of the process. It organises the tasks in chronological order and identify them by
type, e.g. process, decision, data, etc.
2. Compare and contrast sequential and conditional flowcharting structures,
highlighting their unique characteristics and applications in representing process
flows.
S.NO Sequential Flowcharts Conditional Flowcharts
1 Consists of sequential steps Consists of More than one sequence flow
2 Conditions are not involved Conditions will be present and evaluated
3 Loops may not present Loops may be present
4 Used to solve simple problems like Used to solve complex problems.
“addition of two numbers”.
5 Symbols used here Symbols used here

3. Evaluate and design flowchart representations for loops or iterative processes,


considering factors such as loop conditions, initialization, and termination.
Ans: Flowchart representations for loops or iterative processes are used to illustrate
the execution of repeated steps until a certain condition is met. They typically include
loop conditions, initialization, and termination criteria. Here's a simple explanation
of these components:
1. Loop Conditions: Loop conditions specify the condition that needs to be evaluated
at the beginning or end of each iteration to determine whether the loop should continue
or terminate. It acts as a controlling factor for the loop. If the condition is true, the
loop continues; if it's false, the loop terminates.
2. Initialization: Initialization refers to the initial setup or assignment of values to
variables before the loop begins. It can include assigning initial values to loop
control variables or any necessary setup steps required before entering the loop.
3. Termination: Termination determines the condition that, when met, causes the
loop to stop executing and the program to continue with the next statement or exit
the loop entirely. It can be based on reaching a certain count, a specific value, or
any other condition that signifies the end of the loop.
When designing flowchart representations for loops or iterative processes, it's
important to consider these factors to ensure the loop behaves as expected and the
desired outcome is achieved.
4. Examine the similarities and differences between flow charts and algorithms in the
context of program development and evaluate their effectiveness in designing
and comprehending complex processes. Support your analysis with concrete
examples.
Flowcharts and algorithms are both tools used in program development to design
and comprehend complex processes. While they have some similarities, they also
have differences in terms of their visual representation and level of detail. Let's
examine their similarities and differences and evaluate their effectiveness.
Similarities:
1. Visualization: Both flowcharts and algorithms provide a visual representation of
the logical flow and sequence of steps in a process. They help in visualizing the
structure and flow of a program or process.
2. Sequential Execution: Both flowcharts and algorithms depict the sequential
execution of steps or actions. They show the order in which instructions or tasks
are performed.
3. Decision Making: Both flowcharts and algorithms include decision points
where the program flow diverges based on conditions or logical choices. They
represent branching paths or conditional statements.
Differences:
1. Notation: Flowcharts use graphical symbols and shapes to represent different
elements, such as start/end points, process steps, decision points, and connectors.
On the other hand, algorithms are usually written in a structured or programming
language-specific syntax using a combination of textual instructions, variables,
and control structures.
2. Level of Detail: Flowcharts provide a high-level overview of the process,
focusing on the flow and sequence of steps. They are suitable for communicating
complex processes to a broader audience. Algorithms, on the other hand, offer a
more detailed and precise description of the steps, including variables, data types,
loops, and conditional statements. They are intended for implementation by
programmers.
Effectiveness:
1. Designing Complex Processes: Flowcharts are effective in designing complex
processes as they provide a visual representation that helps identify potential
bottlenecks, redundancies, or errors in the logic. They allow for easy communication
and collaboration among stakeholders.
2. Comprehending Processes: Flowcharts are useful for comprehending complex
processes as they provide a high-level overview and allow users to understand the
flow and sequence of steps without getting into the nitty-gritty details. They are
particularly effective for non-technical stakeholders or users who need to grasp the
overall process without diving into the code.
3. Implementing Algorithms: Algorithms, with their detailed and precise
instructions, are effective for programmers during the implementation phase. They
provide a clear roadmap for writing code by specifying variables, data structures,
control flow, and calculations.
Example:
Consider a simple example of finding the maximum of three numbers:
- A flowchart for this process would include start/end symbols, decision points
(comparing numbers), and process steps (assigning the maximum value).
- An algorithm for the same process would be written in a programming language,
specifying variables, conditions, and assignments.
Both the flowchart and algorithm serve their purposes effectively. The flowchart
allows non-programmers to understand the process flow, while the algorithm
provides the necessary instructions for implementation by programmers.
In conclusion, flowcharts and algorithms are both valuable tools in program
development. Flowcharts aid in visualizing complex processes and communicating
them effectively, while algorithms provide a detailed description of steps for
implementation. The choice between them depends on the target audience, level of
detail required, and the specific stage of the development process.

Algorithm for sum of N numbers:


Step1: start
Step2: Read N number
Step3: Initialize sum=0, I=1
Step4: Repeat steps 5, 6 until the condition satisfies I<=N
Step5: sum=sum+I
Step6: I=I+1
Step7: Display sum value as
results Step8: Stop.

Flowchart for Sum of N Numbers as follows:


Lab:
1. ABC Company wants to calculate the monthly salary for its employees based
on various components suchas basicpay,DA, HRA,and deductions for taxes
and provident fund. The company follows the following rules for salary
calculation:
 The basic pay is a fixed amount each employee receives.
 DA is calculated as a percentage of the basic pay.
 HRA is calculated as a percentage of the basic pay.
 The gross salary is the sum of the basicpay, DA, and HRA.
 The net salary is the gross salary minus deductions for taxes and provident fund.
Develop an algorithm and flowchart to calculate the gross and net salary of the
employee. Include the necessary steps to calculate the net salary.

Algorithm:
Step 1: Start the algorithm.
Step 2: Read the basic pay and assign it to a variable called "basic_pay".
Step 3: Read the percentage of DA (DA%) and assign it to a variable called "da_percentage".
Step 4: Read the percentage of HRA (HRA%) and assign it to a variable called
"hra_percentage".
Step 5: Read the deductions for taxes and assign it to a variable called "tax_deductions".
Step 6: Read the deductions for provident fund and assign it to a variable
called "pf_deductions".
Step 7: Calculate DA by multiplying the basic_pay by (da_percentage/100):
"da = basic_pay * (da_percentage/100)".
Step 8: Calculate HRA by multiplying the basic_pay by (hra_percentage/100):
"hra = basic_pay * (hra_percentage/100)".
Step 9: Calculate the gross salary by adding the basic_pay, DA, and
HRA: "gross_salary = basic_pay + da + hra".
Step 10: Calculate the net salary by subtracting the deductions (tax_deductions and
pf_deductions) from the gross_salary:
"net_salary = gross_salary - tax_deductions - pf_deductions".
Step 11: Display the gross_salary and net_salary.
Step 12: End the algorithm.
Flowchart:
2. Sarah is a student who wants to calculate her average grade for a semester.
Assist Sarah in writing an algorithm to calculate her average grade based on the
marks she received in different subjects. Create an algorithm and flowchart for
Sarah to calculate her average grade for the semester using the marks she
obtained in different subjects. Include the necessary steps to calculate the average.

Algorithm:
Step 1: Start the algorithm.

Step 2: Read the number of subjects Sarah took and assign it to a variable called
"num_subjects".

Step 3: Initialize a variable called "total_marks" to

0. Step 4: Repeat the following steps for each

subject:

- Read the marks obtained in the subject and assign it to a variable called "marks".

- Add the marks to the total_marks: "total_marks = total_marks + marks".

Step 5: Calculate the average grade by dividing the total_marks by the number of subjects:
"average_grade = total_marks / num_subjects".

Step 6: Display the average

grade. Step 7: End the algorithm.


Flowchart:
3. John is a programmer who wants to convert a given temperature in Celsius to
Fahrenheit. Help John indeveloping analgorithm and flowchart to perform this
conversion. Design an algorithm for John to convert a given temperature in
Celsius to Fahrenheit. Provide step-by-step in structions for performing the
conversion.

Algorithm:
Step 1: Start the algorithm.
Step 2: Read the temperature in Celsius and assign it to a variable called "celsius".
Step 3: Calculate the temperature in Fahrenheit using the formula: "fahrenheit = (celsius ×
9/5) + 32".
Step 4: Display the temperature in
Fahrenheit. Step 5: End the algorithm.

Flowchart:
Start

"Enter Temperature in Celsius :"


GET Celsius

Fahrenheit ← (Celsius * 9 / 5) + 32

PUT Fahrenheit¶

End
Post-Lab
1. The Tall Men Next Door
Next door to me live four brothers of different heights. Their average height is 74 inches, and
the difference in height among the first three men is two inches. The difference between the
third and the fourth man is six inches.
Can you tell how tall is each brother?
Algorithm and Flowchart
To find the heights of the four brothers based on the given information, you can use the
following algorithm:
1. Initialize variables for the heights of the four brothers: A, B, C, and D.
2. Set up the following equations based on the given information:
- The average height of the four brothers is 74 inches:
(A + B + C + D) / 4 = 74
- The difference in height among the first three brothers is two inches:
B=A+2
C=A+4
- The difference between the third and fourth brothers is six inches:
D=C-6
3.Substitute the expressions for B, C, and D into the average height
equation: (A + (A + 2) + (A + 4) + (A + 4 - 6)) / 4 = 74
4. Simplify and solve for A:
(4A + 4) / 4 = 74
4A + 4 = 4 * 74
4A + 4 = 296
4A = 296 - 4
4A = 292
A = 292 / 4
A = 73
5. Calculate the heights of the other brothers using the relationships you established earlier:
-B=A+2
-C=A+4
-D=C-6
6. Display the heights of all four brothers (A, B, C, and D).
Flowchart:

Start

(A+B+C+D)/4=74 A+B+C+D=74*4 A+B+C+D=296


Sum ← 4 * 74

B=A+2 C=A+4 D=C+6


A+(A+2)+(A+4)+(C+6)=296 A+A+2+A+4+A+4+6=296 4A+10+6=296
h1 ← (Sum - 16) / 4 4A=296-16
4A=280 A=280/4 A=70

B=A+2
h2 ← h1 + 2

C=A+4
h3 ← h1 + 4

D=C+6
h4 ← h3 + 6

End
2. Driving Through the Country

I decided to travel through the country leisurely and on the first day I did only 7 miles. On the
last day Idid 51 miles, increasing my journey by 4 miles per day.

How many days did I travel and how far?

Algorithm and Flowchart

Start

a←7

d←4

tn ← 51

tn=a+(n-1)*d tn=a+dn-d tn+d=a+dn (tn+d-a)//d=n

n ← (tn + d - a) / d

td ← n / 2 * (a + tn)

PUT "Days travelled" +n¶

PUT "How Far : " +td¶

End
Skill:

1. Alex loves reading books and has a collection of novels. Help Alex write an
algorithm to organize the novels based on their genres in alphabetical order.
Write an algorithm and flowchart to help Alex organize their collection of novels
basedon genres in alphabetical order. Include the necessary steps to accomplish this
task.

Algorithm:
1. Start the algorithm.

2. Create an empty list called "novels".

3. Repeat the following steps until all the novels have been categorized:

a. Prompt the user to input the title of a novel and assign it to a variable called
"novel_title".

b. Prompt the user to input the genre of the novel and assign it to a variable called
"genre".

c. Create a dictionary entry with "novel_title" as the key and "genre" as the value.

d. Append the dictionary entry to the "novels" list.

4. Sort the "novels" list based on the genre in alphabetical order.

5. Display the organized list of novels with their corresponding genres.

6. End the algorithm.


Flowchart:

Start

"Enter N Value:" GET n

i←1

Loop

Yes i>n

No

"Enter Book Name: " GET names[i]

PUT "The Names: "+names[i]¶

i←i+1

bubbleSort(names, n)

End
2. If a participant can make one submission every 45 seconds, and a contest lasts for
Y minutes, create an algorithm and flowchart to find the maximum number of
submissions that the participant can make during the contest? Assume the
participant is allowed to make submissions until the last second of the contest.

Algorithm:
Step 1: Start

Step 2: Read the duration of the contest (Y minutes).

Step 3: Convert the duration of the contest from minutes to seconds (total_seconds = Y *
60).

Step 4: Calculate the maximum number of submissions possible (max_submissions =


total_seconds / 45).

Step 5: Display the maximum number of submissions.

Step 6: End

Flowchart:

Start

"Read the Duration of the contest in Y minutes :" GET Y

total_seconds ← Y * 60

Max_submissions ← total_seconds / 45

PUT Max_submissions¶

End
3. Michael wants to find the largest number amongaset of given numbers. Help
Michael write an algorithm to determine the largest number from the given
inputs. Create an algorithm and flowchart for Michael to find the largest number
amongaset of given inputs. Provide step-by-step instructions to identify the largest
number.

Algorithm:
Step 1: Start
Step 2: Read the number of inputs (N) from the user.
Step 3: Initialize a variable `largest` to store the largest
number. Step 4: For each input from 1 to N:
a. Read the input value.
b. If it is the first input or the current input is greater than the `largest`, update
`largest` with the current input value.
Step 5: Display the value of `largest` as the largest
number. Step 6: End
Flowchart::

Start

"Enter number of elements"


GET n

maximum ← 0

i←0

PUT "Entered Values : "¶

Loop

No i<n

Yes

"Enter an element" GET a

PUT a¶

Yes maximum<a No

maximum ← a

i←i+1

PUT
"Maximum="+maximum

End
4. A construction worker needs to paint the exterior walls of a rectangular building.
The dimensions of the walls are L meters in length, H meters in height, and W
meters in width. If the cost of painting Is Rs.20 per square meter, what will be the
total cost of painting the walls? Prepare an algorithm and flowchart to calculate
the total cost of painting.

Algorithm:
1. Start.
2. Read the dimensions of the building (L, H, W).
3. Calculate the area of the walls: Area = 2 * L * H + 2 * W * H
4. Multiply the area by the cost per square meter to get the total cost:Total cost =
Area * Cost per square meter
5. Print the total cost.
6. End.
Flowchart:
5. An ice cream vendor brings 'i' liters of ice cream to a fair. Each cone requires 0.25
liters of icecream. If the vendor sells 80 cones, Develop an algorithm and flowchart
to find the number of liters of icecream left with the vendor.

Algorithm:
Step 1: Start
Step 2: Read the initial amount of ice cream brought by the vendor (i liters).
Step 3: Calculate the total ice cream used for 80 cones (total_used = 80 *
0.25). Step 4: Calculate the ice cream left with the vendor (left = i -
total_used).
Step 5: Display the value of 'left' as the number of liters of ice cream left.
Step 6: End

Flowchart:
6. Amanda is planning a party and wants to determine the total number of guests
attending. Assist Amanda by writing an algorithm to calculate the total number of
guests based on the number of adults and children invited. Create an algorithm
and flowchart for Amanda to calculate the total number of guests attending her
party, considering the number of adults and children invited. Include the
necessary steps to calculate the total number of guests.

Algorithm:
Step 1: Start the algorithm.
Step 2: Read the number of adults invited and assign it to a variable called "adults".
Step 3: Read the number of children invited and assign it to a variable called
"children".
Step 4: Calculate the total number of guests by adding the number of adults and children:
"total_guests = adults + children".
Step 5: Display the total number of guests attending the
party. Step 6: End the algorithm.

Flowchart:

Start

"Enter Number of Audlts invited :"


GET Adults

"Enter Number of Children Inviting :" GET Children

TotalGuests ← Adults + Children

PUT TotalGuests¶

End
Week-3
Prelab:
1. List the various datatypes supported by the C programming language.
Ans: The C programming language supports several data types, including:
Integer Types:
i : A signed integer type.
sho : A signed short integer type.
lo : A signed long integer type.
longlo : A signed long long integer type (available in C99 and later).
unsigned : An unsigned integer type.
unsigned short: An unsigned short integer type.
unsigned long : An unsigned long integer type.
unsigned long long : An unsigned long long integer type (available in C99 and later).
Floating-Point Types:
float: A single-precision floating-point type.
double: A uble-precision floating-point type.
do : A long double-precision floating-point type.
Character Types:
char: A character type representing a single
signed char: Acharacter. signed character type.
unsigned char: An unsigned character type.
Derived Types:
enum: An enumeration type that defines a set of named integer constants.
struct: A user-defined composite type that groups together variables of different
types under a single name.
union: A user-defined composite type that allows storing different data types in the
same memory location.
Void Type:
void: A special type that represents the absence of a
value. Boolean Type:
C does not have a built-in boolean type, but it is often simulated using integer types,
where 0 represents false and non-zero values represent true.

2. Explain the usage of the sizeof operator to determine the size of a datatype.

Ans:Thesizeof operator in C is used to determine the size in bytes of a data type or a


variable. It is a compile-time operator that returns the size of its operand. The syntax of the
size operator is as follows:
sizeof(type)
sizeof(expression)
Short-circuit evaluation is a behavior exhibited by logical operators (`&&` and `||`) in C
where the second operand of the operator is not evaluated if the result of the expression can
be determined based on the value of the first operand alone. This behavior can provide
optimizations and prevent unnecessary evaluations.
3. Explore the concept of short-circuit evaluation in C, specifically in relation to
logical operators (&& and ||).
Ans:
In C, the logical AND operator (`&&`) and the logical OR operator (`||`) both exhibit short-
circuit evaluation. Here's how it works:
1. Logical AND (`&&`):
When using `&&`, if the first operand evaluates to false (0), the second operand is
not evaluated because the overall result of the expression will always be false. This is
because for the logical AND operation, both operands need to be true for the result to be
true. If the first operand is false, there's no need to evaluate the second operand.
Example:
```c
int a =
5;
int b = 10;
if (a > 0 && b > 0) {
// Both conditions are evaluated only if a > 0 is true
// If a > 0 is false, b > 0 is not
evaluated printf("Both conditions are true\
n");
}
```
2. Logical OR (`||`):
When using `||`, if the first operand evaluates to true (non-zero), the second operand
is not evaluated because the overall result of the expression will always be true. This is
because for the logical OR operation, at least one operand needs to be true for the result to
be true. If the first operand is true, there's no need to evaluate the second operand.
Example:
```c
int a =
5;
int b = 10;
if (a > 0 || b > 0) {
// Both conditions are evaluated only if a > 0 is false
// If a > 0 is true, b > 0 is not
evaluated printf("At least one condition is
true\n");
}
Short-circuit evaluation is not limited to just if statements. It can be applied in other
contexts as well, such as in the expressions of while loops, for loops, and ternary operators.
It's important to note that short-circuit evaluation can be leveraged for efficiency and to
avoid potential errors when the second operand has side effects or relies on specific
conditions. However, care should be taken to ensure that the evaluation order of operands
does not affect the correctness of the program.
4. How do you declare and initialize a pointer variable in C? Provide an example.
Ans:
The pointer in c language can be declared using * (asterisk symbol). It is also
known as indirection pointer used to dereference a pointer.

int number =
88 int
*pNumber;
pNumber = &number;
pNumber int *pAnother = &number;

5. Discuss the significance of the "static" storage class in C. How is it different from
the "auto" storage class?
Ans:
The static storage class instructs the compiler to keep a local variable in existence
during the life-time of the program instead of creating and destroying it each time it comes
into and goes out of scope. Therefore, making local variables static allows them to maintain
their values between function calls.
A static variable exists for the whole simulation; an automatic variable exists only
for the lifetime of the task, function, or block - they are created when the task, function or
block is entered and destroyed when it is left.
6. You are designing a temperature monitoring system using C. The system requires
variables to store temperature values in different contexts. Discuss which storage
classes (global, local, static, register, external) would be suitable for the following
scenarios and explain your reasoning:
a) A variable that needs to be accessed and modified by multiple functions within
the system.
b) A variable that needs to retain its value between function calls.
c) A variable that needs to have fast access for efficient computation.
d) A variable that needs to be shared between multiple source files in the
project. Ans:
a) A variable that needs to be accessed and modified by multiple functions within
the system. In this scenario, a global variable would be suitable. A global variable is
accessible and modifiable by all functions within the system.
b) A variable that needs to retain its value between function calls. For this
scenario, a static variable would be appropriate. A static variable retains its value between
function calls, meaning its value persists even when the function is called multiple
times.
c) A variable that needs to have fast access for efficient computation. For efficient
computation and fast access, a register variable can be used. A register variable is stored in
the CPU registers, which provide fast access for efficient computation. However, it's
important to note that the use of the regist keyword is merely a suggestion to the compiler,
and it's up to the compiler to decide whether to allocate the variable in a register.
d) A variable that needs to be shared between multiple source files in the project. In
this case, an external variable would be suitable. An external variable is defined in one
source file and can be accessed by other source files in the project. It allows sharing of data
between exte
different files by using the keyword to declare the variable in the other source files
that need access to it.

Predicttheoutput!
1.
#include <stdio.h>
intmain(){
inta = 5;
floatb=3.5;
int result = a + b; printf("%d\
n", result);return0;
}

Output :8

2.
#include <stdio.h>
intmain(){
inta=10;
intb=20;
intresult=a*b/4%3;
printf("%d\n", result);
return 0;
}
Output:2

3.
#include<stdio.h>
int main() {
inta=15;
intb=10;
intresult=(a>b)&&(b!=0);
printf("%d\n",result);
return0;
}
Output:1
4.
#include <stdio.h>
Intmain(){
inta=10;
intb=5;
intresult=(a>b)||(a==10);
printf("%d\n",result);
return0;
}
Output:1

5.
#include <stdio.h>
Intmain(){
intx=3,y=2;
intresult=x*y-y/x%y;
printf("%d\n", result);
return0;
}
Output :6

6.
#include <stdio.h>
intmain(){
intx=5;
int*ptr1=&x;
int **ptr2 = &ptr1;
printf("%d\n", **ptr2);
return 0;
}
Output: 5

7.
#include <stdio.h>
intmain(){
intx=5;
int *ptr1,
*ptr2;
ptr1=&x;
ptr2 = ptr1;
printf("%d\n", *ptr2);
return0;
}
Output :5
8.
#include <stdio.h>
intmain(){
intx=51;
int *ptr = &x;
printf("%d\n", *ptr);
x=15;
printf("%d\n", *ptr);
return0;
}
Output :51 15

9.
#include <stdio.h>
intmain(){
float*ptr; printf("Sizeofptr:%lubytes\
n",sizeof(ptr)); return0;
}
Output :Size of ptr:8 bytes

10.
#include <stdio.h>
intmain(){
doublearr[5];
printf("Size of arr: %lu bytes\n", sizeof(arr));
return0;
}
Output: Size of arr 40 bytes
11.
#include <stdio.h>
intmain(){
int x = 10;
if(x>5){
printf("Hello\n");
}
printf("Goodbye\n");
return0;
}
Output: Hello Goodbye
Find the syntax error, logical errors if any in the following code snippet:

1.
#include <stdio.h>
intmain()[
printf("Hello,KLUFamily!\n")
return0;
]
error: expected declaration specifiers or '...' before string constant
error: expected identifier or '(' before ']' token

2.
#Include[stdio.h]
intmain(){
int x = 5, y = 0;
intresult=x/y;
printf("Theresultis:%d\n",result);
return0;
}
invalid preprocessing directive #Include;
error: initializer element is not constant
2 | int x = 5, y = 0; int result = x / y;
|^
error: expected declaration specifiers or '...' before string constant
3 | printf("The result is: %d\n", result); return 0;
| ^~~~~~~~~~~~~~~~~~~~~
error: expected declaration specifiers or '...' before 'result'
3 | printf("The result is: %d\n", result); return 0;
| ^~~~~~
3 | printf("The result is: %d\n", result); return 0;
| ^~~~~~
error: expected identifier or '(' before '}'
token 4 | }
|^

3.
#include <stdio.h>
intmain(){
intx=5;
int*ptr;
*ptr= &x;
printf("%d\n",*ptr);
return 0;
}
Segmentation fault
4.
#include <stdio.h>
intmain(){
intx = -5;
if(x){
printf("xisnotzero\n");
}
else{
printf("xiszero\n";
}
Return0;
}
error: expected ')' before ';'
token 8 | printf("x is zero\n";
|~^
|)
error: expected ';' before '}'
token 8 | printf("x is zero\n";
|^
|;
9|}
|~
Lab:
1. You are working as a financial analyst at a bank. As part of your job, you need to
calculate the maturity amount for fixed deposits (FD) based on the principal
amount, interest rate, and duration. Write a C program that takes the principal
amount, interest rate, and duration (inyears) asin put from the user. Calculate and
display the maturity amount using the simple interest formula: Maturity Amount =
Principal + (Principal
* Interest Rate * Duration).
Code:
#include <stdio.h>
void main() {
double principal, interestRate, duration, maturityAmount;
printf("Enter the principal amount: ");
scanf("%lf", &principal);
printf("Enter the interest rate: ");
scanf("%lf", &interestRate);
printf("Enter the duration in years:
"); scanf("%lf", &duration);
maturityAmount = principal + (principal * interestRate * duration);
printf("Maturity amount: %.2lf\n", maturityAmount);
}
Output:
Enter the principal amount: 100000
Enter the interest rate: 0.2
Enter the duration in years:
4 Maturity amount:
180000.00
2. Jenny, a budding mathematician, was studying the concept of area and perimeter.
She was given a rectangular garden with a known length and width. Jenny wondered
if she could find the area with out knowing the width. Can you help Jenny derive a
formula to calculate the area of a rectangle using only the length and perimeter?

If you have the length and height of the rectangle, you can calculate the area using the
formula: Area = Length * Height.
However, if you only have the length and perimeter, you cannot calculate the area
accurately.

#include <stdio.h>
void main()
{
double length, perimeter, area;
printf("Enter the length of rectangle: ");
scanf("%lf", &length);
printf("Enter the perimeter of the rectangle: ");
scanf("%lf", &perimeter);
area = ( (perimeter * length / 2) - (length * length) );
printf("The area of the rectangle is: %.2lf\n", area);
}
Output:
Enter the length of rectangle: 4
Enter the perimeter of the rectangle: 6
The area of the rectangle is: -4.00
3. Develop a C program that computes the hypotenuse of a right-angled triangle given
the lengths of its two perpendicular sides. Prompt the user to enter the lengths and
display the result. (Pythagoreantheorem: Hypotenuse2 = Side12 + Side22).

#include <stdio.h>
#include <math.h>
void main()
{
double side1, side2, hypotenuse;
printf("Enter the length of side 1:
"); scanf("%lf", &side1);
printf("Enter the length of side 2:
"); scanf("%lf", &side2);
hypotenuse = sqrt((side1 * side1) + (side2 *
side2)); printf("The hypotenuse is: %.2lf\n",
hypotenuse);
}

Oustput:
Enter the length of side 1:
3 Enter the length of side
2: 4 The hypotenuse is:
5.00
Skilll:
1. Imagine a scenario where there is a coconut tree with multiple coconuts hanging
from it. There is a person standing at a distance of "D" meters away from the tree.
The coconuts are positioned at a height of "H" meters from the ground. Could you
please help write a C Program that calculates the angle at which the person should
aim in order to hit the coconuts? (Hint: you can use the inverse tangent function
(atan() in C) to determine the angle based on the ratio of the height of the coconuts
to the distance from the tree.).

Code:
#include <stdio.h>
#include <math.h>
#define PI 3.14159
double calculateAngle(double distance, double height) {
double radians = atan(height / distance); // Calculate the angle in
radians double degrees = radians * (180.0 / PI); // Convert radians to
degrees return degrees;
}

int main() {
double distance, height;
printf("Welcome to the Coconut Angle Calculator!\n");
printf(" \n");
printf("Enter the distance from the tree (in meters):
"); scanf("%lf", &distance);
printf("Enter the height of the coconuts (in meters): ");
scanf("%lf", &height);
double angle = calculateAngle(distance, height);
printf("\nThe angle to aim in order to hit the coconuts: %.2f degrees\n", angle); printf("\
nThank you for using the Coconut Angle Calculator. Goodbye!\n");
return 0;
}
Output:
Welcome to the Coconut Angle Calculator!

Enter the distance from the tree (in meters):


20 Enter the height of the coconuts (in
meters): 10
The angle to aim in order to hit the coconuts: 26.57 degrees
Thank you for using the Coconut Angle Calculator. Goodbye!
2. In a far away kingdom, two treasure hunters named Alex and Bella embarked on
a daring quest to find valuable treasures. While exploring a mysterious cave, they
stumbled upon two treasure chests, each containing a unique gemstone. Curiosity
took over, and they decided to swap the gemstones inside the chests. However, a
magical enchantment prevented them from directly swapping the gemstones. To
fulfill their quest and restore the treasures to their rightful chests, Alex and Bella
realized they could use a third variable and arithmetic operations. Can you help
them by writing a C program that takes the values of the gemstones as input, and
swap their values.

Code:

#include <stdio.h>
int main() {
int gemstone1, gemstone2, temp;
printf("Welcome to the Gemstone Swapper!\n");
printf(" \n");
printf("Enter the value of gemstone 1: ");
scanf("%d", &gemstone1);
printf("Enter the value of gemstone 2:
"); scanf("%d", &gemstone2); printf("\
nBefore swapping:\n");
printf("Gemstone 1: %d\n", gemstone1);
printf("Gemstone 2: %d\n", gemstone2);
// Swapping the values using a temporary
variable temp = gemstone1;
gemstone1 = gemstone2;
gemstone2 = temp;
printf("\nAfter swapping:\n");
printf("Gemstone 1: %d\n", gemstone1);
printf("Gemstone 2: %d\n", gemstone2);
printf("\nThank you for using the Gemstone Swapper. Goodbye!\n");
return 0;
}

Output:
Welcome to the Gemstone Swapper!

Enter the value of gemstone 1:


33 Enter the value of gemstone
2: 42 Before swapping:
Gemstone 1: 33
Gemstone 2: 42
After swapping:
Gemstone 1: 42
Gemstone 2: 33

Thank you for using the Gemstone Swapper. Goodbye!


1. Jake, a diligent student, was learning about the Pythagoreantheorem. He wondered
if there were other similar theorems that could be used to calculate the lengths of
sides in right angles. Intrigued by trigonometry, Jack approached you for
guidance. Write a C program that introduces Jake to the concept of trigonometry
and help him understand how to calculate side lengths and angles using
trigonometric functions.
Code:
#include <stdio.h>
#include <math.h>
int main() {
double angle, side1, side2;
char choice;
printf("Welcome to the Trigonometry Calculator!\n");
printf(" \n");
do {
printf("\nEnter the angle in degrees:
"); scanf("%lf", &angle);
printf("Enter the length of side 1:
"); scanf("%lf", &side1);
printf("Enter the length of side 2: ");
scanf("%lf", &side2); printf("\
nTrigonometric Functions:\n");
printf("1. Calculate the length of the hypotenuse (Side 3)\n");
printf("2. Calculate the value of the sine of the angle\n");
printf("3. Calculate the value of the cosine of the angle\n");
printf("4. Calculate the value of the tangent of the angle\n");
printf("\nEnter your choice (1-4): ");
scanf(" %c", &choice);
switch (choice) {
case '1':
{
double hypotenuse = sqrt((side1 * side1) + (side2 * side2)); printf("\
nThe length of the hypotenuse (Side 3) is: %.2f\n", hypotenuse);
break;
}
case '2':
{
double sine = sin(angle * M_PI / 180);
printf("\nThe value of the sine of the angle is: %.2f\n",
sine); break;
}
case '3':
{
double cosine = cos(angle * M_PI / 180);
printf("\nThe value of the cosine of the angle is: %.2f\n",
cosine); break;
}
case '4':
{
double tangent = tan(angle * M_PI / 180);
printf("\nThe value of the tangent of the angle is: %.2f\n", tangent);
break;
}
default:
printf("\nInvalid choice! Please enter a valid option.\n");
}
printf("\nDo you want to continue? (Y/N):
"); scanf(" %c", &choice);
} while (choice == 'Y' || choice == 'y');
printf("\nThank you for using the Trigonometry Calculator. Goodbye!\n");
return 0;
}

Output:
Welcome to the Trigonometry Calculator!

Enter the angle in degrees:


90 Enter the length of side 1:
2 Enter the length of side 2:
3

Trigonometric Functions:
1. Calculate the length of the hypotenuse (Side 3)
2. Calculate the value of the sine of the angle
3. Calculate the value of the cosine of the angle
4. Calculate the value of the tangent of the
angle Enter your choice (1-4): 1
The length of the hypotenuse (Side 3) is:
3.61 Do you want to continue? (Y/N): Y
Enter the angle in degrees:
45 Enter the length of side 1:
2 Enter the length of side 2:
8

Trigonometric Functions:
1. Calculate the length of the hypotenuse (Side 3)
2. Calculate the value of the sine of the angle
3. Calculate the value of the cosine of the angle
4. Calculate the value of the tangent of the
angle Enter your choice (1-4): 3
The value of the cosine of the angle is:
0.71 Do you want to continue? (Y/N): n
Thank you for using the Trigonometry Calculator. Goodbye!
2. Emma, an enthusiastic mathematician, was exploring the concept of probability. She
loved playing card games and wondered how to calculate the probability of
drawing a certain card from a deck without replacement. Emma approached you,
seeking your expertise. Write a C program to guide Emma through the concept of
conditional probability and help her calculate the desired probability.

Code:
#include <stdio.h>
int main() {
int totalCards = 52, i;
int remainingCards = totalCards;
int desiredCards;
int trials;
printf("Welcome to the Probability Calculator!\n");
printf(" \n");
printf("Enter the number of desired cards: ");
scanf("%d", &desiredCards);
printf("Enter the number of trials:
"); scanf("%d", &trials);
double probability = 1.0;
for (i = 0; i < trials; i++)
{
probability *= (double)desiredCards / remainingCards;
desiredCards--;
remainingCards--;
}
printf("\nThe probability of drawing %d card(s) from a deck without replacement in %d
trial(s) is: %.4f\n", trials, trials, probability);
printf("\nThank you for using the Probability Calculator. Goodbye!\n");
return 0;
}
Output:
Welcome to the Probability Calculator!

Enter the number of desired cards:


1 Enter the number of trials: 5
The probability of drawing 5 card(s) from a deck without replacement in 5 trial(s) is: -
0.0000 Thank you for using the Probability Calculator. Goodbye!
3. Emily, a young architect, was working on designing a cylindrical water tank for a
new building. As she was finalizing the plans, she needed to calculate the surface
area of the cylinder to determine the amount of material required for its
construction. However, she was unsure of the exact formula and the steps involved
in the calculation. Can you help Emily by writing a C program that assists her in
calculating the surface area of a cylinder?

Code:

#include <stdio.h>

#include <math.h>

int main() {
double radius, height;
printf("Welcome to the Cylinder Surface Area Calculator!\n");
printf(" \n");
printf("Enter the radius of the cylinder: ");
scanf("%lf", &radius);
printf("Enter the height of the cylinder:
"); scanf("%lf", &height);
double surfaceArea = 2 * M_PI * radius * (radius + height);
printf("\nThe surface area of the cylinder is: %.2f\n", surfaceArea);
printf("\nThank you for using the Cylinder Surface Area Calculator. Goodbye!\n");
return 0;
}

Output:
Welcome to the Cylinder Surface Area Calculator!

Enter the radius of the cylinder: 6


Enter the height of the cylinder: 15
The surface area of the cylinder is:
791.68

Thank you for using the Cylinder Surface Area Calculator. Goodbye!
4. Hemanth is an architect who wants to design a garden with a beautiful polygon-
shaped fountain at its center. He needs to calculate the area of the polygon so that
he can determine the appropriate size for the fountain. Help Hemanth by writing a
C program that calculates the area of a regular polygon when given the number of
sides and the length of each side.

Code:
#include <stdio.h>

#include <math.h>

int main() {
int numSides;
double sideLength;

printf("Welcome to the Regular Polygon Area Calculator!\n");


printf(" \n");

printf("Enter the number of sides of the polygon:


"); scanf("%d", &numSides);
printf("Enter the length of each side:
"); scanf("%lf", &sideLength);
double area = (numSides * sideLength * sideLength) / (4 * tan(M_PI /
numSides)); printf("\nThe area of the regular polygon is: %.2f\n", area);
printf("\nThank you for using the Regular Polygon Area Calculator. Goodbye!\n");
return 0;
}

Output:
Welcome to the Regular Polygon Area Calculator!

Enter the number of sides of the polygon: 5


Enter the length of each side: 3
The area of the regular polygon is: 15.48
Thank you for using the Regular Polygon Area Calculator. Goodbye!
5. Prathima loves ice cream cones and wants to decorate the surface of her favorite
ice cream cone with colorful stickers. To know how many stickers she needs, she
wants to calculate the surface area of the cone. Help Prathima by writing a C
program that calculates the surface area of a cone when given the radius of the
base and the slant height.

Code:

#include <stdio.h>
#include <math.h>
int main() {

double radius, slantHeight;


printf("Welcome to the Cone Surface Area Calculator!\n");
printf(" \n");
printf("Enter the radius of the cone's base: ");
scanf("%lf", &radius);
printf("Enter the slant height of the cone:
"); scanf("%lf", &slantHeight);
double surfaceArea = M_PI * radius * (radius + slantHeight); printf("\
nThe surface area of the cone is: %.2f\n", surfaceArea);
printf("\nThank you for using the Cone Surface Area Calculator. Goodbye!\n");
return 0;
}

Output:
Welcome to the Cone Surface Area Calculator!

Enter the radius of the cone's base: 4


Enter the slant height of the cone: 15

The surface area of the cone is:

238.76

Thank you for using the Cone Surface Area Calculator. Goodbye!
6. Write a program that uses the static storage class to keep track of the number of
times a user inputs a certain value. The program should ask the user to enter a
value, increment a static variable each time the value is entered, and output the
current count.

Code:
#include <stdio.h>
void countOccurrences(int value) {
static int count = 0; // Static variable to keep track of the count
count++; // Increment the count each time the function is called with the value
printf("The value %d has been entered %d times.\n", value, count);
}

int main() {
int value;
printf("Welcome to the Value Occurrence Counter!\n");
printf(" \n");
printf("Enter a value (0 to quit): ");
scanf("%d", &value);
while (value != 0) {
countOccurrences(value);
printf("Enter another value (0 to quit):
"); scanf("%d", &value);
}
printf("\nThank you for using the Value Occurrence Counter. Goodbye!\n");
return 0;
}

Output:
Welcome to the Value Occurrence Counter!

Enter a value (0 to quit): 1


The value 1 has been entered 1
times. Enter another value (0 to
quit): 2
The value 2 has been entered 2
times. Enter another value (0 to
quit): 1
The value 1 has been entered 3
times. Enter another value (0 to
quit): 67
The value 67 has been entered 4
times. Enter another value (0 to quit):
8
The value 8 has been entered 5
times. Enter another value (0 to
quit): 1
The value 1 has been entered 6
times. Enter another value (0 to
quit): 1
The value 1 has been entered 7
times. Enter another value (0 to
quit): 1
The value 1 has been entered 8
times. Enter another value (0 to
quit): 1
The value 1 has been entered 9 times.
Enter another value (0 to quit): 1
The value 1 has been entered 10 times.
Enter another value (0 to quit):2
The value 2 has been entered 11
times. Enter another value (0 to quit):
0
Thank you for using the Value Occurrence Counter. Goodbye!

Dear All, Please utilize the following programming exercise for the Skill Question 6 of
Week 3:

7. Write a C program that allows the user to input the student ID, name, and marks
of three different subjects for one student. Calculate the total marks and average
marks for the student. Finally, present the student details, total marks, and
average marks in tabular format with appropriate column headers, ensuring
proper alignment and precision in the output.
Code:
#include <stdio.h>
int main() {
int studentID;
char studentName[50];
float marks1, marks2, marks3;
float totalMarks, averageMarks;

// Input student details


printf("Enter Student ID: ");
scanf("%d", &studentID);
printf("Enter Student Name: ");
scanf("%s", studentName);

// Input marks for three subjects


printf("Enter Marks for Subject 1:
"); scanf("%f", &marks1);
printf("Enter Marks for Subject 2:
"); scanf("%f", &marks2);
printf("Enter Marks for Subject 3:
"); scanf("%f", &marks3);

// Calculate total marks and average


marks totalMarks = marks1 + marks2 +
marks3; averageMarks = totalMarks / 3;

// Print student details, total marks, and average marks in tabular format
printf("\n");
printf("Student Details:\n");
printf(" \n");
printf("Student ID : %d\n", studentID);
printf("Student Name : %s\n", studentName);
printf(" \n");
printf("Subject | Marks\n");
printf(" \n");
printf("Subject 1 | %.2f\n", marks1);
printf("Subject 2 | %.2f\n", marks2);
printf("Subject 3 | %.2f\n", marks3);
printf(" \n");
printf("Total Marks : %.2f\n", totalMarks);
printf("Average Marks: %.2f\n", averageMarks);
printf(" \n");

return 0;
}

Output:
Enter Student ID: 7732
Enter Student Name: ANANTH
Enter Marks for Subject 1: 90
Enter Marks for Subject 2: 80
Enter Marks for Subject 3: 99

Student Details:
Student ID : 7732
Student Name : ANANTH
Subject | Marks
Subject 1 | 90.00
Subject 2 | 80.00
Subject 3 | 99.00
Total Marks : 269.00
Average Marks: 89.67
Week-4

Prelab:
1. What are the different types of conditional statements available in C?
In C programming language, there are the following types of conditional statements in c.
a) if Statement: if Statement is a basic conditional statement in C Programming. If
Statement is used as a single statement in C program, then code insidethe if block will
execute if a condition is true. It is also called a one-way selection statement.
b) if-else Statement:if-else Statement in c allows two-way selection. If the given
condition is true, then program control goes inside the if block and executes the
Statement.
c) nested if-else Statement: A nested if-else statement is used to check more than one
condition. Nested if-else is also known as a multi-way selection statement. If there is
a series of decisions is involved in a statement, we use if else in nested form.
d) switch Statement: A switch case statement in C Programming tests the value of a
choice variable and compares it with multiple cases. When the case match is found, a
block of statements associated with that specific case is executed.Each case in a block
of a switch has a different choice which is referred to as an identifier. When the user
enters a value, then the value provided by the user is compared with all the cases
inside the switch block until the exact match is found.If a case match is not found,
then the default statement is executed, and the control goes out of the switch block.

e) if-else if ladder:The if-else-if conditional Statement in c is used to execute one code


from multiple conditions. It is also known as a multi-path decision statement. It is a
sequence of if-else statements where every if a statement is associated with else if
Statement and last would be an else statement.
2. Explain the purpose of using a switch case statement in C. How does it differ from
using multiple if-else statements?
In C programming, a switch case statement is used to make decisions based on the
value of a given expression. It provides an alternative to using multiple if-else
statements when you have a series of conditions to check against a single variable.
The purpose of a switch case statement is to simplify code readability and
maintainability in scenarios where there are multiple possible values or conditions to
evaluate. It allows you to write cleaner code by grouping related conditions together
and specifying the corresponding actions to be taken for each condition.
The general syntax of a switch case statement in C is as follows:
```c
switch (expression) {
case constant1:
// code to be executed if expression matches
constant1 break;
case constant2:
// code to be executed if expression matches
constant2 break;
// ...
default:
// code to be executed if expression doesn't match any
constant break;
}

Here's how a switch case statement differs from using multiple if-else statements:
1. Expression evaluation: In a switch case statement, the expression is evaluated only
once. Once the matching condition is found, the corresponding block of code is
executed, and the control exits the switch statement. In contrast, with multiple if-else
statements, each condition is evaluated one by one until a matching condition is found,
potentially leading to redundant evaluations.
2. Simplicity and readability: A switch case statement provides a more compact and
readable way to handle multiple conditions, especially when there are many options. It
allows you to group related conditions together and clearly define the actions for each
case, making the code easier to understand and maintain.
3. Limited conditions: Switch case statements work effectively when the conditions to
be evaluated are discrete values or constants. They are well-suited for situations where
the value of a variable needs to be compared against a fixed set of values.
4. Fall-through behavior: One notable feature of a switch case statement is the ability
to use the `break` statement. After executing a case, the control exits the switch
statement unless there is a `break` statement, which transfers control to the end of the
switch block. This allows for selective execution of code blocks based on matching
conditions. In contrast, if-else statements execute the first matching condition and then
exit, without allowing further conditions to be evaluated.
It's important to note that while switch case statements offer advantages in certain
scenarios, multiple if-else statements still have their own merits and may be more
suitable in other situations, such as when evaluating complex conditions involving
ranges or boolean expressions. The choice between switch case and if-else depends on
the specific requirements and readability of the code.
3. What is the advantage of using a nested if statement instead of a single if statement
in C? Provide an example scenario where a nested if statement is more suitable.
The advantage of using a nested if statement instead of a single if statement in C is that it
allows for more complex and specific conditional logic. By nesting one if statement inside
another, you can create a hierarchical structure of conditions, where each nested if statement is
evaluated only if the preceding condition is true. This allows you to make decisions based on
multiple criteria.
A scenario where a nested if statement is more suitable is when you need to check for multiple
conditions and perform different actions based on the combinations of those conditions. Here's
an example
#include <stdio.h>
int main() {
int age;
char gender;
printf("Enter your age:
"); scanf("%d", &age);
printf("Enter your gender (M/F): ");
scanf(" %c", &gender);
if (age >= 18) {
if (gender == 'M') {
printf("You are an adult male.\n");
} else if (gender == 'F') {
printf("You are an adult female.\
n");
} else {
printf("Invalid gender input.\n");
}
} else {
printf("You are not an adult.\n");
}
return 0;
}
In this example, we want to determine the category of a person based on their age and gender. If
the age is 18 or above, we use a nested if statement to further check the gender. Depending on
the gender, different messages are displayed. If the age is below 18, a message indicating non-
adult status is printed. The nested if statement allows us to handle the gender-specific cases
within the broader condition of being an adult, providing more specific output based on
multiple criteria.
4. In C, when should you use a switch case statement instead of nested if
statements? Provide an example scenario where a switch case statement is more
appropriate.
A switch case statement in C is more appropriate than nested if statements when you have
a single variable or expression that you want to compare against multiple constant values.
It provides a concise and efficient way to handle multiple cases without the need for
extensive if-else nesting. Here's an example scenario where a switch case statement is
more suitable:
#include <stdio.h>
int main() {
int day;
printf("Enter a number between 1 and 7:
"); scanf("%d", &day);
switch (day)
{ case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
case 6:
printf("Saturday\n");
break;
case 7:
printf("Sunday\n");
break;
default:
printf("Invalid input\n");
}
return
0;
}
In this example, we want to take a user input representing a day of the week (as a number
between 1 and 7) and display the corresponding day's name. Instead of using nested if
statements, we can utilize a switch case statement. Each case represents a possible value
of the variable `day`, and the corresponding action is taken when a match is found. The
`break` statement is used to exit the switch case block once the correct case is executed.
Switch case statements are especially useful when you have a limited number of distinct
cases and want to avoid repetitive if-else conditions. They offer a more readable and
efficient solution for handling multiple possibilities based on a single variable.

5. Provide an example of how you would use the ternary operator to assign a value
based on a condition.
The ternary operator in C is a concise way to assign a value to a variable based on a
condition. It has the following syntax:
variable = (condition) ?value_if_true : value_if_false;

Here's an example of how you can use the ternary operator to assign a value based
on a condition:
#include <stdio.h>
int main() {
int number;
char* result;
printf("Enter a number:
"); scanf("%d",
&number);
result = (number > 0) ? "Positive" : "Non-positive";
printf("The number is %s.\n", result);
return 0;
}
In this example, we take a user input `number` and assign the value `"Positive"` to the
`result` variable if `number` is greater than 0. Otherwise, we assign the value `"Non-
positive"`. The ternary operator `(number > 0) ? "Positive" : "Non-positive"` evaluates the
condition `number > 0`. If the condition is true, the value `"Positive"` is assigned to
`result`; otherwise, the value `"Non-positive"` is assigned.
The ternary operator is particularly useful when you want to assign a value to a variable
based on a simple condition without the need for an if-else statement. It provides a
compact and readable way to make such assignments in a single line of code.
6. What are some scenarios where using the ternary operator can improve code
readability and efficiency?
The ternary operator can improve code readability and efficiency in several scenarios,
including:

1. **Simple conditional assignments**: When you have a simple condition and want to
assign a value to a variable based on that condition, using the ternary operator can make the
code more concise and readable. It avoids the need for writing an if-else statement for a
single assignment.
2. **Inline conditionals**: In situations where you need to make a quick decision within an
expression or function call, the ternary operator allows you to embed the condition directly,
making the code more compact and easier to understand. It eliminates the need for separate
if-else blocks or additional variable assignments.
3. **Initializing variables**: When initializing variables based on a condition, the ternary
operator can be used to provide a clear and concise way to set the initial value. This can be
particularly useful in cases where the initialization depends on a simple condition.
4. **Avoiding repetitive if-else blocks**: In some cases, using the ternary operator can
help reduce the repetition of if-else blocks, leading to cleaner code. Instead of repeating
similar conditional checks in multiple places, the ternary operator allows you to consolidate
the condition and the assignment in a single line.
5. **Functional programming**: In functional programming paradigms, where
immutability is emphasized, the ternary operator can be useful for assigning values without
the need for mutable variables or state changes. It promotes a more functional and
declarative coding style.
However, it's important to note that the ternary operator should be used judiciously. While
it can enhance readability and efficiency in certain scenarios, excessive nesting or
complex conditions can make the code harder to understand. In such cases, it's often better
to use if- else statements for better readability and maintainability.
Lab:
In-Lab

1. Chef and Chefina are playing with dice. In one turn, both of them roll their dice at
once. They consider a turn to be good if the sum of the numbers on their dice is greater
than 6 Given that in a particula rturn Chef and Chefina got X and Y on their
respective dice, find whether the turn was good.
https://www.codechef.com/problems/GDTURN?tab=statement
Code:

#include <stdio.h>
int main(void) {
// your code goes
here int T;
scanf("%d", &T);
while (T--) {
int X, Y;
scanf("%d %d", &X,
&Y); if (X + Y > 6)
printf("YES\n");
else printf("NO\
n");
}
}

2. Chef has been working hard to compete in Master Chef. He is ranked X out of all
contestants. However, only 1010 contestants would be selected for thefinals. Check
whether Chef made it to the top 1010 or not?
https://www.codechef.com/problems/TOP10?tab=statement
Code:
#include <stdio.h>
int main(void) {
// your code goes
here int T;
scanf("%d", &T);
while (T--) {
int X;
scanf("%d", &X);
if (X <= 10)
printf("YES\n");
else printf("NO\
n");

}
return 0
}
3. Apple considers any iPhone with a battery health of 80% or above, to be in
optimal condition.Given that your iPhoneh as X% battery health, find whether it
is in optimal condition.
https://www.codechef.com/problems/BTRYHLTH?tab=statement
Code:

#include <stdio.h>
int main(void) {
// your code goes here
int T;
scanf("%d", &T);
while (T--) {
int X;
scanf("%d", &X);
if (X >= 80)
printf("YES\n");
else printf("NO\
n");
}
return 0;
}
Post-Lab

1. Solve the problem in the hacker rank platform.


https://www.hackerrank.com/challenges/conditional-statements-in-c/problem
Code:
char *string[] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
(n <= 9)?printf("%s",string[n -1]) : printf("Greater than 9");
2. In a classic chase, Tom is running after Jerry as Jerry has eaten Tom's favourite
food. Jerry is running at a speed of X metres per second while Tom is chasing
him at a speed of Y metres persecond.Determine whether Tom will be able to
catch Jerry. Note that initially Jerry is not at the same position as Tom.
https://www.codechef.com/problems/JERRYCHASE
Code:
#include <stdio.h>
int main(void) {
int num;
scanf("%d",&num);
while(num--){
int tom,jerr; scanf("%d
%d",&tom,&jerr);
if(tom<jerr) printf("YES\
n");
else printf("NO\
n");
}
// your code goes
here return 0;
}

3. Chef has started studying for the up coming test. The text book has N pages in
total. Chef wants to read at most X pages a day for Y days. Find out whether it is
possible for Chef to complete the whole book.
https://www.codechef.com/problems/READPAGES
Code:

#include <stdio.h>
int main(void) {
int t;
scanf("%d",&t);
while(t--) {
int N, X, Y, S;
scanf("%d%d%d",&N,&X,&Y);
S=X*Y;
if(N<=S)
printf("YES\n");
else printf("NO\
n");
}
// your code goes
here return 0;
}
Skilll:
1. Chef has finally got the chance of his lifetime to drive in the F1 tournament. But,
there is one problem. Chef did not know about the 107% rule and now he is
worried whether he will be allowed to race in the main event or not. Given the
fastest finish time as X seconds and Chef's finish time as Y seconds, determine
whether Chef will be allowed to race in the main event or not. Note that, Chef will
only be allowed to race if his finish time is within 107% of the fastest finish time.

https://www.codechef.com/problems/F1RULE
Code:

#include <stdio.h>
int main(void) {
int T;
scanf("%d",&T);
while(T--) {
int X,Y;
float f;
scanf("%d%d",&X,&Y);
f=X*107/100;
if(Y<=f)
printf("YES\n");
else printf("NO\
n");
}
// your code goes
here return 0;
}

2. Chef wants to host a party with a total of N people. However, the party hall has
a capacity of X people. Find whether Chef can host the party.
https://www.codechef.com/problems/RIGHTTHERE?tab=statement
Code:

#include <stdio.h>
int main(void) {
int T;
scanf("%d",&T);
while(T--) {
int N,X;
scanf("%d%d",&N,&X);
if(X>=N)
printf("YES\n");
else
printf("NO\n");
}
// your code goes
here return 0;
}
3. Chef has to attend an exam that starts in X minutes, but ofcourse, watching shows
takes priority. Every episode of the show that Chef is watching, is 24 minutes long.
If he starts watching a new episode now, will he finish watching it strictly before
the exam starts?
https://www.codechef.com/problems/ONEMORE?tab=statement

Code:
#include <stdio.h>
int main(void) {
int t;
scanf("%d",&t);
while(t--) {
int x;
scanf("%d",&x);
if(x>24) {
printf("Yes\n");
}
else {
printf("No\n");
}
}

return 0;
}

4. Chef has to travel to an other place. For this, he can avail any one of two
cab services.
a. The first cab service charges X rupees.
b. The second cab service charges Y rupees.
Chef wants to spend the minimum amount of money. Which cab service should Chef
take?
https://www.codechef.com/problems/CABS?tab=statement (The Cheaper Cab - Problems -
CodeChef)
Code:
#include <stdio.h>
int main(void) {
int T;
scanf("%d",&T);
while(T--) {
int X,Y; scanf("%d
%d",&X,&Y); if(X>Y)
printf("SECOND\n");
else if(X<Y)
printf("FIRST\n");
else
printf("ANY\n");
}
// your code goes
here return 0;
}
5. Chef categorizes an Instagram account as spam, if, the following count of the
account is more than 10 times the count of followers. Given the following and
follower count of an account as X and Y respectively, find whether it is a spam
account.
https://www.codechef.com/problems/INSTAGRAM?tab=statement
Code:
#include <stdio.h>
int isSpamAccount(int following, int followers)
{ if (following > 10 * followers)
return 1; // It's a spam account
else
return 0; // It's not a spam account
}
int main(void) {
int T; // Number of test
cases scanf("%d", &T);
while (T--) {
int X, Y; // Following and follower
count scanf("%d %d", &X, &Y);
if (isSpamAccount(X,
Y)) printf("YES\n");
else printf("NO\
n");
}
// your code goes here
return 0;
}

6. Chef is watching TV. The current volume of the TV is X. Pressing the volume up
button of the TV remote increases the volume by 11 while pressing the volume
down button decreases the volume by 11. Chef wants to change the volume from X to
Y. Find the minimum number of button presses required to do so.
https://www.codechef.com/problems/VOLCONTROL
Code:
#include <stdio.h>
#include <stdlib.h>
int minButtonPresses(int X, int Y)
{ int diff = abs(X - Y);
return diff; // Minimum number of button presses required is the absolute difference between
X and Y
}
int main(void) {
int T; // Number of test
cases scanf("%d", &T);
while (T--) {
int X, Y; // Initial and final volume of the
TV scanf("%d %d", &X, &Y);
int minPresses = minButtonPresses(X, Y);
printf("%d\n", minPresses);
}
// your code goes
here return 0;
}
Week-5
Prelab:
1. Discuss the difference between the prefix and postfix increment operators (++
variable and variable ++) in C. How are they used, and what are their effects on
the variable?
Ans:
In C, the prefix and postfix increment operators (++variable and variable++) are
used to increase the value of a variable by 1. However, they have some important differences in
how they are used and their effects on the variable.
1. Prefix Increment Operator (++variable):
The prefix increment operator (++variable) is used before the variable. When this
operator is used, the value of the variable is incremented by 1, and the updated value is used
in the expression where the operator is used.
For example:
int a =
5; int b = ++a;
After executing this code, the value of `a` becomes 6, and the value of `b` also
becomes 6 because the prefix increment operator increments the value of `a` before assigning it
to `b`.
2. Postfix Increment Operator (variable++):
The postfix increment operator (variable++) is used after the variable. When this
operator is used, the value of the variable is incremented by 1, but the original value of the
variable is used in the expression where the operator is used.
For example:
int a = 5;
int b = a+
+;
After executing this code, the value of `a` becomes 6, but the value of `b` becomes
5 because the postfix increment operator assigns the original value of `a` (5) to `b` and then
increments `a`.
The key difference between the prefix and postfix increment operators is their
effect on the variable when used in an expression. The prefix increment operator
increments the variable and uses the updated value in the expression, while the postfix
increment operator also increments the variable but uses the original value in the expression.
It's important to note that both operators can be used with any variable that has a
modifiable value (e.g., integers, floating-point numbers), and their behavior remains the
same regardless of the data type.
2. What is the purpose of the unary negation operator (-) in C? How does it work,
and whateffectdoesithaveontheoperand?
Ans:
In C, the unary negation operator (-) is used to negate the value of an operand. Its
purpose is to change the sign of a numeric value, effectively turning a positive value into a
negative one, and vice versa.

The unary negation operator works by placing a minus sign (-) before the operand.
When applied to a numeric value, it reverses the sign of the value. If the operand is
positive, it becomes negative, and if the operand is negative, it becomes positive.
Here are a few examples to illustrate the usage and effect of the unary negation
operator:
int a = 5;
int b = -
a;

In this example, the value of `a` is 5. By applying the unary negation operator to
`a` with `-a`, the value of `b` becomes -5. The positive value of `a` is negated, resulting in a
negative value.

int c = -
10; int d =
-c;
In this example, the value of `c` is -10.By applying the unary negation operator to
`c` with `-c`, the value of `d` becomes 10. The negative value of `c` is negated, resulting in
a positive value.
The unary negation operator can be used with various numeric data types,
including integers and floating-point numbers. Its effect is consistent across these types,
reversing the sign of the operand.
It's important to note that the unary negation operator does not modify the original
value of the operand. It only produces a negated value for use in expressions or
assignments. If you want to modify the value of a variable directly, you would need to use
an assignment statement, such as `variable = -variable`.
3. Explain thedifferencebetween awhileloop,ado-while loop, and a forloop in C.When
would you choose one loop type over the others?
Ans:
In C, while loop, do-while loop, and for loop are three types of loop constructs that
allow repetitive execution of a block of code. They have some differences in syntax and
behavior, and the choice of which loop type to use depends on the specific requirements of
the program.
1. while loop:
A while loop repeatedly executes a block of code as long as a given condition is
true. The condition is checked before the execution of the loop body, and if it evaluates to
true, the loop body is executed. After each iteration, the condition is checked again, and the
loop continues until the condition becomes false.
Syntax:
while (condition) {
// code to be executed
}
Example:
int i = 0;
while (i < 5) {
printf("%d ",
i); i++;
}
In this example, the loop will execute the code block as long as the condition `i <
5` is true. It will print the values of `i` from 0 to 4.
2. do-while loop:
A do-while loop is similar to a while loop, but with a difference in the order of
execution. The loop body is executed first, and then the condition is checked. If the
condition is true, the loop continues execution, otherwise, it terminates.
Syntax:
do {
// code to be executed
} while (condition);
Example:
int i =
0; do {
printf("%d ",
i); i++;
} while (i < 5);
In this example, the loop will execute the code block at least once, regardless of
the condition. It will print the values of `i` from 0 to 4, similar to the while loop.
3. for loop:
A for loop is designed to iterate over a sequence of values. It consists of an
initialization statement, a condition, and an increment/decrement statement, all within the
loop declaration. The initialization statement is executed only once at the beginning. Then,
the condition is checked, and if it evaluates to true, the loop body is executed. After each
iteration, the increment/decrement statement is executed, and the loop continues until the
condition becomes false.
Syntax:
for (initialization; condition; increment/decrement) {
// code to be executed
}
Example:
for (int i = 0; i < 5; i++)
{ printf("%d ", i);
}
In this example, the loop initializes `i` to 0, and as long as `i < 5` is true, it executes
the code block. The loop prints the values of `i` from 0 to 4.
When to choose one loop type over the others:
Use a while loop when you want to execute a block of code based on a condition,
and the number of iterations is not known beforehand.
Use a do-while loop when you want to execute a block of code at least once,
regardless of the condition, and then repeat it as long as the condition is true.
Use a for loop when you have a specific number of iterations or want a compact
way to express the loop with initialization, condition, and increment/decrement in a single
line.
The choice of loop type depends on the specific requirements of your program, the
iteration logic, and the conditions under which you want the loop to execute.
4. Howcanyouavoidcreatinganinfiniteloopunintentionallyinyourprogram?Provideanex
ample.
Ans:
To avoid creating an infinite loop unintentionally in your C program, you need to
ensure that the loop's termination condition is properly defined and will eventually become
false. Here are a few strategies to prevent infinite loops:
1. Update the loop control variable:
Ensure that the loop control variable (such as a counter) is being updated correctly
inside the loop. Failing to update the control variable may cause the loop condition to
remain true indefinitely.
Example:
int i = 0;
while (i < 5)
{
printf("%d ", i);
// Missing increment statement i++;
}
In this example, the loop will never terminate because the `i` variable is not being
incremented inside the loop. To fix this, you need to add the increment statement `i++;` to
ensure that `i` eventually becomes greater than or equal to 5, causing the loop condition to
become false.
2. Use a suitable loop condition:
Ensure that the loop condition is properly defined and will eventually evaluate to
false. Carefully consider the conditions that control the loop to avoid scenarios where the
condition is always true.
Example:

int i = 0;
while (i > 0)
{
printf("%d ",
i); i++;
}
In this example, the loop condition `i > 0` will always be false because `i` is
initially 0, and there is no code inside the loop that modifies the value of `i`. To prevent an
infinite loop, you need to adjust the loop condition to something that will eventually
become false, such as `i < 5`.
3. Use break or return statements:
Include appropriate break or return statements inside the loop to explicitly
terminate the loop under certain conditions. This can help prevent infinite loops when a
specific condition is met.
Example:
while (1)
{ int
value;
printf("Enter a value (-1 to exit):
"); scanf("%d", &value);
if (value == -1) {
break; // Terminate the loop if -1 is entered
}
printf("You entered: %d\n", value);
}
In this example, the loop continues indefinitely until the user enters `-1`. At that
point, the `break` statement is executed, and the loop is terminated.
By following these strategies and ensuring that your loop conditions are correctly
defined and will eventually become false, you can avoid unintentionally creating infinite
loops in your C programs.
5. Howcanyoucontroltheexecutionflowinnestedloopsusingthe"break"statement?
Ans:
In C, the "break" statement is used to terminate the execution of a loop
prematurely. When used within nested loops, it allows you to control the execution flow by
breaking out of one or more levels of nested loops. Here's how you can use the "break"
statement to control the execution flow in nested loops:
1. Breaking out of the innermost loop:
To break out of the innermost loop in a nested loop structure, you can simply use
the "break" statement within the loop body where the condition for termination is met. This
will immediately exit the innermost loop and resume execution after the loop.
Example:
for (int i = 1; i <= 3; i++)
{ for (int j = 1; j <= 3; j+
+) { if (i == 2 && j == 2)
{
break; // Break out of the innermost loop
}
printf("%d %d\n", i, j);
}
}
In this example, when `i` is equal to 2 and `j` is equal to 2, the "break" statement is
executed, terminating the innermost loop. As a result, the output will be:
11
12
13
21
2. Breaking out of multiple levels of nested loops:
If you need to break out of multiple levels of nested loops simultaneously, you can
use labeled loops and the "break" statement with the corresponding label. A label is a user-
defined identifier followed by a colon (:).
Example:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
for (int k = 1; k <= 3; k++)
{
if (i == 2 && j == 2 && k == 2) {
break; // Break out of the labeled loop
}
printf("%d %d %d\n", i, j, k);
}
}
}
In this example, the "break" statement is used with a label to break out of all three
levels of nested loops. When `i` is equal to 2, `j` is equal to 2, and `k` is equal to 2, the
labeled loop is terminated. The output will be:
1 11
112
113
121
By using the "break" statement strategically within nested loops, you can control
the execution flow and terminate the loops based on specific conditions.
6. What precautions should you take when using nested loops to avoid potential issues
like in finite loops?
Ans:
When using nested loops in C, it's important to take certain precautions to avoid
potential issues like infinite loops. Here are some precautions you should consider:
1. Ensure proper initialization and update of loop control variables:
Make sure that each loop control variable is correctly initialized before entering the
loop and updated properly within the loop body. Failing to initialize or update a loop
control variable can result in unexpected behavior or infinite loops.
Example:
int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 5; j++) {
// Loop body code
}
}
2. Define appropriate loop termination conditions:
Ensure that each loop has a well-defined termination condition that will eventually
become false. The termination condition should depend on the loop control variables or
other relevant factors. Be cautious not to create a condition that is always true, leading to
an infinite loop.
Example:
int i, j;
for (i = 0; i < 3; i++)
{ for (j = 0; j < 5; j+
+) {
// Loop body code
}
}
3. Use break or continue statements judiciously:
Avoid excessive or incorrect use of break and continue statements within nested
loops, as they can disrupt the intended flow and cause unexpected behavior. Use them only
when necessary and ensure they are placed appropriately to avoid infinite loops.
Example:
int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 5; j++) {
if (condition) {
break; // Avoid using break unnecessarily
}
// Loop body code
}
}
4. Test and validate the loop logic:
Test your nested loop structure thoroughly with various input values to ensure that
it executes as expected and terminates correctly. Identify any potential issues during testing
and fix them before deploying your code.
Example:
int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 5; j++) {
// Loop body code
}
}
By following these precautions, you can mitigate the risks of potential issues like
infinite loops when working with nested loops in C. It's essential to maintain control over
the loop structure, validate the loop logic, and ensure proper initialization, update, and
termination conditions to achieve the desired loop behavior.
Lab:
In-Lab:

1. Sum of digits of five digit number. Given the five digit number, print the sum of
its digits. Input: 10564, Output: 16
https://www.hackerrank.com/challenges/sum-of-digits-of-a-five-digit-number
Code:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int n, a, m, sum=0,
i=0; scanf("%d", &n);
m=n;
while(m>0) {
m=m/10;
i++;
}
printf("%d\n",i);
if(i==5) {
while(n>0) {
a = n%10;
sum =
sum+a; n =
n/10;
}
printf("\n%d",sum);
}

return 0;
}
2. Solve the problem in hackerrank platform.
https://www.hackerrank.com/challenges/for-loop-in-c/problem
Code:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main()
{
int a, b;
scanf("%d\n%d", &a, &b);
char *str[] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
"even", "odd"};
scanf("%d\n%d", &a, &b);
for (int i=a; i<=b; i++)// i=
8
{
if (i <= 9)
{
printf ("%s\n", str[i-1]);
}
else
{
printf ("%s\n", str[9+(i%2)]);
}
}
return 0;
}
3. A great deal of energy is lost as metabolic heat when the organisms from one
trophic level are consumed by the next level. Suppose in Chefland the energy
reduces by a factor of K, i.e, if initially, the energy is X, then the transfer of
energy to the next tropic level is ⌊K/X⌋. This limits the length of foodchain which
is defined to be the highest level receiving non-zero energy. E is the energy at the
lowest tropic level. Given E and K for an ecosystem, find the maximum length of
foodchain.
Note: ⌋⌊x⌋ denoted the floor function, and it returns the greatest integer that is less
than or equal to x (i.e rounds down to the nearest integer).
For example, ⌊1.4⌋=1, ⌊5⌋=5, ⌊−1.5⌋=−2, ⌊−3⌋=−3, ⌊0⌋=0.
Input Format
 First line will contain T, number of testcases. Then the testcases follow.
 Each testcase contains a single line of input, two integers E,
K. Output Format
For each testcase, output in a single line answer to the
problem. https://www.codechef.com/problems/FODCHAIN?
tab=statement Code:
#include <stdio.h>
int main(void) {
int turns;
scanf("%d",&turns);
int i = 0;
for(i;i<turns;i++)
{
int start,length;
scanf("%d %d", &start,&length);
int level=1;
while(1){
start = start /
length; if(start>0)
level++;
else
break;
}
printf("%d\n",level);
}
return 0;
}
Post-Lab
1. Solve the problem in the hacker rank platform (Day 5: Loops | HackerRank)
https://www.hackerrank.com/challenges/30-loops/problem
Code:
int main()
{
int n = parse_int(ltrim(rtrim(readline())));
for(int i=1; i<=10; i++) {
printf("%d x %d = %d\n",n,i,(n*i));
}
return 0;
}
2.
 Alice likes numbers which are even, and are a multiple of 7.
 Bob likes numbers which are odd, and are a multiple of
9. Alice, Bob, and Charlie find a number A.
 If Alice likes A, Alice takes home the number.
 If Bob likes A, Bob takes home the number.
 If both Alice and Bob don't like the number, Charlie takes it home. Given A,
find who takes it home.

https://www.codechef.com/problems/FAVOURITENUM?tab=statement
Code:

#include <stdio.h>
int main(void) {
int T;
scanf("%d",&T);
while(T--) {
int X;
char S;
scanf("%d%c",&X,&S); if(X
%7==0&&X%2==0)
printf("Alice\n");
else if(X%9==0&&X%2!=0)
printf("Bob\n");
else
printf("Charlie\n");
}
return 0;
}
3. Chef owns a car that can run 15 kilometers using 1 liter of petrol. He wants to
attend a programming camp at DAIICT. X liters of petrol is present in Chef's car.
The distance between his house and DAIICT is Y kilometers. Determine whether
Chef can attend the event and return to his home with the given amount of petrol.
Note: Chef has to return back to home, so the total distance to be covered would be
2⋅Y.
https://www.codechef.com/problems/CANCHEF
Code:
#include <stdio.h>
int main(void) {
int T;
scanf("%d",&T);
while(T--) {
int X,Y; scanf("%d
%d",&X,&Y);
if(X*15>=Y*2)
printf("YES\n");
else printf("NO\
n");
}
return 0;
}
Skilll:
1. Listen to this story: a boy and his father, a computer programmer, are playing
with wooden blocks. They are building a pyramid. Their pyramid is a bit weird, as
it is actually a pyramid- shaped wall - it's flat. The pyramid is stacked according to
one simple principle: each lower layer contains one block more than the layer
above. The figure illustrates the rule used by the builders:

Note: the height is measured by the number of fully completed layers - if the builders
don't have a sufficient number of blocks and cannot complete the next layer, they
finish their work immediately.
Sample input: 6
Expected output: The height of the pyramid: 3 Sample
input: 1000
Expected output: The height of the pyramid: 44
Code:
#include <stdio.h>
int main() {
int blocks, height, layer, i;
printf("Enter the number of blocks: ");
scanf("%d", &blocks);
height = 0;
layer = 1;
while (blocks > 0) {
if (blocks >= layer)
{ blocks -= layer;
height++;
} else
{ brea
k;
}
layer++;
}
printf("The height of the pyramid is: %d\n", height);
return 0;
}
Output:
Enter the number of blocks: 6
The height of the pyramid is: 3
Enter the number of blocks:
1000 The height of the pyramid
is: 44
2. Solve the following pattern problem

https://www.codechef.com/problems/BICBPAT1

Code:
#include <stdio.h>
int min(int a, int b)
{
return (a < b) ? a : b;
}
void printPattern(int n)
{ int size = 2 * n - 1;
for (int i = 0; i < size; i++)
{ for (int j = 0; j < size; j+
+) {
// Calculate the value at each position
int value = n - min(min(i, j), min(size - i - 1, size - j - 1));
// Print the value followed by a space
printf("%d ", value);
}
// Move to the next line after printing each
row printf("\n");
}
}

int main()
{ int n;
scanf("%d", &n);
// Print the
pattern
printPattern(n);

return 0;
}

Output:
4 4 4 4 4 4 4
4 3 3 3 3 3 4
4 3 2 2 2 3 4
4 3 2 1 2 3 4
4 3 2 2 2 3 4
4 3 3 3 3 3 4
4 4 4 4 4 4 4
3. A semester in Chef's University has 120 working days. The University's requirement is
that a student should be present for at least 75% of the working days in the semester. If
not, the student is failed. Chef has been taking a lot of holidays, and is now concerned
whether he can pass the attendance requirement or not. N working days have already
passed, and you are given N bits -B1, B2, …, BN. Bi=0 denotes that Chef was absent on the
ith day, and Bi = 1denotes that Chef was present on that day. Can Chef hope to pass the
requirement by the end of the semester?
https://www.codechef.com/problems/ATTENDU?tab=statement
Code:
#include <stdio.h>
int main(void) {
int T;
scanf("%d",&T);
while(T--)
{
int X;
scanf("%d",&X);
char b[X];
scanf("%s", b);
int d=0;
for(int i=0; i<X; i++)
{
if(b[i]=='0')
d++;
}
if(d>30)
printf("NO\n");
else printf("YES\
n");

}
return 0;
}
4. There are N piles where the i'th pile consists of Ai stones. Chef and Chefina are
playing a game taking alternate turns with Chef starting first. In his/her turn, a
player can choose any non- empty pile and remove exactly 1 stone from it. The
game ends when exactly 1 pile becomes empty. The player who made the last move
wins. Determine the winner if both players play optimally.
https://www.codechef.com/JULY221D/problems/GAMEOFPILES1
Code:
#include <stdio.h>
int main(void) {
int T;
scanf("%d", &T);

while (T--)
{ int N;
scanf("%d", &N);
int i, stones, odd_found =
0; for (i = 0; i < N; i++) {
scanf("%d", &stones);
if (stones % 2 != 0) {
odd_found = 1;
}
}

if (odd_found) {
printf("CHEF\n");
} else {
printf("CHEFINA\n");
}
}
// your code goes
here return 0;
}
5. write the c program for following pattern

Code:
#include <stdio.h>
int main() {
int i, j;
for (i = 5; i >= 1; i--) {
for (j = 1; j <= i; j++)
{ printf("%d ",
j);
}
printf("\n");
}
return 0;
}

Output:
12345
1234
123
12
1
6. Write a program to obtain a number N and increment its value by 1 if the number
is divisible by 4 otherwise decrement its value by 1.
https://www.codechef.com/problems/DECINC
Code:
#include <stdio.h>
int main() {
int N;
printf("Enter a number: ");
scanf("%d", &N);
if (N % 4 == 0) {
N += 1;
}
else {
N -= 1;
}
printf("Updated value of N: %d\n", N);
return 0;
}
Output:
Enter a number: 34
Updated value of N: 33
Enter a number: 400
Updated value of N:
401
Code:

Output:

Dear All, Please utilize the following programming exercise for the Post Lab Question 3 of
Week 5:
Chef owns a car that can run 15 kilometers using 1 liter of petrol.He wants to attend a
programming camp at DAIICT. X liters of petrol is present in Chef's car. The distance
between his house and DAIICT is Y kilometers.Determine whether Chef can attend the
event and return to his home with the given amount of petrol.
Note: Chef has to return back to home, so the total distance to be covered would be
2⋅Y. https://www.codechef.com/problems/CANCHEF

Week-5
Pre-Lab
1. Discuss the difference between the prefix and postfix increment operators (++variable
and variable++) in C. How are they used, and what are their effects on the variable?

2. What is the purpose of the unary negation operator (-) in C? How does it work, and
what effect does it have on the operand?

3. Explain the difference between a while loop, a do-while loop, and a for loop in C.
When would you choose one loop type over the others?

4. How can you avoid creating an infinite loop unintentionally in your program? Provide
an example.

5. How can you control the execution flow in nested loops using the "break" statement?

6. What precautions should you take when using nested loops to avoid potential issues
like infinite loops?

In-Lab

1. Sum of digits of five digit number


Given the five digit number, print the sum of its digits.

Input
10564
Output
16
https://www.hackerrank.com/challenges/sum-of-digits-of-a-five-digit-number
2. Solve the problem in hackerrank platform. https://www.hackerrank.com/challenges/for-
loop- in-c/problem

3.

Post-lab
1. Solve the problem in the hackerrank platform
https://www.hackerrank.com/challenges/30- loops/problem

3. solve the problem in the codechef platform


https://www.codechef.com/learn/BC00LP06/problems/LOOP1

Skill

1. Listen to this story: a boy and his father, a computer programmer, are playing with wooden
blocks. They are building a pyramid.Their pyramid is a bit weird, as it is actually a pyramid-
shaped wall - it's flat. The pyramid is stacked according to one simple principle: each lower layer
contains one block more than the layer above.

The figure illustrates the rule used by the builders:

Note: the height is measured by the number of fully completed layers - if the builders don't
have a sufficient number of blocks and cannot complete the next layer, they finish their
work immediately.

Sample input: 6
Expected output: The height of the pyramid: 3 Sample
input: 1000
Expected output: The height of the pyramid: 44

2.Solve the following pattern problem

https://www.codechef.com/problems/BICBPAT1

.
3. A semester in Chef's University has 120 working days. The University's requirement
is that a student should be present for at least 75% of the working days in the semester. If not,
the student is failed. Chef has been taking a lot of holidays, and is now concerned whether he
can pass the attendance requirement or not. N working days have already passed, and you are
given N bits -B1, B2, …, BN. Bi=0 denotes that Chef was absent on the ith day, and Bi =

1denotes that Chef was present on that day. Can Chef hope to pass the requirement by the
end of the semester?

https://www.codechef.com/problems/ATTENDU?tab=statement

4. There are N piles where the ith pile consists of Aistones. Chef and Chefina are playing a
game taking alternate turns with Chef starting first. In his/her turn, a player can choose any
non- empty pile and remove exactly 1 stone from it. The game ends when exactly 1 pile
becomes empty. The player who made the last move wins. Determine the winner if both
players play optimally.
https://www.codechef.com/JULY221D/problems/GAMEOFPILES1

5. write the c program for following pattern

6.Write a program to obtain a number N and increment its value by 1 if the number is
divisible by 4 otherwise decrement its value by 1.

https://www.codechef.com/problems/DECINC
Week-6

Prelab:
1. What is a 1D array in
C? Ans:
In C programming, a 1D array is a linear collection of elements of the same data type
stored in contiguous memory locations. It is also referred to as a one-dimensional array
because it represents a single row or a single column of elements.
The 1D array is defined by specifying the data type of its elements, followed by the
array name and the number of elements it can hold within square brackets. For example, to
declare a 1D array of integers called "numbers" that can store 5 elements, you would write:
int numbers[5];
The array elements can be accessed using their indices, which start from 0 and go
up to the size of the array minus 1. For instance, to access the third element of the
"numbers" array, you would use:
int thirdElement = numbers[2];
You can initialize the array at the time of declaration by providing a comma-
separated list of values enclosed in curly braces. For example:
int numbers[5] = {1, 2, 3, 4, 5};
1D arrays are widely used in C programming to store and manipulate a sequence of
related data items, such as a list of numbers, characters, or any other data type supported by
C. They provide a simple and efficient way to work with a collection of elements.

2. How do you declare and initialize a 1D array in


C? Ans:
In C, you can declare and initialize a 1D array using the following
syntax: datatype arrayName[arraySize] = {element1, element2, ..., elementN};
Here's an example of declaring and initializing a 1D array of
integers: int numbers[5] = {1, 2, 3, 4, 5};
In the above example, we declare an array called `numbers` of size 5 and initialize it with
the values 1, 2, 3, 4, and 5.
Alternatively, if you only provide some initial values and leave out the rest, the remaining
elements will be automatically initialized to zero:
int numbers[5] = {1, 2, 3};
In this case, the array `numbers` will be initialized with the values 1, 2, 3, 0, 0.
It's worth noting that in C, arrays are zero-indexed, meaning the first element is accessed
using an index of 0, the second element with an index of 1, and so on.
3. How do you access elements of a 1D array in C?

Ans:
In C, elements of a 1D array can be accessed using the array name and the index of
the element. The index represents the position of the element within the array, starting from
0 for the first element. Here's an example of how to access elements of a 1D array in C
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50}; // Example array
// Accessing individual elements
printf("Element at index 0: %d\n", arr[0]);
printf("Element at index 1: %d\n", arr[1]);
printf("Element at index 2: %d\n", arr[2]);
printf("Element at index 3: %d\n", arr[3]);
printf("Element at index 4: %d\n", arr[4]);
return 0;
}
In this example, the array `arr` is declared with 5 elements. To access an element,
you use the array name `arr` followed by the index enclosed in square brackets
(`[]`). For instance, `arr[0]` accesses the first element, `arr[1]` accesses the second
element, and so on.
When you run the above program, it will output:
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50
You can access any valid index within the range of the array. Accessing elements
outside the valid range can lead to undefined behavior or runtime errors.

4. Can you change the size of a 1D array dynamically in C? If yes, how? If no, why
not?
Ans:
In the C programming language, the size of a 1D array is fixed at the time of its
declaration. Once the array is created, its size cannot be changed dynamically. The reason
for this is that C arrays are allocated contiguous blocks of memory, and the size of the
allocated memory is determined during compilation.
If you need to change the size of an array dynamically in C, you have a few options:
1. Use dynamic memory allocation: Instead of using a regular array, you can
allocate memory dynamically using functions like `malloc()`, `calloc()`, or `realloc()`. With
these functions, you can allocate memory of a different size and copy the contents of the
original array to the new memory block. However, this approach requires manual memory
management and can be error-prone if not handled carefully.
Here's an example of dynamically resizing an array using `realloc()`:
#include <stdio.h>
#include <stdlib.h>
int main() {
int* array = malloc(sizeof(int) * 5);
// Initialize the array
// Increase the size of the array
int* resizedArray = realloc(array, sizeof(int) * 10);
if (resizedArray != NULL) {
array = resizedArray;
// Update the array pointer to the resized array
// Continue using the array with the new size
} else {
// Handle the case where memory allocation fails
// Original array remains intact
}
// Deallocate memory when done
free(array);
return 0;
}

2. Use a data structure that provides dynamic resizing: Instead of using a regular C array,
you can use a data structure such as a linked list or a dynamic array implementation
(vector) from a third-party library. These data structures handle the resizing internally,
allowing you to append or remove elements without explicitly managing memory
allocation.

It's important to note that dynamically resizing an array can incur performance
overhead dueto memory reallocation and data copying. Therefore, if you know the
maximum size of thearray in advance or have a fixed-size requirement, it'sgenerally more
efficient to use afixed size array.

5. How do you pass a 1D array to a function in


C? Ans:
In C, you can pass a 1D array to a function by declaring the array parameter as
a pointer. Here's an example:
#include <stdio.h>
// Function that takes a 1D array as a parameter
void processArray(int* arr, int size) {
// Access elements of the array using pointer
arithmetic for (int i = 0; i< size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int myArray[] = {1, 2, 3, 4, 5};
int size = sizeof(myArray) / sizeof(myArray[0]);
// Pass the array to the
function processArray(myArray,
size);
return 0;
}
In the example above, the `processArray` function takes an integer pointer `arr` as a
parameter and an integer `size` to represent the size of the array. Inside the function,
you can access the elements of the array using pointer arithmetic.
In the `main` function, we declare an array called `myArray` and calculate its size by
dividing the total size of the array by the size of a single element. Then we call the
`processArray` function and pass the array along with its size as arguments.
Note that when passing an array to a function, you only need to pass the array name
without brackets (e.g., `myArray` instead of `myArray[]`). The array name itself
represents the address of the first element of the array, which can be treated as a
pointer.
In-Lab
1. You are given a large integer represented as an integer array digits, where each
digits[i] is the ith digit of the integer. The digits are ordered from most significant
to least significant in left-to-right order. The large integer does not contain any
leading 0's. Increment the large integer by one and return the resulting array of
digits.
https://leetcode.com/problems/plus-one/description/
Code:
#include <stdio.h>
#include <stdlib.h>
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* plusOne(int* digits, int digitsSize, int* returnSize){
int carry = 1; // Initialize carry to 1 since we want to increment the
number int i;
// Traverse the digits from right to
left for (i = digitsSize - 1; i >= 0; i--)
{
digits[i] += carry; // Add the carry to the current
digit carry = digits[i] / 10; // Compute the new carry
digits[i] %= 10; // Update the current digit

if (carry == 0) // If there is no carry, we can stop the increment


break;
}
if (carry == 1) {
// If there is still a carry, we need to prepend a new
digit (*returnSize) = digitsSize + 1;
int* result = (int*)malloc((*returnSize) * sizeof(int));
result[0] = carry;
for (i = 1; i < (*returnSize); i++)
{ result[i] = digits[i - 1];
}
return result;
} else {
(*returnSize) = digitsSize;
return digits;
}
}
int main()
{ int n=0;
printf("Enter N:");
scanf("%d",&n);
int digits[n];
int digitsSize = sizeof(digits) / sizeof(digits[0]);
int returnSize = 0,i;
for(i=0;i<n;i++) {
scanf("%d", &digits[i]);
}
int* result = plusOne(digits, digitsSize, &returnSize);
printf("Result: ");
for (i = 0; i < returnSize; i++)
{ printf("%d ", result[i]);
}
free(result); // Free the allocated
memory return 0;
}
Output:
Enter N:3
321
Result: 3 2 2
2. Most programmers will tell you that one of the ways to improve your performance
in competitive programming is to practice a lot of problems.
Our Chef took the above advice very seriously and decided to set a target for himself.
Chef decides to solve at least 10 problems every week for 4 weeks.
Given the number of problems he actually solved in each week over 4 weeks as
P1,P2,P3, and P4, output the number of weeks in which Chef met his
target. Input Format
There is a single line of input, with 4 integers P1,P2,P3, and P4. These are the number
of problems solved by Chef in each of the 4 weeks.
Output Format
Output a single integer in a single line - the number of weeks in which Chef solved at
least 10 problems. Further details…
https://www.codechef.com/problems/PRACTICEPERF
Code:
#include <stdio.h>
int main() {
int p1, p2, p3, p4;
scanf("%d %d %d %d", &p1, &p2, &p3, &p4);
int weeks = 0; // Counter variable for weeks with at least 10 problems
solved if (p1 >= 10)
weeks++; // Check if week 1 meets the target
if (p2 >= 10)
weeks++; // Check if week 2 meets the target
if (p3 >= 10)
weeks++; // Check if week 3 meets the
target if (p4 >= 10)
weeks++; // Check if week 4 meets the target
printf("%d\n", weeks);
return 0;
}
3. Code Chef recently revamped its practice page to make it easier for users to
identify the next problems they should solve by introducing some new
features:Recent Contest Problems - contains only problems from the last 2
contests Separate Un- Attempted, Attempted, and All tabs
Problem Difficulty Rating - the Recommended dropdown menu has various
difficulty ranges so that you can attempt the problems most suited to your
experience Popular Topics and Tags
Like most users, Chef didn’t know that he could add problems to a personal to-do
list by clicking on the magic '+' symbol on the top-right of each problem page. But
once he found out about it, he went crazy and added loads of problems to his to-do
list without looking at their difficulty rating.
Chef is a beginner and should ideally try and solve only problems with difficulty
rating strictly less than
1000. Given a list of difficulty ratings for problems in the Chef’s to-do list, please
help him identify how many of those problems Chef should remove from his to-do
list, so that he is only left with problems of difficulty rating less than 1000
https://www.codechef.com/problems/TODOLIST?tab=statement
Code:
int main(void) {

int T,N,i,DRi,j,C;
scanf("%d",&T); for(i=0;i<T;i+
+)
{
scanf("%d",&N);
C=0;
for(j=0;j<N;j++)
{
scanf("%d",&DRi);
if (DRi>=1000)
C++;
}
printf("%d\n",C);
}

return 0;
}
Post-lab:
1. You are given an array prices where prices[i] is the price of a given stock on the ith
day.
You want to maximize your profit by choosing a single day to buy one stock and
choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot
achieve any profit, return 0.
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/
Code:

#include <stdio.h>
int maxProfit(int* prices, int pricesSize) {
int minPrice = prices[0];
int maxProfit = 0;
for (int i = 1; i<pricesSize; i++)
{ if (prices[i] <minPrice) {
minPrice = prices[i];
} else if (prices[i] - minPrice>maxProfit)
{ maxProfit = prices[i] - minPrice;
}
}
return maxProfit;
}

int main() {
int prices[] = {7, 1, 5, 3, 6, 4};
int pricesSize = sizeof(prices) / sizeof(prices[0]);
int result = maxProfit(prices, pricesSize);
printf("The maximum profit is: %d\n", result);
return 0;
}
2. Given a non-empty array of integers nums, every element appears twice except
for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only
constant extra space.
https://leetcode.com/problems/single-number/description/
Code:
#include <stdio.h>
int singleNumber(int* nums, int numsSize) {
int result = 0;
for (int i = 0; i<numsSize; i++)
{ result ^= nums[i];
}
return result;
}
int main() {
int nums[] = {2, 2, 1};
int numsSize = sizeof(nums) / sizeof(nums[0]);
int result = singleNumber(nums, numsSize);
printf("The single element is: %d\n", result);
return 0;
}

3. Given an array nums of size n, return the majority element.


The majority element is the element that appears more than ⌊n / 2⌋ times. You may
assume that the majority element always exists in the array.
https://leetcode.com/problems/majority-element/description/
Code:
int majorityElement(int* nums, int numsSize) {
int candidate = nums[0];
int count = 1;
for (int i = 1; i<numsSize; i++)
{ if (nums[i] == candidate) {
count++;
} else {
count--;
if (count == 0)
{
candidate = nums[i];
count = 1;
}
}
}
return candidate;
}
Skilll:
1. You are asked to calculate factorials of some small positive integers. Inputn
integer t,1<=t<=100, denoting the number of testcases, followed by t lines, each
containing a single integer n, 1<=n<=100.
Output
For each integer n given at input, display a line with the value
of https://www.codechef.com/problems/FCTRL2?
tab=statement Code:
#include<stdio.h>
int main()
{
int t,n,a[200],i,j,k,l,m;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
m=1;
a[0]=1;
for(j=2;j<=n;j++)
{
l=0;
for(k=0;k<m;k++)
{
a[k]=a[k]*j+l;
l=a[k]/10; a[k]=a[k]
%10;
}
while(l)
{
a[k]=l%10; k+
+;
m++;
l=l/10;
}
}
for(i=m-1;i>=0;i--)
printf("%d",a[i]);

printf("\n");
}
return 0;
}
2. The game of billiards involves two players knocking 3 balls around on a green
baize table. Well, there is more to it, but for our purposes this is sufficient.
The game consists of several rounds and in each round both players obtain a score,
based on how well they played. Once all the rounds have been played, the total score
of each player is determined by adding up the scores in all the rounds and the player
with the higher total score is declared the winner.
The Siruseri Sports Club organises an annual billiards game where the top two
players of Siruseri play against each other. The Manager of Siruseri Sports Club
decided to add his own twist to the game by changing the rules for determining the
winner. In his version, at the end of each round, the cumulative score for each player
is calculated, and the leader and her current lead are found. Once all the rounds are
over the player who had the maximum lead at the end of any round in the game is
declared the winner.
https://www.codechef.com/problems/TLG?tab=statement
Code:
#include <stdio.h>
int main(void) {
int n,i;
scanf("%d",&n);
int a[n],b[n],lead[n],win[n];
for(i=0;i<n;i++)
{
scanf("%d%d",&a[i],&b[i]);
}
int sum1=0,sum2=0;
for(i=0;i<n;i++)
{
sum1+=a[i];
sum2+=b[i];
if(sum1>sum2)
{
lead[i]=sum1-sum2;
win[i]=1;
}
else{
lead[i]=sum2-sum1;
win[i]=2;
}
}
int w=0,l=0;
for(i=0;i<n;i++){
if(l<=lead[i])
{
l=lead[i];
w=win[i];
}
}
printf("%d %d",w,l);

return 0;
}
3. Vasya likes the number 239. Therefore, he considers a number pretty if its last
digit 2, 3 or 9.
Vasya wants to watch the numbers between L and R (both inclusive), so he asked you to
determine how many pretty numbers are in this range. Can you help him?
https://www.codechef.com/problems/NUM239
Code:
#include <stdio.h>
int main(void) {
int t;
scanf("%d", &t);
while(t > 0) {
if(t >= 1 && t <= 100)
{
int l, r, c = 0;
scanf("%d %d", &l, &r);
if(l >= 1 && l <= r && r <= (pow(10, 5)))
{
for(int i = l; i <= r; i++)
{
if(i%10==2 || i%10==3 || i%10==9)
c++;
}
printf("%d\n", c);
}
}
t--;
}
return 0;
}
4. You are participating in a contest which has 11 problems (numbered 1 through
11). The first eight problems (i.e. problems 1,2,…,8)are scorable, while the last
three problems (9,10 and 11) are non- scorable ― this means that any submissions
you make on any of these problems do not affect your total score.
Your total score is the sum of your best scores for all scorable problems. That is, for
each scorable problem, you look at the scores of all submissions you made on that
problem and take the maximum of these scores (or 0 if you didn't make any
submissions on that problem); the total score is the sum of the maximum scores you
took.You know the results of all submissions you made. Calculate your total score.
https://www.codechef.com/problems/WATSCORE?tab=statement
Code:
#include <stdio.h>
int main(void) {
int t;
scanf("%d",&t);
while(t--){
int n;
scanf("%d",&n);
int p[n],s[n];
for(int i=0;i<n;i++){
scanf("%d %d",&p[i],&s[i]);
}
for(int i=0;i<n;i++){
if(p[i]>8){
s[i]=0;
}
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(p[i]==p[j]&&i!=j&&s[i]!=0&&s[j]!=0){
if(s[i]>=s[j]){
s[j]=0;
}
}
}
}
int sum=0;
for(int i=0;i<n;i++){
sum=sum+s[i];
}
printf("%d\n",sum);
}
return 0;
}
5. Solve the problem in HackerRank platform
https://www.hackerrank.com/challenges/arrays-ds/problem
Code:
#include<assert.h>
#include<ctype.h>
#include<limits.h>
#include<math.h>
#include<stdbool.h>
#include<stddef.h>
#include<stdint.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char* readline();
char* ltrim(char*);
char* rtrim(char*);
char** split_string(char*);
intparse_int(char*);

/*
* Complete the 'reverseArray' function below.
*
* The function is expected to return an INTEGER_ARRAY.
* The function accepts INTEGER_ARRAY a as parameter.
*/
/*
* To return the integer array from the function, you should:
* - Store the size of the array to be returned in the result_count variable
* - Allocate the array statically or dynamically
*
* For example,
* int* return_integer_array_using_static_allocation(int* result_count) {
* *result_count = 5;
*
* static int a[5] = {1, 2, 3, 4, 5};
*
* return a;
*}
*
* int* return_integer_array_using_dynamic_allocation(int* result_count) {
* *result_count = 5;
* int *a = malloc(5 * sizeof(int));
* for (int i = 0; i< 5; i++) {
* *(a + i) = i + 1;
* }
*
* return a;
*}
*
*/
int* reverseArray(inta_count, int* a, int* result_count) {
// Allocate memory for the result array
int* result = (int*)malloc(a_count * sizeof(int));
// Reverse the elements of the input array and store them in the result array
for (inti = 0; i<a_count; i++) {
result[i] = a[a_count - i - 1];
}
*result_count = a_count; // Update the size of the result
array return result;
}

int main()
{
FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");
int arr_count = parse_int(ltrim(rtrim(readline())));
char** arr_temp = split_string(rtrim(readline()));
int* arr = malloc(arr_count * sizeof(int));
for (inti = 0; i<arr_count; i++) {
intarr_item = parse_int(*(arr_temp + i));
*(arr + i) = arr_item;
}
intres_count;
int* res = reverseArray(arr_count, arr, &res_count);
for (inti = 0; i<res_count; i++) {
fprintf(fptr, "%d", *(res +
i)); if (i != res_count - 1) {
fprintf(fptr, " ");
}
}
fprintf(fptr, "\n");
fclose(fptr);
return0;
}
char* readline() {
size_talloc_length = 1024;
size_tdata_length = 0;
char* data = malloc(alloc_length);
while (true) {
char* cursor = data + data_length;
char* line = fgets(cursor, alloc_length - data_length,
stdin); if(!line) {
break;
}
data_length += strlen(cursor);
if (data_length<alloc_length - 1 || data[data_length - 1] == '\n')
{ break;
}
alloc_length<<= 1;
data = realloc(data, alloc_length);
if(!data) {
data = '\0';
break;
}
}
if (data[data_length - 1] == '\n')
{ data[data_length - 1] = '\0';
data = realloc(data, data_length);
if(!data) {
data = '\0';
}
} else {
data = realloc(data, data_length +
1); if(!data) {
data = '\0';
} else {
data[data_length] = '\0';
}
}
return data;
}
char* ltrim(char* str)
{ if(!str) {
return'\0';
}
if(!*str) {
return str;
}
while (*str != '\0'&&isspace(*str)) {
str++;
}
return str;
}
char* rtrim(char* str) {
if(!str) {
return'\0';
}
if(!*str) {
return str;
}
char* end = str + strlen(str) - 1;
while (end >= str &&isspace(*end)) {
end--;
}
*(end + 1) = '\
0'; return str;
}

char** split_string(char* str) {


char** splits = NULL;
char* token = strtok(str, "
"); int spaces = 0;
while (token) {
splits = realloc(splits, sizeof(char*) * ++spaces);
if(!splits) {
return splits;
}
splits[spaces - 1] = token;
token = strtok(NULL, "
");
}
return splits;
}
intparse_int(char* str) {
char* endptr;
int value = strtol(str, &endptr,
10); if (endptr == str || *endptr !=
'\0') { exit(EXIT_FAILURE);
}
return value;
}
6. Solve the problem in HackerRank platform
https://www.hackerrank.com/challenges/array-left-rotation/problem
Code:
#include <assert.h>
#include <ctype.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* readline();
char* ltrim(char*);
char* rtrim(char*);
char** split_string(char*);

int parse_int(char*);
/*
* Complete the 'rotateLeft' function below.
*
* The function is expected to return an INTEGER_ARRAY.
* The function accepts following parameters:
* 1. INTEGER d
* 2. INTEGER_ARRAY arr
*/
/*
* To return the integer array from the function, you should:
* - Store the size of the array to be returned in the result_count variable
* - Allocate the array statically or dynamically
*
* For example,
* int* return_integer_array_using_static_allocation(int* result_count) {
* *result_count = 5;
*
* static int a[5] = {1, 2, 3, 4, 5};
*
* return a;
*}
* int* return_integer_array_using_dynamic_allocation(int* result_count) {
* *result_count = 5;
*
* int *a = malloc(5 * sizeof(int));
*
* for (int i = 0; i < 5; i++) {
* *(a + i) = i + 1;
* }
*
* return a;
*}
*
*/
int* rotateLeft(int d, int arr_count, int* arr, int* result_count) {
// Calculate the effective rotation amount
int rotations = d % arr_count;
// Create a new array to store the rotated elements
int* rotated_arr = malloc(arr_count * sizeof(int));
// Perform the rotation
for (int i = 0; i < arr_count; i++) {
int new_index = (i + rotations) % arr_count;
rotated_arr[i] = arr[new_index];
}
// Set the result count and return the rotated array
*result_count = arr_count;
return
}

int main()
{
FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");
char** first_multiple_input = split_string(rtrim(readline()));
int n = parse_int(*(first_multiple_input + 0));
int d = parse_int(*(first_multiple_input + 1));
char** arr_temp = split_string(rtrim(readline()));
int* arr = malloc(n * sizeof(int));
for (int i = 0; i < n; i++) {
int arr_item = parse_int(*(arr_temp + i));
*(arr + i) = arr_item;
}
int result_count;
int* result = rotateLeft(d, n, arr, &result_count);
for (int i = 0; i < result_count; i++) {
fprintf(fptr, "%d", *(result +
i)); if (i != result_count - 1) {
fprintf(fptr, " ");
}
}
fprintf(fptr, "\n");
fclose(fptr);
return 0;
}
char* readline() {
size_t alloc_length = 1024;
size_t data_length = 0;
char* data = malloc(alloc_length);
while (true) {
char* cursor = data + data_length;
char* line = fgets(cursor, alloc_length - data_length, stdin);
if (!line) {
break;
}
data_length += strlen(cursor);
if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') {
break;
}
alloc_length <<= 1;
data = realloc(data, alloc_length);
if (!data) {
data = '\
0'; break;
}
}
if(data[data_length-1]=='\n'){
data[data_length-1]='\0';
data=realloc(data,data_length);
if(!data){
data='\0';
}
}else{ data=realloc(data,data_lengt
h+1); if(!data){
data='\0';
}else{ data[data_length
]='\0';
}
}
returndata;
}
char*ltrim(char*str){
if(!str){
return'\0';
}
if(!*str){
returnstr;
}
while(*str!='\0'&&isspace(*str)){
str++;
}
returnstr;
}
char*rtrim(char*str){
if(!str){
return'\0';
}

if(!*str){
returnstr;
}
char*end=str+strlen(str)-1;
while(end>=str&&isspace(*end)){
end--;
}
*(end+1)='\0';
returnstr;
}
char**split_string(char*str){
char**splits=NULL;
char*token=strtok(str,"");
intspaces=0;
while(token){
splits=realloc(splits,sizeof(char*)*++spaces);
if(!splits){
returnsplits;
}
splits[spaces-1]=token;
token=strtok(NULL,"");
}
returnsplits;
}
intparse_int(char*str){
char*endptr;
intvalue=strtol(str,&endptr,10);
if(endptr==str||*endptr!='\0'){
exit(EXIT_FAILURE);
}
returnvalue;
}

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int N;
int d;
scanf("%d %d", &N, &d);
int A[N];
for (int i = 0; i < N; i++)
{
scanf("%d", &A[i]);
}
for (int i = 0; i < N; i++)
{
printf("%d ", A[(i + d) % N]);
}
puts("");
return 0;
}
7. Solve "Constructing a Number" problem in HackerRank.
https://www.hackerrank.com/challenges/constructing-a-number/problem
Code:
#include <assert.h>
#include <ctype.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* readline();
char* ltrim(char*);
char* rtrim(char*);
char** split_string(char*);
int parse_int(char*);

/*
* Complete the 'canConstruct' function below.
*
* The function is expected to return a STRING.
* The function accepts INTEGER_ARRAY a as parameter.
*/

/*
* To return the string from the function, you should either do static allocation or
dynamic a llocation
*
* For example,
* char* return_string_using_static_allocation() {
* static char s[] = "static allocation of string";
*
* return s;
*}
*
* char* return_string_using_dynamic_allocation() {
* char* s = malloc(100 * sizeof(char));
*
* s = "dynamic allocation of string";
*
* return s;
*}
*
*/
char* canConstruct(int a_count, int* a) {
long int sum = 0;
for (int i = 0; i < a_count; i++) {
sum += a[i];
}
if (sum % 3 == 0) {
return "Yes";
} else {
return "No";
}
// Return "Yes" or "No" denoting whether you can construct the required number.
}

int main()
{
FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");
int t = parse_int(ltrim(rtrim(readline())));
for (int t_itr = 0; t_itr < t; t_itr++) {
int n = parse_int(ltrim(rtrim(readline())));
char** a_temp = split_string(rtrim(readline()));
int* a = malloc(n * sizeof(int));
for (int i = 0; i < n; i++) {
int a_item = parse_int(*(a_temp + i));
*(a + i) = a_item;
}
char* result = canConstruct(n,
a); fprintf(fptr, "%s\n", result);
}
fclose(fptr);
return 0;
}
char* readline() {
size_t alloc_length = 1024;
size_t data_length = 0;
char* data = malloc(alloc_length);
while (true) {
char* cursor = data + data_length;
char* line = fgets(cursor, alloc_length - data_length, stdin);
if (!line) {
break;
}
data_length += strlen(cursor);
if (data_length < alloc_length - 1 || data[data_length - 1] == '\n')
{ break;
}
alloc_length <<= 1;
data = realloc(data, alloc_length);
if (!data) {
data = '\
0'; break;
}
}
if (data[data_length - 1] == '\n')
{ data[data_length - 1] = '\0';
data = realloc(data, data_length);
if (!data) {
data = '\0';
}
} else {
data = realloc(data, data_length + 1);
if (!data) {
data = '\0';
} else {
data[data_length] = '\0';
}
}
return data;
}
char* ltrim(char* str)
{ if (!str) {
return '\0';
}
if (!*str) {
return str;
}
while (*str != '\0' && isspace(*str))
{ str++;
}
return str;
}
char* rtrim(char* str)
{ if (!str) {
return '\0';
}
if (!*str) {
return str;
}
char* end = str + strlen(str) - 1;
while (end >= str && isspace(*end))
{ end--;
}
*(end + 1) = '\
0'; return str;
}
char** split_string(char* str) {
char** splits = NULL;
char* token = strtok(str, "
"); int spaces = 0;
while (token) {
splits = realloc(splits, sizeof(char*) * ++spaces);
if (!splits) {
return splits;
}
splits[spaces - 1] = token;
token = strtok(NULL, "
");
}
return splits;
}
int parse_int(char* str) {
char* endptr;
int value = strtol(str, &endptr, 10);
if (endptr == str || *endptr != '\0')
{ exit(EXIT_FAILURE);
}
return value;
}
Week-7
Prelab:
1. What are bitwise operators in C? Name some commonly used bitwise operators.
Ans:
Bitwise operators are characters that represent actions (bitwise operations) to be performed on single
bits. They operate at the binary level and perform operations on bit patterns that involve the
manipulation of individual bits.
Operator Meaning Example
& Bitwise AND operator (P&Q)=12, which is 0000 1100
~ Bitwise Ones complement (~P)=~(60), which is,. 1100
0011 operator
^ Bitwise XOR operator (P|Q)=61, which is. 0011 1101
>> Shift operator (Right) p>>2=15 which is, 0000 1111
<< Shift operator (Left) P<<2=240 which is, 1111 0000

2. Explain the purpose of the bitwise AND (&) operator. Provide an example demonstrating
its usage.
Ans:
The purpose of the bitwise AND operator is to extract specific bits or perform masking operations.
By using the bitwise AND operator with a bitmask, you can selectively enable or disable certain bits
in a binary representation.
Example:
#include <stdio.h>
int main() {
unsigned int bitmask = 0x0F; // Binary: 00001111
unsigned int value = 0x57; // Binary: 01010111
unsigned int result = value & bitmask;
printf("Result: 0x%X\n", result); // Output: Result: 0x07 (Binary: 00000111)
return 0;
}

3. How does the bitwise OR (|) operator work? Illustrate its usage with an example
Ans:
The bitwise OR (‘|’) operator in C is used to perform a bitwise logical OR operation between two
operands. It compares each corresponding bit of the operands. It compares each corresponding bit of
the operands and sets the result bit to 1 if at least one of the bits is 1. Otherwise, it sets the result bit
is o.
#include <stdio.h>
int main () {
unsigned int bitmask = 0x0F; // Binary: 00001111
unsigned int value = 0x57; // Binary: 01010111
unsigned int result = value | bitmask;
printf ("Result: 0x%X\n", result); // Output: Result: 0x5F (Binary: 01011111)
return 0;
}
4. What is recursion in programming? Explain with an example in C.
Ans:
Recursion is a programming concept where a function calls itself during its execution. In other
words, a recursive function solves a problem by breaking it down into smaller sub problems of the
same nature. It continues to call itself on these smaller sub problems until a base case is reached,
which provides a termination condition to stop the recursion.
Example:
#include <stdio.h>
unsigned int factorial (unsigned int n) {
// Base case: factorial of 0 is 1
if (n == 0) {
return 1;
}
// Recursive case: multiply n by factorial of (n-1)
else {
return n * factorial (n - 1);
}}
int main () {
unsigned int num = 5;
unsigned int result = factorial(num);
printf ("Factorial of %u is %u\n", num, result); // Output: Factorial of 5 is 120
return 0; }

5. How does recursion work? Describe the process of recursion execution in C.


Ans:
Recursion works by breaking down a complex problem into smaller, similar sub problems and
solving them in a recursive manner. The process of recursion execution in C can be described as
follows:
1. A recursive function is called with an initial input or argument.
2. The function checks for a base case, which is a condition that specifies when the recursion
should stop. If the base case is met, the function returns a result.
3. If the base case is not met, the function breaks the problem down into smaller sub problems
and calls itself with a modified input or argument.
4. The function enters a new instance or invocation of itself, known as a recursive call. It
suspends the execution of the current instance and starts executing the new instance.
5. The new instance of the function has its own set of variables and parameters.
6. Steps 2-5 are repeated for the new instance. The function checks the base case, and if it is not
met, it further breaks down the problem and makes another recursive call.
7. This process continues until the base case is met. Each recursive call adds a new frame to the
call stack.
8. Once the base case is reached, the innermost recursive call returns a result.
9. The result is propagated back through the call stack, and each instance of the function returns
its own result.
10. The function instances are unwound from the call stack in a last-in-first-out (LIFO) order.
11. The final result is obtained from the initial function call.
In-Lab
1. Solve the problem in the Hacker Rank platform.
https://www.hackerrank.com/challenges/bitwise-operators-in-c/problem
Code:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
//Complete the following function.
void calculate_the_maximum(int n, int k) {
int maxAnd = 0, maxOr = 0, maxXor = 0;
for (int i = 1; i <= n; i++) {
for (int j = i + 1; j <= n; j++) {
int bitAnd = i & j;
int bitOr = i | j;
int bitXor = i ^ j;
if (bitAnd > maxAnd && bitAnd < k) {
maxAnd = bitAnd;
}
if (bitOr > maxOr && bitOr < k) {
maxOr = bitOr;
}
if (bitXor > maxXor && bitXor < k) {
maxXor = bitXor;
}
}
}
printf("%d\n%d\n%d\n", maxAnd, maxOr, maxXor);
//Write your code here.
}
int main() {
int n, k;
scanf("%d %d", &n, &k);
calculate_the_maximum(n, k);
return 0;
}
2. Given an integer n, return true if it is a power of three. Otherwise, return false. An integer
n is a power of three, if there exists an integer x such that n == 3x.
https://leetcode.com/problems/power-of-three/description/
Code:
bool isPowerOfThree(int n){
if (n <= 0)
return false;
while (n % 3 == 0) {
n /= 3;
}
return n == 1;
}
3. You are climbing a staircase. It takes n steps to reach the top. Each time you can either
climb 1 or 2 steps. In how many distinct ways can you climb to the top?
https://leetcode.com/problems/climbing-stairs/
Code:
int climbStairs(int n){
if (n <= 2)
return n;
int dp[n+1];
dp[0] = 0;
dp[1] = 1;
dp[2] = 2;
for (int i = 3; i <= n; i++) {
dp[i] = dp[i-1] + dp[i-2];
}
return dp[n];
}
Post-lab:
1. Given an integer n, return true if it is a power of four. Otherwise, return false. An integer
n is a power of four, if there exists an integer x such that n == 4x.
https://leetcode.com/problems/power-of-four/description/
Code:
bool isPowerOfFour(int n){
long x = 1;
while(x < n) {
x <<= 2;
};
return n == x;
}

2. You are given an integer N. You need to print N! - the factorial of N. Input The first line of
the input contains a single integer T denoting the number of test cases. The description of T
test cases follows. The first and only line of each test case contains a single integer N.
Output For each test case print a single line containing a single integer N!
https://www.codechef.com/DSCA2019/problems/NSECDS13?tab=statement
Code:
#include <stdio.h>
unsigned long long factorial(int n) {
unsigned long long result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
int main() {
int t;
scanf("%d", &t);
for (int i = 0; i < t; i++) {
int n;
scanf("%d", &n);
unsigned long long fact = factorial(n);
printf("%llu\n", fact);
}
return 0;
}
3. The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci
sequence, such that each number is the sum of the two preceding ones, starting from 0 and
1.
https://leetcode.com/problems/fibonacci-number/
Code:
int fib(int n) {
int f0=0, f1=1;
if(n<2) return n;
for(int i=2;i<=n;i++){
int temp=f1;
f1=f0+f1;
f0=temp;
}
return f1;
}
4. Kristen loves playing with and comparing numbers. She thinks that if she takes two
different positive numbers, the one whose digits sum to a larger number is better than the
other. If the sum of digits is equal for both numbers, then she thinks the smaller number is
better. For example, Kristen thinks that 13 is better than 31 and that12 is better than 11 .
Given an integer,n ,can you find the divisor of n that Kristin will consider to be the best?
https://www.hackerrank.com/challenges/best-divisor/problem
Code:
#include <stdio.h>
int sumOfDigits(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
int getDivisor(int n) {
int Divisor = 1;
int maxSum = 1;
for (int i = 2; i <= n; i++) {
if (n % i == 0) {
int divisorSum = sumOfDigits(i);
if (divisorSum > maxSum) {
maxSum = divisorSum;
Divisor = i;
}
}
}
return Divisor;
}
int main() {
int n;
scanf("%d", &n);
int result = getDivisor(n);
printf("%d\n", result);
return 0;
}
Skill:
1. A perfect number is a positive integer that is equal to the sum of its positive divisors,
excluding the number itself. A divisor of an integer x is an integer that can divide x evenly.
Given an integer n, return true if n is a perfect number, otherwise return false.
https://leetcode.com/problems/perfect-number/description/
Code:
#include <stdio.h>
#include <stdbool.h>
bool checkPerfectNumber (int num) {
if (num <= 1)
return false;
int sum = 1; // Start with 1 since it is always a divisor
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
sum += i;
if (i * i != num) // Avoid counting the square root twice
sum += num / i;
}
}
return sum == num;
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
bool isPerfect = checkPerfectNumber (num);
if (isPerfect)
printf("The number is a perfect number.\n");
else
printf("The number is not a perfect number.\n");
return 0;
}
2. Given an integer num, repeatedly add all its digits until the result has only one digit, and
return it.
https://leetcode.com/problems/add-digits/description/
Code:
int addDigits(int num){
int sum = 0;
while(num > 0 || sum > 9)
{
if(num == 0)
{
num = sum;
sum = 0;
}
sum += num % 10;
num /= 10;
}
return sum;
}

int main()
{
int num = 1234;
printf("%d",digSum(num));
return 0;
}
3. There is a series, where the next term is the sum of pervious three terms. Given the first
three terms of the series, a, b and c and respectively, you have to output the n th term of
the series using recursion.
Recursive method for calculating n’th term is given below.
Input Format:
 The first line contains a single integer, n.
 The next line contains 3 space-separated integers, a, b, and c.
Constraints
 1≤ n ≤ 20
 1≤a,b,c ≤ 100
https://www.hackerrank.com/challenges/recursion-in-c/problem
Code:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
//Complete the following function.

int find_nth_term(int n, int a, int b, int c) {


if (n == 1) {
return a;
} else if (n == 2) {
return b;
} else if (n == 3) {
return c;
} else {
return find_nth_term(n - 1, a, b, c) + find_nth_term(n - 2, a, b, c) + find_nth_term(n - 3, a, b,
c);
}
//Write your code here.
}

int main() {
int n, a, b, c;

scanf("%d %d %d %d", &n, &a, &b, &c);


int ans = find_nth_term(n, a, b, c);

printf("%d",
ans);
return 0;
}
4. Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the
value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
https://leetcode.com/problems/reverse-integer/description/
Code:
#include <stdio.h>
#include <limits.h>

int reverse(int x) {
int reversed = 0;

while (x != 0) {
// Check if reversing x will cause overflow or underflow
if (reversed > INT_MAX / 10 || (reversed == INT_MAX / 10 && x % 10 > 7))
return 0;
if (reversed < INT_MIN / 10 || (reversed == INT_MIN / 10 && x % 10 < -8))
return 0;

reversed = reversed * 10 + x % 10;


x /= 10;
}

return reversed;
}

int main() {
int x;
printf("Enter an integer: ");
scanf("%d", &x);

int reversed = reverse(x);


printf("Reversed integer: %d\n", reversed);

return 0;
}
5. Given an integer array nums, move all 0's to the end of it while maintaining the relative
order of the non-zero elements.
https://leetcode.com/problems/move-zeroes/description/
Code:
void moveZeroes(int* nums, int numsSize){
int j = 0;
bool zero = false;
for (int i = 0; i < numsSize; i++) {
if (nums[i] == 0 && !zero) {
zero = !zero;
j = i;
}
else if (nums[i] != 0 && zero) {
nums[j++] = nums[i];
nums[i] = 0;
}
}
}

6. Write a function that takes the binary representation of an unsigned integer and returns
the number of '1' bits it has (also known as the Hamming weight).
https://leetcode.com/problems/number-of-1-bits/description/
Code:
int hammingWeight(uint32_t n) {
if (n == 0) {
return 0;
}
int count = 0;
while (n) {
if (n & 1) {
count++;
}
n >>= 1;
}
return count;
}
7. Martha is interviewing at Subway. One of the rounds of the interview requires her to cut a
bread of size l X b into smaller identical pieces such that each piece is a square having
maximum possible side length with no leftover piece of bread.
https://www.hackerrank.com/challenges/restaurant/problem

Code:
#include <stdio.h>

int getNumberOfSquares(int l, int b) {


// Find the greatest common divisor using Euclid's algorithm
int gcd = 1;
int smaller = (l < b) ? l : b;
for (int i = 2; i <= smaller; i++) {
if (l % i == 0 && b % i == 0) {
gcd = i;
}
}

// Calculate the number of squares of maximum size


int numSquares = (l * b) / (gcd * gcd);
return numSquares;
}

int main() {
int t;
scanf("%d", &t);

while (t--) {
int l, b;
scanf("%d %d", &l, &b);

int numSquares = getNumberOfSquares(l, b);


printf("%d\n", numSquares);
}

return 0;
}

#include <stdlib.h>
#include <stdio.h>
int gcd(int x, int y) {
if (y == 0)
return x;
return gcd(y, x% y);
}
int main() {
int T;
scanf("%d\n", &T);
for(int i=0; i<T; i++) {
int l, b;
scanf("%d %d\n", &l, &b);
int c = gcd(l, b); printf("%d\
n", l / c * (b / c));
}
return 0;
}

8. Given two-dimensional points in space, determine whether they lie on some vertical or
horizontal line. If yes, print YES; otherwise, print NO.
https://www.hackerrank.com/challenges/points-on-a-line/problem
Code:
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
int x, y;
int x0, y0;
scanf("%d %d", &x0, &y0);
int isHorizontal = 1; // Assume points are on a horizontal line
int isVertical = 1; // Assume points are on a vertical line
for (int i = 1; i < n; i++) {
scanf("%d %d", &x, &y);
if (x != x0) {
isVertical = 0; // At least one point has a different x-coordinate
}
if (y != y0) {
isHorizontal = 0; // At least one point has a different y-coordinate
}
}
if (isHorizontal || isVertical) {
printf("YES\n");
} else {
printf("NO\n");
}

return 0;
}
Predict the O/P:
#include <stdio.h>
void foo(int n) {
if (n > 0) {
printf("%d ", n);
foo(n - 1)
printf("%d ", n);
}
}
int main() {
foo(3);
return 0;
}
1. What is the output of the above program?
a) 3 2 1 1 2 3
b) 3 2 1
c) 1 2 3
d) 1 2 3 3 2 1

#include <stdio.h>
int bar(int n) {
if (n <= 0) {
return 0;
} else {
return n + bar(n - 2);
}
}

int main() {
int result = bar(7);
printf("%d", result);
return 0;
}
2. What is the output of the above program?
a) 20
b) 16
c) 14
d) 12

#include <stdio.h>
void baz(int n) {
if (n > 0) {
baz(n / 2);
printf("%d ", n % 2);
}
}
int main() {
baz(10);
return 0;
}
3. What is the output of the above program?
a) 1 0 1 0
b) 0 1 0 1
c) 0 0 1 0 1
d) 1 1 0 1

#include <stdio.h>
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
int main() {
int result = factorial(5);
printf("%d", result);
return 0;
}
4. What is the output of the above program?
a) 120
b) 24
c) 25
d) 20

#include <stdio.h>
int power(int base, int exponent) {
if (exponent == 0) {
return 1;
} else {
return base * power(base, exponent - 1);
}
}
int main() {
int result = power(2, 4);
printf("%d", result);
return 0;
}
5. What is the output of the above program?
a) 16
b) 8
c) 32
d) 64
Week-8
Prelab:
1. What is the difference between char* and char[] when declaring and working with strings in
C? Ans:
char[] is a character array whereas char* is a pointer reference. char[] is a specific section of
memory in which we can do things like indexing, whereas char* is the pointer that points to the
memory location.

2. Explain the purpose and usage of the strcat() function in C string


handling. Ans:
The strcat() function which defined under the string.h header file in c concatenates two strings and returns
a string in which the two strings are appended. The function takes the source and destination strings as
parameters and returns the destination string where the destination and source strings are appended.
For example, if we pass the strings "I love" and "coding" to the strcat in c, the strcat function in c
returns "I love coding".
char *strcat(char *dest, const char *src);
3. How can you determine the length of a string without using the strlen()
function? Ans:
To determine the length of a string without using the `strlen()` function, you can implement your
own function or use alternative methods. Here are a few approaches:
1. Manual Iteration: Iterate over the characters in the string until you reach the null character (`'\0'`)
that marks the end of the string. Count the number of iterations to determine the length. Here's an
example implementation:
size_t stringLength(const char* str) {
size_t length = 0;
while (str[length] != '\0') {
length++;
}
return length;
}
2. Pointer Arithmetic: Use pointer arithmetic to iterate through the characters of the string until you
encounter the null character. Calculate the offset between the initial pointer and the null character
pointer to determine the length. Here's an example
size_t stringLength(const char* str) {
const char* ptr = str;
while (*ptr) {
ptr++;
}
return ptr - str;
}
3. For Loop: Iterate over the string using a `for` loop, checking each character until you reach the
null character. Similar to the previous methods, count the iterations to determine the length. Here's
an example:
size_t stringLength(const char* str) {
size_t length;
for (length = 0; str[length] != '\0'; length++) {
// Empty loop body
}
return length;
}
4.Array Indexing: Utilize array indexing to access each character of the string and increment a
counter until the null character is encountered. This approach is similar to the manual iteration
method but uses an index variable instead of a pointer. Here's an example:
```c
size_t stringLength(const char* str) {
size_t length = 0;
while (str[length]) {
length++;
}
return length;
}
These alternative methods essentially iterate over the characters of the string until they find the null
character, indicating the end of the string. By counting the number of iterations or calculating the
difference between pointers, you can determine the length of the string. However, keep in mind that
the `strlen()` function is a standard library function optimized for performance and should generally
be preferred unless there are specific constraints or requirements that prevent its use.

4. Discuss the importance of null-terminated strings in C programming and explain why the
null character is necessary.
Ans:
Null-terminated strings are fundamental in C programming and play a crucial role in string
handling. A null-terminated string is a character array where the string data is followed by a
null character (`'\0'`) to mark the end of the string. The null character is necessary for
several reasons:
1. String Length: The null character serves as a sentinel value that indicates the end of the
string. By convention, C functions that operate on strings use the null character as a
termination criterion. Functions like `strlen()` rely on encountering the null character to
determine the length of a string.
2. String Manipulation: C provides a set of string manipulation functions (`strcpy()`,
`strcat()`, etc.) that operate on null-terminated strings. These functions iterate over the
characters until they encounter the null character, enabling them to perform operations
accurately. Without the null character, these functions would have no way to determine
where the string ends.
3. String Printing: When printing strings using functions like `printf()`, the null character
acts as a stopping condition. The `"%s"` format specifier instructs `printf()` to output
characters until it reaches the null character, ensuring that the string is printed correctly.
4. Memory Management: The null character helps with memory management and
allocation. By reserving one extra character space for the null character at the end of a
string, C programmers can determine the exact size needed to store the string and allocate
memory accordingly. It also ensures that functions like `strlen()` and `strncpy()` behave as
expected, avoiding buffer overflows and memory corruption.
5. Compatibility: The null-terminated string convention is widely used and expected in C
programming. Many libraries, APIs, and system functions rely on null-terminated strings.
Adhering to this convention ensures compatibility and seamless integration with existing
code and libraries.
6. String Comparison: String comparison functions like `strcmp()` or `strncmp()` rely on
the presence of the null character to compare strings. These functions iterate over the
characters until they encounter a difference or the null character, allowing for accurate
comparisons.

5. What are the potential risks or errors that can occur when working with strings in C?
How can you avoid or mitigate these issues?
Ans:
1. Buffer Overflow: One of the most significant risks is exceeding the allocated buffer size
while manipulating strings. It can lead to memory corruption and security vulnerabilities like
stack smashing or arbitrary code execution. To avoid this, you can:
- Ensure that you allocate enough memory for the string and any operations you perform on
it.
- Use functions that limit the number of characters written, such as `snprintf()` instead of
`sprintf()`.
- Check the length of input strings before copying or concatenating them.

2. Null Termination: C strings are null-terminated, meaning they end with a null character (`'\
0'`). Failing to properly null-terminate a string can lead to unexpected behavior and memory
access issues. To prevent this, make sure to:
- Allocate sufficient memory to accommodate the null terminator.
- Always set the null terminator explicitly after modifying a string.

3. Uninitialized Pointers: When using pointers to manipulate strings, uninitialized pointers


can cause crashes, memory corruption, or undefined behavior. To mitigate this, initialize
pointers to `NULL` when declaring them and assign valid memory addresses before
performing any operations.

4. Off-by-One Errors: C arrays and strings are zero-indexed, so it's crucial to be mindful of
off-by-one errors. Mistakenly accessing or iterating beyond the array bounds can lead to
undefined behavior or memory access issues. Pay attention to loop conditions, index
calculations, and string length calculations to avoid off-by-one errors.
5. String Manipulation Functions: C provides various string manipulation functions like
`strcpy()`, `strcat()`, and `sprintf()`. However, these functions may not perform bounds
checking and can lead to buffer overflow vulnerabilities. Prefer safer alternatives such as
`strncpy()`, `strncat()`, and `snprintf()`, which allow specifying the maximum number of
characters to copy or concatenate.
6. Memory Leaks: Dynamically allocated memory for strings should be freed when it's no
longer needed. Failing to release allocated memory can result in memory leaks. Ensure that
you appropriately deallocate memory using `free()` to prevent this issue.
7. Inefficient Operations: Some string operations, such as repeated concatenation using
`strcat()`, can be inefficient as they require traversing the entire string each time. Consider
using more efficient data structures like dynamically resizing arrays or linked lists to avoid
performance issues with extensive string manipulations.
8. Encoding and Character Set Issues: C strings are typically represented as ASCII or
character arrays, which may not adequately handle non-ASCII characters or different character
sets. When working with internationalization or handling non-ASCII characters, consider using
wide character strings (`wchar_t`) and the corresponding wide character functions like
`wcscpy()` or `wcslen()`.
In-Lab
1. Louise joined a social networking site to stay in touch with her friends. The signup page
required her to input a name and a password. However, the password must be strong. The
website considers a password to be strong if it satisfies the following criteria:
 Its length is at least 6.
 It contains at least one digit.
 It contains at least one lowercase English character.
 It contains at least one uppercase English character.
 It contains at least one special character. The special characters are: !@#$
%^&*() https://www.hackerrank.com/challenges/strong-password/problem
Code:
#include <stdio.h>
#include <stdbool.h>
bool isDigit(char c) {
return c >= '0' && c <= '9';
}
bool isLowercase(char c) {
return c >= 'a' && c <= 'z';
}
bool isUppercase(char c) {
return c >= 'A' && c <= 'Z';
}
bool isSpecial(char c) {
char specialCharacters[] = "!@#$%^&*()-+";
for (int i = 0; i < sizeof(specialCharacters) - 1; i++) {
if (c == specialCharacters[i]) {
return true;
}
}
return false;
}
int minimumNumber(int n, char* password) {
int missingChars = 0;
bool hasDigit = false;
bool hasLowercase = false;
bool hasUppercase = false;
bool hasSpecial = false;
for (int i = 0; i < n; i++) {
char c = password[i];
if (isDigit(c)) {
hasDigit = true;
} else if (isLowercase(c)) {
hasLowercase = true;
} else if (isUppercase(c)) {
hasUppercase = true;
} else if (isSpecial(c)) {
hasSpecial = true;
}
}
if (!hasDigit) {
missingChars++;
}
if (!hasLowercase) {
missingChars++;
}
if (!hasUppercase) {
missingChars++;
}
if (!hasSpecial) {
missingChars++;
}
if (n + missingChars < 6) {
missingChars += 6 - (n + missingChars);
}
return missingChars;
}

int main() {
int n;
scanf("%d", &n);
char password[101];
scanf("%s", password);
int answer = minimumNumber(n, password);
printf("%d\n", answer);

return 0;
}
2. A space explorer's ship crashed on Mars! They send a series of SOS messages to Earth for
help.

Letters in some of the SOS messages are altered by cosmic radiation during transmission.
Given the signal received by Earth as a string, , determine how many letters of the SOS
message have been changed by radiation.
s = ‘SOSTOT’
Example
The original message was SOSSOS. Two of the message's characters were changed in transit.
Function Description
Complete the marsExploration function in the editor
below. marsExploration has the following parameter(s):
 string s: the string as received on
Earth Returns
 int: the number of letters changed during transmission
https://www.hackerrank.com/challenges/mars-exploration/proble
m Code:
#include <assert.h>
#include <ctype.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* readline();

/*
* Complete the 'marsExploration' function below.
*
* The function is expected to return an INTEGER.
* The function accepts STRING s as parameter.
*/

int marsExploration(char* s) {
int count = 0;
int i = 0;
while (s[i] != '\0') {
if (s[i] != 'S') {
count++;
}
i++;
if (s[i] != 'O') {
count++;
}
i++;
if (s[i] != 'S') {
count++;
}
i++;
}
return count;
}
int main()
{
FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");
char* s = readline();
int result = marsExploration(s);
fprintf(fptr, "%d\n", result);
fclose(fptr);
return 0;
}
char* readline() {
size_t alloc_length = 1024;
size_t data_length = 0;
char* data = malloc(alloc_length);
while (true) {
char* cursor = data + data_length;
char* line = fgets(cursor, alloc_length - data_length, stdin);
if (!line) {
break;
}
data_length += strlen(cursor);
if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') {
break;
}
alloc_length <<= 1;
data = realloc(data, alloc_length);
if (!data) {
data = '\0';
break;
}
}
if (data[data_length - 1] == '\n') {
data[data_length - 1] = '\0';
data = realloc(data, data_length);
if (!data) {
data = '\0';
}
} else {
data = realloc(data, data_length + 1);
if (!data) {
data = '\0';
} else {
data[data_length] = '\0';
}
}
return data;
}
3. Chef has a string S with him. Chef is happy if the string contains a contiguous substring of
length strictly greater than 2 in which all its characters are vowels.
Determine whether Chef is happy or not.
Note that, in english alphabet, vowels are a, e, i, o, and u.
https://www.codechef.com/problems/HAPPYSTR?tab=statement
Code:

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
bool isVowel(char c) {
// Function to check if a character is a vowel
return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
}
bool isHappyString(char* s) {
int length = strlen(s);
for (int i = 0; i < length - 2; i++) {
if (isVowel(s[i]) && isVowel(s[i+1]) && isVowel(s[i+2])) {
return true; // Found a happy substring
}
}
return false; // No happy substring found
}

int main() {
int T;
scanf("%d", &T); // Read the number of test cases
while (T--) {
char s[1001];
scanf("%s", s); // Read the string
if (isHappyString(s)) {
printf("HAPPY\n");
} else {
printf("SAD\n");
}
}
return 0;
}
Post-lab:
1. Given two strings needle and haystack, return the index of the first occurrence of
needle in haystack, or -1 if needle is not part of haystack.
https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/description/
Code:
#include <stdio.h>
#include <string.h>
// Function to build the prefix table for the KMP algorithm
void buildPrefixTable(char* needle, int* prefixTable) {
int m =
strlen(needle); int
length = 0;
int i = 1;
prefixTable[0]
= 0; while (i <
m) {
if (needle[i] ==
needle[length]) { length++;
prefixTable[i] =
length; i++;
} else {
if (length != 0) {
length = prefixTable[length - 1];
} else {
prefixTable[i]
= 0; i++;
}
}
}
}
// Function to perform string matching using the KMP algorithm
int strStr(char* haystack, char* needle) {
int n = strlen(haystack);
int m = strlen(needle);

if (m == 0) {
return 0; // Empty needle, needle is part of haystack at index 0
}
int prefixTable[m];
buildPrefixTable(needle, prefixTable);
int i = 0; // Index for haystack
int j = 0; // Index for needle
while (i < n) {
if (haystack[i] == needle[j]) {
i++;
j++;
}
if (j == m) {
return i - j; // Found a match, return the starting index of the match
} else if (i < n && haystack[i] != needle[j]) {
if (j != 0) {
j = prefixTable[j - 1];
} else {
i++;
}
}
}

return -1; // No match found


}
int main() {
char haystack[10001];
char needle[10001];
printf("Enter haystack: ");
scanf("%s", haystack);
printf("Enter needle: ");
scanf("%s", needle);
int result = strStr(haystack, needle);
printf("Index of the first occurrence of needle in haystack: %d\n", result);
return 0;
}
2. Given a string s consisting of words and spaces, return the length of the last word in the
string. A word is a maximal substring consisting of non-space characters only.
https://leetcode.com/problems/length-of-last-word/description/
Code:
#include <stdio.h>
#include <string.h>
int lengthOfLastWord(char* s) {
int len = strlen(s);
int length = 0;
int i = len - 1;
// Skip trailing spaces
while (i >= 0 && s[i] == ' ') {
i--;
}
// Count the characters of the last word
while (i >= 0 && s[i] != ' ') {
length++;
i--;
}
return length;
}
int main() {
char s[10001];
printf("Enter the string: ");
fgets(s, sizeof(s), stdin);
s[strcspn(s, "\n")] = '\0'; // Remove the newline character
int result = lengthOfLastWord(s);
printf("Length of the last word: %d\n", result);
return 0;
}
3. Given a string s, reverse only all the vowels in the string and return it.
The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases,
more than once.
https://leetcode.com/problems/reverse-vowels-of-a-string/description/
Code:
#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
#include <string.h>

void swap(char* a, char* b) {


char temp = *a;
*a = *b;
*b = temp;
}

char* reverseVowels(char* s) {
int left = 0;
int right = strlen(s) - 1;
while (left < right) {
while (left < right && !strchr("aeiouAEIOU", s[left]))
left++;
while (left < right && !strchr("aeiouAEIOU", s[right]))
right--;
if (left < right) {
swap(&s[left], &s[right]);
left++;
right--;
}
}
return s;
}

int main() {
char s[300001];
printf("Enter the string: ");
fgets(s, sizeof(s), stdin);
s[strcspn(s, "\n")] = '\0'; // Remove the newline character
char* result = reverseVowels(s);
printf("Reversed vowels: %s\n", result);
return 0;
}
4. You have been given a String S. You need to find and print whether this string is
a palindrome or not. If yes, print "YES" (without quotes), else print "NO"
(without quotes).
https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-
output/practice-problems/algorithm/palindrome-check-2/
Code:
#include <stdio.h>
int main(){
char ch[1000];
scanf("%s",ch);
int l=strlen(ch);
(ch[0]==ch[l-1])?printf("YES"):printf("NO");

}
Skill:
1. Not everyone probably knows that Chef has younger brother Jeff. Currently Jeff learns to
read. He knows some subset of the letter of Latin alphabet. In order to help Jeff to study,
Chef gave him a book with the text consisting of N words. Jeff can read a word iff it
consists only of the letters he knows. Now Chef is curious about which words his brother
will be able to read, and which are not. Please help him!
Input
 The first line of the input contains a lowercase Latin letter string S, consisting of the
letters Jeff can read. Every letter will appear in S no more than once. The second line of
the input contains an integer N denoting the number of words in the book. Each of the
following N lines contains a single lowercase Latin letter string Wi, denoting the ith word
in the book.
Output
 For each of the words, output "Yes" (without quotes) in case Jeff can read it, and
"No" (without quotes) otherwise.
Constraints
 1 ≤ |S| ≤ 26
 1 ≤ N ≤ 1000
 1 ≤ |Wi| ≤ 12
 Each letter will appear in S no more than once.
 S, Wi consist only of lowercase Latin letters.
Link:https://www.codechef.com/problems/ALPHABET
Code:
#include <stdio.h>
#include <string.h>
int main() {
char jeffLetters[27];
scanf("%s", jeffLetters);

int n;
scanf("%d", &n);

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


char word[13];
scanf("%s", word);

int canRead = 1;
for (int j = 0; j < strlen(word); j++) {
int letterFound = 0;
for (int k = 0; k < strlen(jeffLetters); k++) {
if (word[j] == jeffLetters[k]) {
letterFound = 1;
break;
}
}

if (!letterFound) {
canRead = 0;
break;
}
}

printf("%s\n", canRead ? "Yes" : "No");


}

return 0;
}
2. Timur loves codeforces. That's why he has a string s having length 10 made containing only
lowercase Latin letters. Timur wants to know how many indices string s differs from the
string "codeforces". For example string s= "coolforsez" differs from "codeforces" in 4 indices, shown
in bold.
https://codeforces.com/problemset/problem/1829/A
Code:
#include<stdio.h>
#include<string.h>
int countDifferences(char*s){
char target[]="codeforces";
int differences =0;
for(int i =0; i <10; i++){
if(s[i]!= target[i]){
differences++;
}
}
return differences;
}

int main(){
int t;
scanf("%d",&t);
while(t--){
char s[11];
scanf("%s", s);
int differences = countDifferences(s);
printf("%d\n", differences);
}
return0;
}
3. An input string S of length N is transferred through the network using a special protocol.
The protocol can send the string through a series of operations. In one operation, we can
choose a lower case english alphabet C and do one of the following:
Transfer 1 copy of C through the network.
Transfer 2 copies of C through the network.
Each of the above transfers take 1 unit of
time.
Find the minimum time in which we can transfer the entire string S through the network.
https://www.codechef.com/problems/STRP?tab=statement
Code:

#include <stdio.h>
#include <string.h>
int minTimeToTransferString(char* s, int length) {
int operations = 0;
for (int i = 0; i < length; i++) {
int count = 1; // Number of copies of current character to transfer
// Check if the current character is the same as the next character
while (i + 1 < length && s[i] == s[i + 1]) {
count++;
i++;
}
operations += (count + 1) / 2; // Add the minimum number of operations for the current
character
}

return operations;
}
int main() {
int T;
scanf("%d", &T); // Read the number of test cases

while (T--) {
int N;
scanf("%d", &N); // Read the length of the string

char S[100001];
scanf("%s", S); // Read the string

int result = minTimeToTransferString(S, N);


printf("%d\n", result);
}

return 0;
}
4. Given two strings s and t, return true if t is an anagram of s, and false otherwise.
An Anagram is a word or phrase formed by rearranging the letters of a different word
or phrase, typically using all the original letters exactly once.
https://leetcode.com/problems/valid-anagram/
Code:
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
bool isAnagram(char* s, char* t) {
int count[26] = {0};
int len_s = strlen(s);
int len_t = strlen(t);
if (len_s != len_t) {
return false;
}
for (int i = 0; i < len_s; i++) {
count[s[i] - 'a']++;
}
for (int i = 0; i < len_t; i++) {
count[t[i] - 'a']--;
}
for (int i = 0; i < 26; i++) {
if (count[i] != 0) {
return false;
}
}
return true;
}
int main() {
char s[50001];
char t[50001];

printf("Enter string s: ");


scanf("%s", s);

printf("Enter string t: ");


scanf("%s", t);

if (isAnagram(s, t)) {
printf("true\n");
} else {
printf("false\n");
}
return 0;}
5. Given a string s, find the first non-repeating character in it and return its index. If it
does not exist, return -1.
https://leetcode.com/problems/first-unique-character-in-a-string/
Code:
#include <stdio.h>
#include <string.h>
int firstUniqChar(char* s) {
int count[26] = {0}; // Array to store the frequency of characters
int length = strlen(s);
// Calculate the frequency of characters
for (int i = 0; i < length; i++) {
count[s[i] - 'a']++;
}
// Find the first character with a frequency of 1
for (int i = 0; i < length; i++) {
if (count[s[i] - 'a'] == 1) {
return i;
}
}
return -1; // No non-repeating character found
}
int main() {
char s[100001];
printf("Enter string s: ");
scanf("%s", s);
int result = firstUniqChar(s);
printf("Index of the first non-repeating character: %d\n", result);
return 0;
}
6. There is a robot starting at the position (0, 0), the origin, on a 2D plane. Given a sequence of
its moves, judge if this robot ends up at (0, 0) after it completes its moves.
You are given a string moves that represents the move sequence of the robot where
moves[i] represents its ith move. Valid moves are 'R' (right), 'L' (left), 'U' (up), and 'D'
(down).
Return true if the robot returns to the origin after it finishes all of its moves, or false otherwise.
Note: The way that the robot is "facing" is irrelevant. 'R' will always make the robot move to
the right once, 'L' will always make it move left, etc. Also, assume that the magnitude of the
robot's movement is the same for each move.
X
Code:
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
bool judgeCircle(char* moves) {
int x = 0; // Horizontal displacement
int y = 0; // Vertical displacement
int length = strlen(moves);
// Calculate the displacements
for (int i = 0; i < length; i++) {
switch (moves[i]) {
case 'R':
x++;
break;
case 'L':
x--;
break;
case 'U':
y++;
break;
case 'D':
y--;
break;
}
}
// Check if the robot returns to the origin
if (x == 0 && y == 0) {
return true;
} else {
return false;
}
}
int main() {
char moves[20001];
printf("Enter the move sequence: ");
scanf("%s", moves);
if (judgeCircle(moves)) {
printf("The robot returns to the origin.\n");
} else {
printf("The robot does not return to the origin.\n");
}

return 0;
}

7. Solve the problem in the hacker Rank platform.


https://www.hackerrank.com/challenges/funny-string/problem
Code:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {
int T, N, funny, i, r;
char S[10001];

scanf("%d\n", &T);
while (T--) {
scanf("%s\n", S);
N = strlen(S);
funny = 1;
for(i=1, r=N-2; i<N; i++, r--) {
if (fabs(S[i]-S[i-1]) != fabs(S[r]-S[r+1])) {
funny = 0;
break;
}
}
if(funny==1)
printf("Funny\n");
else
printf("Not Funny\n");
}
return 0;
}
8. Chandu is a bad student. Once his teacher asked him to print the reverse of a given
string. He took three hours to solve it. The teacher got agitated at Chandu and asked you
the same question. Can you solve it?
https://www.hackerearth.com/practice/algorithms/string-algorithm/basics-of-string-
manipulation/practice-problems/algorithm/terrible-chandu/
Code:
#include <stdio.h>
#include <string.h>
int main()
{
int t,n,i ;
char ch[30] ;
scanf("%d",&t) ;
while(t--)
{
scanf("%s",ch);
n=strlen(ch) ;
for(i=n-1;i>=0;i--)
printf("%c",ch[i]);
printf("\n");
}
return 0;
}
9. There is a string s of lowercase English letters that is repeated infinitely many times. Given
an integer n find and print the number of letter a's in the first n letters of the infinite string.
https://www.hackerrank.com/challenges/repeated-string/problem
Code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char s[1000];
long n, i, strLength, count = 0;
//printf("Enter a string");
scanf("%s",s);
scanf("%ld",&n);
strLength = strlen(s);
for (i = 0; i < strLength; i++) {
if (s[i] == 'a') {
++count;
}
}
long repeatedTimes = n / strLength;
long stringLeftLength = n - (strLength * repeatedTimes);
long extra = 0;
for (long i = 0; i < stringLeftLength; i++) {
if (s[i] == 'a') {
++extra;
}
}
long totalCount = (repeatedTimes * count) + extra;
printf("%ld",totalCount);
return 0;
}
Week-9
Prelab:
1. Can linear search be used on both sorted and unsorted arrays? Explain why or why not.
Ans:
In linear search, we iterate through each element of the array and compare it with the target
element we are searching for. If a match is found, we return the index of the element
1. Unsorted Arrays:
Linear search can be used on unsorted arrays because there is no specific order
orarrangement of elements. Since there is no predefined order, we must check each element of
thearray until we find amatch or reach the end of the array. This makes linear search a suitable
choice for unsorted arrays.
2. Sorted Arrays:
Linear search can also be used on sorted arrays, but it may not be the most efficient
approach. The advantage of using linear search on a sorted array is that if the target element is
found early in the array, the search can be terminated. However, the worst-case time complexity
of linear search is O(n), where n is the size of the array. In contrast, if the array is sorted, other
search algorithms like binary search can provide a more efficient search with a time complexity
of O(log n).
In summary, linear search can be used on both sorted and unsorted arrays, but for sorted
arrays, other search algorithms like binary search are generally preferred due to their more
efficient time complexity.
2. How would you handle the case where the array is not sorted when using binary
search? Ans:
When using binary search, the array must be sorted in order for the algorithm to work
correctly. If the array is not sorted, binary search cannot be directly applied. However, there are
a couple of options to handle this situation:
1. Sort the Array:
The first option is to sort the array before performing the binary search. You can use a
sorting algorithm such as quicksort, mergesort, or heapsort to sort the array in ascending order.
Once the array is sorted, you can then apply the binary search algorithm to find the desired
element efficiently.
2. Choose a Different Search Algorithm:
If sorting the array is not desirable or feasible, you can choose a different search algorithm
that is suitable for unsorted arrays, such as linear search. Linear search can be used on both
sorted and unsorted arrays, as discussed earlier. Although linear search has a higher time
complexity of O(n) compared to binary search, it can still find the desired element in an
unsorted array.
It is important to consider the requirements of your specific problem and the characteristics
of the array (sorted or unsorted) when selecting the appropriate search algorithm.
3. In what scenarios is binary search most
effective? Ans:
Binary search is most effective in scenarios where the following conditions are met:
1. Sorted Data: Binary search works on sorted data. It is specifically designed to search
efficiently in a sorted collection of elements, whether it's an array, a list, or any other data
structure. If the data is not sorted, binary search cannot be applied.
2. Random Access: Binary search requires random access to the elements of the collection.
This means that the elements can be accessed directly by their index or position. In array-based
implementations, random access is usually available, but in other data structures like linked
lists, binary search may not be practical due to the lack of random access.
3. Large Data Sets: Binary search becomes increasingly efficient as the size of the data set
grows. The time complexity of binary search is logarithmic (O(log n)), which means it can
handle large data sets much more efficiently compared to linear search algorithms (O(n)).
4. High Retrieval Frequency: Binary search is particularly useful when the same search
needs to be performed multiple times on the same sorted data set. Since binary search reduces
the search space by half with each comparison, it quickly converges to the desired element,
making subsequent searches faster.
5. Resource Constraints: Binary search can be advantageous in scenarios where there are
resource constraints, such as limited memory or processing power. It requires fewer
comparisons compared to linear search algorithms, resulting in reduced time and computational
requirements.
It's worth noting that binary search is not suitable for scenarios where the data is frequently
updated or modified, as maintaining the sorted order after each modification can be costly.
Additionally, binary search may not be the best choice if the data set is small or the search is
performed infrequently, as the overhead of implementing binary search may outweigh its
benefits in such cases.

4. Can bubble sort be used on both small and large arrays? Explain why or why
not. Ans:
Bubble sort can be used on both small and large arrays, but its efficiency and suitability vary
depending on the size of the array.
Bubble sort is a simple comparison-based sorting algorithm that repeatedly swaps adjacent
elements if they are in the wrong order until the entire array is sorted. It has a time complexity
of O(n^2), where 'n' is the number of elements in the array. This means that the time taken to
sort the array grows quadratically with the number of elements.
For small arrays (with a relatively small number of elements), bubble sort can be a viable
option. The overhead of implementing and maintaining more complex sorting algorithms might
outweigh the benefits, especially if the array is already partially sorted or nearly sorted. Bubble
sort's simplicity and ease of implementation make it suitable for small arrays where efficiency
is not a critical factor.
However, as the size of the array grows larger, bubble sort becomes increasingly
inefficient. With a time complexity of O(n^2), bubble sort performs poorly compared to more
efficient sorting algorithms like quicksort, mergesort, or heapsort, which have average time
complexities of O(n log n). For large arrays, bubble sort's quadratic time complexity can result
in significantly longer execution times, making it impractical and inefficient.
Therefore, while bubble sort can technically be used on both small and large arrays, it is
generally not recommended for large arrays or situations where efficiency is crucial. Other
sorting algorithms are better suited for larger data sets, as they offer faster and more efficient
sorting performance.

5. How would you optimize bubblesort to reduce the number of comparisons and
swaps? Ans:
1. Flagging: The flagging technique involves introducing a variable to keep track of whether any
swaps occurred during a pass of the array. If no swaps occur during a pass, it means the array is already
sorted, and the algorithm can terminate early. This avoids unnecessary iterations when the array is
already in its sorted state.
Here's an example of an optimized bubble sort implementation with flagging:
function optimizedBubbleSort(array):
n = length(array)
swapped = true
while swapped:
swapped = false
for i from 0 to n-2:
if array[i] > array[i+1]:
swap(array[i], array[i+1])
swapped = true
return array
2. Early Termination: The early termination technique involves stopping the algorithm if no swaps
occur during a pass before reaching the end of the array. Since the largest elements "bubble" towards
the end of the array after each pass, if no swaps occur during a pass, it means the remaining elements
are already in their correct sorted positions.
Here's an example of an optimized bubble sort implementation with early termination:
function optimizedBubbleSort(array):
n = length(array)
for i from 0 to n-1:
swapped = false
for j from 0 to n-1-i:
if array[j] > array[j+1]:
swap(array[j], array[j+1])
swapped = true
if not swapped:
break
return array
By implementing these optimizations, bubble sort can reduce the number of comparisons and
swaps, making it more efficient. However, it's important to note that even with these optimizations,
bubble sort still has a worst-case time complexity of O(n^2). For larger arrays, other sorting algorithms
like quicksort, mergesort, or heapsort are generally more efficient options.
In-Lab
1. Given an array of integers nums and an integer target, return indices of the two numbers
such that theyadd up to target. You may assume that each input would have exactly one
solution, and you may notuse the same element twice. You can return the answer in any
order.
Input:nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0,
1]. Constraints:
 2 <= nums.length<= 104
 -109<= nums[i] <= 109
 -109<= target <= 109
Link: https://leetcode.com/problems/two-sum/
Code:
int* twoSum(int* nums, int numsSize, inttarget, int* returnSize){
int *arr;
*returnSize=2;
for(int i=0;i<numsSize;i++){
for(int j=i+1;j<numsSize;j++){
if(nums[i]+nums[j]==target){
arr=(int *)malloc(sizeof(int)*2);
arr[0]=i;
arr[1]=j;
}
}
}
return arr;
}
2. Given an array of integers, sort the array in ascending order using the Bubble Sort
algorithm above.Once sorted, print the following three lines:
 Array is sorted in numSwaps swaps., where is the number of swaps that took place.
 First Element: firstElement, where is the first element in the sorted array.
 Last Element: lastElement, where is the last element in the sorted
array. Input
The first line contains an integer, n, the size of the array a.The second line contains n space-
separated integers a[i].
Output
Print an integer -numbers of swaps.Print first element and last element.
Constraints
 2<=n<=600
 1<=a[i]<=2*106
Link :https://www.hackerrank.com/challenges/ctci-bubble-sort/problem
Code:
#include <assert.h>
#include <ctype.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* readline();
char* ltrim(char*);
char* rtrim(char*);
char** split_string(char*);
int parse_int(char*);
/*
* Complete the 'countSwaps' function below.
*
* The function accepts INTEGER_ARRAY a as parameter.
*/
void countSwaps(int a_count, int* a) {
int swaps = 0;
bool swapped;
for (int i = 0; i < a_count - 1; i++) {
swapped = false;
for (int j = 0; j < a_count - i - 1; j++) {
if (a[j] > a[j + 1]) {
// Swap elements a[j] and a[j + 1]
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
swaps++;
swapped = true;
}
}
if (!swapped) {
// Array is already sorted, no need to continue
break;
}
}
printf("Array is sorted in %d swaps.\n", swaps);
printf("First Element: %d\n", a[0]);
printf("Last Element: %d\n", a[a_count - 1]);
}

int main()
{
int n = parse_int(ltrim(rtrim(readline())));
char** a_temp = split_string(rtrim(readline()));
int* a = malloc(n * sizeof(int));
for (int i = 0; i < n; i++) {
int a_item = parse_int(*(a_temp + i));
*(a + i) = a_item;
}
countSwaps(n, a);
return 0;
}
char* readline() {
size_t alloc_length = 1024;
size_t data_length = 0;
char* data = malloc(alloc_length);
while (true) {
char* cursor = data + data_length;
char* line = fgets(cursor, alloc_length - data_length, stdin);
if (!line) {
break;
}
data_length += strlen(cursor);
if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') {
break;
}
alloc_length <<= 1;
data = realloc(data, alloc_length);
if (!data) {
data = '\0';
break;
}
}

if (data[data_length - 1] == '\n') {
data[data_length - 1] = '\0';
data = realloc(data, data_length);
if (!data) {
data = '\0';
}
} else {
data = realloc(data, data_length + 1);
if (!data) {
data = '\0';
} else {
data[data_length] = '\0';
}
}
return data;
}
char* ltrim(char* str) {
if (!str) {
return '\0';
}
if (!*str) {
return str;
}
while (*str != '\0' && isspace(*str)) {
str++;
}
return str;
}
char* rtrim(char* str) {
if (!str) {
return '\0';
}
if (!*str) {
return str;
}
char* end = str + strlen(str) - 1;
while (end >= str && isspace(*end)) {
end--;
}
*(end + 1) = '\0';
return str;
}
char** split_string(char* str) {
char** splits = NULL;
char* token = strtok(str, " ");
int spaces = 0;
while (token) {
splits = realloc(splits, sizeof(char*) * ++spaces);
if (!splits) {
return splits;
}
splits[spaces - 1] = token;
token = strtok(NULL, " ");
}
return splits;
}
int parse_int(char* str) {
char* endptr;
int value = strtol(str, &endptr, 10);
if (endptr == str || *endptr != '\0') {
exit(EXIT_FAILURE);
}
return value;
}
3. You are a product manager and currently leading a team to develop a new product.
Unfortunately, the latest version of your product fails the quality check. Since each version
is developedbased on the previous version, all the versions after a bad version are also bad.
Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one,
which causes all the following ones to be bad. You are given an API bool isBadVersion(version)
which returns whether version is bad. Implement a function to find the first bad version. You
should minimize the number ofcalls to the API.
Example 1:
Input: n = 5, bad =
4 Output: 4
Explanation:
call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true
Then 4 is the first bad
version.
Example 2:
Input: n = 1, bad = 1
Output: 1
Link:https://leetcode.com/problems/first-bad-version/description/
Code:
// Forward declaration of the API function isBadVersion.
boolisBadVersion(intversion);
intfirstBadVersion(intn) {
int left = 1;
int right = n;

while (left < right) {


int mid = left + (right - left) / 2;

if (isBadVersion(mid)) {
right = mid;
} else {
left = mid + 1;
}
}

returnleft;
}
Post-lab:
Code:
1. Solve the problem in the hacker rank platform
https://www.hackerrank.com/challenges/sorting-array-of-strings/problem
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int lexicographic_sort(const char* a, const char* b) {
return strcmp(a, b);
}
int lexicographic_sort_reverse(const char* a, const char* b) {
return strcmp(b, a);
}
int sort_by_number_of_distinct_characters(const char* a, const char* b) {
int count_a = 0, count_b = 0;
int freq_a[26] = {0}, freq_b[26] = {0};
// Count distinct characters in string a
for (int i = 0; a[i] != '\0'; i++) {
if (freq_a[a[i] - 'a'] == 0) {
count_a++;
freq_a[a[i] - 'a'] = 1;
}
}
// Count distinct characters in string b
for (int i = 0; b[i] != '\0'; i++) {
if (freq_b[b[i] - 'a'] == 0) {
count_b++;
freq_b[b[i] - 'a'] = 1;
}
}

if (count_a == count_b) {
return strcmp(a, b);
} else {
return count_a - count_b;
}
}

int sort_by_length(const char* a, const char* b) {


int len_a = strlen(a);
int len_b = strlen(b);
if (len_a == len_b) {
return strcmp(a, b);
} else {
return len_a - len_b;
}
}
void string_sort(char** arr, const int len, int (*cmp_func)(const char* a, const char* b)) {
int i, j;
char* temp;
for (i = 0; i < len - 1; i++) {
for (j = 0; j < len - i - 1; j++) {
if ((*cmp_func)(arr[j], arr[j + 1]) > 0) {
// Swap arr[j] and arr[j+1]
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main()
{
int n;
scanf("%d", &n);
char** arr;
arr = (char**)malloc(n * sizeof(char*));
for(int i = 0; i < n; i++){
*(arr + i) = malloc(1024 * sizeof(char));
scanf("%s", *(arr + i));
*(arr + i) = realloc(*(arr + i), strlen(*(arr + i)) + 1);
}
string_sort(arr, n, lexicographic_sort);
for(int i = 0; i < n; i++)
printf("%s\n", arr[i]);
printf("\n");
string_sort(arr, n, lexicographic_sort_reverse);
for(int i = 0; i < n; i++)
printf("%s\n", arr[i]);
printf("\n");
string_sort(arr, n, sort_by_length);
for(int i = 0; i < n; i++)
printf("%s\n", arr[i]);
printf("\n");
string_sort(arr, n, sort_by_number_of_distinct_characters);
for(int i = 0; i < n; i++)
printf("%s\n", arr[i]);
printf("\n");
}
2. Consider an array of numeric strings where each string is a positive number with any
where from 1 to 106 digits. Sort the array's elements in non-decreasing, or ascending order
of their integer values andreturn the sorted array.
https://www.hackerrank.com/challenges/big-sorting/problem
Code:
#include <assert.h>
#include <ctype.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* readline();
char* ltrim(char*);
char* rtrim(char*);
int parse_int(char*);
/*
* Complete the 'bigSorting' function below.
*
* The function is expected to return a STRING_ARRAY.
* The function accepts STRING_ARRAY unsorted as parameter.
*/

/*
* To return the string array from the function, you should:
* - Store the size of the array to be returned in the result_count variable
* - Allocate the array statically or dynamically
*
* For example,
* char** return_string_array_using_static_allocation(int* result_count) {
* *result_count = 5;
*
* static char* a[5] = {"static", "allocation", "of", "string", "array"};
*
* return a;
*}
*
* char** return_string_array_using_dynamic_allocation(int* result_count) {
* *result_count = 5;
*
* char** a = malloc(5 * sizeof(char*));
*
* for (int i = 0; i < 5; i++) {
* *(a + i) = malloc(20 * sizeof(char));
* }
*
* *(a + 0) = "dynamic";
* *(a + 1) = "allocation";
* *(a + 2) = "of";
* *(a + 3) = "string";
* *(a + 4) = "array";
*
* return a;
*}
*
*/
int compare(const void* a, const void* b) {
const char* str_a = *(const char**)a;
const char* str_b = *(const char**)b;
int len_a = strlen(str_a);
int len_b = strlen(str_b);
if (len_a == len_b) {
return strcmp(str_a, str_b);
} else {
return len_a - len_b;
}
}
char** bigSorting(int unsorted_count, char** unsorted, int* result_count) {
qsort(unsorted, unsorted_count, sizeof(char*), compare);
*result_count = unsorted_count;
return unsorted;
}
int main()
{
FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");
int n = parse_int(ltrim(rtrim(readline())));
char** unsorted = malloc(n * sizeof(char*));
for (int i = 0; i < n; i++) {
char* unsorted_item = readline();
*(unsorted + i) = unsorted_item;
}
int result_count;
char** result = bigSorting(n, unsorted, &result_count);
for (int i = 0; i < result_count; i++) {
fprintf(fptr, "%s", *(result + i));
if (i != result_count - 1) {
fprintf(fptr, "\n");
}
}
fprintf(fptr, "\n");
fclose(fptr);
return 0;
}
char* readline() {
size_t alloc_length = 1024;
size_t data_length = 0;
char* data = malloc(alloc_length);
while (true) {
char* cursor = data + data_length;
char* line = fgets(cursor, alloc_length - data_length, stdin);
if (!line) {
break;
}
data_length += strlen(cursor);
if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') {
break;
}
alloc_length <<= 1;
data = realloc(data, alloc_length);
if (!data) {
data = '\0';
break;
}
}

if (data[data_length - 1] == '\n') {
data[data_length - 1] = '\0';
data = realloc(data, data_length);
if (!data) {
data = '\0';
}
} else {
data = realloc(data, data_length + 1);
if (!data) {
data = '\0';
} else {
data[data_length] = '\0';
}
}
return data;
}
char* ltrim(char* str) {
if (!str) {
return '\0';
}
if (!*str) {
return str;
}
while (*str != '\0' && isspace(*str)) {
str++;
}
return str;
}
char* rtrim(char* str) {
if (!str) {
return '\0';
}
if (!*str) {
return str;
}

char* end = str + strlen(str) - 1;


while (end >= str && isspace(*end)) {
end--;
}
*(end + 1) = '\0';
return str;
}
int parse_int(char* str) {
char* endptr;
int value = strtol(str, &endptr, 10);

if (endptr == str || *endptr != '\0') {


exit(EXIT_FAILURE);
}
return value;
}
3. You You have N rectangles. A rectangle is golden if the ratio of its sides is in
between[1.6,1.7] , bothinclusive. Your task is to find the number of golden rectangles.
https://www.hackerearth.com/practice/algorithms/searching/linear-search/practice-
problems/algorithm/almost-golden-rectangular-1c9d72c0/
Code:
#include<stdio.h>
#include<string.h>
int main()
{
int n;
scanf("%d",&n);
double w,h,x,y;
int count=0;
for(int i=1;i<=n;i++){
scanf("%lf%lf",&w,&h);
x=w/h;
y=h/w; if((x>=1.60)&&(x<=1.70)||
(y>=1.60)&&(y<=1.70))
count+=1;
}
printf("%d",count);
return 0;
}
4. You You are given an array A of size N, and Q queries to deal with. For each query, you
are given aninteger X, and you're supposed to find out if X is present in the array A or
not.
https://www.hackerearth.com/practice/algorithms/searching/binary-search/practice-
problems/algorithm/discover-the-monk/
Code:
#include <stdio.h>
#include <stdlib.h>
int cmpfunc(const void* a, const void* b) {
return (*(int*)a - *(int*)b);
}
int binarySearch(int arr[], int n, int x) {
int start = 0;
int end = n - 1;
while (start <= end) {
int mid = (start + end) / 2;
if (arr[mid] == x) {
return 1; // Found X
} else if (arr[mid] < x) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return 0; // X not found
}

int main() {
int N, Q;
scanf("%d %d", &N, &Q);
int* A = (int*)malloc(N * sizeof(int));
for (int i = 0; i< N; i++) {
scanf("%d", &A[i]);
}
// Sort the array A in ascending order
qsort(A, N, sizeof(int), cmpfunc);

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


int X;
scanf("%d", &X);
// Perform binary search on the sorted array A
int result = binarySearch(A, N, X);
if (result) { printf("YES\
n");
} else {
printf("NO\n");
}
}
free(A);
return 0;
}
Skill:
1. You are given an array A of size N. You are also given an integer X. You need to find if X
is present in the array A or not. If X is present then print "YES" otherwise print "NO"
without quotes.
Input
 The first line of the input contains a single integer T denoting the number of test
cases. Thedescription of
 T test cases follows. The first line of each test case contains a single integer N.
 The second line contains N space-separated integers .
 The third line contains a single integer
X. Output
For each test case, print a single line containing the string "YES" if X is present inA or
"NO" otherwise (without quotes).
Constraints
 1<=T<=10
 1<=N<=105
 -109<=Ai, X <=109
Link :https://www.codechef.com/DSCA2019/problems/NSECDS08
Code:
#include <stdio.h>
int isPresent(int* arr, int n, int x) {
for (int i = 0; i< n; i++) {
if (arr[i] == x) {
return 1; // X is present
}
}
return 0; // X is not present
}

int main() {
int t;
scanf("%d", &t);
while (t--) {
int n;
scanf("%d", &n);

int* arr = (int*)malloc(n * sizeof(int));


for (int i = 0; i< n; i++) {
scanf("%d", &arr[i]);
}
int x;
scanf("%d", &x);
int present = isPresent(arr, n, x);
if (present) {
printf("YES\n");
} else {
printf("NO\n");
}
free(arr);
}
return 0;
}
2. The citizens of Byteland regularly play a game. They have blocks each denoting some
integer from 0to 9. These are arranged together in a random manner without seeing to form
different numbers keepingin mind that the first block is never a 0. Once they form a
number, they read in the reverse order to checkif the number and its reverse is the same.
If both are same, then the player wins. We call such numbers palindrome.
Ash happens to see this game and wants to simulate the same in the computer. As the first step
he wantsto take an input from the user and check if the number is a palindrome and declare
if the user wins ornot.
Input
 The first line of the input contains T, the number of test cases. This is followed by T
lines containing an integer N.
Output
 For each input output "wins" if the number is a palindrome and "loses" if not, in a
new line.
Constraints
 1<=T<=20
 1<=N<=20000
Link: https://www.codechef.com/problems/PALL01
Code:
#include <stdio.h>
int isPalindrome(int n) {
int reverse = 0;
int temp = n;
while (temp != 0) {
int digit = temp % 10;
reverse = reverse * 10 + digit;
temp /= 10;
}
if (n == reverse) {
return 1; // Palindrome
} else {
return 0; // Not a palindrome
}
}
int main() {
int t;
scanf("%d", &t);
while (t--) {
int n;
scanf("%d", &n);
if (isPalindrome(n)) {
printf("wins\n");
} else {
printf("loses\n");
}
}
return 0; }
3. Shahid is a computer science student and his teacher gave him a simple question to solve
withintime but he is little busy in his life, so he asked you to solve this problem.Problem
statement : You have been given an array of positive integers A1,A2,...,An with legnthN
and you have to print an array of same legnth(N) where the values in the new array are
the sum of every number in the array, except the number at that index.
Input:
 The first line of input contains a single integer T denoting the number of test cases.
 Each test cases contain two lines.First line contains N, the length of the array and
second linecontains N space separated positive integers.
Output:
For each test case, output a single array of same length.Constraints:
 1 ≤ T ≤ 100
 1 ≤ N ≤105
 0 <= A[i] <= 109
Link: https://www.codechef.com/problems/ARRPROB
Code:
#include <stdio.h>
#include <stdlib.h>
void calculateArraySum(int arr[], int n) {
long long sum = 0;
for (int i = 0; i< n; i++) {
sum += arr[i];
}
for (int i = 0; i< n; i++) {
printf("%lld ", sum - arr[i]);
}
printf("\n");
}

int main() {
int t;
scanf("%d", &t);

while (t--) {
int n;
scanf("%d", &n);

int* arr = (int*)malloc(n * sizeof(int));


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

calculateArraySum(arr, n);
free(arr);
}
return 0;
}
4. Given an array $A$ of size $N$. Sort the array using Bubble Sort and print the sorted array.
Input
 The first line of the input contains a single integer TT denoting the number of test cases.
The description of TT test cases follows.
 The first line of each test case contains a single integer NN.
 The second line contains NN space-separated integers A1,A2,…,ANA1,A2,…,AN.
Output
 For each test case print a single line containing NN space-separated integers -
the sortedarray.
Link: https://www.codechef.com/DSCA2019/problems/NSECDS04
Code:
#include<stdio.h>
#include<stdlib.h>
bubblesort(int arr[],int n){
int m,x,y;
for(m=0;m<n-1;m++){
for(x=0;x<n-1-m;x++){
if(arr[x]>arr[x+1]){
y=arr[x+1];
arr[x+1]=arr[x];
arr[x]=y;
}
}
}
}
int main(){
int n,*ar,i,k,j,t;
scanf("%d\n",&t);
for(i=0;i<t;i++){
scanf("%d\n",&n);
ar=(int *)malloc(sizeof(int)*n);
for(j=0;j<n;j++){
scanf("%d ",&ar[j]);
}
bubblesort(ar,n);
for(k=0;k<n;k++){
printf("%d ",ar[k]);
}
}
}
5. Given an integer array nums and an integer val, remove all occurrences of val in nums in-
place. Theorder of the elements may be changed. Then return the number of elements in
nums which are not equalto val. Consider the number of elements in nums which are not
equal to val be k, to get accepted, youneed to do the following things: Change the array
nums such that the first k elements of nums containthe elements which are not equal to val.
The remaining elements of nums are not important as well as thesize of nums. Return k.
Sample Input: nums = [3,2,2,3], val = 3Sample
Output: 2, nums = [2,2,_,_]
Explanation: Your function should return k = 2, with the first two elements of nums being
2.It does not matter what you leave beyond the returned k (hence they are underscores).
Link: https://leetcode.com/problems/remove-element/
Code:
int removeElement(int* nums, int numsSize, int val) {
int i = 0;
for (int j = 0; j < numsSize; j++) {
if (nums[j] != val) {
nums[i] = nums[j];
i++;
}
}
return i;
}
6. Solve the problem in the hackerrank platform

https://www.hackerrank.com/challenges/compare-the-triplets/problem
Code:
#include <assert.h>
#include <ctype.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* readline();
char* ltrim(char*);
char* rtrim(char*);
char** split_string(char*);
int parse_int(char*);

/*
* Complete the 'compareTriplets' function below.
*
* The function is expected to return an INTEGER_ARRAY.
* The function accepts following parameters:
* 1. INTEGER_ARRAY a
* 2. INTEGER_ARRAY b
*/
/*
* To return the integer array from the function, you should:
* - Store the size of the array to be returned in the result_count variable
* - Allocate the array statically or dynamically
*
* For example,
* int* return_integer_array_using_static_allocation(int* result_count) {
* *result_count = 5;
*
* static int a[5] = {1, 2, 3, 4, 5};
*
* return a;
*}
*
* int* return_integer_array_using_dynamic_allocation(int* result_count) {
* *result_count = 5;
*
* int *a = malloc(5 * sizeof(int));
*
* for (int i = 0; i < 5; i++) {
* *(a + i) = i + 1;
* }
*
* return a;
*}
*
*/
int* compareTriplets(int a_count, int* a, int b_count, int* b, int* result_count) {
int score_a = 0;
int score_b = 0;
for (int i = 0; i < a_count; i++) {
if (a[i] > b[i]) {
score_a++;
} else if (a[i] < b[i]) {
score_b++;
}
}
int* result = malloc(2 * sizeof(int));

result[0] = score_a;
result[1] = score_b;
*result_count = 2;
return result;

}
int main()
{
FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");
char** a_temp = split_string(rtrim(readline()));
int* a = malloc(3 * sizeof(int));
for (int i = 0; i < 3; i++) {
int a_item = parse_int(*(a_temp + i));
*(a + i) = a_item;
}
char** b_temp = split_string(rtrim(readline()));
int* b = malloc(3 * sizeof(int));
for (int i = 0; i < 3; i++) {
int b_item = parse_int(*(b_temp + i));
*(b + i) = b_item;
}
int result_count;
int* result = compareTriplets(3, a, 3, b, &result_count);
for (int i = 0; i < result_count; i++) {
fprintf(fptr, "%d", *(result + i));
if (i != result_count - 1) {
fprintf(fptr, " ");
}
}
fprintf(fptr, "\n");
fclose(fptr);
return 0;
}

char* readline() {
size_t alloc_length = 1024;
size_t data_length = 0;
char* data = malloc(alloc_length);
while (true) {
char* cursor = data + data_length;
char* line = fgets(cursor, alloc_length - data_length, stdin);
if (!line) {
break;
}
data_length += strlen(cursor);
if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') {
break;
}
alloc_length <<= 1;
data = realloc(data, alloc_length);

if (!data) {
data = '\0';
break;
}
}
if (data[data_length - 1] == '\n') {
data[data_length - 1] = '\0';
data = realloc(data, data_length);
if (!data) {
data = '\0';
}
} else {
data = realloc(data, data_length + 1);
if (!data) {
data = '\0';
} else {
data[data_length] = '\0';
}
}
return data;
}

char* ltrim(char* str) {


if (!str) {
return '\0';
}
if (!*str) {
return str;
}
while (*str != '\0' && isspace(*str)) {
str++;
}
return str;
}

char* rtrim(char* str) {


if (!str) {
return '\0';
}
if (!*str) {
return str;
}
char* end = str + strlen(str) - 1;
while (end >= str && isspace(*end)) {
end--;
}

*(end + 1) = '\0';

return str;
}

char** split_string(char* str) {


char** splits = NULL;
char* token = strtok(str, " ");
int spaces = 0;
while (token) {
splits = realloc(splits, sizeof(char*) * ++spaces);
if (!splits) {
return splits;
}
splits[spaces - 1] = token;
token = strtok(NULL, " ");
}
return splits;
}

int parse_int(char* str) {


char* endptr;
int value = strtol(str, &endptr, 10);
if (endptr == str || *endptr != '\0') {
exit(EXIT_FAILURE);
}
return value;
}
7. Solve the problem in the hackerrank platform

https://www.hackerrank.com/challenges/simple-array-sum/problem

Code:
#include <assert.h>
#include <ctype.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* readline();
char* ltrim(char*);
char* rtrim(char*);
char** split_string(char*);
int parse_int(char*);
/*
* Complete the 'simpleArraySum' function below.
*
* The function is expected to return an INTEGER.
* The function accepts INTEGER_ARRAY ar as parameter.
*/
int simpleArraySum(int ar_count, int* ar) {
int sum = 0;
for (int i = 0; i < ar_count; i++) {
sum += ar[i];
}
return sum;
}
int main()
{
FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");
int ar_count = parse_int(ltrim(rtrim(readline())));
char** ar_temp = split_string(rtrim(readline()));
int* ar = malloc(ar_count * sizeof(int));
for (int i = 0; i < ar_count; i++) {
int ar_item = parse_int(*(ar_temp + i));
*(ar + i) = ar_item;
}
int result = simpleArraySum(ar_count, ar);
fprintf(fptr, "%d\n", result);
fclose(fptr);
return 0;
}
char* readline() {
size_t alloc_length = 1024;
size_t data_length = 0;
char* data = malloc(alloc_length);
while (true) {
char* cursor = data + data_length;
char* line = fgets(cursor, alloc_length - data_length, stdin);
if (!line) {
break;
}
data_length += strlen(cursor);
if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') {
break;
}
alloc_length <<= 1;
data = realloc(data, alloc_length);
if (!data) {
data = '\0';
break;
}
}
if (data[data_length - 1] == '\n') {
data[data_length - 1] = '\0';
data = realloc(data, data_length);
if (!data) {
data = '\0';
}
} else {
data = realloc(data, data_length + 1);
if (!data) {
data = '\0';
} else {
data[data_length] = '\0';
}
}
return data;
}
char* ltrim(char* str) {
if (!str) {
return '\0';
}
if (!*str) {
return str;
}
while (*str != '\0' && isspace(*str)) {
str++;
}
return str;
}
char* rtrim(char* str) {
if (!str) {
return '\0';
}
if (!*str) {
return str;
}
char* end = str + strlen(str) - 1;
while (end >= str && isspace(*end)) {
end--;
}
*(end + 1) = '\0';
return str;
}
char** split_string(char* str) {
char** splits = NULL;
char* token = strtok(str, " ");
int spaces = 0;
while (token) {
splits = realloc(splits, sizeof(char*) * ++spaces);
if (!splits) {
return splits;
}
splits[spaces - 1] = token;
token = strtok(NULL, " ");
}
return splits;
}
int parse_int(char* str) {
char* endptr;
int value = strtol(str, &endptr, 10);
if (endptr == str || *endptr != '\0') {
exit(EXIT_FAILURE);
}
return value;
}
8. Solve the problem in the hackerrank platform

https://www.hackerrank.com/challenges/reverse-array-c/problem

Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, *arr, i;
scanf("%d", &num);
arr = (int*) malloc(num * sizeof(int));
for(i = 0; i < num; i++) {
scanf("%d", arr + i);
}
/* Reverse the array */
int start = 0;
int end = num - 1;
while (start < end) {
/* Swap elements */
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
/* Move pointers */
start++;
end--;
}
/* Print the reversed array */
for(i = 0; i < num; i++)
printf("%d ", *(arr + i));
free(arr);
return 0;
}
9. Solve the problem in the hackerrank platform

https://www.hackerrank.com/challenges/dynamic-array-in-c/problem

Code:1
#include <stdio.h>
#include <stdlib.h>
/*
* This stores the total number of books in each shelf.
*/
int* total_number_of_books;

/*
* This stores the total number of pages in each book of each shelf.
* The rows represent the shelves and the columns represent the books.
*/
int** total_number_of_pages;
int main()
{
int total_number_of_shelves;
scanf("%d", &total_number_of_shelves);

int total_number_of_queries;
scanf("%d", &total_number_of_queries);

total_number_of_books = (int*)malloc(total_number_of_shelves * sizeof(int));


total_number_of_pages = (int**)malloc(total_number_of_shelves * sizeof(int*));

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


total_number_of_books[i] = 0;
total_number_of_pages[i] = NULL;
}

while (total_number_of_queries--) {
int type_of_query;
scanf("%d", &type_of_query);

if (type_of_query == 1) {
int x, y;
scanf("%d %d", &x, &y);

// Increase the number of books on the x'th shelf


total_number_of_books[x]++;

// Allocate memory for the new book


total_number_of_pages[x] = (int*)realloc(total_number_of_pages[x], total_number_of_book
s[x] * sizeof(int));

// Add the number of pages to the new book total_number_of_pages[x]


[total_number_of_books[x] - 1] = y;
} else if (type_of_query == 2) {
int x, y;
scanf("%d %d", &x, &y);
printf("%d\n", *(*(total_number_of_pages + x) + y));
} else {
int x;
scanf("%d", &x);
printf("%d\n", *(total_number_of_books + x));
}
}

if (total_number_of_books) {
free(total_number_of_books);
}

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


if (*(total_number_of_pages + i)) {
free(*(total_number_of_pages + i));
}
}

if (total_number_of_pages) {
free(total_number_of_pages);
}

return 0;
}

Code:2
#include <stdio.h>
#include <stdlib.h>
/*
* This stores the total number of books in each shelf.
*/
int* total_number_of_books;
/*
* This stores the total number of pages in each book of each shelf.
* The rows represent the shelves and the columns represent the books.
*/
int** total_number_of_pages;
int main()
{
int total_number_of_shelves;
scanf("%d", &total_number_of_shelves);
int total_number_of_queries;
scanf("%d", &total_number_of_queries);
total_number_of_books = (int *) calloc(sizeof(int), total_number_of_shelves);
total_number_of_pages = (int **) calloc(sizeof(int *), total_number_of_shelves);
while (total_number_of_queries--)
{
int type_of_query;
scanf("%d", &type_of_query);
if (type_of_query == 1) {
/*
* Process the query of first type here.
*/
int x, y;
scanf("%d %d", &x, &y);
total_number_of_books[x]++;
total_number_of_pages[x] = realloc(total_number_of_pages[x], sizeof(int *) * total_number
_of_books[x]);
total_number_of_pages[x][total_number_of_books[x] - 1] = y;
} else if (type_of_query == 2) {
int x, y;
scanf("%d %d", &x, &y);
printf("%d\n", *(*(total_number_of_pages + x) + y));
} else {
int x;
scanf("%d", &x);
printf("%d\n", *(total_number_of_books + x));
}
}
if (total_number_of_books) {
free(total_number_of_books);
}
for (int i = 0; i < total_number_of_shelves; i++) {
if (*(total_number_of_pages + i)) {
free(*(total_number_of_pages + i));
}
}
if (total_number_of_pages) {
free(total_number_of_pages);
}
return 0;
}
Week-10
Prelab:
1. What is a 2D array? How is it different from a 1D array?
Ans:
A 2D array, also known as a two-dimensional array, is a data structure that organizes data
elements in a grid-like format with rows and columns. It can be visualized as a table or a matrix. In
programming, a 2D array is often implemented as an array of arrays, where each element in the
outer array represents a row, and each element within the inner arrays represents a column element.
A 1D array, on the other hand, is a linear data structure that stores elements in a contiguous
block of memory. It can be thought of as a simple list of elements.
The main difference between a 1D array and a 2D array lies in their organization and access
patterns. In a 1D array, elements are accessed using a single index, whereas in a 2D array, elements
are accessed using two indices (row and column indices). This allows for more structured
representation and manipulation of data in a tabular form.
2. How do you declare and initialize a 2D array in your programming language of choice?
Ans:
In C, you can declare and initialize a 2D array using the following syntax:
// Declare and initialize a 2D array of size 3x3
int array[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
The initialization is done by providing the values within nested curly braces. Each inner set of
braces represents a row in the 2D array, and the elements within the inner braces represent the
values in each column.Make sure to provide the appropriate size and initialize the array elements
correctly based on your specific requirements.
3. What is the purpose of the malloc function in C? How does it allocate memory?
Ans:
In C, the `malloc` function is used to dynamically allocate memory during program execution.
Its purpose is to allocate a specified number of bytes from the heap, which is a region of memory
used for dynamic memory allocation.
void* malloc(size_t size);
The `malloc` function takes a single argument, `size`, which specifies the number of bytes to
allocate. It returns a pointer to the allocated memory block of the requested size, or `NULL` if the
allocation fails.
The `malloc` function provides flexibility in allocating memory dynamically at runtime, allowing
you to allocate memory as needed and adjust the size of data structures during program execution.
However, it is crucial to manage memory properly, freeing it when it is no longer needed to avoid
memory leaks.
4. How does the calloc function differ from malloc? When would you use calloc instead of
malloc?
Ans:
The `calloc` function in C is used to dynamically allocate memory, just like the `malloc` function.
However, there are a few key differences between the two:
1. **Initialization**: The major difference is that `calloc` initializes the allocated memory to zero,
whereas `malloc` does not initialize the memory. With `calloc`, the allocated memory is
guaranteed to be initialized to zero values.
2. **Arguments**: The function signatures of `malloc` and `calloc` are slightly different. The
`calloc` function takes two arguments: the number of elements to allocate (`num`) and the size
in bytes of each element (`size`). On the other hand, `malloc` takes a single argument
specifying the total size in bytes to allocate.
You would use `calloc` instead of `malloc` when you need the allocated memory to be initialized to
zero or when you are working with data structures that require zero-initialized memory. This can
be particularly useful for arrays, matrices, or buffers that need to be cleared or initialized to a
known state before use.
On the other hand, if you do not require zero-initialized memory, or you intend to initialize the
memory yourself, you can use `malloc` for dynamic memory allocation.
It's worth noting that both `malloc` and `calloc` can fail to allocate memory if there is insufficient
memory available. Therefore, it's essential to check the return value for `NULL` to handle such
scenarios appropriately.
5. Explain the usage of the realloc function. How does it differ from malloc and calloc?
Ans:
The `realloc` function in C is used to dynamically change the size of a previously allocated block
of memory. It allows you to resize the memory block allocated by `malloc`, `calloc`, or a previous
`realloc` call. The `realloc` function can be used to either increase or decrease the size of the
allocated memory block.
The syntax for `realloc` is as follows:
void* realloc(void* ptr, size_t size);
The key differences between `realloc` and `malloc`/`calloc` are as follows:
1. **Resizing**: `realloc` allows you to change the size of an existing memory block, whereas
`malloc` and `calloc` are used to allocate new memory blocks. `realloc` can be used to both
increase and decrease the size of the memory block.
2. **Preserving Data**: When you use `realloc` to increase the size of a memory block, the
existing data in the block is preserved. If possible, `realloc` extends the memory block in place,
meaning the original pointer is returned. However, if it is not possible to extend the block in
place, a new block is allocated, and the data from the original block is copied to the new block.
In contrast, `malloc` and `calloc` always allocate new memory blocks, so they don't preserve
the data from previous allocations.
3. **Null Pointer Handling**: If the `ptr` argument passed to `realloc` is `NULL`, `realloc`
behaves like `malloc` and allocates a new memory block of the specified size. If the `
In-Lab
1. Chef is learning linear algebra. Recently, he learnt that for a square matrix M, trace(M)
is defined as the sum of all elements on the main diagonal of M (an element lies on the
main diagonal if its row index and column index are equal).
Now, Chef wants to solve some exercises related to this new quantity, so he wrote down a square
matrix A with size N×N. A square sub-matrix of A with size L×L is a contiguous block of L×L
elements of A. Formally, if B is a sub-matrix of A with size L×L, then there must be integers r and c
(1 ≤ r, c ≤ N+1−L) such that B(i,j) = A(r+i−1,c+j−1) for each 1 ≤ i , j ≤ L.
Help Chef find the maximum trace of a square sub-matrix of A.
Input
 The first line of the input contains a single integer T denoting the number of test
cases. The description of T test cases follows. The first line of each test case contains a
single integer N.
 The first line of each test case contains a single integer N.
 N lines follow. For each i (1 ≤ i ≤ N), the i-th of these lines contains N space-separated
integersA(i,1),A(i,2),…,A(i ,N) denoting the i-th row of the matrix A.
Output
For each test case, print a single line containing one integer — the maximum possible trace.
Constraints
 1<=T<=10
 1<=N<=105
 -109<=Ai, X <=109

Example Input:
1
3
125
634
271
Example Output: 13
Explanation: Example case 1: The sub-matrix with the largest trace is 6 3 2 7 which has
traceequal to 6+7=13. (This sub-matrix is obtained for r=2,c=1,L=2.)

https://www.codechef.com/problems/TRACMAT?tab=statement
Code:
#include <stdio.h>
int main() {
int t,x,temp=0,tot=0,i,j;
scanf("%d",&t);
for(x=0;x<t;x++) {
int n,a[50][50];
scanf("%d", &n);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d", &a[i][j]);
for(i=0;i<n-1;i++) {
for(j=0;j<n-1;j++) {
temp=a[i][j]+a[i+1][j+1];
if (tot<temp)
tot=temp;
}
}
printf("%d\n", tot);
}
return 0;

}
2. Joe and Lilly are best friends. They are not good in matrix concepts. Joe created a matrix
A & Lillycreated a matrix B. They want to find the multiplication matrix of two matrices
A & B.
Help Joe and Lilly to solve the problem.
Input:
The first line contains a number, t, denoting the number of test cases.
Next line is to take the no.of rows & columns of matrix A separated with space.After
that take the matrix values of A separated with space.
Next line is to take the no.of rows & columns of matrix B separated with space.After
that take the matrix values of B separated with space.
Output
If the multiplication is possible, then print the output matrix values separated with space. else
print "IMPOSSIBLE" (without quotes).
Constraints:
1 ≤ t ≤ 100
1 ≤ A[i,j] ≤ 1000
1 ≤ B[i,j] ≤ 1000
Input:
3
22
1234
22
1111
13
123
32
100110
13
345
12
89
Output:
3377
42
IMPOSSIBLE
https://www.codechef.com/problems/GE04?tab=statement
Code:
#include <stdio.h>
int main() {
int t;
scanf("%d", &t);
while (t--) {
int rowsA, colsA, rowsB, colsB;
scanf("%d %d", &rowsA, &colsA);
int A[10][10];
for (int i = 0; i<rowsA; i++) {
for (int j = 0; j <colsA; j++) {
scanf("%d", &A[i][j]);
}
}
scanf("%d %d", &rowsB, &colsB);
int B[10][10];
for (int i = 0; i<rowsB; i++) {
for (int j = 0; j <colsB; j++) {
scanf("%d", &B[i][j]);
}
}
if (colsA != rowsB) {
printf("IMPOSSIBLE\n");
continue;
}
int C[10][10];
for (int i = 0; i<rowsA; i++) {
for (int j = 0; j <colsB; j++) {
C[i][j] = 0;
for (int k = 0; k <colsA; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
for (int i = 0; i<rowsA; i++) {
for (int j = 0; j <colsB; j++) {
printf("%d ", C[i][j]);
}
printf("\n");
}
}
return 0;
}
3. You are given an m x n integer matrix matrix with the following two
properties: Each row is sorted in non-decreasing order.
The first integer of each row is greater than the last integer of the previous row.Given an integer
target, return true if target is in matrix or false otherwise.

Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3


Output: true
https://leetcode.com/problems/search-a-2d-
matrix/

Code:
bool searchMatrix(int** matrix, int matrixSize, int* matrixColSize, int target){

int start=0,row=matrixSize,column=*matrixColSize;
int end=row*column-1;
while(start<=end)
{
int mid=(start+end)/2;
int r=mid/(column),c=mid % column;
if(matrix[r][c]==target)
return true;
else if(matrix[r][c]<target)
start=mid+1;
else
end=mid-1;
}
return false;
}

#include <stdbool.h>
#include <stdio.h>

bool searchMatrix(int** matrix, int matrixSize, int* matrixColSize, int target) {


int rows = matrixSize;
int cols = matrixColSize[0];

int left = 0;
int right = rows * cols - 1;
while (left <= right) {
int mid = left + (right - left) /
2; int row = mid / cols;
int col = mid % cols;
int value = matrix[row][col];

if (value == target)
{ return true;
} else if (value < target)
{ left = mid + 1;
} else {
right = mid - 1;
}
}

return false;
}

int main() {
int matrixSize = 3;
int matrixColSize[3] = {4, 4, 4};
int** matrix = (int**)malloc(matrixSize *
sizeof(int*)); for (int i = 0; i<matrixSize; i++) {
matrix[i] = (int*)malloc(matrixColSize[i] * sizeof(int));
}
matrix[0][0] = 1;
matrix[0][1] = 3;
matrix[0][2] = 5;
matrix[0][3] = 7;
matrix[1][0] = 10;
matrix[1][1] = 11;
matrix[1][2] = 16;
matrix[1][3] = 20;
matrix[2][0] = 23;
matrix[2][1] = 30;
matrix[2][2] = 34;
matrix[2][3] = 60;
int target = 3;
bool result = searchMatrix(matrix, matrixSize, matrixColSize,
target); printf("%s\n", result ? "true" : "false"); // Output: true

for (int i = 0; i<matrixSize; i++)


{ free(matrix[i]);
}
free(matrix);

return 0;
}
Post-lab:
1. Solve the problem in the hackerrank platform
https://www.hackerrank.com/challenges/2d-array/problem
Code:
#include <assert.h>
#include <ctype.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* readline();
char* ltrim(char*);
char* rtrim(char*);
char** split_string(char*);
int parse_int(char*);
/*
* Complete the 'hourglassSum' function below.
*
* The function is expected to return an INTEGER.
* The function accepts 2D_INTEGER_ARRAY arr as parameter.
*/
int hourglassSum(int arr_rows, int arr_columns, int** arr) {
int maxSum = -63; // Initialize to smallest possible sum (-9 * 7 = -63)
for (int i = 0; i < arr_rows - 2; i++) {
for (int j = 0; j < arr_columns - 2; j++) {
int sum = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] +
arr[i + 1][j + 1] +
arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2];
if (sum > maxSum) {
maxSum = sum;
}
}
}
return maxSum;
}
int main()
{
FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");
int** arr = malloc(6 * sizeof(int*));
for (int i = 0; i < 6; i++) {
*(arr + i) = malloc(6 * (sizeof(int)));
char** arr_item_temp = split_string(rtrim(readline()));
for (int j = 0; j < 6; j++) {
int arr_item = parse_int(*(arr_item_temp + j));
*(*(arr + i) + j) = arr_item;
}
}
int result = hourglassSum(6, 6, arr);
fprintf(fptr, "%d\n", result);
fclose(fptr);
return 0;
}
char* readline() {
size_t alloc_length = 1024;
size_t data_length = 0;
char* data = malloc(alloc_length);
while (true) {
char* cursor = data + data_length;
char* line = fgets(cursor, alloc_length - data_length, stdin);
if (!line) {
break;
}
data_length += strlen(cursor);
if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') {
break;
}
alloc_length <<= 1;
data = realloc(data, alloc_length);
if (!data) {
data = '\0';
break;
}
}
if (data[data_length - 1] == '\n') {
data[data_length - 1] = '\0';

data = realloc(data, data_length);


if (!data) {
data = '\0';
}
} else {
data = realloc(data, data_length + 1);
if (!data) {
data = '\0';
} else {
data[data_length] = '\0';
}
}
return data;
}
char* ltrim(char* str) {
if (!str) {
return '\0';
}
if (!*str) {
return str;
}
while (*str != '\0' && isspace(*str)) {
str++;
}
return str;
}
char* rtrim(char* str) {
if (!str) {
return '\0';
}
if (!*str) {
return str;
}
char* end = str + strlen(str) - 1;
while (end >= str && isspace(*end)) {
end--;
}
*(end + 1) = '\0';
return str;
}
char** split_string(char* str) {
char** splits = NULL;
char* token = strtok(str, " ");
int spaces = 0;
while (token) {
splits = realloc(splits, sizeof(char*) * ++spaces);
if (!splits) {
return splits;
}
splits[spaces - 1] = token;
token = strtok(NULL, " ");
}
return splits;
}
int parse_int(char* str) {
char* endptr;
int value = strtol(str, &endptr, 10);
if (endptr == str || *endptr != '\0') {
exit(EXIT_FAILURE);
}
return value;
}
2. solve the problem in the hackerrank platform
https://www.hackerrank.com/challenges/30-2d-arrays/problem
Code:
#include <stdio.h>
#define ROWS 6
#define COLS 6
int hourglassSum(int arr[ROWS][COLS]) {
int maxSum = -63; // Initialize to smallest possible sum (-9 * 7 = -63)
for (int i = 0; i< ROWS - 2; i++) {
for (int j = 0; j < COLS - 2; j++) {
int sum = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] +
arr[i + 1][j + 1] +
arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2];

if (sum >maxSum) {
maxSum = sum;
}
}
}

return maxSum;
}

int main() {
int arr[ROWS][COLS];

// Read input array


for (int i = 0; i< ROWS; i++) {
for (int j = 0; j < COLS; j++) {
scanf("%d", &arr[i][j]);
}
}

int result = hourglassSum(arr);


printf("%d\n", result);

return 0;
}
3. You are given an m x n integer grid accounts where accounts[i][j] is the amount of money
the ithcustomer has in the jth bank. Return the wealth that the richest customer has.
A customer's wealth is the amount of money they have in all their bank accounts. The richest
customeris the customer that has the maximum wealth.
https://leetcode.com/problems/richest-customer-wealth/description/
Code:
#include <stdio.h>
int maximumWealth(int** accounts, int m, int n) {
int max_wealth = 0;
for (int i = 0; i< m; i++)
{ int wealth = 0;
for (int j = 0; j < n; j++) {
wealth += accounts[i]
[j];
}
if (wealth >max_wealth) {
max_wealth = wealth;
}
}
return max_wealth;
}

int main() {
int m =
2; int n =
3;
int** accounts = (int**)malloc(m *
sizeof(int*)); for (int i = 0; i< m; i++) {
accounts[i] = (int*)malloc(n * sizeof(int));
}
accounts[0][0] = 1;
accounts[0][1] = 2;
accounts[0][2] = 3;
accounts[1][0] = 3;
accounts[1][1] = 2;
accounts[1][2] = 1;

int result = maximumWealth(accounts, m,


n); printf("%d\n", result); // Output: 6
for (int i = 0; i< m; i++)
{ free(accounts[i]);
}
free(accounts);
return 0;
}

int maximumWealth(int** accounts, int accountsSize, int* accountsColSize){


int max=0;
for(int i=0;i<accountsSize;i++)
{
int w=0;
for(int j=0;j<accountsColSize[i];j++)
{
w += accounts[i][j];
}
if(w>max)
max = w;
}
return max;
}
4. Given a square matrix mat, return the sum of the matrix diagonals.
Only include the sum of all the elements on the primary diagonal and all the elements on the
secondarydiagonal that are not part of the primary diagonal.

https://leetcode.com/problems/matrix-diagonal-sum/description

Code:
int diagonalSum(int** mat, int matSize, int* matColSize){
int sum = 0;
int n = matSize;
for (int i = 0; i< n; i++) {
sum += mat[i][i];
sum += mat[n-1-i][i];
}
if (n % 2 == 1) sum -= mat[n/2][n/2];
return sum;
}

#include <stdio.h>
int diagonalSum(int** mat, int n) {
int sum = 0;
for (int i = 0; i< n; i++) {
sum += mat[i][i]; // Primary diagonal
sum += mat[i][n - 1 - i]; // Secondary diagonal
}
// Subtract the duplicate element if n is odd
if (n % 2 == 1) {
sum -= mat[n / 2][n / 2];
}

return sum;
}

int main() {
int n = 3;
int** mat = (int**)malloc(n * sizeof(int*));
for (int i = 0; i< n; i++) {
mat[i] = (int*)malloc(n * sizeof(int));
}

mat[0][0] = 1;
mat[0][1] = 2;
mat[0][2] = 3;
mat[1][0] = 4;
mat[1][1] = 5;
mat[1][2] = 6;
mat[2][0] = 7;
mat[2][1] = 8;
mat[2][2] = 9;

int result = diagonalSum(mat, n);


printf("%d\n", result); // Output: 25

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


free(mat[i]);
}
free(mat);

return 0;
}
Skill:
1. Write a program to perform matrix multiplication. If Multiplication cannot be done
for a givenmatrices then print "NOT POSSIBLE"

Input:
1)Read the row & column size of matrix 12)Read the
matrix 1 3)Read the row & column size of matrix 24)Read
the matrix 2
Output:
Resultant
Matrix.
Sample Input Sample Output
22 7 10
12 15 22
34
22
12
34
https://www.hackerearth.com/problem/algorithm/matrix-multiplication-12/

Code:
#include <stdio.h>
int main() {
int rowsA, colsA, rowsB, colsB;
scanf("%d %d", &rowsA, &colsA);
int matrixA[10][10];
for (int i = 0; i<rowsA; i++) {
for (int j = 0; j <colsA; j++) {
scanf("%d", &matrixA[i][j]);
}
}
scanf("%d %d", &rowsB, &colsB);
int matrixB[10][10];
for (int i = 0; i<rowsB; i++) {
for (int j = 0; j <colsB; j++) {
scanf("%d", &matrixB[i][j]);
}
}
if (colsA != rowsB) {
printf("NOT POSSIBLE\n");
return 0;
}
int result[10][10];
for (int i = 0; i<rowsA; i++) {
for (int j = 0; j <colsB; j++) {
result[i][j] = 0;
for (int k = 0; k <colsA; k++) {
result[i][j] += matrixA[i][k] * matrixB[k][j];
}
}
}

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


for (int j = 0; j <colsB; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}
2. Given two sorted arrays nums1 and nums2 of size m and n respectively, return the
median of the twosorted arrays.
Input: nums1 = [1,3], nums2 =
[2] Output: 2.00000
Explanation: merged array = [1,2,3] and median is
https://leetcode.com/problems/median-of-two-sorted-arrays/description/
Code:
#include <stdio.h>
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size)
{ int mergedSize = nums1Size + nums2Size;
int merged[mergedSize];

int i = 0, j = 0, k = 0;
while (i< nums1Size && j < nums2Size)
{ if (nums1[i] <= nums2[j]) {
merged[k] = nums1[i];
i+
+; } else {
merged[k] = nums2[j];

j+
+;
} k+
+;
}

while (i< nums1Size) {


merged[k] = nums1[i];
i++;
k++;
}

while (j < nums2Size) {


merged[k] = nums2[j];
j++;
k++;
}

int middle = mergedSize /


2; if (mergedSize % 2 ==
0) {
return (merged[middle - 1] + merged[middle]) / 2.0;
} else {
return merged[middle];
}
}

int main() {
int nums1[] = {1, 3};
int nums2[] = {2};
int nums1Size = sizeof(nums1) / sizeof(nums1[0]);
int nums2Size = sizeof(nums2) / sizeof(nums2[0]);
double median1 = findMedianSortedArrays(nums1, nums1Size, nums2, nums2Size);
printf("Example 1: %.5f\n", median1);

int nums3[] = {1, 2};


int nums4[] = {3, 4};
int nums3Size = sizeof(nums3) / sizeof(nums3[0]);
int nums4Size = sizeof(nums4) / sizeof(nums4[0]);
double median2 = findMedianSortedArrays(nums3, nums3Size, nums4, nums4Size);
printf("Example 2: %.5f\n", median2);
return 0;
}
3. Given a m x n grid filled with non-negative numbers, find a path from top left to bottom
right, whichminimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.

Input: grid = [[1,3,1],[1,5,1],[4,2,1]]


Output: 7
Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the
sum. https://leetcode.com/problems/minimum-path-sum/
Code:
#include <stdio.h>
int minPathSum(int** grid, int gridSize, int* gridColSize) {
int m = gridSize;
int n = *gridColSize;

int dp[m][n];
dp[0][0] = grid[0][0];

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


dp[0][i] = dp[0][i - 1] + grid[0][i];
}

// Initialize the first column


for (int i = 1; i< m; i++) {
dp[i][0] = dp[i - 1][0] + grid[i][0];
}
for (int i = 1; i< m; i++) {
for (int j = 1; j < n; j++) {
dp[i][j] = grid[i][j] + fmin(dp[i - 1][j], dp[i][j - 1]);
}
}

return dp[m - 1][n - 1];


}

int main() {
int grid1[3][3] = {{1, 3, 1}, {1, 5, 1}, {4, 2, 1}};
int* grid1Ptr[3] = {grid1[0], grid1[1], grid1[2]};
int grid1Size = 3;
int grid1ColSize = 3;
int result1 = minPathSum(grid1Ptr, grid1Size, &grid1ColSize);
printf("Example 1: %d\n", result1);

int grid2[2][3] = {{1, 2, 3}, {4, 5, 6}};


int* grid2Ptr[2] = {grid2[0], grid2[1]};
int grid2Size = 2;
int grid2ColSize = 3;
int result2 = minPathSum(grid2Ptr, grid2Size, &grid2ColSize);
printf("Example 2: %d\n", result2);

return 0;
}
4. Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that
the majority element always exists in the array.
Input: nums = [3,2,3]
Output: 3
https://leetcode.com/problems/majority-
element/ Code:
#include <stdio.h>
int majorityElement(int* nums, int numsSize) {
int majority = nums[0];
int count = 1;
for (int i = 1; i<numsSize; i++) {
if (count == 0) {
majority = nums[i];
}
if (nums[i] == majority) {
count++;
} else {
count--;
}
}
return majority;
}

int main() {
int nums1[] = {3, 2, 3};
int nums1Size = sizeof(nums1) / sizeof(nums1[0]);
int majority1 = majorityElement(nums1, nums1Size);
printf("Example 1: %d\n", majority1);
int nums2[] = {2, 2, 1, 1, 1, 2, 2};
int nums2Size = sizeof(nums2) / sizeof(nums2[0]);
int majority2 = majorityElement(nums2, nums2Size);
printf("Example 2: %d\n", majority2);
return 0;
}
5. Given a sorted array of distinct integers and a target value, return the index if the
target is found. Ifnot, return the index where it would be if it were inserted in order.
Input: nums = [1,3,5,6], target =
5 Output: 2
https://leetcode.com/problems/search-insert-position/
Code:
#include <stdio.h>
int searchInsert(int* nums, int numsSize, int target) {
int low = 0;
int high = numsSize - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return low;
}

int main() {
int nums1[] = {1, 3, 5, 6};
int nums1Size = sizeof(nums1) / sizeof(nums1[0]);
int target1 = 5;
int index1 = searchInsert(nums1, nums1Size, target1);
printf("Example 1: %d\n", index1);
int nums2[] = {1, 3, 5, 6};
int nums2Size = sizeof(nums2) / sizeof(nums2[0]);
int target2 = 2;
int index2 = searchInsert(nums2, nums2Size, target2);
printf("Example 2: %d\n", index2);
int nums3[] = {1, 3, 5, 6};
int nums3Size = sizeof(nums3) / sizeof(nums3[0]);
int target3 = 7;
int index3 = searchInsert(nums3, nums3Size, target3);
printf("Example 3: %d\n", index3);
return 0;
}
6. Given a m x n matrix grid which is sorted in non-increasing order both row-wise and
column- wise,return the number of negative numbers in grid.

https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/description/
Code:
#include <stdio.h>
int countNegatives(int** grid, int gridSize, int* gridColSize) {
int count = 0;
int m = gridSize;
int n = *gridColSize;
int i = 0;
int j = n - 1;

while (i< m && j >= 0) {


if (grid[i][j] < 0) {
count += (m - i);
j--;
} else {
i++;
}
}
return count;
}
int main() {
int grid1[4][4] = {
{4, 3, 2, -1},
{3, 2, 1, -1},
{1, 1, -1, -2},
{-1, -1, -2, -3}
};
int* gridPtr1[4] = {grid1[0], grid1[1], grid1[2], grid1[3]};
int gridColSize1[4] = {4, 4, 4, 4};
int result1 = countNegatives(gridPtr1, 4, gridColSize1);
printf("Example 1: %d\n", result1);

int grid2[2][2] = {
{3, 2},
{1, 0}
};
int* gridPtr2[2] = {grid2[0], grid2[1]};
int gridColSize2[2] = {2, 2};
int result2 = countNegatives(gridPtr2, 2, gridColSize2);
printf("Example 2: %d\n", result2);

return 0;
}
Week-11
Prelab:
1. What is a structure in C, and how is it different from an
array? Ans:
It is a user defined type of data in C. It creates a collection of data types. One can use a structure
for grouping items of possibly varied types into a single one. It is a collection of varied items that get
stored at contiguous memory locations.

Key Structure Array


Definition Structure can be defined as a data On other hand Array is a type of
structure used as container which data structure used as container
can hold variables of different which can hold variables of same
types. type and do not support multiple
data type variables.
Memory Allocation Memory allocation for input data in While in case of array the input
structure does not necessary to be data stored in contiguous memory
in consecutive memory location. allocation which implies that array
stores data in such memory model
where it assigns consecutive
memory blocks (that is, memory
blocks having consecutive
addresses).
Accessibility In order to access the element in On other hand in case of Array we
Structure we require to have the can access the element by index.
name of that element i.e it is
mandatory to have element name
for its retrieval from Structure.
Pointer Structure do not have concept of On other hand in case of Array it
Pointer internally. internally implements Pointer
which always points to the first
element of Array.
Instantiation Structure object can be created after On other hand in case of Array we
declaration later in the program. can't create its object after
declaration.
DataType Structure supports multiple data- On other hand in case of Array we
type variables as input. can't have different data-type
variable as input as it only supports
same type data variables.
Performance
Structure due to use defined data On other hand in case of Array
type become slow in performance access and searching of element is
as access and searching of element faster and hence better in
is slower in Structure as compare to performance.
Array.
2. How do you declare a structure in C? Provide an
example. Ans:
Declaration of structure in C:
struct structure_name {
data_type member_name1;
data_type member_name2;
...
...
};
The struct keyword is used to start the declaration of a structure. The structure_name is the
name of the structure, and it can be any valid identifier. The data_type is the type of the data
member, and it can be any valid data type in C. The member_name is the name of the data
member, and it can also be any valid identifier.
Example:
#include <stdio.h>
struct student {
char *name;
int age;
int grade;
};
int main() {
struct student student1 = {"John Doe", 20, 10};
struct student student2 = {"Jane Doe", 18, 12};
printf("The name of student1 is %s\n", student1.name);
printf("The age of student1 is %d\n", student1.age);
printf("The grade of student1 is %d\n", student1.grade);
printf("The name of student2 is %s\n", student2.name);
printf("The age of student2 is %d\n", student2.age);
printf("The grade of student2 is %d\n", student2.grade);
return 0;
}
3. Explain the concept of nested structures. Give an example of a nested structure and how
you would access its members.
Ans:
Nested structures are structures that are declared inside other structures. This allows you
to group related data together in a way that is easy to access and manage.
For example, you could have a structure called employee that contains the employee's name,
age, and salary. You could then have a nested structure called address that contains the
employee's street address, city, state, and zip code. The address structure could be nested inside
the employee structure, so that the employee's address is always associated with the employee's
other data.
struct employee {
char *name;
int age;
int salary;
struct address {
char *street_address;
char *city;
char *state;
int zip_code;
};
};
4. How can you pass a structure to a function? Discuss both pass-by-value and pass-by-
reference methods.
Ans:
There are two ways to pass a structure to a function in C: pass-by-value and pass-by-reference.
Pass-by-value: In pass-by-value, a copy of the structure is passed to the function. This means that
any changes made to the structure inside the function will not affect the original structure.
struct employee {
char *name;
int age;
int salary;
};

void print_employee(struct employee employee) {


printf("The name of the employee is %s\n", employee.name);
printf("The age of the employee is %d\n", employee.age);
printf("The salary of the employee is %d\n", employee.salary);
}

int main() {
struct employee employee1 = {"John Doe", 20, 10000};
print_employee(employee1);

return 0;
}
Pass-by-reference:
In pass-by-reference, the address of the structure is passed to the function. This means that any
changes made to the structure inside the function will affect the original structure.
struct employee {
char *name;
int age;
int salary;
};
void print_employee(struct employee *employee) {
printf("The name of the employee is %s\n", employee->name);
printf("The age of the employee is %d\n", employee->age);
printf("The salary of the employee is %d\n", employee->salary);
}
int main() {
struct employee employee1 = {"John Doe", 20, 10000};
print_employee(&employee1);

return 0;
}
The method you use to pass a structure to a function depends on your specific needs. If you need
to make changes to the structure inside the function, then you should use pass-by-reference.
5. What are structure members and how do you access them? Provide an
example. Ans:
Structure is a collection of related data items. The data items in a structure are called members. Each
member has a name and a data type.
To access a member of a structure, you can use the dot operator. For example, if you have a structure
called employee with a member called name.
struct employee {
char *name;
int age;
int salary;
};

struct employee employee1 = {"John Doe", 20, 10000};


printf("The name of the employee is %s\n", employee1->name);
In-Lab
1. You are building a payroll system for a company with multiple departments. Design a
program using structures that stores employee details such as name, employee ID, and
salary. Implement an array of structures to store employee records for each
department. Calculate the total salary expenditure for each department and display it.
Additionally, identify the department with the highest salary expenditure and
acknowledge it as the top-performing department.
Code:
#include <stdio.h>
#include <stdlib.h>

#define MAX_DEPARTMENTS 10
#define MAX_EMPLOYEES 100

struct Employee {
char name[50];
int employeeID;
double salary;
};

struct Department {
char name[50];
int numEmployees;
struct Employee employees[MAX_EMPLOYEES];
double totalSalary;
};

int main() {
struct Department departments[MAX_DEPARTMENTS];
int numDepartments, i, j;
double highestExpenditure = 0;
int topDepartmentIndex = 0;

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


scanf("%d", &numDepartments);

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


printf("Enter the name of department %d: ", i+1);
scanf("%s", departments[i].name);

printf("Enter the number of employees in department %d: ", i+1);


scanf("%d", &departments[i].numEmployees);

departments[i].totalSalary = 0;

for (j = 0; j < departments[i].numEmployees; j++) {


printf("Enter the name, employee ID, and salary of employee %d: ", j+1);
scanf("%s %d %lf", departments[i].employees[j].name,
&departments[i].employees[j].employeeID, &departments[i].employees[j].salary);

departments[i].totalSalary += departments[i].employees[j].salary;
}

if (departments[i].totalSalary > highestExpenditure) {


highestExpenditure = departments[i].totalSalary;
topDepartmentIndex = i;
}
}

printf("\nDepartment-wise Salary Expenditure:\n");

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


printf("%s: %.2lf\n", departments[i].name, departments[i].totalSalary);
}

printf("\nTop-performing department: %s\n", departments[topDepartmentIndex].name);

return 0;
}

2. VGP logistics is a premium Cargo service for Sending/receiving parcels from


Vijayawada to Singapore. You are appointed as Manager in delivery department and
need to maintain the arrivaland delivery of the consignments sent/received. Create a
structure consignment with the followingmembers
Consignment_id, name, from, to, DOS (Date of Shipment), net_weight, Address.For
Example:
Consignment_id: 1008Name: Haier Steamer From: Vijayawada To:
Singapore DOS (Date of Shipment): 30-may-2023net_weight: 28.8 kg
Address: Mint Street Chennai
Code
:
#include <stdio.h>
#include <stdlib.h>

struct consignment {
int consignment_id;
char name[50];
char from[50];
char to[50];
char DOS[20];
float net_weight;
char address[100];
};

int main() {
int num_consignments;
printf("Enter the number of consignments: ");
scanf("%d", &num_consignments);

struct consignment consignments[num_consignments];


for(int i=0; i<num_consignments; i++) {
printf("\nEnter details for consignment %d:\n", i+1);
printf("Consignment ID: ");
scanf("%d", &consignments[i].consignment_id);
printf("Name: ");
scanf("%s", consignments[i].name);
printf("From: ");
scanf("%s", consignments[i].from);
printf("To: ");
scanf("%s", consignments[i].to);
printf("Date of Shipment (DD/MM/YYYY): ");
scanf("%s", consignments[i].DOS);
printf("Net Weight: ");
scanf("%f", &consignments[i].net_weight);
printf("Address: ");
scanf("%s", consignments[i].address);
}

printf("\n---Consignment Details---\n");
for(int i=0; i<num_consignments; i++) {
printf("\nConsignment %d:\n", i+1);
printf("Consignment ID: %d\n", consignments[i].consignment_id);
printf("Name: %s\n", consignments[i].name);
printf("From: %s\n", consignments[i].from);
printf("To: %s\n", consignments[i].to);
printf("Date of Shipment: %s\n", consignments[i].DOS);
printf("Net Weight: %.2f\n", consignments[i].net_weight);
printf("Address: %s\n", consignments[i].address);
}

return 0;
}
3. You have been assigned the task of developing a student grading system for a
prestigious college. Design a program using structures that stores student details, such as
name, roll number, and marks in various subjects. Implement an array of structures to
store multiple student records and calculatethe overall percentage for each student.
Additionally, provide a functionality to generate a grade for each student based on their
percentage and display it alongside their record.
Code:
#include <stdio.h>
#define MAX_STUDENTS 10

struct student {
char name[50];
int roll_number;
int marks[5];
float percentage;
char grade;
};

void calculate_percentage(struct student *s) {


int i;
int total_marks = 0;
for ( i = 0; i < 5; i++) {
total_marks += s->marks[i];
}
s->percentage = (float)total_marks / 500 * 100;
}

char get_grade(float percentage) {


if (percentage >= 90) {
return 'A';
} else if (percentage >= 80) {
return 'B';
} else if (percentage >= 70) {
return 'C';
} else if (percentage >= 60) {
return 'D';
} else {
return 'F';
}
}

int main() {
int i,j;
struct student students[MAX_STUDENTS];
int no_of_students = 0;

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


scanf("%d", &no_of_students);
for (i = 0; i < no_of_students; i++) {
printf("Enter student name: ");
scanf("%s", students[i].name);
printf("Enter student roll number: ");
scanf("%d", &students[i].roll_number);
printf("Enter student marks: ");
for (j = 0; j < 5; j++) {
scanf("%d", &students[i].marks[j]);
}
}

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


calculate_percentage(&students[i]);
students[i].grade = get_grade(students[i].percentage);
}

printf("Student details:\n");
for (i = 0; i < no_of_students; i++) {
printf("Name: %s\n", students[i].name);
printf("Roll number: %d\n", students[i].roll_number);
printf("Percentage: %.2f\n", students[i].percentage);
printf("Grade: %c\n", students[i].grade);
}

return 0;
}
Post-lab:
1. You are developing a soldier management system for an army unit. Each soldier's
record consistsof the following information: name, rank, and years of service. Implement
an array of structures to store the records of multiple soldiers. Write a C program to
calculate and display the averageyears of service for all soldiers in the unit.
Code:
#include <stdio.h>
struct soldier {
char name[100];
char rank[100];
int years_of_service;
};

int main() {
int num_soldiers, i;
struct soldier soldiers[100];

// Get the number of soldiers.


printf("Enter the number of soldiers: ");
scanf("%d", &num_soldiers);

// Get the information for each soldier.


for (i = 0; i < num_soldiers; i++) {
printf("Enter the name of soldier %d: ", i + 1);
scanf("%s", soldiers[i].name);
printf("Enter the rank of soldier %d: ", i + 1);
scanf("%s", soldiers[i].rank);
printf("Enter the years of service of soldier %d: ", i + 1);
scanf("%d", &soldiers[i].years_of_service);
}

// Calculate the average years of service.


int total_years_of_service = 0;
for (i = 0; i < num_soldiers; i++) {
total_years_of_service += soldiers[i].years_of_service;
}
float average_years_of_service = (float)total_years_of_service / num_soldiers;

// Display the average years of service.


printf("The average years of service is %.2f.\n", average_years_of_service);

return 0;
}
2. You are working on a ship management system for a naval fleet. Each ship's record
contains the following details: name, type (e.g., aircraft carrier, destroyer), and year of
commissioning. Implement an array of structures to store the ship records. Write a C
program to search for aspecific type of ship within the fleet and display the names of all
ships belonging to that type.
Code:

#include <stdio.h>
struct ship {
char name[100];
char type[100];
int year_of_commissioning;
};

int main() {
int num_ships, i, j;
struct ship ships[100];
char type_of_ship[100];

// Get the number of ships.


printf("Enter the number of ships: ");
scanf("%d", &num_ships);

// Get the information for each ship.


for (i = 0; i < num_ships; i++) {
printf("Enter the name of ship %d: ", i + 1);
scanf("%s", ships[i].name);
printf("Enter the type of ship %d: ", i + 1);
scanf("%s", ships[i].type);
printf("Enter the year of commissioning of ship %d: ", i + 1);
scanf("%d", &ships[i].year_of_commissioning);
}

// Get the type of ship to search for.


printf("Enter the type of ship to search for: ");
scanf("%s", type_of_ship);

// Search for the ships of the specified type.


for (i = 0; i < num_ships; i++) {
if (strcmp(ships[i].type, type_of_ship) == 0) {
printf("The name of ship %d is %s.\n", i + 1, ships[i].name);
}
}

return 0;
}
3. You have been assigned the task of developing a pilot roster system for an air force
squadron. Each pilot's record includes the following information: name, rank, and flight
hours. Implementan array of structures to store the pilot records. Write a C program to
find and display the pilotwith the highest number of flight hours in the squadron.
Code:

#include <stdio.h>
#include <string.h>

struct pilot {
char name[100];
char rank[100];
int flight_hours;
};

int main() {
int num_pilots, i, max_index;
struct pilot pilots[100];
int max_flight_hours = 0;

// Get the number of pilots.


printf("Enter the number of pilots: ");
scanf("%d", &num_pilots);

// Get the information for each pilot.


for (i = 0; i < num_pilots; i++) {
printf("Enter the name of pilot %d: ", i + 1);
scanf("%s", pilots[i].name);
printf("Enter the rank of pilot %d: ", i + 1);
scanf("%s", pilots[i].rank);
printf("Enter the flight hours of pilot %d: ", i + 1);
scanf("%d", &pilots[i].flight_hours);

// Update the maximum flight hours if necessary.


if (pilots[i].flight_hours > max_flight_hours) {
max_flight_hours = pilots[i].flight_hours;
max_index = i;
}
}

// Display the pilot with the highest number of flight hours.


printf("The pilot with the highest number of flight hours is %s.\n", pilots[max_index].name);

return 0;
}
Skill:
1. /*Solve the problem in the hacker Rank platform
https://www.hackerrank.com/challenges/c-tutorial-struct/problem
Code:
#include <stdio.h>
struct Student {
int age;
char first_name[50];
char last_name[50];
int standard;
};
int main() {
struct Student student;
scanf("%d", &student.age);
scanf("%s", student.first_name);
scanf("%s", student.last_name);
scanf("%d", &student.standard);

printf("%d %s %s %d\n", student.age, student.first_name, student.last_name,


student.standard);

return 0;
}*/ This program not allow you to submit in hackerrank, it accepts only C++ code

2. You are working on a reservation system for a luxurious hotel. Create a program using
structures that stores guest details, including name, room number, and check-in date.
Implement an array of structures to store multiple guest records and allow the hotel staff
to search for guests by either their room number or name. Provide an additional feature that
calculates the duration of each guest's stay and generates the total revenue earned by the
hotel.
Code:
#include <stdio.h>
#include <string.h>
#include <time.h>

struct Guest {
char name[50];
int room_number;
struct tm check_in_date;
};

int main() {
int i, n, total_revenue = 0;
char search_term[50];
struct Guest guests[100];

// Get the number of guests.


scanf("%d", &n);

// Read the guest details.


for (i = 0; i < n; i++) {
scanf("%s %d", guests[i].name, &guests[i].room_number);
scanf("%d/%d/%d", &guests[i].check_in_date.tm_year, &guests[i].check_in_date.tm_mon,
&guests[i].check_in_date.tm_mday);
}

// Menu driven program.


while (1) {
int choice;
printf("1. Search for guest\n2. Calculate duration of stay\n3. Generate total revenue\n4. Exit\n");
scanf("%d", &choice);

switch (choice) {
case 1:
// Search for guest by name or room number.
//char search_term[50];
scanf("%s", search_term);
for (i = 0; i < n; i++) {
if (strcmp(guests[i].name, search_term) == 0 || guests[i].room_number == atoi(search_term))
{
printf("%s %d %d/%d/%d\n", guests[i].name, guests[i].room_number,
guests[i].check_in_date.tm_year, guests[i].check_in_date.tm_mon,
guests[i].check_in_date.tm_mday);
}
}
break;
case 2:
// Calculate the duration of each guest's stay.
//int total_revenue = 0;
for (i = 0; i < n; i++) {
struct tm check_out_date;
int days_stayed;
char *end_of_month;
check_out_date = guests[i].check_in_date;
end_of_month = strchr(asctime(&check_out_date), '\n');
*end_of_month = '\0';
days_stayed = (int)difftime(mktime(&check_out_date), mktime(&guests[i].check_in_date));
total_revenue += days_stayed * 1000;
}
printf("Total revenue: %d\n", total_revenue);
break;
case 3:
// Generate the total revenue earned by the hotel.
break;
case 4:
// Exit.
return 0;
default:
printf("Invalid choice.\n");
}
}

return 0;
}

3. You have been tasked with developing a library management system for a renowned
library. Create a program using structures that stores book information, including title,
author, and publication year.Implement an array of structures to store multiple book
records and allow the librarian to search forbooks by either title or author's name. Enhance
the system by enabling the librarian to borrow andreturn books, updating the book status
accordingly.
Code:
#include <stdio.h>
#include <string.h>
struct Book {
char title[50];
char author[50];
int publication_year;
int status; // 0 - Available, 1 - Borrowed
};

int main() {
int i, n;
char search_term[50], book_title[50];
struct Book books[100];

// Get the number of books.


scanf("%d", &n);

// Read the book details.


for (i = 0; i < n; i++) {
scanf("%s %s %d", books[i].title, books[i].author, &books[i].publication_year);
books[i].status = 0; // Available by default
}

// Menu driven program.


while (1) {
int choice;
printf("1. Search for book\n2. Borrow book\n3. Return book\n4. Exit\n");
scanf("%d", &choice);

switch (choice) {
case 1:
// Search for book by title or author.
//char search_term[50];
scanf("%s", search_term);
for (i = 0; i < n; i++) {
if (strcmp(books[i].title, search_term) == 0 || strcmp(books[i].author, search_term) == 0) {
printf("%s %s %d %d\n", books[i].title, books[i].author, books[i].publication_year,
books[i].status);
}
}
break;
case 2:
// Borrow book.
//char book_title[50];
scanf("%s", book_title);
for (i = 0; i < n; i++) {
if (strcmp(books[i].title, book_title) == 0 && books[i].status == 0) {
books[i].status = 1; // Borrowed
printf("Book borrowed successfully.\n");
} else {
printf("Book not available.\n");
}
}
break;
case 3:
// Return book.
//char book_title[50];
scanf("%s", book_title);
for (i = 0; i < n; i++) {
if (strcmp(books[i].title, book_title) == 0 && books[i].status == 1) {
books[i].status = 0; // Available
printf("Book returned successfully.\n");
} else {
printf("Book not borrowed.\n");
}
}
break;
case 4:
// Exit.
return 0;
default:
printf("Invalid choice.\n");
}
}

return 0;
}
4. You have been assigned the task of creating a customer billing system using an array of
structures. Each structure should store the customer's name, account number, and total
amount due. Implement functions to add customer records, display all records, and find the
customer with the highest amount due.
Code:
#include <stdio.h>
#include <string.h>

struct customer {
char name[50];
int account_number;
int amount_due;
};

void add_customer(struct customer *customers, int *num_customers) {


struct customer new_customer;
printf("Enter customer name: ");
scanf("%s", new_customer.name);
printf("Enter customer account number: ");
scanf("%d", &new_customer.account_number);
printf("Enter customer amount due: ");
scanf("%d", &new_customer.amount_due);
customers[*num_customers] = new_customer;
(*num_customers)++;
}

void display_customers(struct customer *customers, int num_customers) {


for (int i = 0; i < num_customers; i++) {
printf("Customer name: %s\n", customers[i].name);
printf("Customer account number: %d\n", customers[i].account_number);
printf("Customer amount due: %d\n", customers[i].amount_due);
}
}

struct customer *find_customer_with_highest_amount_due(struct customer *customers, int


num_customers) {
struct customer *highest_amount_due_customer = NULL;
int highest_amount_due = 0;
for (int i = 0; i < num_customers; i++) {
if (customers[i].amount_due > highest_amount_due) {
highest_amount_due = customers[i].amount_due;
highest_amount_due_customer = &customers[i];
}
}
return highest_amount_due_customer;
}

int main() {
struct customer customers[100];
int num_customers = 0;

add_customer(customers, &num_customers);
add_customer(customers, &num_customers);
add_customer(customers, &num_customers);

display_customers(customers, num_customers);

struct customer *highest_amount_due_customer =


find_customer_with_highest_amount_due(customers, num_customers);
printf("Customer with the highest amount due: %s\n", highest_amount_due_customer->name);

return 0;
}

5. You are working on a car inventory management system using an array of structures.
Each structure should hold the details of a car, including the make, model, and year of
manufacture. Implementfunctions to add car records, display all records, and find the
newest car in the inventory.
Code:.
#include <stdio.h>
#include <string.h>

struct car {
char make[50];
char model[50];
int year;
};

void add_car(struct car *cars, int *num_cars) {


struct car new_car;
printf("Enter car make: ");
scanf("%s", new_car.make);
printf("Enter car model: ");
scanf("%s", new_car.model);
printf("Enter car year: ");
scanf("%d", &new_car.year);
cars[*num_cars] = new_car;
(*num_cars)++;
}

void display_cars(struct car *cars, int num_cars) {


for (int i = 0; i < num_cars; i++) {
printf("Car make: %s\n", cars[i].make);
printf("Car model: %s\n", cars[i].model);
printf("Car year: %d\n", cars[i].year);
}
}

struct car *find_newest_car(struct car *cars, int num_cars) {


struct car *newest_car = NULL;
int newest_year = 0;
for (int i = 0; i < num_cars; i++) {
if (cars[i].year > newest_year) {
newest_year = cars[i].year;
newest_car = &cars[i];
}
}
return newest_car;
}

int main() {
struct car cars[100];
int num_cars = 0;

add_car(cars, &num_cars);
add_car(cars, &num_cars);
add_car(cars, &num_cars);

display_cars(cars, num_cars);

struct car *newest_car = find_newest_car(cars, num_cars);


printf("Newest car: %s %s %d\n", newest_car->make, newest_car->model, newest_car->year);

return 0;
}

6. You are developing a product inventory management system for a retail store. Each
product has aunique identifier, name, price, and quantity in stock. Implement an array of
structures to store the product records. Create functions to add new products, update
product details, display all products,and search for products based on their identifier or
name.
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct product {
char identifier[50];
char name[50];
int price;
int quantity;
};

void add_product(struct product *products, int *num_products) {


struct product new_product;
printf("Enter product identifier: ");
scanf("%s", new_product.identifier);
printf("Enter product name: ");
scanf("%s", new_product.name);
printf("Enter product price: ");
scanf("%d", &new_product.price);
printf("Enter product quantity: ");
scanf("%d", &new_product.quantity);
products[*num_products] = new_product;
(*num_products)++;

void display_products(struct product *products, int num_products) {


printf("No. of Products=%d\n",num_products);
for (int i = 0; i < num_products; i++) {
printf("Product identifier: %s\t", products[i].identifier);
printf("Product name: %s\t", products[i].name);
printf("Product price: %d\t", products[i].price);
printf("Product quantity: %d\n", products[i].quantity);
}
}

struct product *find_product(struct product *products, int num_products) {


char identifier[100];
printf("Enter product identifier to search=");
scanf("%s",identifier);
struct product *found_product = NULL;
for (int i = 0; i < num_products; i++) {

if (strcmp(products[i].identifier, identifier) == 0) {
found_product = &products[i];
break;
}
}
return found_product;
}

int main() {
struct product products[100];
struct product *found_product;
int num_products = 0, i, ch;

while(1)
{
printf("MENU \n 1.Add Product \t 2. Display Products \t 3. Search Product 4. Exit\n");
printf("Enter your choice=");
scanf("%d",&ch);
switch(ch)
{
case 1:
add_product(products, &num_products);
break;
case 2:
display_products(products, num_products);
break;
case 3:
found_product = find_product(products, num_products);
if (found_product != NULL)
printf("Found product: %s %s %d %d\n", found_product->identifier, found_product-
>name, found_product->price, found_product->quantity);
else
printf("Product not found.\n");
break;
case 4:
exit(1);
}
}
return 0;
}

#include <stdio.h>
#include <string.h>
struct Customer {
char name[50];
int account_number;
int amount_due;
};

int main() {
int i, n;
char customer_name[50];
int max_amount_due = 0;
int customer_index = 0;
int customer_account_number;
int customer_amount_due;
struct Customer customers[100];
scanf("%d", &n);

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


scanf("%s %d %d", customers[i].name, &customers[i].account_number,
&customers[i].amount_due);
}

while (1) {
int choice;
printf("1. Add customer record\n2. Display all records\n3. Find customer with highest amount
due\n4. Exit\n");
scanf("%d", &choice);

switch (choice) {
case 1:
// Add customer record.
char customer_name[50];
int customer_account_number;
int customer_amount_due;
scanf("%s %d %d", customer_name, &customer_account_number, &customer_amount_due);
//customers[n] = {customer_name, customer_account_number, customer_amount_due};
n++;
break;
case 2:
for (i = 0; i < n; i++)
{
printf("%s %d %d\n", customers[i].name, customers[i].account_number,
customers[i].amount_due);
}
break;
case 3:
int max_amount_due = 0;
int customer_index = 0;
for (i = 0; i < n; i++) {
if (customers[i].amount_due > max_amount_due) {
max_amount_due = customers[i].amount_due;
customer_index = i;
}
}
printf("Customer with highest amount due: %s %d %d\n", customers[customer_index].name,
customers[customer_index].account_number, customers[customer_index].amount_due);
break;
case 4:
// Exit.
return 0;
default:
printf("Invalid choice.\n");
}
}

return 0;
}
Week-12
Prelab:
1. How do you implement a stack using an array in
C? Ans:
I. Declare a global variable to store the top of the stack. This variable will be used to keep
track of the index of the top element in the stack.
II. Declare an array to store the elements of the stack. The size of the array must be specified
beforehand.
III. Write the functions to push and pop elements from the stack. The push function should
increment the top of the stack and store the new element at the updated index. The pop
function should decrement the top of the stack and return the element at the updated index.
IV. Write the function to check if the stack is empty. This function should simply check if the
top of the stack is equal to -1.
V. Write the function to check if the stack is full. This function should simply check if the top
of the stack is equal to the size of the array.
2. What are the common applications of stacks in real-world scenarios? Provide a few examples.
A Stack can be used for evaluating expressions consisting of operands and operators. Stacks
can be used for Backtracking, i.e., to check parenthesis matching in an expression. It can also be
used to convert one form of expression to another form. It can be used for systematic Memory
Management.
a. Evaluation of Arithmetic Expressions.
b. Backtracking.
c. Delimiter Checking.
d. Reverse a Data.
e. Processing Function Calls.
3. What is a queue, and how does it
work? Ans:
Queue is a data structure designed to operate in FIFO (First in First out) context. In queue
elements are inserted from rear end and get removed from front end. Queue class is container
adapter. Container is an objects that hold data of same type. Queue can be created from different
sequence containers.
4. Explain the applications of queues in real-world scenarios. Provide a few
examples. Ans:
a. CPU scheduling- to keep track of processes for the CPU
b. Handling website traffic - by implementing a virtual HTTP request queue
c. Printer Spooling - to store print jobs
d. In routers - to control how network packets are transmitted or discarded
e. Traffic management - traffic signals use queues to manage intersections
5. Explain the concept of stack overflow and stack underflow. How can these situations
be handled?
Ans:
Stack Overflow: A stack overflow error can occur in a computer program due to excessive
memory usage. This excessive memory usage occurs on the call stack, which is where
information is stored relating to the active subroutines in the program. The call stack has a
limited amount of memory available to it.
Stack underflow: When a stack is empty (i.e. TOP= -1) and we try to delete more element from
it, then this condition is called underflow condition.
In-Lab
1. Design a stack that supports push, pop, top, and retrieving the minimum
element in constant time.Implement the MinStack class:
MinStack() initializes the stack object.
void push(int val) pushes the element val onto the
stack. void pop() removes the element on the top of
the stack. int top() gets the top element of the stack.
int getMin() retrieves the minimum element in the stack.
You must implement a solution with O(1) time complexity for each
function. https://leetcode.com/problems/min-stack/
Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int val;
int min;
} Element;

typedef struct {
Element* stack;
int top;
int capacity;
} MinStack;

MinStack* minStackCreate() {
MinStack* stack = (MinStack*)malloc(sizeof(MinStack));
stack->stack = (Element*)malloc(10000 * sizeof(Element));
stack->top = -1;
stack->capacity = 10000;
return stack;
}

void minStackPush(MinStack* obj, int val) {


if (obj->top == obj->capacity - 1)
return;

Element element;
element.val = val;

if (obj->top == -1 || val< obj->stack[obj->top].min)


element.min = val;
else
element.min = obj->stack[obj->top].min;

obj->stack[++obj->top] = element;
}
void minStackPop(MinStack* obj) {
if (obj->top == -1)
return;

obj->top--;
}

int minStackTop(MinStack* obj) {


if (obj->top == -1)
return -1;

return obj->stack[obj->top].val;
}

int minStackGetMin(MinStack* obj) {


if (obj->top == -1)
return -1;

return obj->stack[obj->top].min;
}

void minStackFree(MinStack* obj) {


free(obj->stack);
free(obj);
}

int main() {
MinStack* minStack = minStackCreate();
minStackPush(minStack, -2);
minStackPush(minStack, 0);
minStackPush(minStack, -3);
printf("%d\n", minStackGetMin(minStack)); // Returns -3
minStackPop(minStack);
printf("%d\n", minStackTop(minStack)); // Returns 0
printf("%d\n", minStackGetMin(minStack)); // Returns -2
minStackFree(minStack);
return 0;
}
2. The next greater element of some element x in an array is the first greater element that
is to the rightof x in the same array.
You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a
subset of nums2.
For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine
the nextgreater element of nums2[j] in nums2. If there is no next greater element, then the
answer for this query is -1.
Return an array ans of length nums1.length such that ans[i] is the next greater element as describedabove.
https://leetcode.com/problems/next-greater-element-i/
Code:
#include <stdio.h>
#include <stdlib.h>

int* nextGreaterElement(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize) {
int* result = (int*)malloc(nums1Size * sizeof(int));
int* stack = (int*)malloc(nums2Size * sizeof(int));
int top = -1;
int i, j;

// Create a mapping of each element in nums2 to its next greater element


int* nextGreater = (int*)malloc(nums2Size * sizeof(int));
for (i = 0; i< nums2Size; i++) {
nextGreater[i] = -1; // Initialize with -1
}

// Use a stack to find the next greater element for each element in nums2
for (i = 0; i< nums2Size; i++) {
while (top != -1 && nums2[i] > nums2[stack[top]]) {
nextGreater[stack[top]] = nums2[i];
top--;
}
stack[++top] = i;
}

// Find the next greater element for each element in nums1


for (i = 0; i< nums1Size; i++) {
result[i] = -1; // Initialize with -1
for (j = 0; j < nums2Size; j++) {
if (nums1[i] == nums2[j]) {
result[i] = nextGreater[j];
break;
}
}
}

free(stack);
free(nextGreater);
*returnSize = nums1Size;
return result;
}

int main() {
int nums1[] = {4, 1, 2};
int nums2[] = {1, 3, 4, 2};
int nums1Size = sizeof(nums1) / sizeof(nums1[0]);
int nums2Size = sizeof(nums2) / sizeof(nums2[0]);

int returnSize;
int* result = nextGreaterElement(nums1, nums1Size, nums2, nums2Size, &returnSize);

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

free(result);
return 0;
}
3. You are keeping the scores for a baseball game with strange rules. At the beginning of
the game, youstart with an empty record.
You are given a list of strings operations, where operations[i] is the ith operation you must apply
to therecord and is one of the following:
An integer x.
Record a new score
of x.'+'.
Record a new score that is the sum of the previous
two scores.'D'.
Record a new score that is the double of the previous
score. 'C'.
Invalidate the previous score, removing it from the record.
Return the sum of all the scores on the record after applying all the operations.
The test cases are generated such that the answer and all intermediate calculations fit in a 32-bit
integerand that all operations are valid.
https://leetcode.com/problems/baseball-game/
Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int calPoints(char **operations, int operationsSize) {


int *stack = (int *)malloc(operationsSize * sizeof(int));
int top = -1;
int score = 0;

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


char *op = operations[i];
if (strcmp(op, "+") == 0) {
stack[top + 1] = stack[top] + stack[top - 1];
score += stack[top + 1];
top++;
} else if (strcmp(op, "D") == 0) {
stack[top + 1] = stack[top] * 2;
score += stack[top + 1];
top++;
} else if (strcmp(op, "C") == 0) {
score -= stack[top];
top--;
} else {
stack[top + 1] = atoi(op);
score += stack[top + 1];
top++;
}
}

free(stack);
return score;
}

int main() {
char *ops1[] = {"5", "2", "C", "D", "+"};
int opsSize1 = sizeof(ops1) / sizeof(ops1[0]);
int result1 = calPoints(ops1, opsSize1);
printf("Result 1: %d\n", result1);

char *ops2[] = {"5", "-2", "4", "C", "D", "9", "+", "+"};
int opsSize2 = sizeof(ops2) / sizeof(ops2[0]);
int result2 = calPoints(ops2, opsSize2);
printf("Result 2: %d\n", result2);

char *ops3[] = {"1", "C"};


int opsSize3 = sizeof(ops3) / sizeof(ops3[0]);
int result3 = calPoints(ops3, opsSize3);
printf("Result 3: %d\n", result3);

return 0;
}
Post-lab:
1. You are a software developer working on a program that involves implementing stack
data structure in C. The program should allow users to input numeric values into the
stack and remove the number with the minimum value from the stack. The minimum
value removal functionality will be implemented as part of the program.

#include <stdio.h>
#include <stdlib.h>
#include
<stdbool.h>

typedef struct Node


{ int data;
struct Node* next;
} Node;

typedef struct Stack


{ Node* top;
Node* minTop;
} Stack;

// Function to create an empty


stack Stack* createStack() {
Stack* stack =
(Stack*)malloc(sizeof(Stack)); stack->top =
NULL;
stack->minTop = NULL;
return stack;
}

// Function to check if the stack is


empty bool isEmpty(Stack* stack) {
return (stack->top == NULL);
}

// Function to push an element onto the


stack void push(Stack* stack, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = stack->top;
stack->top = newNode;

if (stack->minTop == NULL || data <= stack->minTop->data) {


Node* newMinNode = (Node*)malloc(sizeof(Node));
newMinNode->data = data;
newMinNode->next = stack-
>minTop;
stack->minTop = newMinNode;
}
}
// Function to pop an element from the
stack int pop(Stack* stack) {
if (isEmpty(stack)) {
printf("Stack underflow!\n");
return -1;
}

Node* temp = stack->top;


int poppedData = temp-
>data; stack->top = temp-
>next;

if (poppedData == stack->minTop->data)
{ Node* minTemp = stack->minTop;
stack->minTop = minTemp->next;
free(minTemp);
}

free(temp);
return poppedData;
}

// Function to get the minimum value in the


stack int getMinimum(Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty!\
n");
return -1;
}

return stack->minTop->data;
}

int main() {
Stack* stack = createStack();

// Pushing elements into the


stack push(stack, 5);
push(stack, 3);
push(stack, 8);
push(stack, 2);
push(stack, 6);

// Getting the minimum value in the


stack int minVal = getMinimum(stack);
printf("Minimum value in the stack: %d\n", minVal);

// Removing the number with the minimum value from the


stack int removedVal = pop(stack);
printf("Removed value: %d\n", removedVal);
// Getting the new minimum value in the
stack minVal = getMinimum(stack);
printf("Minimum value in the stack after removal: %d\n", minVal);

return 0;
}

2. You are a software developer working on a program that needs to find the next greater
element for each element in a given array. The next greater element for an element 'x' is the
first element on the right side of 'x' which is greater than 'x'. To efficiently solve this
problem, you decide to implement a stack-based approach.

#include <stdio.h>
#include <stdlib.h>

typedef struct {
int value;
int index;
} Element;

typedef struct {
Element* array;
int top;
int capacity;
} Stack;

Stack* createStack(int capacity) {


Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->array = (Element*)malloc(capacity * sizeof(Element));
stack->top = -1;
stack->capacity = capacity;
return stack;
}

void push(Stack* stack, Element element)


{ stack->array[++stack->top] = element;
}

Element pop(Stack* stack) {


return stack->array[stack->top--];
}

Element top(Stack* stack) {


return stack->array[stack->top];
}

int isEmpty(Stack* stack)


{ return stack->top == -
1;
}

void findNextGreater(int arr[], int n) {


Stack* stack = createStack(n);
Element nextGreater[n];

// Traverse the array from right to left


for (int i = n - 1; i>= 0; i--) {
// Pop elements from stack smaller than or equal to
arr[i] while (!isEmpty(stack) && top(stack).value <=
arr[i]) {
pop(stack);
}

if (isEmpty(stack)) {
// No greater element found
nextGreater[i].value = -1;
nextGreater[i].index = i;
} else {
// Found the next greater element
nextGreater[i] = top(stack);
}

Element currElement;
currElement.value = arr[i];
currElement.index = i;
push(stack, currElement);
}

// Print the next greater


elements for (int i = 0; i< n; i+
+) {
if (nextGreater[i].value != -1) {
printf("Next greater element for %d at index %d is %d at index %d\n", arr[i], i,
nextGreater[i].value, nextGreater[i].index);
} else {
printf("Next greater element for %d at index %d does not exist\n", arr[i], i);
}
}

free(stack->array);
free(stack);
}

int main() {
int arr[] = {4, 6, 3, 2, 8, 1, 9, 5};
int n = sizeof(arr) / sizeof(arr[0]);

findNextGreater(arr, n);

return 0;
}
3. You are a software developer working on a program that needs to calculate the average value
of the elements stored in a stack. The program should take a stack as input, traverse
through its elements, and calculate the average value. To accomplish this, you decide to
implement a C program using a stack data structure.

#include <stdio.h>
#include <stdlib.h>

typedef struct Node {


int data;
struct Node* next;
} Node;

typedef struct Stack {


Node* top;
} Stack;

Stack* createStack() {
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->top = NULL;
return stack;
}

int isEmpty(Stack* stack) {


return (stack->top == NULL);
}

void push(Stack* stack, int data) {


Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = stack->top;
stack->top = newNode;
}

int pop(Stack* stack) {


if (isEmpty(stack)) {
printf("Stack underflow!\n");
return -1;
}

Node* temp = stack->top;


int poppedData = temp->data;
stack->top = temp->next;
free(temp);
return poppedData;
}

float calculateAverage(Stack* stack) {


if (isEmpty(stack)) {
printf("Stack is empty!\n");
return 0;
}

int sum = 0;
int count = 0;
Node* current = stack->top;

while (current != NULL) {


sum += current->data;
count++;
current = current->next;
}

return (float)sum / count;


}

int main() {
Stack* stack = createStack();

// Pushing elements into the stack


push(stack, 5);
push(stack, 3);
push(stack, 8);
push(stack, 2);
push(stack, 6);

// Calculating the average value


float average = calculateAverage(stack);
printf("Average value of elements in the stack: %.2f\n", average);

return 0;
}
Skill:

1. In the ancient kingdom of Ayodhya, Prince Rama prepares for his wedding by attempting
to string the mighty Shiva Dhanush bow. To solve the puzzle guarding the bow, he seeks the
help of Hanuman, who implements a C program using a stack. The program accepts
numeric clues and helps Rama track the top element of the stack and find the kth element
from the top. With the aid of the stack program, Rama successfully solves the puzzle,
unlocks the door, strings the bow, and wins Princess Sita's hand in marriage. This scenario
blends elements from the Ramayana with the concept of a stack-based program to provide
an imaginative context for the task.
Code:

#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
// Stack structure
typedef struct {
int top;
int data[MAX_SIZE];
} Stack;

// Function to initialize the stack


void initialize(Stack *stack) {
stack->top = -1;
}

// Function to check if the stack is empty


int isEmpty(Stack *stack) {
return (stack->top == -1);
}

// Function to check if the stack is full


int isFull(Stack *stack) {
return (stack->top == MAX_SIZE - 1);
}

// Function to push an element onto the stack


void push(Stack *stack, int element) {
if (isFull(stack)) {
printf("Stack overflow!\n");
exit(1);
}
stack->data[++stack->top] = element;
}

// Function to pop an element from the stack


int pop(Stack *stack) {
if (isEmpty(stack)) {
printf("Stack underflow!\n");
exit(1);
}
return stack->data[stack->top--];
}

// Function to get the top element of the stack


int getTop(Stack *stack) {
if (isEmpty(stack)) {
printf("Stack is empty!\n");
exit(1);
}
return stack->data[stack->top];
}

// Function to get the kth element from the top of the stack
int getKthFromTop(Stack *stack, int k) {
if (isEmpty(stack) || k <= 0 || k > stack->top + 1) {
printf("Invalid kth element!\n");
exit(1);
}
return stack->data[stack->top - k + 1];
}

int main() {
Stack stack;
initialize(&stack);

// Reading numeric clues


int clue;
while (scanf("%d", &clue) != 'EOF') {
push(&stack, clue);
}

// Finding the top element of the stack


int topElement = getTop(&stack);
printf("Top element of the stack: %d\n", topElement);

// Finding the kth element from the top of the stack


int k;
printf("Enter the value of k: ");
scanf("%d", &k);
int kthElement = getKthFromTop(&stack, k);
printf("%dth element from the top of the stack: %d\n", k, kthElement);

return 0;
}
1. YouaregivenastackofNintegerssuchthatthefirstelementrepresentsthetopofthestackandthelast
element represents the bottom of the stack. You need to pop at least one element from
thestack. At any one moment, you can convert stack into a queue. The bottom of the stack
representsthe front of the queue. You cannot convert the queue back into a stack. Your task
is to removeexactlyKelementssuchthatthesumoftheKremovedelementsismaximised.
https://www.hackerearth.com/practice/data-structures/stacks/basics-of-stacks/practice-
problems/algorithm/staque-1-e790a29f/
Code:
2. Solve the problem in the hackerrank platform
https://www.hackerrank.com/challenges/queue-using-two-stacks/problem
Code:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

#define MAX_SIZE 100000

typedef struct {
int data[MAX_SIZE];
int top;
} Stack;

void initialize(Stack *stack) {


stack->top = -1;
}

int isEmpty(Stack *stack) {


return stack->top == -1;
}

int isFull(Stack *stack) {


return stack->top == MAX_SIZE - 1;
}

void push(Stack *stack, int value) {


if (isFull(stack)) {
printf("Stack overflow\n");
return;
}
stack->data[++stack->top] = value;
}

int pop(Stack *stack) {


if (isEmpty(stack)) {
printf("Stack underflow\n");
return -1;
}
return stack->data[stack->top--];
}
int peek(Stack *stack) {
if (isEmpty(stack)) {
printf("Stack is empty\n");
return -1;
}
return stack->data[stack->top];
}

typedef struct {
Stack s1; // For enqueue operation
Stack s2; // For dequeue operation
} Queue;

void initializeQueue(Queue *queue) {


initialize(&(queue->s1));
initialize(&(queue->s2));
}

void enqueue(Queue *queue, int value) {


push(&(queue->s1), value);
}

void dequeue(Queue *queue) {


if (isEmpty(&(queue->s2))) {
while (!isEmpty(&(queue->s1)))
{ int value = pop(&(queue-
>s1)); push(&(queue->s2),
value);
}
}
pop(&(queue->s2));
}

int front(Queue *queue) {


if (isEmpty(&(queue->s2))) {
while (!isEmpty(&(queue->s1)))
{ int value = pop(&(queue-
>s1)); push(&(queue->s2),
value);
}
}
return peek(&(queue->s2));
}

int main() {
int numQueries;
scanf("%d", &numQueries);

Queue queue;
initializeQueue(&queue);

while (numQueries-- > 0) {


int queryType, value;
scanf("%d", &queryType);
switch (queryType) {
case 1:
scanf("%d", &value);
enqueue(&queue, value);
break;
case 2:
dequeue(&queue);
break;
case 3:
printf("%d\n", front(&queue));
break;
default:
printf("Invalid query type\n");
break;
}
}

return 0;
}
3. The school cafeteria offers circular and square sandwiches at lunch break, referred to
by numbers 0 and 1 respectively. All students stand in a queue. Each student either
prefers square or circular sandwiches.
The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches
are placed in a stack. At each step:
If the student at the front of the queue prefers the sandwich on the top of the stack, they will
take it andleave the queue.
Otherwise, they will leave it and go to the queue's end.
This continues until none of the queue students want to take the top sandwich and are thus
unable toeat.
You are given two integer arrays students and sandwiches where sandwiches[i] is the type of
the ith sandwich in the stack (i = 0 is the top of the stack) and students[j] is the preference of
the jth student inthe initial queue (j = 0 is the front of the queue). Return the number of
students that are unable to eat
https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/
Code:
#include <stdio.h>
int countStudents(int* students, int studentsSize, int* sandwiches, int sandwichesSize) {
int count[2] = {0}; // Count of students preferring each type of sandwich

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


count[students[i]]++; // Count the number of students preferring each type
}

int unableToEat = studentsSize; // Initialize the count of students unable to eat

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


if (count[sandwiches[i]] > 0) {
count[sandwiches[i]]--; // A student took the sandwich they prefer
unableToEat--; // Decrease the count of students unable to eat
} else {
break; // No more students can eat sandwiches, stop the simulation
}
}

return unableToEat;
}

int main() {
int students[] = {1, 1, 0, 0};
int sandwiches[] = {0, 1, 0, 1};
int studentsSize = sizeof(students) / sizeof(students[0]);
int sandwichesSize = sizeof(sandwiches) / sizeof(sandwiches[0]);

int unableToEat = countStudents(students, studentsSize, sandwiches, sandwichesSize);


printf("Number of students unable to eat: %d\n", unableToEat);
return 0;
}
4. You are given an integer array prices where prices[i] is the price of the ith item in a shop.
There is a special discount for items in the shop. If you buy the ith item, then you will receive a
discount equivalent to prices[j] where j is the minimum index such that j > i and prices[j] <=
prices[i].Otherwise, you will not receive any discount at all.
Return an integer array answer where answer[i] is the final price you will pay for the ith item of theshop,
considering the special discount.
https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop/
Code:
#include <stdio.h>
#include <stdlib.h>

int* finalPrices(int* prices, int pricesSize, int* returnSize) {


int* finalPrices = (int*)malloc(pricesSize * sizeof(int)); // Allocate memory for the final prices
int* stack = (int*)malloc(pricesSize * sizeof(int)); // Stack to store indices
int top = -1; // Top of the stack

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


while (top >= 0 && prices[i] <= prices[stack[top]]) {
finalPrices[stack[top]] = prices[stack[top]] - prices[i]; // Apply the discount
top--; // Pop from the stack
}

top++; // Push the current index to the stack


stack[top] = i;
}

// Set the final prices for the remaining indices in the stack
while (top >= 0) {
finalPrices[stack[top]] = prices[stack[top]];
top--;
}

*returnSize = pricesSize; // Set the return size


free(stack); // Free the stack memory
return finalPrices;
}

int main() {
int prices[] = {8, 4, 6, 2, 3};
int pricesSize = sizeof(prices) / sizeof(prices[0]);

int returnSize;
int* result = finalPrices(prices, pricesSize, &returnSize);
printf("Final prices: ");
for (int i = 0; i<returnSize; i++) {
printf("%d ", result[i]);
}
printf("\n");

free(result); // Free the memory allocated for the result

return 0;
}

5. A and B are playing a game. In this game, both of them are initially provided with a list
of Nnumbers. (Both have the same list but their own copy). Now, they both have a
different strategy to play the game. A picks the element from start of his list. B picks from
the end of his list.
https://www.hackerearth.com/practice/data-structures/stacks/basics-of-stacks/practice-
problems/algorithm/fun-game-91510e9f/
Code:
Week-13
Prelab:
1. What is linked list, and how is it different from an array or a
structure? Ans:
It is a linear collection of data elements whose order is not given by their physical placement in
memory. Instead, each element points to the next. It is a data structure consisting of a collection of
nodes which together represent a sequence. An array is a grouping of data elements of equivalent
data type. A linked list is a group of entities called a node. The node includes two segments: data
and address.
2. How do you define and declare a linked list node in C? Provide an
example. Ans:
A node is a struct with at least a data field and a reference to a node of the same type. A node
is called a self-referential object, since it contains a pointer to a variable that refers to a variable of the
same type.
1. Declare head pointer and make it as NULL. struct node { int data; struct node *next; }; struct node
*head = NULL;
2. Create a new node. ...
3. If the head node is NULL, make the new node as head. ...
4. Otherwise, find the last node and set last node => new node.
3. How do you insert a new node at the beginning of a linked list?Explain with code.
Ans:
1. Declare a head pointer and make it as NULL.
2. Create a new node with the given data.
3. Make the new node points to the head node.
4. Finally, make the new node as the head node.
4. How do you delete a specific node from a linked list? Explain with code.
Ans:
To delete a node from the linked list, we need to do the following steps:
1. Find the previous node of the node to be deleted.
2. Change the next of the previous node.
3. Free memory for the node to be deleted.
5. How do you insert a new node at the end of a linked list in a specific
position? Ans:
Steps to Insert node at any position in linked list in C:-
1. Traverse the Linked List till the nth node.
2. Allocate the data and memory for the new node.
3. Assign the next pointer of the specific nth position node to this new node.
4. Assign the next pointer of this newNode to (n+1)th node (Nth node's next)

In-Lab
1. solve the problem in the hackerrank platform
https://www.hackerrank.com/challenges/30-linked-list/problem
Code:
#include <stdlib.h>
#include <stdio.h>
typedef struct Node
{
int data;
struct Node* next;
}Node;

Node* insert(Node *head,int data) {


Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;

if (head == NULL) {
head = newNode;
} else {
Node *current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}

return head;
}

void display(Node *head)


{
Node *start=head;
while(start)
{
printf("%d ",start->data);
start=start->next;
}
}
int main()
{
int T,data;
scanf("%d",&T);
Node *head=NULL;
while(T-->0){
scanf("%d",&data);
head=insert(head,data);
}
display(head);

}
2. solve the problem in the hackerrank platform
https://www.hackerrank.com/challenges/30-linked-list-deletion/problem
Code:
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

typedef struct Node


{
int data;
struct Node* next;
}Node;

Node* removeDuplicates(Node *head){


//Write your code here
if (head == NULL || head->next == NULL) {
return head;
}

Node *current = head;


while (current->next != NULL) {
if (current->data == current->next->data) {
Node *temp = current->next;
current->next = current->next->next;
free(temp);
} else {
current = current->next;
}
}

return head;
}

Node* insert(Node *head,int data)


{
Node *p = (Node*)malloc(sizeof(Node));
p->data = data;
p->next=NULL;

if(head==NULL){
head=p;

}
else if(head->next==NULL)
{
head->next=p;

}
else{
Node *start=head;
while(start->next!=NULL)
start=start->next;

start->next=p;

}
return head;
}
void display(Node *head)
{
Node *start=head;
while(start)
{
printf("%d ",start->data);
start=start->next;
}
}
int main()
{
int T,data;
scanf("%d",&T);
Node *head=NULL;
while(T-->0){
scanf("%d",&data);
head=insert(head,data);
}
head=removeDuplicates(head);
display(head);

}
3. Given the head of a sorted linked list, delete all duplicates such that each element appears
only once. Return the linked list sorted as well.

Input: head =
[1,1,2] Output:[1,2]
https://leetcode.com/problems/remove-duplicates-from-sorted-list/
Code:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
structListNode* deleteDuplicates(structListNode* head){
if (head == NULL || head->next == NULL) {
return head;
}
structListNode* current = head;
while (current->next != NULL) {
if (current->val == current->next->val) {
structListNode* duplicate = current->next;
current->next = duplicate->next;
free(duplicate);
} else {
current = current->next;
}
}
return head;
}
4. Given the head of a linked list and an integer val, remove all the nodes of the linked list that
has Node.val == val, and return the new head.

Input:head=[1,2,6,3,4,5,6],val=6 Output:
[1,2,3,4,5]
https://leetcode.com/problems/remove-linked-list-elements/
Code:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
structListNode* removeElements(structListNode* head, intval){
if (head == NULL) {
return head;
}

while (head != NULL&&head->val == val) {


structListNode* temp = head;
head = head->next;
free(temp);
}

structListNode* current = head;


while (current != NULL&&current->next != NULL) {
if (current->next->val == val) {
structListNode* temp = current->next;
current->next = temp->next;
free(temp);
} else {
current = current->next;
}
}

return head;
}
Post-lab:
1. Solve the problem in the hackerrank platform
https://www.hackerrank.com/challenges/compare-two-linked-lists/problem
Code:
#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* readline();

typedef struct SinglyLinkedListNode SinglyLinkedListNode;


typedef struct SinglyLinkedList SinglyLinkedList;

struct SinglyLinkedListNode {
int data;
SinglyLinkedListNode* next;
};

struct SinglyLinkedList {
SinglyLinkedListNode* head;
SinglyLinkedListNode* tail;
};

SinglyLinkedListNode* create_singly_linked_list_node(int node_data) {


SinglyLinkedListNode* node = malloc(sizeof(SinglyLinkedListNode));

node->data = node_data;
node->next = NULL;

return node;
}

void insert_node_into_singly_linked_list(SinglyLinkedList** singly_linked_list, int node_data) {


SinglyLinkedListNode* node = create_singly_linked_list_node(node_data);

if (!(*singly_linked_list)->head) {
(*singly_linked_list)->head = node;
} else {
(*singly_linked_list)->tail->next = node;
}

(*singly_linked_list)->tail = node;
}

void print_singly_linked_list(SinglyLinkedListNode* node, char* sep, FILE* fptr) {


while (node) {
fprintf(fptr, "%d", node->data);

node = node->next;

if (node) {
fprintf(fptr, "%s", sep);
}
}
}

void free_singly_linked_list(SinglyLinkedListNode* node) {


while (node) {
SinglyLinkedListNode* temp = node;
node = node->next;

free(temp);
}
}

// Complete the compare_lists function below.

/*
* For your reference:
*
* SinglyLinkedListNode {
* int data;
* SinglyLinkedListNode* next;
* };
*
*/
bool compare_lists(SinglyLinkedListNode* head1, SinglyLinkedListNode* head2) {
SinglyLinkedListNode* curr1 = head1;
SinglyLinkedListNode* curr2 = head2;

while (curr1 && curr2) {


if (curr1->data != curr2->data) {
return 0; // Unequal data
}

curr1 = curr1->next;
curr2 = curr2->next;
}

// If both lists are of the same length, return 1; otherwise, return 0.


return (curr1 == NULL && curr2 == NULL) ? 1 : 0;
}

int main()
{
FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");

char* tests_endptr;
char* tests_str = readline();
int tests = strtol(tests_str, &tests_endptr, 10);

if (tests_endptr == tests_str || *tests_endptr != '\0') { exit(EXIT_FAILURE); }

for (int tests_itr = 0; tests_itr < tests; tests_itr++) {


SinglyLinkedList* llist1 = malloc(sizeof(SinglyLinkedList));
llist1->head = NULL;
llist1->tail = NULL;

char* llist1_count_endptr;
char* llist1_count_str = readline();
int llist1_count = strtol(llist1_count_str, &llist1_count_endptr, 10);

if (llist1_count_endptr == llist1_count_str || *llist1_count_endptr != '\0') { exit(EXIT_FAILUR


E); }

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


char* llist1_item_endptr;
char* llist1_item_str = readline();
int llist1_item = strtol(llist1_item_str, &llist1_item_endptr, 10);

if (llist1_item_endptr == llist1_item_str || *llist1_item_endptr != '\0') { exit(EXIT_FAILURE


); }

insert_node_into_singly_linked_list(&llist1, llist1_item);
}

SinglyLinkedList* llist2 = malloc(sizeof(SinglyLinkedList));


llist2->head = NULL;
llist2->tail = NULL;

char* llist2_count_endptr;
char* llist2_count_str = readline();
int llist2_count = strtol(llist2_count_str, &llist2_count_endptr, 10);

if (llist2_count_endptr == llist2_count_str || *llist2_count_endptr != '\0') { exit(EXIT_FAILUR


E); }

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


char* llist2_item_endptr;
char* llist2_item_str = readline();
int llist2_item = strtol(llist2_item_str, &llist2_item_endptr, 10);

if (llist2_item_endptr == llist2_item_str || *llist2_item_endptr != '\0') { exit(EXIT_FAILURE


); }

insert_node_into_singly_linked_list(&llist2, llist2_item);
}

bool result = compare_lists(llist1->head, llist2->head);

fprintf(fptr, "%d\n", result);


}

fclose(fptr);

return 0;
}

char* readline() {
size_t alloc_length = 1024;
size_t data_length = 0;
char* data = malloc(alloc_length);

while (true) {
char* cursor = data + data_length;
char* line = fgets(cursor, alloc_length - data_length, stdin);

if (!line) { break; }

data_length += strlen(cursor);

if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; }

size_t new_length = alloc_length << 1;


data = realloc(data, new_length);

if (!data) { break; }

alloc_length = new_length;
}

if (data[data_length - 1] == '\n') {
data[data_length - 1] = '\0';
}

data = realloc(data, data_length);

return data;
}
2. solve the problem in the hackerrank platform
https://www.hackerrank.com/challenges/reverse-a-linked-list/problem
Code:
#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* readline();

typedef struct SinglyLinkedListNode SinglyLinkedListNode;


typedef struct SinglyLinkedList SinglyLinkedList;

struct SinglyLinkedListNode {
int data;
SinglyLinkedListNode* next;
};

struct SinglyLinkedList {
SinglyLinkedListNode* head;
SinglyLinkedListNode* tail;
};

SinglyLinkedListNode* create_singly_linked_list_node(int node_data) {


SinglyLinkedListNode* node = malloc(sizeof(SinglyLinkedListNode));

node->data = node_data;
node->next = NULL;

return node;
}

void insert_node_into_singly_linked_list(SinglyLinkedList** singly_linked_list, int node_data) {


SinglyLinkedListNode* node = create_singly_linked_list_node(node_data);

if (!(*singly_linked_list)->head) {
(*singly_linked_list)->head = node;
} else {
(*singly_linked_list)->tail->next = node;
}

(*singly_linked_list)->tail = node;
}

void print_singly_linked_list(SinglyLinkedListNode* node, char* sep, FILE* fptr) {


while (node) {
fprintf(fptr, "%d", node->data);

node = node->next;

if (node) {
fprintf(fptr, "%s", sep);
}
}
}

void free_singly_linked_list(SinglyLinkedListNode* node) {


while (node) {
SinglyLinkedListNode* temp = node;
node = node->next;

free(temp);
}
}

/*
* Complete the 'reverse' function below.
*
* The function is expected to return an INTEGER_SINGLY_LINKED_LIST.
* The function accepts INTEGER_SINGLY_LINKED_LIST llist as parameter.
*/

/*
* For your reference:
*
* SinglyLinkedListNode {
* int data;
* SinglyLinkedListNode* next;
* };
*
*/

SinglyLinkedListNode* reverse(SinglyLinkedListNode* llist) {


SinglyLinkedListNode* prev = NULL;
SinglyLinkedListNode* curr = llist;
SinglyLinkedListNode* next = NULL;

while (curr != NULL) {


next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}

return prev;
}

int main()
{
FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");

char* tests_endptr;
char* tests_str = readline();
int tests = strtol(tests_str, &tests_endptr, 10);

if (tests_endptr == tests_str || *tests_endptr != '\0') { exit(EXIT_FAILURE); }

for (int tests_itr = 0; tests_itr < tests; tests_itr++) {


SinglyLinkedList* llist = malloc(sizeof(SinglyLinkedList));
llist->head = NULL;
llist->tail = NULL;

char* llist_count_endptr;
char* llist_count_str = readline();
int llist_count = strtol(llist_count_str, &llist_count_endptr, 10);

if (llist_count_endptr == llist_count_str || *llist_count_endptr != '\0') { exit(EXIT_FAILURE); }

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


char* llist_item_endptr;
char* llist_item_str = readline();
int llist_item = strtol(llist_item_str, &llist_item_endptr, 10);

if (llist_item_endptr == llist_item_str || *llist_item_endptr != '\0') { exit(EXIT_FAILURE); }

insert_node_into_singly_linked_list(&llist, llist_item);
}

SinglyLinkedListNode* llist1 = reverse(llist->head);

char *sep = " ";

print_singly_linked_list(llist1, sep, fptr);


fprintf(fptr, "\n");

free_singly_linked_list(llist1);
}

fclose(fptr);

return 0;
}

char* readline() {
size_t alloc_length = 1024;
size_t data_length = 0;
char* data = malloc(alloc_length);

while (true) {
char* cursor = data + data_length;
char* line = fgets(cursor, alloc_length - data_length, stdin);

if (!line) { break; }

data_length += strlen(cursor);

if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; }

size_t new_length = alloc_length << 1;


data = realloc(data, new_length);

if (!data) { break; }

alloc_length = new_length;
}

if (data[data_length - 1] == '\n') {
data[data_length - 1] = '\0';
}

data = realloc(data, data_length);

return data;
}
3. solve the problem in the hackerrank platform
https://www.hackerrank.com/challenges/insert-a-node-at-the-tail-of-a-linked-
list/problem?isFullScreen=true
Code:
#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* readline();

typedef struct SinglyLinkedListNode SinglyLinkedListNode;


typedef struct SinglyLinkedList SinglyLinkedList;

struct SinglyLinkedListNode {
int data;
SinglyLinkedListNode* next;
};

struct SinglyLinkedList {
SinglyLinkedListNode* head;
};

SinglyLinkedListNode* create_singly_linked_list_node(int node_data) {


SinglyLinkedListNode* node = malloc(sizeof(SinglyLinkedListNode));

node->data = node_data;
node->next = NULL;

return node;
}

void print_singly_linked_list(SinglyLinkedListNode* node, char* sep, FILE* fptr) {


while (node) {
fprintf(fptr, "%d", node->data);

node = node->next;

if (node) {
fprintf(fptr, "%s", sep);
}
}
}

void free_singly_linked_list(SinglyLinkedListNode* node) {


while (node) {
SinglyLinkedListNode* temp = node;
node = node->next;

free(temp);
}
}

// Complete the insertNodeAtTail function below.

/*
* For your reference:
*
* SinglyLinkedListNode {
* int data;
* SinglyLinkedListNode* next;
* };
*
*/
SinglyLinkedListNode* insertNodeAtTail(SinglyLinkedListNode* head, int data) {

SinglyLinkedListNode* new_node = create_singly_linked_list_node(data); // Create a new node


with the given data

if (head == NULL) {
// If the linked list is empty, make the new node as the head
head = new_node;
} else {
SinglyLinkedListNode* current = head;
while (current->next != NULL) {
current = current->next; // Traverse to the last node
}
current->next = new_node; // Attach the new node to the last node's next pointer
}

return head; // Return the updated head of the linked list

int main()
{
FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");

SinglyLinkedList* llist = malloc(sizeof(SinglyLinkedList));


llist->head = NULL;

char* llist_count_endptr;
char* llist_count_str = readline();
int llist_count = strtol(llist_count_str, &llist_count_endptr, 10);

if (llist_count_endptr == llist_count_str || *llist_count_endptr != '\0') { exit(EXIT_FAILURE); }


for (int i = 0; i < llist_count; i++) {
char* llist_item_endptr;
char* llist_item_str = readline();
int llist_item = strtol(llist_item_str, &llist_item_endptr, 10);

if (llist_item_endptr == llist_item_str || *llist_item_endptr != '\0') { exit(EXIT_FAILURE); }

SinglyLinkedListNode* llist_head = insertNodeAtTail(llist->head, llist_item);


llist->head = llist_head;
}

char *sep = "\n";

print_singly_linked_list(llist->head, sep, fptr);


fprintf(fptr, "\n");

free_singly_linked_list(llist->head);

fclose(fptr);

return 0;
}

char* readline() {
size_t alloc_length = 1024;
size_t data_length = 0;
char* data = malloc(alloc_length);

while (true) {
char* cursor = data + data_length;
char* line = fgets(cursor, alloc_length - data_length, stdin);

if (!line) {
break;
}

data_length += strlen(cursor);

if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') {


break;
}

alloc_length <<= 1;

data = realloc(data, alloc_length);

if (!line) {
break;
}
}

if (data[data_length - 1] == '\n') {
data[data_length - 1] = '\0';

data = realloc(data, data_length);


} else {
data = realloc(data, data_length + 1);

data[data_length] = '\0';
}

return data;
}
Skill:
1. In the vast universe, two distinct galactic systems, Galactic System A and Galactic System B,
are on the verge of merging. To study this celestial event, astronomers develop a C program
to merge two sorted singly linked lists representing the stars in each system. The program
takes input from astronomers, merges the linked lists, and creates a single sorted linked list.
By analyzing the merged linked list, astronomers gain insights into the properties and
dynamics of the combined galactic system. This scenario combines the concept of galactic
mergers with the task of merging sorted linked lists, providing an imaginative context for the
programming task.
Code:
#include <stdio.h>
#include <stdlib.h>

typedef struct Node {


int data;
struct Node* next;
} Node;

Node* createNode(int data) {


Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}

Node* insertNode(Node* head, int data) {


Node* newNode = createNode(data);
if (head == NULL) {
head = newNode;
} else {
Node* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
return head;
}
Node* mergeLists(Node* headA, Node* headB) {
if (headA == NULL) {
return headB;
}
if (headB == NULL) {
return headA;
}

Node* mergedHead = NULL;


Node* tail = NULL;

if (headA->data <= headB->data) {


mergedHead = headA;
headA = headA->next;
} else {
mergedHead = headB;
headB = headB->next;
}
tail = mergedHead;

while (headA != NULL &&headB != NULL) {


if (headA->data <= headB->data) {
tail->next = headA;
headA = headA->next;
} else {
tail->next = headB;
headB = headB->next;
}
tail = tail->next;
}

if (headA != NULL) {
tail->next = headA;
}
if (headB != NULL) {
tail->next = headB;
}

return mergedHead;
}

void displayList(Node* head) {


Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}

int main() {
Node* headA = NULL; // Head of the first linked list
Node* headB = NULL; // Head of the second linked list
int n;
printf("Enter the number of nodes in the first linked list: ");
scanf("%d", &n);
printf("Enter the elements of the first linked list in sorted order:\n");
for (int i = 0; i< n; i++) {
int data;
scanf("%d", &data);
headA = insertNode(headA, data);
}

printf("Enter the number of nodes in the second linked list: ");


scanf("%d", &n);
printf("Enter the elements of the second linked list in sorted order:\n");
for (int i = 0; i< n; i++) {
int data;
scanf("%d", &data);
headB = insertNode(headB, data);
}
Node* mergedHead = mergeLists(headA, headB);

printf("Merged Linked List: ");


displayList(mergedHead);

return 0;
}
2. In a popular restaurant called "Palindromia," every dish on the menu is a palindrome.
Chef Amelia wants to develop a C program to check if a given singly linked list
representing the menu items is a palindrome. The program compares the names of the
dishes from both ends, determining if they read the same forwards and backwards. By
using this program, Chef Amelia ensures the authenticity of their palindrome menu and
maintains the restaurant's reputation. This scenario combines the concept of palindrome
food items with the task of checking a singly linked list for palindromicproperties.
Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;

// Function to create a new node


Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}

// Function to insert a node at the end of a linked list


Node* insertNode(Node* head, int data) {
Node* newNode = createNode(data);
if (head == NULL) {
head = newNode;
} else {
Node* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
return head;
}

// Function to merge two sorted linked lists


Node* mergeLists(Node* headA, Node* headB) {
if (headA == NULL) {
return headB;
}
if (headB == NULL) {
return headA;
}

Node* mergedHead = NULL;


Node* tail = NULL;

if (headA->data <= headB->data) {


mergedHead = headA;
headA = headA->next;
} else {
mergedHead = headB;
headB = headB->next;
}
tail = mergedHead;

while (headA != NULL &&headB != NULL) {


if (headA->data <= headB->data) {
tail->next = headA;
headA = headA->next;
} else {
tail->next = headB;
headB = headB->next;
}
tail = tail->next;
}

if (headA != NULL) {
tail->next = headA;
}
if (headB != NULL) {
tail->next = headB;
}

return mergedHead;
}

// Function to display a linked list


void displayList(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}

int main() {
Node* headA = NULL; // Head of the first linked list
Node* headB = NULL; // Head of the second linked list

// Reading the number of nodes in the first linked list


int n;
printf("Enter the number of nodes in the first linked list: ");
scanf("%d", &n);

// Reading the elements of the first linked list


printf("Enter the elements of the first linked list in sorted order:\n");
for (int i = 0; i< n; i++) {
int data;
scanf("%d", &data);
headA = insertNode(headA, data);
}

// Reading the number of nodes in the second linked list


printf("Enter the number of nodes in the second linked list: ");
scanf("%d", &n);
// Reading the elements of the second linked list
printf("Enter the elements of the second linked list in sorted order:\n");
for (int i = 0; i< n; i++) {
int data;
scanf("%d", &data);
headB = insertNode(headB, data);
}

// Merging the two linked lists


Node* mergedHead = mergeLists(headA, headB);

// Displaying the merged linked list


printf("Merged Linked List: ");
displayList(mergedHead);

return 0;
}
1. Givenasinglylinkedlist,findmiddleofthelinkedlist.Forexample,
ifgivenlinkedlistis1->2->3->4->5thenoutputshouldbe3.
Ifthereareevennodes,thentherewouldbetwomiddlenodes,weneedtoprintsecondmiddleelement.Fore
xample,ifgivenlinkedlistis1->2->3->4->5->6thenoutputshouldbe
https://www.hackerearth.com/problem/algorithm/find-the-middle-of-a-given-linked-list-using-
recursion/
Code:
#include <stdio.h>
#include <stdlib.h>
// Structure for a node in the linked list
struct Node {
int data;
struct Node* next;
};

// Function to insert a node at the end of the linked list


void insert(struct Node** head, int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;

if (*head == NULL) {
*head = newNode;
} else {
struct Node* curr = *head;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = newNode;
}
}
// Function to find the middle element of the linked list
int findMiddle(struct Node* head) {
struct Node* slowPtr = head;
struct Node* fastPtr = head;
while (fastPtr != NULL &&fastPtr->next != NULL) {
slowPtr = slowPtr->next;
fastPtr = fastPtr->next->next;
}
return slowPtr-
}

int main() {
int n;
scanf("%d", &n);
struct Node* head = NULL;
for (int i = 0; i< n; i++) {
int data;
scanf("%d", &data);
insert(&head, data);
}
int middle = findMiddle(head);
printf("%d\n", middle);
return
}

2. AftergettingherPhD,Christiehasbecomeacelebrityatheruniversity,andherfacebookprofileisfu
lloffriendrequests.Beingthenicegirlsheis,Christiehasacceptedalltherequests.
NowKuldeepisjealousofalltheattentionsheisgettingfromotherguys,soheaskshertodeletesomeoftheguysfr
omherfriendlist.
Toavoida'scene',Christiedecidestoremovesomefriendsfromherfriendlist,sincesheknowsthepop
ularityofeachofthefriendshehas,sheusesthefollowingalgorithmtodeleteafriend.3.Giventheheadofasi
nglylinkedlist,returnthemiddlenodeofthelinkedlist.
https://www.hackerearth.com/practice/data-structures/linked-list/singly-linked-list/practice-
problems/algorithm/remove-friends-5/
Code:
3. If there are two middle nodes, return the second middle node.

Input:head=[1,2,3,4,5]
Output:[3,4,5]
Explanation: The middle node of the list is node 3.
https://leetcode.com/problems/middle-of-the-linked-list/
Code:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
structListNode* middleNode(structListNode* head){
structListNode *slow = head;
structListNode *fast = head;

while (fast != NULL&&fast->next != NULL) {


slow = slow->next;
fast = fast->next->next;
}
return slow;
}
InsertanodeattheheadofalinkedlistGivenapointertotheheadofalinkedlist,insertanewnodebefore
thehead.Thenextvalueinthenewnodeshouldpointtoheadandthedatavalueshouldbereplacedwith
agivenvalue.Returnareferencetothenewheadofthelist.Theheadpointergivenmaybenullmeaning
thattheinitiallistisempty.
InputFormat
Thefirstlinecontainsanintegern,thenumberofelementstobeinsertedattheheadofthelist.Thenextn
linescontainanintegereach,theelementstobeinserted,oneperfunctioncall.
Explanation
IntiallythelistinNULL.Afterinserting383,thelistis383->NULL.Afterinserting484,thelistis484-
>383->NULL.
Afterinserting392,thelistis392->484->383->NULL.
Afterinserting975,thelistis975->392->484->383->NULL.
Afterinserting321,thelistis321->975->392->484->383->NULL.
https://www.hackerrank.com/challenges/insert-a-node-at-the-head-of-a-linked-

4. In preparation for a Bharatanatyam performance, Guru Lakshmi wants to remove


duplicate dance steps from an unsorted linked list representing the choreography. She
develops a C program that removes duplicates, ensuring each step appears only once in
the sequence. By using the program, Guru Lakshmi streamlines the dance routines,
creating a cohesive and visually appealing Bharatanatyam performance. This scenario
combines the concept of Bharatanatyam with the task of removing duplicates from an
unsorted linked list.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

typedef struct Node {


char data[100];
struct Node* next;
} Node;

Node* createNode(char data[]) {


Node* newNode = (Node*)malloc(sizeof(Node));
strcpy(newNode->data, data);
newNode->next = NULL;
return newNode;
}
Node* insertNode(Node* head, char data[]) {
Node* newNode = createNode(data);
if (head == NULL) {
head = newNode;
} else {
Node* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
return head;
}

Node* removeDuplicates(Node* head) {


if (head == NULL || head->next == NULL) {
return head;
}

Node* current = head;


while (current != NULL) {
Node* runner = current;
while (runner->next != NULL) {
if (strcmp(current->data, runner->next->data) == 0) {
Node* temp = runner->next;
runner->next = runner->next->next;
free(temp);
} else {
runner = runner->next;
}
}
current = current->next;
}

return head;
}
void displayList(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%s ", current->data);
current = current->next;
}
printf("\n");
}

int main() {
Node* head = NULL; // Head of the linked list
stepsint n;
printf("Enter the number of dance steps: ");
scanf("%d", &n);
getchar();

printf("Enter the dance steps:\


n");
for (int i = 0; i< n; i++) {
char step[100];
fgets(step, sizeof(step), stdin);
step[strcspn(step, "\n")] = '\0';
head = insertNode(head, step);
}

head = removeDuplicates(head);

printf("Updated dance steps:\n");


displayList(head);

return 0;
}

5. Delete the node at a given position in a linked list and return a reference to the head
node. The head is at position 0.The list may be empty after you delete the node. In that
case, return a null value.
Example
List=0->1->2->3
Position=2
After removing the node at position 2. Llist = 0-> 1-> 3.
Input Format
The first line of input contains an integer n, the number of elements in the linked list.
Each of the next lines contains an integer, the node data values in order. The last line
contains an integer, position, the position of the node to delete.
https://www.hackerrank.com/challenges/delete-a-node-from-a-linked- list/problem?
isFullScreen=false
Code:
#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* readline();
typedef struct SinglyLinkedListNode SinglyLinkedListNode;
typedef struct SinglyLinkedList SinglyLinkedList;

struct SinglyLinkedListNode {
int data;
SinglyLinkedListNode* next;
};

struct SinglyLinkedList {
SinglyLinkedListNode* head;
SinglyLinkedListNode* tail;
};

SinglyLinkedListNode* create_singly_linked_list_node(int node_data) {


SinglyLinkedListNode* node = malloc(sizeof(SinglyLinkedListNode));
node->data = node_data;
node->next = NULL;
return node;
}
void insert_node_into_singly_linked_list(SinglyLinkedList** singly_linked_list, int node_data) {
SinglyLinkedListNode* node = create_singly_linked_list_node(node_data);

if (!(*singly_linked_list)->head) {
(*singly_linked_list)->head = node;
} else {
(*singly_linked_list)->tail->next = node;
}
(*singly_linked_list)->tail = node;
}
void print_singly_linked_list(SinglyLinkedListNode* node, char* sep, FILE* fptr) {
while (node) {
fprintf(fptr, "%d", node->data);

node = node->next;

if (node) {
fprintf(fptr, "%s", sep);
}
}
}
void free_singly_linked_list(SinglyLinkedListNode* node) {
while (node) {
SinglyLinkedListNode* temp = node;
node = node->next;

free(temp);
}
}
/*
* Complete the 'deleteNode' function below.
*
* The function is expected to return an INTEGER_SINGLY_LINKED_LIST.
* The function accepts following parameters:
* 1. INTEGER_SINGLY_LINKED_LIST llist
* 2. INTEGER position
*/
/*
* For your reference:
*
* SinglyLinkedListNode {
* int data;
* SinglyLinkedListNode* next;
* };
*
*/
SinglyLinkedListNode* deleteNode(SinglyLinkedListNode* llist, int position) {
// Case 1: If the list is empty
if (llist == NULL) {
return llist;
}
// Case 2: If the node to be deleted is the head node
if (position == 0) {
SinglyLinkedListNode* temp = llist;
llist = llist->next;
free(temp);
return llist;
}
// Case 3: Find the previous node of the node to be deleted
SinglyLinkedListNode* prev = NULL;
SinglyLinkedListNode* curr = llist;
int count = 0;
while (curr != NULL && count < position) {
prev = curr;
curr = curr->next;
count++;
}
// Case 4: If the position is out of bounds
if (curr == NULL) {
return llist;
}
// Case 5: Delete the node at the given position
prev->next = curr->next;
free(curr);
return llist;
}

int main()
{
FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");
SinglyLinkedList* llist = malloc(sizeof(SinglyLinkedList));
llist->head = NULL;
llist->tail = NULL;
char* llist_count_endptr;
char* llist_count_str = readline();
int llist_count = strtol(llist_count_str, &llist_count_endptr, 10);
if (llist_count_endptr == llist_count_str || *llist_count_endptr != '\0') { exit(EXIT_FAILURE); }
for (int i = 0; i < llist_count; i++) {
char* llist_item_endptr;
char* llist_item_str = readline();
int llist_item = strtol(llist_item_str, &llist_item_endptr, 10);
if (llist_item_endptr == llist_item_str || *llist_item_endptr != '\0') { exit(EXIT_FAILURE); }
insert_node_into_singly_linked_list(&llist, llist_item);
}
char* position_endptr;
char* position_str = readline();
int position = strtol(position_str, &position_endptr, 10);
if (position_endptr == position_str || *position_endptr != '\0') { exit(EXIT_FAILURE); }
SinglyLinkedListNode* llist1 = deleteNode(llist->head, position);
char *sep = " ";
print_singly_linked_list(llist1, sep, fptr);
fprintf(fptr, "\n");
free_singly_linked_list(llist1);
fclose(fptr);
return 0;
}
char* readline() {
size_t alloc_length = 1024;
size_t data_length = 0;
char* data = malloc(alloc_length);
while (true) {
char* cursor = data + data_length;
char* line = fgets(cursor, alloc_length - data_length, stdin);
if (!line) { break; }
data_length += strlen(cursor);
if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; }
size_t new_length = alloc_length << 1;
data = realloc(data, new_length);
if (!data) { break; }
alloc_length = new_length;
}
if (data[data_length - 1] == '\n') {
data[data_length - 1] = '\0';
}
data = realloc(data, data_length);
return data;
}
6. A team of researchers led by Dr. Gupta is studying India's population distribution. They
want to analyze specific subsets of the population by removing elements with odd indices
from a singly linked list containing population data for different regions. By using a C
program to remove these elements, the researchers streamline their analysis and gain
valuable insights into population trends and demographics. This scenario combines the
concept of India's population analysis with the task of removing elements with odd
indices from a linked list.
Code:
#include <stdio.h>
#include <stdlib.h>
#include
<stdbool.h>

typedef struct Node


{ int data;
struct Node* next;
} Node;

// Function to create a new node


Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}

// Function to insert a node at the end of a linked


list Node* insertNode(Node* head, int data) {
Node* newNode = createNode(data);
if (head == NULL) {
head = newNode;
} else {
Node* current = head;
while (current->next != NULL)
{ current = current->next;
}
current->next = newNode;
}
return head;
}

// Function to remove elements with odd indices from a linked list


Node* removeElementsWithOddIndices(Node* head) {
if (head == NULL || head->next == NULL) {
return head;
}

Node* current = head;


Node* prev = NULL;
bool removeNext =
false; int index = 1;
while (current != NULL)
{ if (index % 2 == 1) {
if (prev == NULL) {
head = current->next;
} else {
prev->next = current->next;
}
Node* temp = current;
current = current->next;
free(temp);
removeNext = true;
} else {
prev = current;
current = current->next;
removeNext = false;
}
index++;
}

return head;
}

// Function to display a linked list


void displayList(Node* head) {
Node* current = head;
while (current != NULL)
{
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}

int main() {
Node* head = NULL; // Head of the linked list

// Reading the number of regions


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

// Reading the population data for each region


printf("Enter the population data for each region:\
n");
for (int i = 0; i< n; i++)
{ int population;
scanf("%d", &population);
head = insertNode(head, population);
}
// Removing elements with odd indices from the linked list
head = removeElementsWithOddIndices(head);

// Displaying the updated linked list


printf("Updated population data:\n");
displayList(head);

return 0;
}
7. Giventhepointertotheheadnodeofalinkedlist,changethenextpointersofthenodessothattheirorde
risreversed.Theheadpointergivenmaybenullmeaningthattheinitiallistisempty.
Example
referencesthelist1 - >2 - >3 - >NULL
Manipulate the next pointers of each node in place and return head, now referencing the
head of thelist.3- >2- >1- >NULL
InputFormat
Thefirstlinecontainsanintegert,thenumberoftestcases.Eachtestcasehasthefollowingformat:Thefi
rstlinecontainsaninteger,thenumberofelementsinthelinkedlist.
Eachofthenextnlinescontainsaninteger,thedatavaluesoftheelementsinthelinkedlist.
Constraints
1<=t<=10
1<=n<=1000
1<=list[i]<=1000, wherelist[i] is the ith element in the list.
https://www.hackerrank.com/challenges/reverse-a-linked-list/problem?isFullScreen=false
Code:
#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* readline();
typedef struct SinglyLinkedListNode SinglyLinkedListNode;
typedef struct SinglyLinkedList SinglyLinkedList;

struct SinglyLinkedListNode {
int data;
SinglyLinkedListNode* next;
};

struct SinglyLinkedList {
SinglyLinkedListNode* head;
SinglyLinkedListNode* tail;
};

SinglyLinkedListNode* create_singly_linked_list_node(int node_data) {


SinglyLinkedListNode* node = malloc(sizeof(SinglyLinkedListNode));
node->data = node_data;
node->next = NULL;
return
}

void insert_node_into_singly_linked_list(SinglyLinkedList** singly_linked_list, int node_data) {


SinglyLinkedListNode* node = create_singly_linked_list_node(node_data);
if (!(*singly_linked_list)->head) {
(*singly_linked_list)->head = node;
} else {
(*singly_linked_list)->tail->next = node;
}
(*singly_linked_list)->tail =
}

void print_singly_linked_list(SinglyLinkedListNode* node, char* sep, FILE* fptr) {


while (node) {
fprintf(fptr, "%d", node->data);
node = node->next;
if (node) {
fprintf(fptr, "%s", sep);
}
}
}

void free_singly_linked_list(SinglyLinkedListNode* node) {


while (node) {
SinglyLinkedListNode* temp = node;
node = node->next;
free(temp);
}
}

/*
* Complete the 'reverse' function below.
*
* The function is expected to return an INTEGER_SINGLY_LINKED_LIST.
* The function accepts INTEGER_SINGLY_LINKED_LIST llist as parameter.
*/
/*
* For your reference:
*
* SinglyLinkedListNode {
* int data;
* SinglyLinkedListNode* next;
* };
*
*/

SinglyLinkedListNode* reverse(SinglyLinkedListNode* llist) {


SinglyLinkedListNode* prev = NULL;
SinglyLinkedListNode* curr = llist;
SinglyLinkedListNode* next = NULL;
while (curr != NULL) {
next = curr-
>next; curr-
prev = curr;
curr = next;
}

}
return
int main()
{
FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");
char* tests_endptr;
char* tests_str = readline();
int tests = strtol(tests_str, &tests_endptr, 10);
if (tests_endptr == tests_str || *tests_endptr != '\0') { exit(EXIT_FAILURE); }
for (int tests_itr = 0; tests_itr < tests; tests_itr++) {
SinglyLinkedList* llist = malloc(sizeof(SinglyLinkedList));
llist->head = NULL;
llist->tail = NULL;
char* llist_count_endptr;
char* llist_count_str = readline();
int llist_count = strtol(llist_count_str, &llist_count_endptr, 10);
if (llist_count_endptr == llist_count_str || *llist_count_endptr != '\0') { exit(EXIT_FAILURE);
}

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


char* llist_item_endptr;
char* llist_item_str = readline();
int llist_item = strtol(llist_item_str, &llist_item_endptr, 10);
if (llist_item_endptr == llist_item_str || *llist_item_endptr != '\0') { exit(EXIT_FAILURE);
}
insert_node_into_singly_linked_list(&llist, llist_item);
}

SinglyLinkedListNode* llist1 = reverse(llist->head);


char *sep = " ";
print_singly_linked_list(llist1, sep, fptr);
fprintf(fptr, "\n");
free_singly_linked_list(llist1
}
fclose(fptr);
return
}

char* readline() {
size_t alloc_length = 1024;
size_t data_length = 0;
char* data = malloc(alloc_length);
while (true) {
char* cursor = data + data_length;
char* line = fgets(cursor, alloc_length - data_length, stdin);
if (!line) { break; }
data_length += strlen(cursor);

if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; }


size_t new_length = alloc_length << 1;
data = realloc(data, new_length);
if (!data) { break; }
alloc_length = new_length;
}
if (data[data_length - 1] == '\n') {
data[data_length - 1] = '\0';
}
data = realloc(data, data_length);
return
}

You might also like