0% found this document useful (0 votes)
4 views64 pages

C Program Answer

The document outlines several C programming tasks, each with specific requirements and sample inputs/outputs. Tasks include validating a 5-digit PIN, calculating student grades based on marks, determining compass directions from angles, calculating discounts based on purchase amounts, and more. Each task is accompanied by example code snippets and explanations of how the programs work.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views64 pages

C Program Answer

The document outlines several C programming tasks, each with specific requirements and sample inputs/outputs. Tasks include validating a 5-digit PIN, calculating student grades based on marks, determining compass directions from angles, calculating discounts based on purchase amounts, and more. Each task is accompanied by example code snippets and explanations of how the programs work.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1. Check weather the given number is a 5 digit number without using loops.

In a user
authentication system, individuals are prompted to input a numerical PIN to access
their accounts. This program efficiently verifies whether the entered PIN is a 5-digit
number. Upon input, the system evaluates the length of the number without using
loops, determining if it precisely consists of five digits. If the PIN meets this criteria, the
system grants access, allowing users to securely manage their accounts. However, if
the PIN does not match the required format, the system prompts the user to re-enter a
valid 5-digit PIN for authentication, ensuring robust security measures are maintained.
(The input may be a positive or negative number ) .

Task:
• Get a numeric input from the user
• Check whether the given digit is a 5 digit number or not
• If it is a 5 digit number display “xx is a 5-digit number”
• If not, display “ yy is not a 5-digit number”

(The statements inside the brackets are for understanding purpose only)

Sample Input 1:
345 (3 digit input )

Sample Output1 :
345 is not a 5-digit number

Sample Input 2:
36893 (5 digit input )

Sample Output 2:
36893 is a 5-digit number

ANSWER ------------------>

#include <stdio.h>

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

if ((num >= 10000 && num <= 99999) || (num <= -10000 && num >= -99999)) {
printf("%d is a 5-digit number\n", num);
} else {
printf("%d is not a 5-digit number\n", num);
}

return 0;
}

How it works:
The condition checks if the number is between 10000 to 99999 (positive) or -10000 to -
99999 (negative).

No need to use abs() or loops — it stays simple.

Only scanf and if condition used — beginner-friendly.

---------------------------------

2.) In a school's examination system, students input their subject marks into this
program for automatic grading. After entering marks for Physics, Chemistry, Biology,
Mathematics, and Computer Science, the program calculates the overall percentage
and assigns a grade based on predefined criteria. If the student fails to score above 35
in any subject, the program notifies them of their failure and prompts them to improve
their scores. This tool aids educators in efficiently evaluating student performance and
providing timely feedback for academic progress.

Task:
• Get 5 subject marks from the user as input
• Check whether the entered marks are in the range of 0-100
• If not display “Invalid input! Marks must be between 0 and 100.”
• Check whether the student is passed in all subjects (student should score more than
35 to get pass)
• Calculate the percentage of the student and display it in 2 decimal places
• (Eg : “55.20%”)
• Finally display the Grade of the Student
• If percentage is
o Greater than 90 - Grade A
o Between 81-90 - Grade B
o Between 71-80 - Grade C
o Between 61-70 - Grade D
o Between 41-60 - Grade E
o Less than or equal to 40 - Grade F
• Grades will not be displayed(but display percenatge) if the student has fail mark in any
of the subjects, then display “Failed! You need to score above 35 in all subjects”
(The statements inside the brackets are for understanding purpose only)

Sample Input 1:
93(subject 1 mark)
92(subject 2 mark)
85(subject 3 mark)
65(subject 4 mark)
90(subject 5 mark)

Sample Output1 :
85.00% (percentage)
Grade B (Grade)

Sample Input 2:
32
78
56
80
79

Sample Output 2:
65.00%
Failed! You need to score above 35 in all subjects.

ANSWER ------------------>

#include <stdio.h>

int main() {
int phy, chem, bio, math, comp;
float total, percentage;

// Getting marks input


scanf("%d", &phy);
scanf("%d", &chem);
scanf("%d", &bio);
scanf("%d", &math);
scanf("%d", &comp);

// Check if all marks are between 0 and 100


if (phy < 0 || phy > 100 || chem < 0 || chem > 100 || bio < 0 || bio > 100 || math < 0 || math
> 100 || comp < 0 || comp > 100) {
printf("Invalid input! Marks must be between 0 and 100.\n");
return 0;
}

// Check for failure in any subject


if (phy <= 35 || chem <= 35 || bio <= 35 || math <= 35 || comp <= 35) {
total = phy + chem + bio + math + comp;
percentage = total / 5.0;
printf("%.2f%%\n", percentage);
printf("Failed! You need to score above 35 in all subjects.\n");
return 0;
}

// Calculate percentage
total = phy + chem + bio + math + comp;
percentage = total / 5.0;

// Display percentage
printf("%.2f%%\n", percentage);

// Display Grade
if (percentage > 90) {
printf("Grade A\n");
} else if (percentage >= 81 && percentage <= 90) {
printf("Grade B\n");
} else if (percentage >= 71 && percentage <= 80) {
printf("Grade C\n");
} else if (percentage >= 61 && percentage <= 70) {
printf("Grade D\n");
} else if (percentage >= 41 && percentage <= 60) {
printf("Grade E\n");
} else {
printf("Grade F\n");
}

return 0;
}

3.. Determining Compass Direction Based on Input Angle


Write a C program that takes an angle as input and determines the corresponding
compass direction. The program should:

The program should determine and print the corresponding compass direction
according to the following ranges:
North: Between 337 to 22 degrees.
Northeast: Between 23 to 67 degrees.
East: Between 68 to 112 degrees.
Southeast: Between 113 to 157 degrees.
South: Between 158 to 202 degrees.
Southwest: Between 203 to 247 degrees.
West: Between 248 to 292 degrees.
Northwest: Between 293 to 337 degrees.
The input angle falls within the range of 0 to 360 degrees.

Constraints:

The input will be an integer angle in degrees.


If the input angle is negative or greater than 360, it should print “ Invalid Input”
The program must use if-else statements without any inbuilt functions.

Input:

An integer representing the angle (in degrees).

Output:

A string representing the corresponding compass direction.

Sample Input 1:
45

Sample Output 1:

Northeast

Sample Input 2:
370
Sample Output 2:

Invalid Input

ANSWER ------------------>

#include <stdio.h>

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

// Check for valid range


if (angle < 0 || angle > 360) {
printf("Invalid Input\n");
}
else {
// Check compass direction
if ((angle >= 337 && angle <= 360) || (angle >= 0 && angle <= 22)) {
printf("North\n");
}
else if (angle >= 23 && angle <= 67) {
printf("Northeast\n");
}
else if (angle >= 68 && angle <= 112) {
printf("East\n");
}
else if (angle >= 113 && angle <= 157) {
printf("Southeast\n");
}
else if (angle >= 158 && angle <= 202) {
printf("South\n");
}
else if (angle >= 203 && angle <= 247) {
printf("Southwest\n");
}
else if (angle >= 248 && angle <= 292) {
printf("West\n");
}
else if (angle >= 293 && angle <= 336) {
printf("Northwest\n");
}
}

return 0;
}

4. Discount percentage based on their total purchase


You are assigned to create a program that calculates the discount percentage a
customer is eligible for based on their total purchase amount and membership status.
Additionally, you need to update the program to calculate and display the total bill
amount after applying the discount.

1. Members get a 20% discount on purchases of ₹5000 or more.


2. A 10% discount is applied to purchases between ₹1000 and ₹4999.99.
3. For purchases less than ₹1000, members receive a 5% discount.
4. Non members receive a 15% discount on purchases of ₹5000 or more and a 5%
discount on purchases between ₹1000 and ₹4999.99.
5. There are no discounts for non-members on purchases below ₹1000.

If the second input is 1 then he is a Member else input is 0 then he is Non Member. The
input data type is float except member status
(The statements inside the brackets are for understanding purpose only)

Sample Input 1:
100.00 (Purchases Amount)
1 (Members Status)

Sample Output 1:
You are eligible for a 5.00% discount
Your final bill is 95.00

Sample Input 2:
1000.00
0

Sample Output 2:
You are eligible for a 5.00% discount
Your final bill is 950.00

ANSWER ------------------>

#include <stdio.h>

