Explore fun coding problems in C using nested loops. Learn how to solve real-world challenges like tracking sports scores or designing seating charts. Perfect for beginners and anyone wanting to get better at programming.
Multiplication Table Generator
Imagine you are a teacher preparing multiplication tables for your students. You need to print multiplication tables for numbers from 1 up to a certain number, so the students can use them for practice. Write a C program that takes a maximum number as input and generates the multiplication tables for all numbers from 1 to the input number.
Test Case
Input
Enter the maximum number to generate multiplication tables: 2
Expected Output
Multiplication table for 1:
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
1 x 5 = 5
1 x 6 = 6
1 x 7 = 7
1 x 8 = 8
1 x 9 = 9
1 x 10 = 10
Multiplication table for 2:
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
- The program starts by asking the user to enter a maximum number to specify the range for multiplication tables. This input is stored in the variable
maxNumber
. - The program then uses a nested loop structure to generate the tables.
- The outer loop starts from 1 and runs up to
maxNumber
. - Inside this outer loop, an inner loop runs from 1 to 10 to generate the products for the current number.
- The inner loop calculates the product of the current number from the outer loop and the current value of the inner loop. This product is then printed in the format
i x j = product
. - After completing the inner loop for one number, the program moves to the next number in the outer loop and repeats the process. Once all numbers are processed, the program ends.
#include <stdio.h> int main() { int maxNumber; printf("Enter the maximum number to generate multiplication tables: "); scanf("%d", &maxNumber); for (int i = 1; i <= maxNumber; i++) { printf("Multiplication table for %d:\n", i); for (int j = 1; j <= 10; j++) { printf("%d x %d = %d\n", i, j, i * j); } printf("\n"); } return 0; }
Movie Theater Seating Chart
Imagine you are managing a movie theater, and you need to create a seating chart for your customers. Each seat is identified by a row and seat number. Write a program in C language that takes the number of rows and the number of seats per row as input and generates a seating chart.
Test Case
Input
Enter the number of rows: 3
Enter the number of seats per row: 5
Expected Output
Row 1 Seat 1 Row 1 Seat 2 Row 1 Seat 3 Row 1 Seat 4 Row 1 Seat 5
Row 2 Seat 1 Row 2 Seat 2 Row 2 Seat 3 Row 2 Seat 4 Row 2 Seat 5
Row 3 Seat 1 Row 3 Seat 2 Row 3 Seat 3 Row 3 Seat 4 Row 3 Seat 5
- The program starts by asking the user to input the number of rows and the number of seats per row. These inputs are stored in the variables
rows
andseatsPerRow
. - The program then uses a nested loop structure to generate the seating chart.
- The outer loop starts from 1 and iterates through each row.
- Inside the outer loop, the inner loop iterates through each seat in the current row.
- For each combination of row and seat, the program prints the seat label in the format Row X Seat Y. After printing all the seats in a row, the program adds a newline to separate rows.
- This continues until all rows and seats are displayed.
#include <stdio.h> int main() { int rows; int seatsPerRow; printf("Enter the number of rows: "); scanf("%d", &rows); printf("Enter the number of seats per row: "); scanf("%d", &seatsPerRow); for (int i = 1; i <= rows; i++) { for (int j = 1; j <= seatsPerRow; j++) { printf("Row %d Seat %d ", i, j); } printf("\n"); } return 0; }
Library Book Organizer
Imagine you are working in a library, and you need to organize books on shelves. Each shelf has multiple rows, and each row can hold a certain number of books. The librarian will tell you how many shelves and rows there are, and the number of books to be placed in each row. Write a C program that takes the number of shelves, rows per shelf, and books per row as input and displays the arrangement.
Test Case
Input
Enter the number of shelves: 2
Enter the number of rows per shelf: 2
Enter the number of books per row: 4
Expected Output
Shelf 1:
Row 1: Book 1 Book 2 Book 3 Book 4
Row 2: Book 1 Book 2 Book 3 Book 4
Shelf 2:
Row 1: Book 1 Book 2 Book 3 Book 4
Row 2: Book 1 Book 2 Book 3 Book 4
- The program starts by asking the user to input the number of shelves, rows per shelf, and books per row. These inputs are stored in
numShelves
,numRows
, andbooksPerRow
, respectively. - The program then uses a nested loop structure.
- The outer
for
loop iterates through the shelves. - Inside the outer loop, another
for
loop iterates through the rows on the current shelf. - Within the second loop, an additional
for
loop is used to count and print the books in the current row. Thefor
loop starts at 1 and runs up to the number of books per row, displaying the book number. - After processing all rows on a shelf, the program moves to the next shelf until all shelves and rows are displayed.
#include <stdio.h> int main() { int numShelves; int numRows; int booksPerRow; printf("Enter the number of shelves: "); scanf("%d", &numShelves); printf("Enter the number of rows per shelf: "); scanf("%d", &numRows); printf("Enter the number of books per row: "); scanf("%d", &booksPerRow); for (int i = 1; i <= numShelves; i++) { printf("Shelf %d:\n", i); for (int j = 1; j <= numRows; j++) { printf(" Row %d: ", j); for (int k = 1; k <= booksPerRow; k++) { printf("Book %d ", k); } printf("\n"); } printf("\n"); } return 0; }
Magic Potion Brewing
Imagine you are helping out in a wizard’s potion shop. Wizards come to you with empty buckets to brew potions. Each bucket has several sections for mixing the potion, and the number of sections can vary for each wizard. The amount of ingredients needed for each section depends on its position. For example, the first section needs 5 extra units, the second needs 10 extra units, and so on. The base amount of ingredients for each section is always 20 units.
Your job is to calculate how many total ingredients each wizard needs for their bucket. Wizards will keep coming, and for each wizard, you’ll first ask how many sections are in their bucket, then calculate the total ingredients required for that wizard
Test Case
Input
Enter the number of wizards: 2
Enter the number of sections in Wizard 1’s bucket: 3
Enter the number of sections in Wizard 2’s bucket: 4
Expected Output
Wizard 1:
Section 1: 25 ingredients
Section 2: 30 ingredients
Section 3: 35 ingredients
Total ingredients needed for Wizard 1: 90
Wizard 2:
Section 1: 25 ingredients
Section 2: 30 ingredients
Section 3: 35 ingredients
Section 4: 40 ingredients
Total ingredients needed for Wizard 2: 130
- The program starts by asking the user to enter the number of wizards. This input is stored in the variable
numWizards
. - A
while
loop is used to process each wizard one by one. - Inside the
while
loop, the program asks for the number of sections in the current wizard’s bucket. This input is stored innumSections
. - A
for
loop is then used to calculate the ingredients needed for each section. - The
for
loop calculates the ingredients for a section using the formula, Ingredients for Section=20+5×Section Position. - The program keeps adding up the ingredients for all sections and stores the total in
totalIngredients
. - After finishing all sections for the current wizard, the program displays the total ingredients required for that wizard.
- The program moves to the next wizard and repeats the process until all wizards are served.
#include <stdio.h> int main() { int numWizards; int numSections; printf("Enter the number of wizards: "); scanf("%d", &numWizards); int wizard = 1; while (wizard <= numWizards) { printf("Enter the number of sections in Wizard %d's bucket: ", wizard); scanf("%d", &numSections); int totalIngredients = 0; printf("Wizard %d:\n", wizard); for (int i = 1; i <= numSections; i++) { int ingredientsForSection = 20 + 5 * i; totalIngredients += ingredientsForSection; printf(" Section %d: %d ingredients\n", i, ingredientsForSection); } printf("Total ingredients needed for Wizard %d: %d\n\n", wizard, totalIngredients); wizard++; } return 0; }
Starry Night
Imagine you are designing a stage backdrop for a school play. The backdrop should display a magical staircase of stars, where the number of stars increases by exactly 1 at each level. For example, the first level has 1 star, the second level has 2 stars, the third level has 3 stars, and so on. The number of levels should be customizable so that the stage can match the play’s theme. Write a program in C language that takes the number of levels as input and prints the staircase of stars.
Test Case
Input
Enter the number of levels for the star staircase: 5
Expected Output
*
**
***
****
*****
- The program starts by asking the user to input the number of levels for the star staircase. This input is stored in the variable
levels
. - The program uses a
for
loop to iterate through each level of the staircase. Each level corresponds to one iteration of the loop. - Inside the loop, another
for
loop is used to print the stars for the current level. The number of stars printed corresponds to the level number. For example, the first level prints 1 star, the second prints 2 stars, and so on. - After printing the stars for one level, the program moves to the next line using
printf("\n")
to prepare for the next level. - This process continues until all levels are printed, with each level having one more star than the previous one.
#include <stdio.h> int main() { int levels; printf("Enter the number of levels for the star staircase: "); scanf("%d", &levels); for (int i = 1; i <= levels; i++) { for (int j = 1; j <= i; j++) { printf("*"); } printf("\n"); } return 0; }
Treasure Chest Code Generator
Imagine you are part of a team of explorers who have discovered a treasure chest in an ancient ruin. The chest can only be unlocked by entering a secret code. The code is a grid of numbers, where the numbers in each row increase by a fixed amount, and the first number in each row is also different.
Write a program in C that asks for the number of rows in the grid, the starting number of the first row, and the amount by which the numbers increase across columns. The program should generate the grid and display it as the treasure chest code.
Test Case
Input
Enter the number of rows in the grid: 3
Enter the starting number of the first row: 5
Enter the amount by which numbers increase: 2
Expected Output
5 7 9
7 9 11
9 11 13
- The program begins by asking the user to input the number of rows in the grid, the starting number of the first row, and the step size by which the numbers increase. These inputs are stored in the variables
numRows
,startNumber
, andstepSize
, respectively. - A
for
loop starts and iterates over the rows of the grid. The loop variablei
represents the row index. - Inside the row loop, another
for
loop is used to generate the columns in the current row. The loop variablej
represents the column index. - Each number in the grid is calculated using the formula,
Number=startNumber+(i×stepSize)+(j×stepSize)
. - The calculated number is printed, and the inner loop continues until all columns for the current row are printed.
- Once a row is completed, the program moves to the next line to start printing the next row.
#include <stdio.h> int main() { int numRows; int startNumber; int stepSize; printf("Enter the number of rows in the grid: "); scanf("%d", &numRows); printf("Enter the starting number of the first row: "); scanf("%d", &startNumber); printf("Enter the amount by which numbers increase: "); scanf("%d", &stepSize); for (int i = 0; i < numRows; i++) { for (int j = 0; j < numRows; j++) { printf("%d ", startNumber + i * stepSize + j * stepSize); } printf("\n"); } return 0; }
Crossing the Desert Sands
You and your team are on an adventurous desert journey. Each day, you must cross multiple checkpoints to refill your water supplies. The number of checkpoints increases as the days go on, and the amount of water collected at each checkpoint also varies. Write a C program that asks for the number of days in the journey, the number of checkpoints on the first day, the increment in checkpoints for each day, and the base amount of water collected at the first checkpoint of each day. For each day, calculate and display the water collected at each checkpoint and the total water collected by the end of the journey.
Test Case
Input
Enter the number of days in the journey: 3
Enter the number of checkpoints on the first day: 2
Enter the increment in checkpoints for each day: 1
Enter the base water collected at the first checkpoint: 10
Expected Output
Day 1:
Checkpoint 1: 10 liters of water
Checkpoint 2: 13 liters of water
Total water collected after Day 1: 23 liters
Day 2:
Checkpoint 1: 10 liters of water
Checkpoint 2: 13 liters of water
Checkpoint 3: 16 liters of water
Total water collected after Day 2: 62 liters
Day 3:
Checkpoint 1: 10 liters of water
Checkpoint 2: 13 liters of water
Checkpoint 3: 16 liters of water
Checkpoint 4: 19 liters of water
Total water collected after Day 3: 120 liters
- The program begins by asking the user to input the number of days, the number of checkpoints on the first day, the increment in checkpoints for each day, and the base amount of water collected at the first checkpoint. These inputs are stored in
numDays
,checkpointsOnFirstDay
,checkpointIncrement
, andbaseWater
, respectively. - The program uses a nested while loop to simulate the journey.
- The outer
while
loop handles the progression of days, while the innerwhile
loop handles each checkpoint for the current day. - For each day, the number of checkpoints is calculated as Checkpoints on Day=checkpointsOnFirstDay+(dayIndex×checkpointIncrement).
- For each checkpoint, the water collected is calculated using the formula Water at Checkpoint=baseWater+(checkpointIndex×3).
- The program accumulates the total water collected across all days and displays the results for each day. After processing all checkpoints for a day, the program moves to the next day.
#include <stdio.h> int main() { int numDays; int checkpointsOnFirstDay; int checkpointIncrement; int baseWater; printf("Enter the number of days in the journey: "); scanf("%d", &numDays); printf("Enter the number of checkpoints on the first day: "); scanf("%d", &checkpointsOnFirstDay); printf("Enter the increment in checkpoints for each day: "); scanf("%d", &checkpointIncrement); printf("Enter the base water collected at the first checkpoint: "); scanf("%d", &baseWater); int day = 1; int totalWater = 0; while (day <= numDays) { int checkpoints = checkpointsOnFirstDay + (day - 1) * checkpointIncrement; int checkpoint = 1; printf("Day %d:\n", day); while (checkpoint <= checkpoints) { int waterAtCheckpoint = baseWater + (checkpoint - 1) * 3; totalWater += waterAtCheckpoint; printf(" Checkpoint %d: %d liters of water\n", checkpoint, waterAtCheckpoint); checkpoint++; } printf("Total water collected after Day %d: %d liters\n\n", day, totalWater); day++; } return 0; }
Vehicle Fuel Efficiency Tracker
You are managing a fleet of vehicles, and each vehicle has a specific fuel efficiency (kilometers per liter) and a distance to travel. The vehicles must be fueled incrementally to cover their respective distances. The pump dispenses fuel one liter at a time, and the total fuel dispensed for each vehicle must be calculated.
Write a program in C that calculates the fuel required for each vehicle based on its fuel efficiency and distance to be traveled. The program should display the fuel dispensed for each vehicle and the total fuel dispensed for the entire fleet.
Test Case
Input
Enter the number of vehicles: 2
Enter the fuel efficiency of Vehicle 1 (km per liter): 15
Enter the distance Vehicle 1 needs to travel (in km): 150
Enter the fuel efficiency of Vehicle 2 (km per liter): 10
Enter the distance Vehicle 2 needs to travel (in km): 120
Expected Output
Vehicle 1 requires 10 liters of fuel.
Vehicle 2 requires 12 liters of fuel.
Total fuel required for all vehicles: 22 liters
- The program starts by asking the user to enter the number of vehicles. This input is saved in the
numVehicles
variable. - For each vehicle, the program prompts the user to enter the fuel efficiency of the vehicle in kilometers per liter and the distance it needs to travel using a
for
loop. These inputs are saved in the variablesfuelEfficiency
anddistance
, respectively. - Next, the program calculates the fuel required for each vehicle using a
do-while
loop by incrementally dispensing fuel. The calculation starts withdispensedFuel
initialized to 0. - The program increases the fuel one liter at a time and checks if the distance that can be covered with the dispensed fuel (
dispensedFuel * fuelEfficiency
) is less than the required distance. This process continues until the condition is false. - After determining the required fuel for the current vehicle, the program adds this value to
totalFuel
. - The fuel required for the current vehicle is displayed immediately after calculation.
- This process repeats for all vehicles. Once all vehicles have been processed, the program displays the total fuel required for the fleet.
#include <stdio.h> int main() { int numVehicles, totalFuel = 0; printf("Enter the number of vehicles: "); scanf("%d", &numVehicles); for (int i = 1; i <= numVehicles; i++) { int fuelEfficiency, distance, dispensedFuel = 0; printf("Enter the fuel efficiency of Vehicle %d (km per liter): ", i); scanf("%d", &fuelEfficiency); printf("Enter the distance Vehicle %d needs to travel (in km): ", i); scanf("%d", &distance); do { dispensedFuel++; } while (dispensedFuel * fuelEfficiency < distance); printf("Vehicle %d requires %d liters of fuel.\n", i, dispensedFuel); totalFuel += dispensedFuel; } printf("\nTotal fuel required for all vehicles: %d liters.\n", totalFuel); return 0; }
Tic-Tac-Toe Treasure Hunt
You are creating a treasure-hunting game for a 3×3 grid. One of the cells contains a hidden jackpot treasure, while the rest contain regular treasures. The player must guess the grid positions one by one to uncover the jackpot. After each guess, the game asks the player to confirm if they want to continue or quit. If the player finds the jackpot, the game ends immediately. If the player decides to quit early, the game ends, and the total number of guesses is displayed.
Write a C program to take the jackpot’s position as input, allow the player to guess grid positions, and ask for confirmation to continue after each guess.
Test Case
Input
As the game creator, set the jackpot’s position:
Enter the row number (1-3) of the jackpot: 2
Enter the column number (1-3) of the jackpot: 3
The game begins! Let the player guess the jackpot position.
Player, guess the row number (1-3): 1
Player, guess the column number (1-3): 1
Do you want to continue? (y/n): y
Player, guess the row number (1-3): 2
Player, guess the column number (1-3): 3
Expected Output
No jackpot here. Keep guessing!
Congratulations! The player found the jackpot at (2, 3) in 2 guesses.
- The program starts by asking the game creator to set the jackpot’s position. The creator is asked to enter the row and column numbers for the jackpot, which are saved in the variables
jackpotRow
andjackpotCol
. - To make sure the inputs are valid (between 1 and 3), the program uses separate
while
loops for both the row and column. - If the entered value is not within this range, the program displays an error message and asks for a valid input until a correct value is provided.
- Once the jackpot’s position is set, the program lets the player start guessing.
- The game uses a
while (1)
loop, which runs until the player finds the jackpot or chooses to quit. - For each guess, the player is asked to input a row and column. These inputs are checked using
while
loops to ensure they are valid. - If the inputs are out of range, the program shows an error message and asks for valid values.
- After the player enters a valid guess, the program checks if the guessed position matches the jackpot’s position:
- If the guess is correct, the program congratulates the player, shows the jackpot’s position, and displays the total number of guesses. The program then ends immediately using a
return
statement. - If the guess is wrong, the program tells the player that the jackpot is not at that position.
- After every incorrect guess, the program asks the player if they want to keep playing or quit. This is done using another loop that asks the player to type ‘y’ to continue or ‘n’ to quit.
- If the player decides to quit, the program ends and displays the total guesses made.
- If the player wants to continue, the game goes back to let them make another guess.
- The program keeps track of how many guesses the player has made using the
totalGuesses
variable. This counter increases every time the player makes a guess. - The game ends when the player finds the jackpot or chooses to quit.
#include <stdio.h> int main() { int jackpotRow, jackpotCol, guessedRow, guessedCol, totalGuesses = 0; char choice; printf("As the game creator, set the jackpot's position:\n"); printf("Enter the row number (1-3) of the jackpot: "); scanf("%d", &jackpotRow); while (jackpotRow < 1 || jackpotRow > 3) { printf("Invalid input! Enter a row number between 1 and 3: "); scanf("%d", &jackpotRow); } printf("Enter the column number (1-3) of the jackpot: "); scanf("%d", &jackpotCol); while (jackpotCol < 1 || jackpotCol > 3) { printf("Invalid input! Enter a column number between 1 and 3: "); scanf("%d", &jackpotCol); } printf("\nThe game begins! Let the player guess the jackpot position.\n"); while (1) { printf("Player, guess the row number (1-3): "); scanf("%d", &guessedRow); while (guessedRow < 1 || guessedRow > 3) { printf("Invalid input! Enter a row number between 1 and 3: "); scanf("%d", &guessedRow); } printf("Player, guess the column number (1-3): "); scanf("%d", &guessedCol); while (guessedCol < 1 || guessedCol > 3) { printf("Invalid input! Enter a column number between 1 and 3: "); scanf("%d", &guessedCol); } totalGuesses++; if (guessedRow == jackpotRow && guessedCol == jackpotCol) { printf("Congratulations! The player found the jackpot at (%d, %d) in %d guesses.\n", jackpotRow, jackpotCol, totalGuesses); break; } else { printf("No jackpot here. Keep guessing!\n"); } while (1) { printf("Do you want to continue? (y/n): "); scanf(" %c", &choice); if (choice == 'y' || choice == 'Y') { break; } else if (choice == 'n' || choice == 'N') { printf("\nThe player chose to quit. Total guesses made: %d.\n", totalGuesses); return 0; } else { printf("Invalid input! Please enter 'y' to continue or 'n' to quit.\n"); } } } return 0; }
Autonomous Vehicle Grid Simulation
You are tasked with simulating the movement of an autonomous vehicle on a grid-based road system. The vehicle starts at the top-left corner of the grid and moves left to right within each row until it reaches the bottom-right corner. Optionally, the user can choose to add one blocked cell in the grid, which will prevent the vehicle from passing through that position. Write a C program that first takes the grid size (number of rows and columns) as input. Then, ask the user if they want to add a blocked cell. If yes, take the row and column of the blocked position as input. At each step, the program should display the grid, marking the vehicle’s position with V
, the blocked cell with B
, and empty cells with _
. If the vehicle encounters the blocked cell, the simulation should stop with an appropriate message. If the vehicle reaches the bottom-right corner, the simulation ends successfully.
Test Case
Input
Enter number of rows: 3
Enter number of columns: 3
Do you want to add a blocked cell? (y/n): y
Enter the row and column of the blocked cell: 2 3
Expected Output
Step 0:
V _ _
_ _ B
_ _ _
Step 1:
_ V _
_ _ B
_ _ _
Step 2:
_ _ V
_ _ B
_ _ _
Step 3:
_ _ _
V _ B
_ _ _
Step 4:
_ _ _
_ V B
_ _ _
Step 5:
_ _ _
_ _ V
_ _ _
Vehicle encountered a blocked cell at (2, 3). Simulation stopped.
- The program starts by asking the user to enter the number of rows and columns of the grid. These values are saved in the variables
rows
andcols
respectively. - The program then asks the user if they want to add a blocked cell, which is a position in the grid that the vehicle cannot traverse. This input is stored in the variable
addBlocked
. - If the user chooses to add a blocked cell by entering
y
orY
, the program prompts the user to input the row and column indices of the blocked cell. These inputs are stored in the variablesblockedRow
andblockedCol
. - The program validates this input to ensure that the blocked cell is within the bounds of the grid. If the input is invalid , the program outputs an error message and exits.
- The simulation begins with the vehicle positioned at the top-left corner of the grid. This position is represented by the variables
vehicleRow
andvehicleCol
, initialized to 1. The program uses a variablestep
to track the current step of the simulation. - In each step of the simulation, the program displays the current state of the grid using nested
for
loops. The outer loop iterates through the rows of the grid, and the inner loop iterates through the columns. - If the cell matches the current position of the vehicle (
vehicleRow
andvehicleCol
), the program outputsV
to represent the vehicle. - If the cell matches the position of the blocked cell (
blockedRow
andblockedCol
), the program outputsB
to represent the blocked cell. - Otherwise, the program outputs
_
to indicate an empty cell. - After displaying the grid, the program checks if the vehicle has reached the blocked cell. If
vehicleRow
equalsblockedRow
andvehicleCol
equalsblockedCol
, the program outputs a message indicating that the vehicle has encountered the blocked cell, and the simulation stops. - If the vehicle has not encountered the blocked cell, the program moves the vehicle to the next position in the grid. The vehicle moves left to right within a row by incrementing
vehicleCol
. - If the vehicle reaches the end of a row (i.e.,
vehicleCol
exceedscols
), it moves to the first column of the next row by incrementingvehicleRow
and resettingvehicleCol
to 1. - The simulation continues until the vehicle either encounters the blocked cell or reaches the bottom-right corner of the grid. If the vehicle reaches the last cell of the grid (i.e.,
vehicleRow
equalsrows
andvehicleCol
equalscols
), the program outputs a message indicating that the vehicle has successfully completed its journey, and the simulation ends. - If the user does not choose to add a blocked cell, the simulation runs without any obstacles, allowing the vehicle to traverse the grid uninterrupted.
#include <stdio.h> int main() { int rows, cols; int blockedRow = -1, blockedCol = -1; printf("Enter number of rows: "); scanf("%d", &rows); printf("Enter number of columns: "); scanf("%d", &cols); char addBlocked; printf("Do you want to add a blocked cell? (y/n): "); scanf(" %c", &addBlocked); if (addBlocked == 'y' || addBlocked == 'Y') { printf("Enter the row and column of the blocked cell: "); scanf("%d %d", &blockedRow, &blockedCol); if (blockedRow < 1 || blockedRow > rows || blockedCol < 1 || blockedCol > cols) { printf("Invalid blocked cell position. Exiting.\n"); return 1; } } int vehicleRow = 1, vehicleCol = 1; int step = 0; while (1) { printf("Step %d:\n", step); for (int r = 1; r <= rows; r++) { for (int c = 1; c <= cols; c++) { if (r == vehicleRow && c == vehicleCol) { printf("V "); } else if (r == blockedRow && c == blockedCol) { printf("B "); } else { printf("_ "); } } printf("\n"); } printf("\n"); if (vehicleRow == blockedRow && vehicleCol == blockedCol) { printf("Vehicle encountered a blocked cell at (%d, %d). Simulation stopped.\n", blockedRow, blockedCol); break; } if (vehicleCol < cols) { vehicleCol++; } else if (vehicleRow < rows) { vehicleRow++; vehicleCol = 1; } else { printf("Vehicle reached the bottom-right corner. Simulation complete.\n"); break; } step++; } return 0; }
Number Matching Game
Imagine you are playing a number-matching game where you need to guess the correct sequence of numbers on each level. At each level, the game provides a specific target number and the number of digits you need to guess to form the target. For example, to match the number 432, you must guess the digits one by one in the correct order. Write a C program that asks for the number of levels and the target number for each level. For each digit in the target number, the program allows multiple guesses until the correct digit is entered. Display the total number of guesses made for each level and the total guesses made for the entire game.
Test Case
Input
Enter the number of levels: 2
Enter the target number for Level 1: 432
Guess the digits of the target number:
Enter your guess for the next digit: 4
Enter your guess for the next digit: 3
Enter your guess for the next digit: 2
Enter the target number for Level 2: 57
Guess the digits of the target number:
Enter your guess for the next digit: 5
Enter your guess for the next digit: 7
Expected Output
Correct!
Correct!
Correct!
Total guesses for Level 1: 3
Correct!
Correct!
Total guesses for Level 2: 2
Congratulations! You completed the game with a total of 5 guesses.
- The program starts by asking the user how many levels they want to play. This number is saved in the variable
numLevels
. - For each level, the user is asked to enter a target number, which is saved in the variable
target
. - To process the target number one digit at a time, the program calculates a value called
divisor
that helps extract the leftmost digit of the number first. - Next, the program processes each digit of the target number. For every digit, the user is asked to guess it.
- The program checks if the guess is correct. If the guess is wrong, the user is prompted to guess again until they get it right.
- Once the correct digit is guessed, the program moves to the next digit.
- After all the digits of the target number are guessed correctly, the program shows the total number of guesses the user made for that level.
- When all levels are completed, the program calculates and displays the total guesses the user made across all levels.
#include <stdio.h> int main() { int numLevels, totalGuesses = 0; printf("Enter the number of levels: "); scanf("%d", &numLevels); for (int level = 1; level <= numLevels; level++) { int target, levelGuesses = 0; printf("Enter the target number for Level %d: ", level); scanf("%d", &target); printf("Guess the digits of the target number:\n"); int currentTarget = target; int divisor = 1; while (currentTarget / divisor >= 10) { divisor *= 10; } while (divisor > 0) { int digit = (currentTarget / divisor) % 10; int guess; do { printf("Enter your guess for the next digit: "); scanf("%d", &guess); levelGuesses++; if (guess == digit) { printf("Correct!\n"); } else { printf("Incorrect. Try again.\n"); } } while (guess != digit); divisor /= 10; } printf("Total guesses for Level %d: %d\n", level, levelGuesses); totalGuesses += levelGuesses; } printf("\nCongratulations! You completed the game with a total of %d guesses.\n", totalGuesses); return 0; }
Symmetrical Starburst Pattern
Imagine you are creating a display for an autonomous car’s dashboard that shows a starburst pattern as a sign of system readiness. This pattern consists of stars (*
) arranged in a symmetrical design. It starts with a single star at the top and expands outward, forming a triangular shape. The pattern is completed by mirroring this triangle below to create a balanced, diamond-like structure. The user will specify the number of rows for the top half of the pattern. Each row is centered with spaces for symmetry. The bottom part mirrors the top, completing the design. Your task is to write a program in C language that generates this pattern based on the user’s input.
Test Case
Input
Enter the number of rows for the pattern: 5
Expected Output
*
* *
* *
* *
* *
* *
* *
* *
*
- The program begins by asking the user to input the number of rows for the top part of the starburst pattern. This value is stored in the variable
rows
. - The program first creates the top part of the pattern. It uses an outer loop to iterate through each row, starting from the first row up to the row specified by the user.
- For each row, the program calculates the number of leading spaces needed to center the stars. This is done using an inner loop that prints spaces, decreasing the number of spaces as the row number increases.
- After printing the spaces, another inner loop is used to print the stars (
*
). The stars are only printed at the edges of the triangle. - If the current position is not at the edge, the program prints a space to make the triangle hollow.
- Once the top part is complete, the program moves to the bottom part of the pattern, which mirrors the top.
- The outer loop starts from the second last row of the top half and goes down to the first row.
- Like the top part, spaces are printed first to center the stars, followed by stars and spaces to maintain the hollow structure.
- At the end of the program, the two parts combine to form a symmetrical diamond pattern.
#include <stdio.h> int main() { int rows; printf("Enter the number of rows for the pattern: "); scanf("%d", &rows); for (int i = 1; i <= rows; i++) { for (int j = 1; j <= rows - i; j++) { printf(" "); } for (int j = 1; j <= 2 * i - 1; j++) { if (j == 1 || j == 2 * i - 1) { printf("*"); } else { printf(" "); } } printf("\n"); } for (int i = rows - 1; i >= 1; i--) { for (int j = 1; j <= rows - i; j++) { printf(" "); } for (int j = 1; j <= 2 * i - 1; j++) { if (j == 1 || j == 2 * i - 1) { printf("*"); } else { printf(" "); } } printf("\n"); } return 0; }
Goods Transport Allocation
You are in charge of managing a goods transport system that operates across three cities. Each city has three warehouses, and each warehouse uses three vehicles to transport goods. Your task is to evenly distribute a given number of goods among all the vehicles across the cities and warehouses. The system must ensure that the goods are allocated as evenly as possible. If the total number of goods cannot be divided equally, the leftover goods should be assigned to the first few vehicles in the distribution. Write a C program that takes the total number of goods as input and calculates how many goods each vehicle should carry. Finally, the program should display the allocation of goods to each vehicle, organized by city and warehouse.
Test Case
Input
Enter the total number of goods to be distributed: 84
Expected Output
Welcome to the Dynamic Goods Transport System
Distributing goods…
City 1:
Warehouse 1:
Vehicle 1: 4 goods
Vehicle 2: 4 goods
Vehicle 3: 4 goods
Warehouse 2:
Vehicle 4: 3 goods
Vehicle 5: 3 goods
Vehicle 6: 3 goods
Warehouse 3:
Vehicle 7: 3 goods
Vehicle 8: 3 goods
Vehicle 9: 3 goods
City 2:
Warehouse 1:
Vehicle 10: 3 goods
Vehicle 11: 3 goods
Vehicle 12: 3 goods
Warehouse 2:
Vehicle 13: 3 goods
Vehicle 14: 3 goods
Vehicle 15: 3 goods
Warehouse 3:
Vehicle 16: 3 goods
Vehicle 17: 3 goods
Vehicle 18: 3 goods
City 3:
Warehouse 1:
Vehicle 19: 3 goods
Vehicle 20: 3 goods
Vehicle 21: 3 goods
Warehouse 2:
Vehicle 22: 3 goods
Vehicle 23: 3 goods
Vehicle 24: 3 goods
Warehouse 3:
Vehicle 25: 3 goods
Vehicle 26: 3 goods
Vehicle 27: 3 goods
Goods distribution complete.
- The program starts by asking the user to enter the total number of goods that need to be distributed. This value is stored in the variable
totalGoods
. - Next, the program calculates the total number of vehicles available in the system. Since there are 3 cities, each with 3 warehouses, and each warehouse has 3 vehicles, the total number of vehicles is calculated as
3 * 3 * 3
, which equals 27. - The program then calculates how many goods can be evenly distributed to each vehicle. This is done by dividing the total goods by the total number of vehicles (
goodsPerVehicle = totalGoods / totalVehicles
). - The remaining goods, which cannot be evenly distributed, are stored in the variable
remainingGoods
(remainingGoods = totalGoods % totalVehicles
). - The program uses three nested loops to represent the cities, warehouses, and vehicles.
- The outer loop iterates through the cities (from 1 to 3). For each city, the program prints its number.
- The middle loop iterates through the warehouses in the current city (from 1 to 3). For each warehouse, the program prints its number.
- The inner loop iterates through the vehicles in the current warehouse (from 1 to 3). For each vehicle, the program assigns the value of
goodsPerVehicle
as the base allocation. - If there are any remaining goods (
remainingGoods > 0
), the program assigns one extra good to the current vehicle and decrements the value ofremainingGoods
- After assigning goods to a vehicle, the program prints the number of goods allocated to it. This process continues until all vehicles in all warehouses and cities have been assigned goods.
- Finally, the program displays a message indicating that the goods distribution is complete.
#include <stdio.h> int main() { int totalGoods; int remainingGoods; printf("Welcome to the Dynamic Goods Transport System\n"); printf("Enter the total number of goods to be distributed: "); scanf("%d", &totalGoods); int totalVehicles = 3 * 3 * 3; int goodsPerVehicle = totalGoods / totalVehicles; remainingGoods = totalGoods % totalVehicles; printf("\nDistributing goods...\n"); int vehicleCount = 0; for (int city = 1; city <= 3; city++) { printf("City %d:\n", city); for (int warehouse = 1; warehouse <= 3; warehouse++) { printf(" Warehouse %d:\n", warehouse); for (int vehicle = 1; vehicle <= 3; vehicle++) { vehicleCount++; int allocatedGoods = goodsPerVehicle; if (remainingGoods > 0) { allocatedGoods++; remainingGoods--; } printf(" Vehicle %d: %d goods\n", vehicleCount, allocatedGoods); } } } printf("\nGoods distribution complete.\n"); return 0; }
Warehouse Stock Tracker
Imagine you are managing a large warehouse divided into sections, aisles, and shelves. Each shelf stores boxes with a certain number of items. You want to keep track of the total stock, the average stock per shelf, and find the shelf with the highest stock. Write a C program that lets the user enter the number of sections, aisles per section, and shelves per aisle. Then, for each shelf, the program should take the number of items as input. Finally, the program should calculate and display the total stock in the warehouse, the average stock per shelf, and the location (section, aisle, and shelf number) of the shelf with the most items.
Test Case
Input
Enter the number of sections: 2
Enter the number of aisles per section: 2
Enter the number of shelves per aisle: 2
Enter the number of items on Section 1, Aisle 1, Shelf 1: 20
Enter the number of items on Section 1, Aisle 1, Shelf 2: 15
Enter the number of items on Section 1, Aisle 2, Shelf 1: 30
Enter the number of items on Section 1, Aisle 2, Shelf 2: 25
Enter the number of items on Section 2, Aisle 1, Shelf 1: 50
Enter the number of items on Section 2, Aisle 1, Shelf 2: 40
Enter the number of items on Section 2, Aisle 2, Shelf 1: 25
Enter the number of items on Section 2, Aisle 2, Shelf 2: 45
Expected Output
— Warehouse Stock Summary —
Total stock in the warehouse: 250
Average stock per shelf: 31.00
Shelf with the most items: Section 2, Aisle 1, Shelf 1 (50 items)
- The program starts by asking the user to input the number of sections, the number of aisles per section, and the number of shelves per aisle. These inputs are stored in the variables
sections
,aisles
, andshelves
, respectively. - Next, the program initializes variables
totalStock
,totalShelves
andmaxStock
to keep track of the total stock , the total number of shelves , and the maximum stock found on a single shelf. It also initializes variablesmaxSection
,maxAisle
, andmaxShelf
to store the location of the shelf with the maximum stock. - The program then enters a nested loop structure. The outer loop iterates over each section (
i
), the middle loop iterates over each aisle in the current section (j
), and the inner loop iterates over each shelf in the current aisle (k
). - Inside the innermost loop, the program asks the user to enter the stock for the current shelf. The input stock is added to the
totalStock
variable, and thetotalShelves
counter is incremented. - After updating the totals, the program checks if the current shelf’s stock exceeds the
maxStock
value. If it does,maxStock
is updated to the current shelf’s stock, and the variablesmaxSection
,maxAisle
, andmaxShelf
are updated to store the location of this shelf. - Once all loops are completed, the program calculates the average stock per shelf by dividing the
totalStock
bytotalShelves
and stores the result in theaverageStock
variable. - Finally, the program displays the total stock in the warehouse, the average stock per shelf, and the location of the shelf with the most items, along with its stock count.
#include <stdio.h> int main() { int sections, aisles, shelves; int totalStock = 0, totalShelves = 0; int maxStock = 0, maxSection = 0, maxAisle = 0, maxShelf = 0; printf("Enter the number of sections: "); scanf("%d", §ions); printf("Enter the number of aisles per section: "); scanf("%d", &aisles); printf("Enter the number of shelves per aisle: "); scanf("%d", &shelves); for (int i = 1; i <= sections; i++) { for (int j = 1; j <= aisles; j++) { for (int k = 1; k <= shelves; k++) { int stock; printf("Enter the number of items on Section %d, Aisle %d, Shelf %d: ", i, j, k); scanf("%d", &stock); totalStock += stock; totalShelves++; if (stock > maxStock) { maxStock = stock; maxSection = i; maxAisle = j; maxShelf = k; } } } } float averageStock = totalStock / totalShelves; printf("\n--- Warehouse Stock Summary ---\n"); printf("Total stock in the warehouse: %d\n", totalStock); printf("Average stock per shelf: %.2f\n", averageStock); printf("Shelf with the most items: Section %d, Aisle %d, Shelf %d (%d items)\n", maxSection, maxAisle, maxShelf, maxStock); return 0; }
Sports Tournament Tracker
Imagine you are organizing a sports tournament for several schools. Each school competes in multiple sports, and every sport has several matches. Your task is to track the scores, find the school with the highest overall score, and identify the sport in which that school performed best. Write a program in C language that allows the user to enter match scores, calculates all results during data entry, and displays the required data when requested.
Test Case
Input
— Sports Tournament Score Tracker —
1- Enter Scores
2- Find Sport with Highest Score for the School with Maximum Overall Score
3- Find School with Highest Overall Score
4- Exit
Enter your choice: 1
Enter the number of schools: 2
Enter the number of sports per school: 2
Enter the number of matches per sport: 2
— Entering Scores for School 1 —
Sport 1:
Enter score for Match 1: 50
Enter score for Match 2: 60
Sport 2:
Enter score for Match 1: 70
Enter score for Match 2: 80
— Entering Scores for School 2 —
Sport 1:
Enter score for Match 1: 90
Enter score for Match 2: 85
Sport 2:
Enter score for Match 1: 75
Enter score for Match 2: 65
Expected Output
Total score for Sport 1: 110
Total score for Sport 2: 150
Total score for School 1: 260
Total score for Sport 1: 175
Total score for Sport 2: 140
Total score for School 2: 315
Scores have been successfully recorded!
- The program starts by asking the user to input the number of schools, the number of sports each school participates in, and the number of matches for each sport. These values are saved in the variables
schools
,sports
, andmatches
, respectively. - It also initializes variables to store the overall maximum score (
overallMaxScore
), the school with the highest overall score (overallMaxSchool
), the sport in which this top-performing school scored the most points (bestSchoolMaxSport
), and the score for that sport (bestSchoolMaxSportScore
). - First, the program enters a loop to record the scores for all schools. For each school, it calculates the total score by iterating through every sport and summing up the scores for all matches in that sport.
- While calculating the total score for a sport, the program checks if this sport has the highest score for the current school. If it does, it updates the sport’s total score and its index as the current school’s best-performing sport.
- After processing all sports for a school, the program compares the school’s total score with the current overall maximum score.
- If the school’s total score is greater, it updates
overallMaxScore
, setsoverallMaxSchool
to the current school, and assigns the best-performing sport and its score tobestSchoolMaxSport
andbestSchoolMaxSportScore
. - When the user selects the option to find the sport with the highest score for the school with the maximum overall score, the program directly displays the values of
bestSchoolMaxSport
andbestSchoolMaxSportScore
without requiring additional input. - If no scores have been recorded yet, it informs the user to enter the scores first.
- Finally, if the user selects the option to find the school with the highest overall score, the program displays the school with the
overallMaxScore
andoverallMaxSchool
. - If no scores are recorded, it prompts the user to input data before proceeding.
- The program ends when the user selects the exit option.
#include <stdio.h> int main() { int schools, sports, matches; int overallMaxScore = 0, overallMaxSchool = 0; int bestSchoolMaxSport = 0, bestSchoolMaxSportScore = 0; while (1) { int choice; printf("\n--- Sports Tournament Score Tracker ---\n"); printf("1. Enter Scores\n"); printf("2. Find Sport with Highest Score for the School with Maximum Overall Score\n"); printf("3. Find School with Highest Overall Score\n"); printf("4. Exit\n"); printf("Enter your choice: "); scanf("%d", &choice); if (choice == 1) { printf("Enter the number of schools: "); scanf("%d", &schools); printf("Enter the number of sports per school: "); scanf("%d", &sports); printf("Enter the number of matches per sport: "); scanf("%d", &matches); overallMaxScore = 0; overallMaxSchool = 0; bestSchoolMaxSport = 0; bestSchoolMaxSportScore = 0; for (int i = 1; i <= schools; i++) { int schoolTotalScore = 0; int currentSchoolMaxSport = 0, currentSchoolMaxSportScore = 0; printf("\n--- Entering Scores for School %d ---\n", i); for (int j = 1; j <= sports; j++) { int sportTotalScore = 0; printf("Sport %d:\n", j); for (int k = 1; k <= matches; k++) { int matchScore; printf(" Enter score for Match %d: ", k); scanf("%d", &matchScore); sportTotalScore += matchScore; } printf(" Total score for Sport %d: %d\n", j, sportTotalScore); schoolTotalScore += sportTotalScore; if (j == 1 || sportTotalScore > currentSchoolMaxSportScore) { currentSchoolMaxSportScore = sportTotalScore; currentSchoolMaxSport = j; } } printf("Total score for School %d: %d\n", i, schoolTotalScore); if (i == 1 || schoolTotalScore > overallMaxScore) { overallMaxScore = schoolTotalScore; overallMaxSchool = i; bestSchoolMaxSport = currentSchoolMaxSport; bestSchoolMaxSportScore = currentSchoolMaxSportScore; } } printf("\nScores have been successfully recorded!\n"); } else if (choice == 2) { if (overallMaxSchool != 0) { printf("For the school with the highest overall score (School %d),\n", overallMaxSchool); printf("the sport with the highest score is Sport %d with %d points.\n",bestSchoolMaxSport, bestSchoolMaxSportScore); } else { printf("No scores have been recorded yet. Please enter scores first.\n"); } } else if (choice == 3) { if (overallMaxSchool != 0) { printf("The school with the highest overall score is School %d with %d points.\n", overallMaxSchool, overallMaxScore); } else { printf("No scores have been recorded yet. Please enter scores first.\n"); } } else if (choice == 4) { printf("Exiting the program. Goodbye!\n"); break; } else { printf("Invalid choice. Please try again.\n"); } } return 0; }