int main() {
float amount, discount = 0.0, finalBill;
int isMember;

// Input purchase amount and membership status


scanf("%f", &amount);
scanf("%d", &isMember);

// Apply discount based on amount and membership status


if (isMember == 1) { // Member
if (amount >= 5000) {
discount = 20.0;
} else if (amount >= 1000 && amount < 5000) {
discount = 10.0;
} else { // Less than 1000
discount = 5.0;
}
} else { // Non-member
if (amount >= 5000) {
discount = 15.0;
} else if (amount >= 1000 && amount < 5000) {
discount = 5.0;
} else {
discount = 0.0;
}
}

// Calculate final bill


finalBill = amount - (amount * discount / 100.0);

// Display output
printf("You are eligible for a %.2f%% discount\n", discount);
printf("Your final bill is %.2f\n", finalBill);

return 0;
}

[Link] in range
Your task is to refine and integrate the provided C program into the school’s educational
software suite. The program should function as follows:
When a student inputs a digit, the program will print the word representation of that digit
from (0 to 9) [ 0-zero, 1-one, 9-nine] and all letters in smaller case.
If the student inputs a negative number, the program will inform them that the number is
negative
If the student inputs a number between 10 and 100 (both included), the program will tell
the user that number is between 10 and 100
For any other input, the program will indicate that it is an invalid input!

(The statements inside brackets are for your understanding purpose only)

Sample Input-1:
200 (input)
Sample Output-1:
invalid input!

Sample Input -2:


79
Sample Output-2:
number is between 10 and 100

ANSWER ------------------>
#include <stdio.h>

int main() {
int num;
scanf("%d", &num); // Input from student

if (num >= 0 && num <= 9) {


// Word representation for digits 0-9
if (num == 0)
printf("zero\n");
else if (num == 1)
printf("one\n");
else if (num == 2)
printf("two\n");
else if (num == 3)
printf("three\n");
else if (num == 4)
printf("four\n");
else if (num == 5)
printf("five\n");
else if (num == 6)
printf("six\n");
else if (num == 7)
printf("seven\n");
else if (num == 8)
printf("eight\n");
else if (num == 9)
printf("nine\n");
}
else if (num < 0) {
// Negative number
printf("number is negative\n");
}
else if (num >= 10 && num <= 100) {
// Number in range 10 to 100
printf("number is between 10 and 100\n");
}
else {
// Any other input
printf("invalid input!\n");
}

return 0;
}

[Link] Preference Checker


Craft a program should prompt the user to enter a seat number. Determine whether the
entered seat number is even or odd.
If the seat number is even print even and , check if it's divisible by 4. If yes, classify it as
back of the theater, otherwise, classify it as middle of the theater
If the seat number is odd print odd and, check if it's divisible by 3. If yes, classify it as
back of the theater; otherwise, classify it as front of the theater

The program should output appropriate messages indicating whether the seat number
is even or odd and its position in the theater.

Hint: Utilize the modulus operator to check if a number is even or odd. Further, consider
additional conditions based on divisibility by 4 or 3 to categorize seats into front,
middle, or back sections.

Sample Input 1:
10

Sample Output 1:
even
middle of the theater

Sample Input 2:
15

Sample Output 2:
odd
back of the theater
ANSWER ------------------>

#include <stdio.h>

int main() {
int seatNumber;
scanf("%d", &seatNumber); // Input seat number

if (seatNumber % 2 == 0) {
printf("even\n");
if (seatNumber % 4 == 0) {
printf("back of the theater\n");
} else {
printf("middle of the theater\n");
}
} else {
printf("odd\n");
if (seatNumber % 3 == 0) {
printf("back of the theater\n");
} else {
printf("front of the theater\n");
}
}

return 0;
}

[Link] Days Counter


Task:
For a calendar application, users input a month number(1-12). The program calculates
and prints the number of days in the specified month also print the quadrant that month
occures . If input is invalid month it should print Invalid Input

Quadrants:
First - From January to March ( 1 to 3)
Second - From April to June ( 4 to 6)
Third - From July to September (7 to 9)
Fourth - from October to December ( 10 to 12)

Explanation for Input and output 2:


8 occurs in Third quadrants and 8 stands for august month and it has 31 days

Sample input 1:
845

Sample output 1:
Invalid Input

Sample input 2:
8

Sample output 2:
Third
31

ANSWER ------------------>

#include <stdio.h>

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

if (month < 1 || month > 12) {


printf("Invalid Input\n");
} else {
// Determine and print quadrant
if (month >= 1 && month <= 3) {
printf("First\n");
} else if (month >= 4 && month <= 6) {
printf("Second\n");
} else if (month >= 7 && month <= 9) {
printf("Third\n");
} else {
printf("Fourth\n");
}

// Determine and print number of days


if (month == 2) {
printf("28\n"); // Assuming non-leap year
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
printf("30\n");
} else {
printf("31\n");
}
}

return 0;
}
8. Calculate Total Points Earned

Write a C program that prompts the user to input a transaction amount n. The program
should calculate and display the total points earned using the formula:

Total Points = n + nn + nnn, where:


n is the transaction amount.
nn is the transaction amount repeated twice.
nnn is the transaction amount repeated three times.

Input:
A single integer n representing the transaction amount.

Output:
The total points earned using the formula: n + nn + nnn.

Constraints:
The transaction amount n will be an integer between 1 and 9 inclusive.

Sample Input 1:
5

Sample Output 1:
615

Sample Input 2:
3

Sample Output 2:
369

ANSWER ------------------>

#include <stdio.h>

int main() {
int n, nn, nnn, total;

scanf("%d", &n);

// Check if n is in the valid range


if (n < 1 || n > 9) {
printf("Invalid Input\n");
return 0;
}

// Build nn and nnn


nn = n * 10 + n; // e.g., 5*10 + 5 = 55
nnn = n * 100 + nn; // e.g., 5*100 + 55 = 555

// Calculate total points


total = n + nn + nnn;

// Output the result


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

return 0;
}

9. Time for Tom to Catch Jerry

In a classic chase scenario, Tom is pursuing Jerry, who has consumed Tom's favourite
food. Jerry runs at a speed of X metres per second, while Tom chases at a speed of Y
metres per second. The task is to determine whether Tom will be able to catch Jerry. It's
important to note that initially, Jerry is not at the same position as Tom.

Task:
Craft a program that takes Jerry's speed (X), Tom's speed (Y), and the initial distance
between them as input, and calculates whether Tom will be able to catch Jerry.
Consider the scenario where Jerry starts at a different position than [Link] task is to
determine whether Tom, with his speed Y metres per second, will be able to catch Jerry,
who dashes at X metres per second. You'll need to calculate the time it takes for Tom to
catch Jerry based on their speeds and the initial distance between them.

Hint:
Use the formula: time = initialDistance / (y - x). If the calculated time is negative, Tom
cannot catch Jerry.

(The statements inside the brackets are for understanding purpose only)

Sample Input 1:
4 (Jerry's speed (X) in meter per second)
8 (Tom's speed (Y) in meter per second)
12 (Enter initial distance in meters)
Sample Output 1:
Tom will catch Jerry in 3.00 seconds.
Sample Input 2:
5
3
10
Sample Output 2:
Tom will not be able to catch Jerry.

ANSWER ------------------>

#include <stdio.h>

int main() {
float jerrySpeed, tomSpeed, distance, time;

// Input: Jerry's speed, Tom's speed, and distance


scanf("%f", &jerrySpeed);
scanf("%f", &tomSpeed);
scanf("%f", &distance);

// Check if Tom is faster than Jerry


if (tomSpeed > jerrySpeed) {
time = distance / (tomSpeed - jerrySpeed);
printf("Tom will catch Jerry in %.2f seconds.\n", time);
} else {
printf("Tom will not be able to catch Jerry.\n");
}

return 0;
}

10. Perfect Square


Task :
Develop a program that prompts users for a positive integer, checks if it's a perfect
square using math and conditionals, and output the result. To handle the negative
number print as "Please enter a Positive Integer".

Perfect square :A perfect square in mathematics is a number that may be expressed as


the result of multiplying an integer by itself. A number that may be written as the
product of an integer and itself .
Example : 4 is considered as perfect square since its result of 2*2
(The statements inside brackets are for your understanding purpose only)
Sample Input 1:
16 (input)
Sample Output 1:
16 is a Perfect Square

Sample Input 2:
2 (input)
Sample Output 2:
2 is not a Perfect Square

ANSWER ------------------>
#include <stdio.h>

int main() {
int num, i = 1, found = 0;

scanf("%d", &num);

if (num < 0) {
printf("Please enter a Positive Integer\n");
return 0;
}

while (i * i <= num) {


if (i * i == num) {
found = 1;
break;
}
i++;
}

if (found == 1) {
printf("%d is a Perfect Square\n", num);
} else {
printf("%d is not a Perfect Square\n", num);
}

return 0;
}

11. Arithmetic Calculator


Task:
Craft a program that should display a menu with options for basic arithmetic
operations.
Users will be prompted to enter their choice of operations (1 to 4) and two numbers. The
program will perform the selected operation and display the result. (Integers only)

Type of Operations:
1for Modulo
2 for Power
3 for Multiplication
4 for Division

Explanation for Sample Input and Output :


The type of operation is selected as 4 means Division.8/3=2 is displayed in Output .

Sample Input:
4
8
3
Sample Output:
2

ANSWER ------------------>

#include <stdio.h>

int main() {
int choice, a, b, result;

// Input choice and two numbers


scanf("%d", &choice);
scanf("%d", &a);
scanf("%d", &b);

// Perform operation based on user choice


if (choice == 1) {
result = a % b;
printf("%d\n", result);
} else if (choice == 2) {
// Power using loop
result = 1;
for (int i = 0; i < b; i++) {
result = result * a;
}
printf("%d\n", result);
} else if (choice == 3) {
result = a * b;
printf("%d\n", result);
} else if (choice == 4) {
result = a / b; // Integer division
printf("%d\n", result);
} else {
// Invalid choice
printf("Invalid choice\n");
}

return 0;
}

[Link] Check
Sce
nario :
You are developing a program to analyze user input. One of the requirements is to check
whether a given character is an alphabet or not. This functionality will help in validating
user input for certain operations where only alphabetic characters are allowed.
Task:1. Check weather the given number is a 5 digit number without using loops. In a
user authentication system, individuals are prompted to input a numerical PIN to
access their accounts. This program efficiently verifies whether the entered PIN is a 5-
digit number. Upon input, the system evaluates the length of the number without using
loops, determining if it precisely consists of five digits. If the PIN meets this criteria, the
system grants access, allowing users to securely manage t
Craft a program to check whether a given character is an alphabet or not. The program
should prompt the user to enter a character, then it should determine if the entered
character is an alphabet or not.
(The statements inside the brackets are for understanding purpose only)

Sample Input : 1
T (input)
Sample Output : 1
T is an Alphabet.
Sample Input : 2
7
Sample Output : 2
7 is not an Alphabet.

ANSWER ------------------>
#include <stdio.h>

int main() {
char ch;
scanf(" %c", &ch); // Notice the space before %c to skip any newline character

// Check if character is an alphabet (A-Z or a-z)


if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
printf("%c is an Alphabet.\n", ch);
} else {
printf("%c is not an Alphabet.\n", ch);
}

return 0;
}

13. Library Management System


Scenario:
You're tasked with developing a library management system for a local community
library. The system should calculate the charges incurred by library members for
overdue books. The library charges a fixed fee per day for each overdue book.

Task:
Write a program that prompts library members to input the number of days they have
exceeded the due date for their library books. The program should then calculate the
total overdue charges based on the number of days and the fixed daily charge set by the
library.

Till 5 days : Rs 2/day


6 to 10 days: Rs 3/day
11 to 15 days: Rs 4/day After
More than 15 days: Rs 5/day

Sample Input 1:
7

Sample Output 1:
21

Sample Input 2:
5

Sample Output 2:
10

ANSWER ------------------>
#include <stdio.h>

int main() {
int days, charges;

// Input number of overdue days


scanf("%d", &days);

// Calculate charges based on the days


if (days <= 5) {
charges = days * 2;
} else if (days <= 10) {
charges = days * 3;
} else if (days <= 15) {
charges = days * 4;
} else {
charges = days * 5;
}

// Output the total charge


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

return 0;
}

14. Calculate Kinetic and Potential Energy

Write a C program that calculates either kinetic energy or potential energy based on
user input. The user will choose between these two options:

[Link] energy: Calculated using the formula KE= 1/2×mass×velocity2.


[Link] energy: Calculated using the formula PE=mass×gravity×height, where
gravity==9.8m/s2.

Your program should:


Based on the choice:
For kinetic energy, ask for mass (in kilograms) and velocity (in meters/second).
For potential energy, ask for mass (in kilograms) and height (in meters).
Calculate and display the appropriate result (kinetic or potential energy).
If an invalid option is entered, print "Invalid Choice".

Constraints:
All inputs will be positive numbers.
You cannot use functions in this program.

Input:
Mass, velocity, and height are all positive floating-point numbers.
The user must enter either 1 or 2 as the calculation option.

Gravity is fixed at 9.8 m/s.


Output:
Display energy values rounded to two decimal places.

Sample Input 1:
1(choice)
10(mass)
5(velocity)

Sample Output 1:
Kinetic Energy: 125.00 Joules

Sample Input 2:
2(choice)
8(mass)
12(height)

Sample Output 2:
Potential Energy: 940.80 Joules

ANSWER ------------------>

#include <stdio.h>

int main() {
int choice;
float mass, velocity, height, energy;
float gravity = 9.8;

// Get user's choice


scanf("%d", &choice);

if (choice == 1) {
// Kinetic Energy: KE = 0.5 * mass * velocity^2
scanf("%f", &mass);
scanf("%f", &velocity);
energy = 0.5 * mass * velocity * velocity;
printf("Kinetic Energy: %.2f Joules\n", energy);
} else if (choice == 2) {
// Potential Energy: PE = mass * gravity * height
scanf("%f", &mass);
scanf("%f", &height);
energy = mass * gravity * height;
printf("Potential Energy: %.2f Joules\n", energy);
} else {
// Invalid input
printf("Invalid Choice\n");
}

return 0;
}

15. Traffic Monitoring

Scenario :
Imagine you're tasked with developing a program for a traffic monitoring system. The
system needs to check if vehicles are exceeding the speed limit on a given road.

Task:
Craft a program that prompts the user to input the speed limit and the speed of a
vehicle. The program should then determine if the vehicle's speed exceeds the speed
limit and issue a warning message if it does.
(The statements inside the brackets are for understanding purpose only)

Sample Input : 1
60 (Speed Limit)
75 (Vehicle's Speed)
Sample Output : 1
75 km Speed limit violation

Sample Input : 2
50 (Speed Limit)
48 (Vehicle's Speed)
Sample Output : 2
48 km within the speed limit

ANSWER ------------------>

#include <stdio.h>

int main() {
int speedLimit, vehicleSpeed;

// Input speed limit and vehicle speed


scanf("%d", &speedLimit);
scanf("%d", &vehicleSpeed);

// Check and print result


if (vehicleSpeed > speedLimit) {
printf("%d km Speed limit violation\n", vehicleSpeed);
} else {
printf("%d km within the speed limit\n", vehicleSpeed);
}

return 0;
}

16. Calculate Kinetic and Potential Energy

Write a C program that calculates either kinetic energy or potential energy based on
user input. The user will choose between these two options:

[Link] energy: Calculated using the formula KE= 1/2×mass×velocity2.


[Link] energy: Calculated using the formula PE=mass×gravity×height, where
gravity==9.8m/s2.

Your program should:


Based on the choice:
For kinetic energy, ask for mass (in kilograms) and velocity (in meters/second).
For potential energy, ask for mass (in kilograms) and height (in meters).
Calculate and display the appropriate result (kinetic or potential energy).
If an invalid option is entered, print "Invalid Choice".

Constraints:
All inputs will be positive numbers.
You cannot use functions in this program.

Input:
Mass, velocity, and height are all positive floating-point numbers.
The user must enter either 1 or 2 as the calculation option.

Gravity is fixed at 9.8 m/s.

Output:
Display energy values rounded to two decimal places.

Sample Input 1:
1(choice)
10(mass)
5(velocity)

Sample Output 1:
Kinetic Energy: 125.00 Joules

Sample Input 2:
2(choice)
8(mass)
12(height)

Sample Output 2:
Potential Energy: 940.80 Joules

ANSWER ------------------>

#include <stdio.h>

int main() {
int choice;
float mass, velocity, height, energy;
float gravity = 9.8;

// Input: user's choice


scanf("%d", &choice);

if (choice == 1) {
// Kinetic Energy
scanf("%f", &mass);
scanf("%f", &velocity);
energy = 0.5 * mass * velocity * velocity;
printf("Kinetic Energy: %.2f Joules\n", energy);
} else if (choice == 2) {
// Potential Energy
scanf("%f", &mass);
scanf("%f", &height);
energy = mass * gravity * height;
printf("Potential Energy: %.2f Joules\n", energy);
} else {
// Invalid option
printf("Invalid Choice\n");
}

return 0;
}
17. 5 digit number checking

Scenario:
Check weather the given number is a 5 digit number without using loops. In a user
authentication system, individuals are prompted to input a numerical PIN to access
their accounts. This program efficiently verifies whether the entered PIN is a 5-digit
number. Upon input, the system evaluates the length of the number without using
loops, determining if it precisely consists of five digits. If the PIN meets this criteria, the
system grants access, allowing users to securely manage their accounts. However, if
the PIN does not match the required format, the system prompts the user to re-enter a
valid 5-digit PIN for authentication, ensuring robust security measures are maintained.
(The input may be a positive or negative number ) .

Task:
• Get a numeric input from the user
• Check whether the given digit is a 5 digit number or not
• If it is a 5 digit number display “xx is a 5-digit number”
• If not, display “ yy is not a 5-digit number”

(The statements inside the brackets are for understanding purpose only)

Sample Input 1:
345 (3 digit input )

Sample Output1 :
345 is not a 5-digit number

Sample Input 2:
36893 (5 digit input )

Sample Output 2:
36893 is a 5-digit number

ANSWER ------------------>

#include <stdio.h>
#include <stdlib.h>
int main() {
int num, absNum;

// Input the number


scanf("%d", &num);

// Get absolute value to handle negative numbers


absNum = abs(num);

// Check if it's a 5-digit number


if (absNum >= 10000 && absNum <= 99999) {
printf("%d is a 5-digit number\n", num);
} else {
printf("%d is not a 5-digit number\n", num);
}

return 0;
}

18. Generate a 5 digit number


In a lottery ticket validation system, users input five individual digits corresponding to
their ticket numbers. This program efficiently combines the digits into a single number,
creating a unique ticket identifier. Users are prompted to input each digit, ensuring they
are between 0 and 9. Upon successful input, the program generates the combined
ticket number, which is then used to verify the ticket's validity and determine potential
winnings. This streamlined process enhances the efficiency of ticket validation,
allowing for swift verification and payout of prizes

Task:
• Get 5 numeric input from the user
• Check whether the numbers are single digit
• Also avoid negative numbers
• It should display the incorrect input as (Eg: “Invalid input for the first integer!”)
• Now, combine the 5 user inputs into a single 5 digit number
• Display “38764”

(The statements inside the brackets are for understanding purpose only)

Sample Input 1:
1(input 1)
7(input 2)
4(input 3)
7(input 4)
9(input 5)
Sample Output1 :
17479 (combined 5 digit number )

Sample Input 2:
2(input 1 )
6 (input 2)
-5 (invalid input)
1 (input 4)
89 (invalid input)

Sample Output 2:
Invalid input for the third integer!
Invalid input for the fifth integer!

ANSWER ------------------>

#include <stdio.h>

int main() {
int d1, d2, d3, d4, d5;
int valid = 1; // Flag to track validity

// Input 5 digits
scanf("%d", &d1);
scanf("%d", &d2);
scanf("%d", &d3);
scanf("%d", &d4);
scanf("%d", &d5);

// Validate each digit


if (d1 < 0 || d1 > 9) {
printf("Invalid input for the first integer!\n");
valid = 0;
}
if (d2 < 0 || d2 > 9) {
printf("Invalid input for the second integer!\n");
valid = 0;
}
if (d3 < 0 || d3 > 9) {
printf("Invalid input for the third integer!\n");
valid = 0;
}
if (d4 < 0 || d4 > 9) {
printf("Invalid input for the fourth integer!\n");
valid = 0;
}
if (d5 < 0 || d5 > 9) {
printf("Invalid input for the fifth integer!\n");
valid = 0;
}

// If all inputs are valid, combine and display the 5-digit number
if (valid) {
int combined = d1 * 10000 + d2 * 1000 + d3 * 100 + d4 * 10 + d5;
printf("%d\n", combined);
}

return 0;
}

[Link] for Tom to Catch Jerry

In a classic chase scenario, Tom is pursuing Jerry, who has consumed Tom's favourite
food. Jerry runs at a speed of X metres per second, while Tom chases at a speed of Y
metres per second. The task is to determine whether Tom will be able to catch Jerry. It's
important to note that initially, Jerry is not at the same position as Tom.

Task:
Craft a program that takes Jerry's speed (X), Tom's speed (Y), and the initial distance
between them as input, and calculates whether Tom will be able to catch Jerry.
Consider the scenario where Jerry starts at a different position than [Link] task is to
determine whether Tom, with his speed Y metres per second, will be able to catch Jerry,
who dashes at X metres per second. You'll need to calculate the time it takes for Tom to
catch Jerry based on their speeds and the initial distance between them.

Hint:
Use the formula: time = initialDistance / (y - x). If the calculated time is negative, Tom
cannot catch Jerry.

(The statements inside the brackets are for understanding purpose only)

Sample Input 1:
4 (Jerry's speed (X) in meter per second)
8 (Tom's speed (Y) in meter per second)
12 (Enter initial distance in meters)
Sample Output 1:
Tom will catch Jerry in 3.00 seconds.

Sample Input 2:
5
3
10
Sample Output 2:
Tom will not be able to catch Jerry.

ANSWER ------------------>

#include <stdio.h>

int main() {
float jerrySpeed, tomSpeed, distance, time;

// Input: Jerry's speed, Tom's speed, and distance


scanf("%f", &jerrySpeed);
scanf("%f", &tomSpeed);
scanf("%f", &distance);

// Check if Tom can catch Jerry


if (tomSpeed > jerrySpeed) {
time = distance / (tomSpeed - jerrySpeed);
printf("Tom will catch Jerry in %.2f seconds.\n", time);
} else {
printf("Tom will not be able to catch Jerry.\n");
}

return 0;
}

[Link] Square
Task :
Develop a program that prompts users for a positive integer, checks if it's a perfect
square using math and conditionals, and output the result. To handle the negative
number print as "Please enter a Positive Integer".

Perfect square :A perfect square in mathematics is a number that may be expressed as


the result of multiplying an integer by itself. A number that may be written as the
product of an integer and itself .
Example : 4 is considered as perfect square since its result of 2*2
(The statements inside brackets are for your understanding purpose only)
Sample Input 1:
16 (input)
Sample Output 1:
16 is a Perfect Square

Sample Input 2:
2 (input)
Sample Output 2:
2 is not a Perfect Square

ANSWER ------------------>

#include <stdio.h>

int main() {
int num, i = 1, found = 0;

// Input the number


scanf("%d", &num);

// Check if number is positive


if (num <= 0) {
printf("Please enter a Positive Integer\n");
return 0;
}

// Check for perfect square using simple multiplication


while (i * i <= num) {
if (i * i == num) {
found = 1;
break;
}
i++;
}

// Output result
if (found) {
printf("%d is a Perfect Square\n", num);
} else {
printf("%d is not a Perfect Square\n", num);
}

return 0;
}
21. employee's salary calculator
ABC Corporation has decided to reward its employees with a special New Year bonus.
The bonus percentage varies based on the employee's gender and salary.
Male employees receive a 5% bonus on their salary, while female employees receive a
10% bonus.
Additionally, if the employee's salary is less than $10,000, they are eligible for an extra
2% bonus.
The company wants a C program to automate the bonus calculation process.
Formula :
Percentage Value=(X/100)*Number
Task:
Write a C program to take input for the employee's salary and gender, calculate the
bonus based on the given criteria, and display the final salary that the employee will
receive.

Input Format:
Salary
Gender(M/F)

Output Format:
Bonus
Final Salary

ANSWER ------------------>

#include <stdio.h>

int main() {
float salary, bonus = 0, finalSalary;
char gender;

// Input salary and gender


scanf("%f", &salary);
scanf(" %c", &gender); // Space before %c handles newline

// Calculate base bonus based on gender


if (gender == 'M' || gender == 'm') {
bonus = (5.0 / 100) * salary;
} else if (gender == 'F' || gender == 'f') {
bonus = (10.0 / 100) * salary;
}

// Add extra 2% bonus if salary < 10000


if (salary < 10000) {
bonus += (2.0 / 100) * salary;
}

finalSalary = salary + bonus;

// Output the bonus and final salary


printf("Bonus: %.2f\n", bonus);
printf("Final Salary: %.2f\n", finalSalary);

return 0;
}

22. Calculate Total Points Earned

Write a C program that prompts the user to input a transaction amount n. The program
should calculate and display the total points earned using the formula:

Total Points = n + nn + nnn, where:


n is the transaction amount.
nn is the transaction amount repeated twice.
nnn is the transaction amount repeated three times.

Input:
A single integer n representing the transaction amount.

Output:
The total points earned using the formula: n + nn + nnn.

Constraints:
The transaction amount n will be an integer between 1 and 9 inclusive.

Sample Input 1:
5

Sample Output 1:
615

Sample Input 2:
3

Sample Output 2:
369
ANSWER ------------------>

#include <stdio.h>

int main() {
int n, nn, nnn, totalPoints;

// Input a single-digit transaction amount


scanf("%d", &n);

// Ensure n is between 1 and 9


if (n >= 1 && n <= 9) {
nn = n * 10 + n; // forms nn
nnn = n * 100 + n * 10 + n; // forms nnn

totalPoints = n + nn + nnn;

printf("%d\n", totalPoints);
} else {
printf("Invalid input! Enter a number between 1 and 9.\n");
}

return 0;
}

23. Check the Number Divisible by 4 and 6


Scenario :
You are a software developer working on a utility program that performs basic arithmetic
operations. Your task is to develop a program that checks if a given number is divisible
by both 4 and 6. This program should take user input, perform the necessary
calculations, and display whether the number satisfies the criteria of divisibility by 4
and 6.
Task :
Craft a program that prompts the user to input a number. The program should then
determine if the entered number is divisible by both 4 and 6. It should display an
appropriate message indicating whether the number meets the divisibility criteria or
not. Handle the Negative number us (“Negative Values are not allowed.”)
(The statements inside the brackets are for understanding purpose only)

Sample Input : 1
24 (Value)
Sample Output : 1
24 is divisible by both 4 and 6.
Sample Input : 2
10 (Value)
Sample Output : 2
10 is not divisible by both 4 and 6.

ANSWER ------------------>

#include <stdio.h>

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

if (num < 0) {
puts("Negative Values are not allowed.");
} else {
if (num % 4 == 0 && num % 6 == 0) {
printf("%d is divisible by both 4 and 6.\n", num);
} else {
printf("%d is not divisible by both 4 and 6.\n", num);
}
}

return 0;
}

24. Booking Confirmation Checker


Craft a program prompts the user to input a seat number within the valid range of 1 to
50. It then checks if the seat is divisible by 3 or 5. If the seat is within the range and
divisible by either 3 or 5, it prints Occupied otherwise, it prints Available. If the entered
seat number is outside the valid range or negative number, then print it as "Invalid".

Hint: Make sure to enter a seat number between 1 and 50 when prompted. The program
will tell you if the seat is available or already booked based on whether it is divisible by 3
or 5.

Sample Input 1:
23

Sample Output 1:
Available

Sample Input 2:
15

Sample Output 2:
Occupied

ANSWER ------------------>

#include <stdio.h>

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

if (seat < 1 || seat > 50) {


puts("Invalid");
} else {
if (seat % 3 == 0 || seat % 5 == 0) {
puts("Occupied");
} else {
puts("Available");
}
}

return 0;
}

25. employee's salary calculator


ABC Corporation has decided to reward its employees with a special New Year bonus.
The bonus percentage varies based on the employee's gender and salary.
Male employees receive a 5% bonus on their salary, while female employees receive a
10% bonus.
Additionally, if the employee's salary is less than $10,000, they are eligible for an extra
2% bonus.
The company wants a C program to automate the bonus calculation process.
Formula :
Percentage Value=(X/100)*Number
Task:
Write a C program to take input for the employee's salary and gender, calculate the
bonus based on the given criteria, and display the final salary that the employee will
receive.

Input Format:
Salary
Gender(M/F)

Output Format:
Bonus
Final Salary

ANSWER ------------------>

#include <stdio.h>

int main() {
float salary, bonus = 0;
char gender;

scanf("%f\n%c", &salary, &gender);

if (gender == 'M' || gender == 'm') {


bonus = (5.0 / 100.0) * salary;
} else if (gender == 'F' || gender == 'f') {
bonus = (10.0 / 100.0) * salary;
} else {
puts("Invalid gender");
return 0;
}

if (salary < 10000) {


bonus = bonus + (2.0 / 100.0) * salary;
}

float finalSalary = salary + bonus;

// Display bonus and final salary


printf("Bonus: %.2f\n", bonus);
printf("Final Salary: %.2f\n", finalSalary);

return 0;
}

26 . Determine the Best Deal Among Three Brands at a Supermarket


You are at a supermarket comparing the prices of the same product from three different
brands. Write a C program that takes the prices of the product from three different
brands and determines which brand offers the best deal (i.e., the lowest price). Your
goal is to choose the brand that helps save the most on your monthly grocery bill.
Input:
Three floating-point numbers representing the prices of the same product from three
different brands.

Output:
The program should print which brand offers the best deal. If two or more brands have
the same lowest price, print "Multiple brands have the same price."

Constraints:
The prices are positive floating-point numbers.
You must not use any inbuilt functions or user-defined functions.

Sample Input 1:
12.99 10.50 14.25

Sample Output 1:
Brand 2 offers the best deal with a price of 10.50

Sample Input 2:
5.99 5.99 6.50

Sample Output 2:
Multiple brands have the same price.

ANSWER ------------------>

#include <stdio.h>

int main() {
float price1, price2, price3;
scanf("%f %f %f", &price1, &price2, &price3);

if (price1 <= 0 || price2 <= 0 || price3 <= 0) {


puts("Invalid price input");
return 0;
}

// Check if all three are equal


if (price1 == price2 && price2 == price3) {
puts("Multiple brands have the same price.");
}
// Check if any two are equal and smallest
else if ((price1 == price2 && price1 < price3) ||
(price1 == price3 && price1 < price2) ||
(price2 == price3 && price2 < price1)) {
puts("Multiple brands have the same price.");
}
// Else find the lowest
else {
if (price1 < price2 && price1 < price3) {
printf("Brand 1 offers the best deal with a price of %.2f\n", price1);
} else if (price2 < price1 && price2 < price3) {
printf("Brand 2 offers the best deal with a price of %.2f\n", price2);
} else {
printf("Brand 3 offers the best deal with a price of %.2f\n", price3);
}
}

return 0;
}

27. Calculate Sunrise and Sunset Times Based on Month Input

Write a C program that prompts the user to input a month (1-12). Based on the entered
month, the program should display the approximate sunrise and sunset times using the
following criteria:

For the months of January, February, October, November, and December:


Sunrise: 7:00 AM
Sunset: 5:30 PM
For the month of March:
Sunrise: 6:30 AM
Sunset: 6:30 PM
For the months of April, May, June, July, and August:
Sunrise: 5:30 AM
Sunset: 7:30 PM
For the month of September:
Sunrise: 6:30 AM
Sunset: 6:00 PM
The program must not use functions or inbuilt functions to solve this problem.

Input:
An integer value representing the month (1 for January, 2 for February, etc.).

Output:
Display the sunrise and sunset times based on the entered month.

Constraints:
The input month should be between 1 and 12 inclusive.
The output should be displayed as follows:
"Sunrise: HH AM/PM"
"Sunset: HH AM/PM"

Sample Input 1:
1(month)

Sample Output 1:
Sunrise: 7:00 AM
Sunset: 5:30 PM

Sample Input 2:
15

Sample Output 2:
Invalid month.

ANSWER ------------------>

#include <stdio.h>

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

if (month < 1 || month > 12) {


puts("Invalid month.");
} else {
if (month == 1 || month == 2 || month == 10 || month == 11 || month == 12) {
puts("Sunrise: 7:00 AM");
puts("Sunset: 5:30 PM");
} else if (month == 3) {
puts("Sunrise: 6:30 AM");
puts("Sunset: 6:30 PM");
} else if (month == 4 || month == 5 || month == 6 || month == 7 || month == 8) {
puts("Sunrise: 5:30 AM");
puts("Sunset: 7:30 PM");
} else if (month == 9) {
puts("Sunrise: 6:30 AM");
puts("Sunset: 6:00 PM");
}
}

return 0;
}

28. 2. Traffic Light System

Scenario :
Imagine you're developing software for a smart city's traffic management system. Your
task is to create a program that simulates a traffic light at an intersection. This program
will control the traffic flow by displaying appropriate messages based on the colour of
the traffic light. If the light is Red, it should print "Stop"; if it's Yellow, it should print
"Proceed with caution"; and if it's Green, it should print "Go".
Task :
Craft a program that simulates a traffic light. Implement to take the current colour of the
traffic light as input and print the corresponding message: "Stop" for Red, "Proceed with
caution" for Yellow, and "Go" for Green. Handle the Invalid Colour us (“Invalid colour.”)
(The statements inside the brackets are for understanding purpose only)

Sample Input : 1
R (Colour of Traffic Light)
Sample Output : 1
Stop
Sample Input : 2
Y (Colour of Traffic Light)
Sample Output : 2
Proceed with caution

ANSWER ------------------>
#include <stdio.h>

int main() {
char color;
scanf(" %c", &color); // space before %c handles newline/whitespace

if (color == 'R' || color == 'r') {


printf("Stop\n");
} else if (color == 'Y' || color == 'y') {
printf("Proceed with caution\n");
} else if (color == 'G' || color == 'g') {
printf("Go\n");
} else {
printf("Invalid colour.\n");
}

return 0;
}

29. Classroom Chaos: Parity Party!


Scenario:
It's a fun Friday afternoon in your computer science class. Your teacher, Ms. Li, is
introducing the concept of parity - whether a number is even or odd. To make it
engaging, she announces a game called "Parity Party!"

Task:
Ms. Li has a secret range of numbers (1 to 100 in this example). If the range greater than
100 then print "Invalid Range" Students take turns calling out integers. Based on the
number called out and the secret range, Ms. Li responds with one of three phrases:
1. If n is odd, print Weird
2. If n is even and in the inclusive range of 2 to 5 , print Not Weird
3. If n is even and in the inclusive range of 6 to 20, print Weird
4. If n is even and greater than 20, print Not Weird

Sample Input:
25
Sample Output:
Weird

ANSWER ------------------>
#include <stdio.h>

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

if (n > 100) {
printf("Invalid Range\n");
} else {
if (n % 2 != 0) {
printf("Weird\n");
} else {
if (n >= 2 && n <= 5) {
printf("Not Weird\n");
} else if (n >= 6 && n <= 20) {
printf("Weird\n");
} else if (n > 20) {
printf("Not Weird\n");
}
}
}

return 0;
}

30. Calculating Taxi Fare

Sarah, a busy professional, finishes her workday and needs to attend an important
meeting across town. She hails a taxi and travels a distance of 15 kilometers to reach
her destination. The taxi driver, using the fare calculation system, computes the fare as
follows:

Since Sarah's journey is between 10 and 100 kilometers, the fare is calculated as
follows:

$110 for the first 10 kilometers


$10 for each additional kilometer beyond the initial 10 kilometers
So, the total fare for Sarah's journey is calculated as $110 (for the first 10 kilometers)
plus $50 (for the additional 5 kilometers at $10 per kilometer), resulting in a total fare of
$160.

The taxi driver displays the fare on the meter, and Sarah pays the amount before exiting
the taxi, satisfied with the convenient and transparent fare calculation system. This new
system ensures fair pricing for passengers while providing clarity for both passengers
and drivers alike, enhancing the overall taxi experience in the city.

Task :

Write a C program to calculate the transportation fare based on the kilometers covered.

Prompt the user to enter the kilometers covered.


• Determine the fare based on the following conditions:
• If the kilometers covered are less than or equal to 10, the fare is 11 per kilometer.
• If the kilometers covered are between 11 and 100 (inclusive), the fare is 10 per
kilometer after the first 10 kilometers.
• If the kilometers covered are more than 100, the fare is 9 per kilometer after the first
100 kilometers.
• Calculate and display the total amount to pay. Display "Invalid" for invalid inputs like
negative numbers and zero.

(The statements inside the brackets are for understanding purpose only)

Sample Input 1 :

105 (kilometers covered)

Sample Output 1 :

Total amount to pay is 1055

Sample Input 2 :

100

Sample Output 2 :

Total amount to pay is 1010

ANSWER ------------------>

#include <stdio.h>

int main() {
int km, fare;

// Input kilometers covered


scanf("%d", &km);

if (km <= 0) {
printf("Invalid\n");
} else if (km <= 10) {
fare = km * 11;
printf("Total amount to pay is %d\n", fare);
} else if (km <= 100) {
fare = 110 + (km - 10) * 10;
printf("Total amount to pay is %d\n", fare);
} else {
fare = 110 + 90 * 10 + (km - 100) * 9;
printf("Total amount to pay is %d\n", fare);
}

return 0;
}

31. Gas Mileage Calculator

Scenario :
You're developing a gas mileage calculator program in your office. The program should
prompt the user to input the number of miles driven and the gallons of gas used. After
calculating the miles per gallon (MPG), the program should classify the gas mileage as
Poor (<15 mpg), Average (15-25 mpg), Good (26-35 mpg), or Excellent (36 and above).
Task:
Develop a program that prompts the user to input miles driven and gallons used,
calculates MPG, and classifies gas mileage. The program should output the calculated
MPG and its classification as Poor, Average, Good, or Excellent based on given ranges.
Hint : mpg = miles / gallons;
(The statements inside the brackets are for understanding purpose only)

Sample Input : 1
600 (Number of miles driven)
20 (Gallons of gas used)
Sample Output : 1
30.00 (Miles per gallon)
Good (Gas mileage)

Sample Input : 2
1800
10
Sample Output : 2
180.00
Excellent

ANSWER ------------------>

#include <stdio.h>
int main() {
float miles, gallons, mpg;

// Input
scanf("%f", &miles);
scanf("%f", &gallons);

// Calculate MPG
mpg = miles / gallons;

// Output MPG
printf("%.2f\n", mpg);

// Classify mileage
if (mpg < 15) {
printf("Poor\n");
} else if (mpg >= 15 && mpg <= 25) {
printf("Average\n");
} else if (mpg >= 26 && mpg <= 35) {
printf("Good\n");
} else if (mpg >= 36) {
printf("Excellent\n");
}

return 0;
}

32. Salary Prediction


Scenario :
Consider that you are a human resources manager at a mid-sized company. Every
year, the company conducts performance evaluations for its employees, and based on
their performance, they receive a salary increment. To streamline the process and
ensure transparency, you've decided to implement a program that calculates and
displays the new salary of each employee based on their current salary and the
percentage increment provided.

Requirements:
1. The program should prompt the user to input the current salary of the employee and
the percentage increment they are eligible for.
2. It should calculate the new salary based on the current salary and the percentage
increment provided.
3. The program should display the new salary to the user in a clear and understandable
format.
Task :
Craft a program to calculate and display the new salary of an employee based on
their current salary and the percentage increment provided to them by the company.

(The statements inside brackets are for your understanding purpose only)

Sample Input 1 :
50000 (current salary)
20 (percentage of increment)

Sample Output 1 :
60000

Sample Input 2 :
35000
5

Sample Output 2 :
36750

ANSWER ------------------>

#include <stdio.h>

int main() {
float currentSalary, incrementPercentage, incrementAmount, newSalary;

// Input: Current salary and increment percentage


scanf("%f", &currentSalary);
scanf("%f", &incrementPercentage);

// Calculate increment amount


incrementAmount = (incrementPercentage / 100) * currentSalary;

// Calculate new salary


newSalary = currentSalary + incrementAmount;

// Output: New salary


printf("%.0f\n", newSalary);

return 0;
}

33. Age Analyzer and Voter Eligibility Checker


Craft a program that prompts the user to input their age. The program that analyzes the
age of an individual, checking their eligibility to vote and categorizing them into different
age groups. The program should take an age as input, validate its range (between 0 and
120), and provide relevant information based on the following criteria:

If the age is 18 or older, the program should print You are eligible to vote
If the age is less than 18, the program should print You are not eligible to vote
Additionally, the program should categorize the age into one of the following groups:
Child (ages 0-12)
Teenager (ages 13-19)
Adult (ages 20-59)
Senior (ages 60-120)
Invalid age (above 120)
If the entered age is outside the range of 0 to 120, the program should display Invalid
age

Sample Input 1:
25

Sample Output 1:
You are eligible to vote
Adult

Sample Input 2:
15

Sample Output: 2:
You are not eligible to vote
Teenager

ANSWER ------------------>

#include <stdio.h>

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

if(age < 0 || age > 120) {


printf("Invalid age\n");
} else {
// Check voter eligibility
if(age >= 18) {
printf("You are eligible to vote\n");
} else {
printf("You are not eligible to vote\n");
}

// Check age category


if(age >= 0 && age <= 12) {
printf("Child\n");
} else if(age >= 13 && age <= 19) {
printf("Teenager\n");
} else if(age >= 20 && age <= 59) {
printf("Adult\n");
} else if(age >= 60 && age <= 120) {
printf("Senior\n");
}
}

return 0;
}

34. The Fitness Challenge


Task:
Craft a program that prompts the user to input the number of steps they took in a day
and time(in minutes) taken for the activity. The program should then categorize their
fitness level as follows:

Conditons :(Steps less than 1 will be considered as invalid )


Less than 5000 steps: Activity Level - 0
5000 to 9999 steps: Activity Level - 25
10000 to 14999 steps: Activity Level - 50
15000 steps and above: Activity Level - 100
Formula to calcluate activity range = steps/ time taken.
Output :
Print the activity range with two decimal points
Display "Invalid Input" for any invalid input.

Explanation for Sample Input and Output 1:


The entered step count 11000 falls under the range from 10000 to 14999 steps so
activity Level is displayed as 50.
Active range =11000/100=110 (100 time taken) and its printed with two decimal point as
110.00

Sample Input:
11000
100
Sample output:
50
110.00
ANSWER ------------------>

#include <stdio.h>

int main() {
int steps, time;
float activityRange;

scanf("%d", &steps);
scanf("%d", &time);

if(steps < 1 || time <= 0) {


printf("Invalid Input\n");
} else {
// Determine activity level
if(steps < 5000) {
printf("0\n");
} else if(steps <= 9999) {
printf("25\n");
} else if(steps <= 14999) {
printf("50\n");
} else {
printf("100\n");
}

activityRange = (float)steps / time;


printf("%.2f\n", activityRange);
}

return 0;
}

35.
1. Calculate the area of different shapes
Write a C program that presents a menu to the user to choose a shape (circle, rectangle,
or triangle). The program should then ask for the necessary dimensions based on the
user’s choice and calculate the area of the chosen shape. The program should print the
calculated area with two decimal precision.

Shapes Choice
1. Circle
2. Rectangle
3. Triangle
if choice is not between 1 to 3 then print Invalid Choice
Hint: For pi value use 22/7 and not 3.14
(The statements inside the brackets are for understanding purpose only)

Sample Input 1:
1 (shape choice)
5 (radius)

Sample Output 1:
Area of the circle: 78.57

Sample Input 2:
2 (shape choice)
4 (length)
5 (width)

Sample Output 2:
Area of the rectangle: 20.00

Input Value Format


For circle
radius - float

For rectangle
length - float
width - float

For triangle
base - float
height - float

ANSWER ------------------>
#include <stdio.h>

int main() {
int choice;
float radius, length, width, base, height, area;

// Prompt shape selection


scanf("%d", &choice);

if (choice == 1) {
// Circle
scanf("%f", &radius);
area = (22.0 / 7.0) * radius * radius;
printf("Area of the circle: %.2f\n", area);
} else if (choice == 2) {
// Rectangle
scanf("%f", &length);
scanf("%f", &width);
area = length * width;
printf("Area of the rectangle: %.2f\n", area);
} else if (choice == 3) {
// Triangle
scanf("%f", &base);
scanf("%f", &height);
area = 0.5 * base * height;
printf("Area of the triangle: %.2f\n", area);
} else {
printf("Invalid Choice\n");
}

return 0;
}

36. Determine the Best Deal Among Three Brands at a Supermarket


You are at a supermarket comparing the prices of the same product from three different
brands. Write a C program that takes the prices of the product from three different
brands and determines which brand offers the best deal (i.e., the lowest price). Your
goal is to choose the brand that helps save the most on your monthly grocery bill.

Input:
Three floating-point numbers representing the prices of the same product from three
different brands.

Output:
The program should print which brand offers the best deal. If two or more brands have
the same lowest price, print "Multiple brands have the same price."

Constraints:
The prices are positive floating-point numbers.
You must not use any inbuilt functions or user-defined functions.

Sample Input 1:
12.99 10.50 14.25

Sample Output 1:
Brand 2 offers the best deal with a price of 10.50
Sample Input 2:
5.99 5.99 6.50

Sample Output 2:
Multiple brands have the same price.

ANSWER ------------------>
#include <stdio.h>

int main() {
float price1, price2, price3;

// Read the three brand prices


scanf("%f%f%f", &price1, &price2, &price3);

// Check if multiple brands have the same lowest price


if ((price1 == price2 && price1 < price3) ||
(price1 == price3 && price1 < price2) ||
(price2 == price3 && price2 < price1) ||
(price1 == price2 && price2 == price3)) {
printf("Multiple brands have the same price.\n");
}
else if (price1 < price2 && price1 < price3) {
printf("Brand 1 offers the best deal with a price of %.2f\n", price1);
}
else if (price2 < price1 && price2 < price3) {
printf("Brand 2 offers the best deal with a price of %.2f\n", price2);
}
else {
printf("Brand 3 offers the best deal with a price of %.2f\n", price3);
}

return 0;
}

37. Vehicle Registration Information System


Create a program that prompts the user to enter details about a vehicle’s size, fuel type,
and intended purpose. The program should:

1. Read the vehicle size as S or M or L, where S means Small, M is Medium, L is Large.


For input S output should be Vehicle Size: Small
2. Read the fuel type as G or D or E, where G is Gasoline, D is Diesel, E is Electric. For
input G output should be Fuel Type: Gasoline
3. Read the vehicle’s purpose as 1 or 2 or 3, where 1 means Personal Use, 2 means
Commercial Use, 3 means Public Transport. For input 2 output should be Purpose:
Commercial use
4. Validate the inputs and display the corresponding information.
5. If any input is invalid, the program should inform the user and terminate. Like Invalid
vehicle size. Invalid fuel type. Invalid purpose.

(The statements inside brackets are for your understanding purpose only)

Sample Input 1:
S (vehicle type)
G (fuel type)
E (purpose)

Sample Output 1:
Vehicle Size: Small
Fuel Type: Gasoline
Invalid purpose

Sample Input 2:
M
D
2

Sample Output 2:
Vehicle Size: Medium
Fuel Type: Diesel
Purpose: Commercial use

ANSWER ------------------>
#include <stdio.h>

int main() {
char size;
char fuel;
char purpose;

// Input
scanf(" %c", &size); // Vehicle size: S/M/L
scanf(" %c", &fuel); // Fuel type: G/D/E
scanf(" %c", &purpose); // Purpose: 1/2/3

// Vehicle Size Check


if (size == 'S') {
printf("Vehicle Size: Small\n");
} else if (size == 'M') {
printf("Vehicle Size: Medium\n");
} else if (size == 'L') {
printf("Vehicle Size: Large\n");
} else {
printf("Invalid vehicle size\n");
return 0;
}

// Fuel Type Check


if (fuel == 'G') {
printf("Fuel Type: Gasoline\n");
} else if (fuel == 'D') {
printf("Fuel Type: Diesel\n");
} else if (fuel == 'E') {
printf("Fuel Type: Electric\n");
} else {
printf("Invalid fuel type\n");
return 0;
}

// Purpose Check
if (purpose == '1') {
printf("Purpose: Personal use\n");
} else if (purpose == '2') {
printf("Purpose: Commercial use\n");
} else if (purpose == '3') {
printf("Purpose: Public Transport\n");
} else {
printf("Invalid purpose\n");
}

return 0;
}

38.
2. BMI calculator

Scenario:
In a health clinic, individuals input their weight and height into this program for a quick
assessment of their Body Mass Index (BMI). After calculating the BMI, the program
categorizes individuals into different weight categories: underweight, normal weight,
overweight, or obese. This tool aids both individuals and healthcare professionals in
gauging potential health risks associated with weight, promoting informed decisions
regarding lifestyle and wellness.
Task:
• Get two inputs for weight and height to calculate BMI
• If invalid height is entered, display “Error: Height | weight cannot be zero or negative”
• (hint : bmi = weight / (height * height))
• Display the BMI with single decimal places
• Display If the BMI is
o Less than 18.5 “Underweight”
o Less than or equal to 25 “Normal weight”
o Less than or equal to 30 “Overweight”
o Less than or equal to 50 “Obese”
Print “Error” if value is not in the range of 0-50 Explanation For Input and Output-1:
BMI=65/(1.8×1.8)=20.06 (Which is Rounded as 20.1)

(The statements inside the brackets are for understanding purpose only)

Sample Input 1:
65 (weight)
1.8 (height)

Sample Output1 :
20.1 (BMI value)
Normal weight

Sample Input 2:
100
1.9

Sample Output 2:
27.7
Overweight

ANSWER ------------------>

#include <stdio.h>

int main() {
float weight, height, bmi;

// Input
scanf("%f", &weight);
scanf("%f", &height);

// Check for invalid input


if (weight <= 0 || height <= 0) {
printf("Error: Height | weight cannot be zero or negative\n");
return 0;
}

// Calculate BMI
bmi = weight / (height * height);

// Check if BMI is in valid range


if (bmi <= 0 || bmi > 50) {
printf("Error\n");
return 0;
}

// Display BMI with one decimal place


printf("%.1f\n", bmi);

// Classification
if (bmi < 18.5) {
printf("Underweight\n");
} else if (bmi <= 25) {
printf("Normal weight\n");
} else if (bmi <= 30) {
printf("Overweight\n");
} else {
printf("Obese\n");
}

return 0;
}

39. Ticketing System

You're developing a ticketing system for a theme park. One of the requirements is to
determine whether a person qualifies for a discount based on their age. If the person is
12 years old or younger, they are eligible for a child discount; otherwise, they must
purchase a regular ticket at full price.

Task:
Craft a program that checks the age of the person and assigns the appropriate ticket
type based on the age criteria mentioned above. Handle the Negative value and age
>100 as "Invalid Age."without quotes. No upper limit for age.
(The statements inside the brackets are for understanding purpose only)

Sample Input : 1
13 (Age)
Sample Output : 1
You are 13 years old. Purchase a regular ticket.

Sample Input : 2
11
Sample Output : 2
You are 11 years old. Qualified for a child discount ticket.

ANSWER ------------------>

#include <stdio.h>

int main() {
int age;

// Input
scanf("%d", &age);

// Validation
if (age < 0 || age > 100) {
printf("Invalid Age\n");
} else {
printf("You are %d years old. ", age);
if (age <= 12) {
printf("Qualified for a child discount ticket.\n");
} else {
printf("Purchase a regular ticket.\n");
}
}

return 0;
}

40. Buzz Numbers

Scenario :
In a mathematics class, students are learning about buzz numbers, a concept where a
number is considered a "buzz" if it is divisible by 9 or if it ends with the digit 9. The
teacher wants to develop a program to help students understand the concept better. It
should prompt the user to enter a number and then output whether the number is a
buzz number or not based on the given input.
Task:
Craft a program that takes a user-inputted integer and determines whether it is a buzz
number or not. The program should use only conditional statements.
(The statements inside the brackets are for understanding purpose only)

Sample Input : 1
18 (Number)
Sample Output : 1
18 is a buzz number.
Sample Input : 2
29 (Number)
Sample Output : 2
29 is a buzz number.

ANSWER ------------------>
#include <stdio.h>

int main() {
int number;

// Input
scanf("%d", &number);

// Check for buzz number


if (number % 9 == 0 || number % 10 == 9) {
printf("%d is a buzz number.\n", number);
} else {
printf("%d is not a buzz number.\n", number);
}

return 0;
}

41. Number in range


Your task is to refine and integrate the provided C program into the school’s educational
software suite. The program should function as follows:
When a student inputs a digit, the program will print the word representation of that digit
from (0 to 9) [ 0-zero, 1-one, 9-nine] and all letters in smaller case.
If the student inputs a negative number, the program will inform them that the number is
negative
If the student inputs a number between 10 and 100 (both included), the program will tell
the user that number is between 10 and 100
For any other input, the program will indicate that it is an invalid input!

(The statements inside brackets are for your understanding purpose only)

Sample Input-1:
200 (input)
Sample Output-1:
invalid input!

Sample Input -2:


79
Sample Output-2:
number is between 10 and 100

ANSWER ------------------>
#include <stdio.h>

int main() {
int number;

// Input from user


scanf("%d", &number);

// Conditions
if (number == 0)
printf("zero\n");
else if (number == 1)
printf("one\n");
else if (number == 2)
printf("two\n");
else if (number == 3)
printf("three\n");
else if (number == 4)
printf("four\n");
else if (number == 5)
printf("five\n");
else if (number == 6)
printf("six\n");
else if (number == 7)
printf("seven\n");
else if (number == 8)
printf("eight\n");
else if (number == 9)
printf("nine\n");
else if (number < 0)
printf("number is negative\n");
else if (number >= 10 && number <= 100)
printf("number is between 10 and 100\n");
else
printf("invalid input!\n");

return 0;
}

42. Seating Preference Checker


Craft a program should prompt the user to enter a seat number. Determine whether the
entered seat number is even or odd.
If the seat number is even print even and , check if it's divisible by 4. If yes, classify it as
back of the theater, otherwise, classify it as middle of the theater
If the seat number is odd print odd and, check if it's divisible by 3. If yes, classify it as
back of the theater; otherwise, classify it as front of the theater

The program should output appropriate messages indicating whether the seat number
is even or odd and its position in the theater.

Hint: Utilize the modulus operator to check if a number is even or odd. Further, consider
additional conditions based on divisibility by 4 or 3 to categorize seats into front,
middle, or back sections.

Sample Input 1:
10

Sample Output 1:
even
middle of the theater

Sample Input 2:
15

Sample Output 2:
odd
back of the theater

#include <stdio.h>

int main() {
int seat;

// Get input
scanf("%d", &seat);

// Check even or odd


if (seat % 2 == 0) {
printf("even\n");

// Check for divisibility by 4


if (seat % 4 == 0)
printf("back of the theater\n");
else
printf("middle of the theater\n");
} else {
printf("odd\n");

// Check for divisibility by 3


if (seat % 3 == 0)
printf("back of the theater\n");
else
printf("front of the theater\n");
}

return 0;
}

43. Determining Compass Direction Based on Input Angle

Write a C program that takes an angle as input and determines the corresponding
compass direction. The program should:

The program should determine and print the corresponding compass direction
according to the following ranges:
North: Between 337 to 22 degrees.
Northeast: Between 23 to 67 degrees.
East: Between 68 to 112 degrees.
Southeast: Between 113 to 157 degrees.
South: Between 158 to 202 degrees.
Southwest: Between 203 to 247 degrees.
West: Between 248 to 292 degrees.
Northwest: Between 293 to 337 degrees.
The input angle falls within the range of 0 to 360 degrees.

Constraints:

The input will be an integer angle in degrees.


If the input angle is negative or greater than 360, it should print “ Invalid Input”
The program must use if-else statements without any inbuilt functions.

Input:

An integer representing the angle (in degrees).


Output:

A string representing the corresponding compass direction.

Sample Input 1:
45

Sample Output 1:

Northeast

Sample Input 2:

370
Sample Output 2:

Invalid Input

ANSWER ------------------>

#include <stdio.h>

int main() {
int angle;

// Input the angle


scanf("%d", &angle);

// Check for invalid input


if (angle < 0 || angle > 360) {
printf("Invalid Input\n");
}
else {
if ((angle >= 337 && angle <= 360) || (angle >= 0 && angle <= 22)) {
printf("North\n");
}
else if (angle >= 23 && angle <= 67) {
printf("Northeast\n");
}
else if (angle >= 68 && angle <= 112) {
printf("East\n");
}
else if (angle >= 113 && angle <= 157) {
printf("Southeast\n");
}
else if (angle >= 158 && angle <=

44. Classroom Chaos: Parity Party!


Scenario:
It's a fun Friday afternoon in your computer science class. Your teacher, Ms. Li, is
introducing the concept of parity - whether a number is even or odd. To make it
engaging, she announces a game called "Parity Party!"

Task:
Ms. Li has a secret range of numbers (1 to 100 in this example). If the range greater than
100 then print "Invalid Range" Students take turns calling out integers. Based on the
number called out and the secret range, Ms. Li responds with one of three phrases:
1. If n is odd, print Weird
2. If n is even and in the inclusive range of 2 to 5 , print Not Weird
3. If n is even and in the inclusive range of 6 to 20, print Weird
4. If n is even and greater than 20, print Not Weird

Sample Input:
25
Sample Output:
Weird

ANSWER ------------------>

#include <stdio.h>

int main() {
int n;

// Input number
scanf("%d", &n);

// Check for valid range


if (n > 100) {
printf("Invalid Range\n");
}
else {
// Check if number is odd
if (n % 2 != 0) {
printf("Weird\n");
}
else {
// Number is even
if (n >= 2 && n <= 5) {
printf("Not Weird\n");
}
else if (n >= 6 && n <= 20) {
printf("Weird\n");
}
else if (n > 20) {
printf("Not Weird\n");
}
}
}

return 0;
}

You might also like