Skip to content

Instantly share code, notes, and snippets.

@wleoncio
Last active May 14, 2025 08:22
Show Gist options
  • Select an option

  • Save wleoncio/e62762ca8737c5d24d62d561abe79a1e to your computer and use it in GitHub Desktop.

Select an option

Save wleoncio/e62762ca8737c5d24d62d561abe79a1e to your computer and use it in GitHub Desktop.
Example files for NRSE 2025
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
* Chemistry Quiz Game
*
* This program is a simple console-based quiz game that tests the user's knowledge of chemistry.
* The game consists of a series of multiple-choice questions, each with four possible answers.
* Players must select the correct option (A, B, C, or D) to score points. The quiz contains five
* predefined questions covering fundamental concepts in chemistry, such as the chemical composition
* of water, pH levels, and the periodic table.
*
* The game flow is as follows:
* 1. The program initializes a set of chemistry-related questions.
* 2. The user is prompted to answer each question in sequence.
* 3. After each question, the user's input is validated, and feedback is provided regarding whether
* the answer was correct or incorrect.
* 4. The program keeps track of the score and displays it at the end of the quiz.
*
* This code also demonstrates basic programming concepts in C, including the use of structures,
* arrays, and functions, making it a suitable example for beginners learning C programming and
* for practicing coding in a text editor.
*/
#define MAX_QUESTIONS 5
#define MAX_ANSWER_LENGTH 50
typedef struct {
char question[256];
char options[4][100];
int correct_option; // 0-based index
} Question;
void initialize_questions(Question questions[]) {
// Initialize a set of quiz questions
strcpy(questions[0].question, "What is the chemical symbol for water?");
strcpy(questions[0].options[0], "A) H2O");
strcpy(questions[0].options[1], "B) CO2");
strcpy(questions[0].options[2], "C) O2");
strcpy(questions[0].options[3], "D) NaCl");
questions[0].correct_option = 0;
strcpy(questions[1].question, "What is the pH of pure water at 25°C?");
strcpy(questions[1].options[0], "A) 6");
strcpy(questions[1].options[1], "B) 7");
strcpy(questions[1].options[2], "C) 8");
strcpy(questions[1].options[3], "D) 5");
questions[1].correct_option = 1;
strcpy(questions[2].question, "What is the main gas found in the air we breathe?");
strcpy(questions[2].options[0], "A) Oxygen");
strcpy(questions[2].options[1], "B) Nitrogen");
strcpy(questions[2].options[2], "C) Carbon Dioxide");
strcpy(questions[2].options[3], "D) Hydrogen");
questions[2].correct_option = 1;
strcpy(questions[3].question, "Which element has the atomic number 1?");
strcpy(questions[3].options[0], "A) Helium");
strcpy(questions[3].options[1], "B) Hydrogen");
strcpy(questions[3].options[2], "C) Oxygen");
strcpy(questions[3].options[3], "D) Lithium");
questions[3].correct_option = 1;
strcpy(questions[4].question, "What is the chemical formula for table salt?");
strcpy(questions[4].options[0], "A) H2O");
strcpy(questions[4].options[1], "B) NaCl");
strcpy(questions[4].options[2], "C) CO2");
strcpy(questions[4].options[3], "D) C6H12O6");
questions[4].correct_option = 1;
}
int main() {
Question questions[MAX_QUESTIONS];
int score = 0;
initialize_questions(questions);
printf("Welcome to the Chemistry Quiz Game!\n");
printf("You will be asked %d questions. For each question, choose the correct option.\n\n", MAX_QUESTIONS);
for (int i = 0; i < MAX_QUESTIONS; i++) {
printf("Question %d: %s\n", i + 1, questions[i].question);
for (int j = 0; j < 4; j++) {
printf("%s\n", questions[i].options[j]);
}
printf("Enter your answer (A, B, C, or D): ");
char answer;
scanf(" %c", &answer);
// Validate the answer and update the score
if (answer >= 'A' && answer <= 'D') {
if (answer - 'A' == questions[i].correct_option) {
printf("Correct!\n");
score++;
} else {
printf("Incorrect! The correct answer was %s\n", questions[i].options[questions[i].correct_option]);
}
} else {
printf("Invalid answer! Please enter A, B, C, or D.\n");
}
printf("\n");
}
printf("Quiz completed! Your score: %d out of %d\n", score, MAX_QUESTIONS);
return 0;
}
# Enhanced Fibonacci Sequence Generator with Statistical Analysis
#
# This Julia program generates Fibonacci numbers up to a specified limit
# and provides statistical analysis, including the sum and average of the
# generated Fibonacci sequence. The Fibonacci sequence is a series of
# numbers where each number is the sum of the two preceding ones, usually
# starting with 0 and 1.
#
# The program takes user input to specify the maximum limit for
# the Fibonacci sequence and outputs both the sequence and statistics.
#
# Users can generate multiple sequences and receive detailed analysis on each one.
# This program demonstrates various fundamental programming concepts in Julia,
# such as defining functions, using loops, error handling, and handling user input,
# making it a comprehensive example for beginners learning the language or for
# practicing with an editor.
#
# Example usage:
# Run the script and follow the prompts to generate Fibonacci numbers and
# receive statistics on the generated series.
function fibonacci(limit)
fibs = Int[]
a, b = 0, 1
while a <= limit
push!(fibs, a)
a, b = b, a + b
end
return fibs
end
function fibonacci_statistics(fibs)
total = sum(fibs)
avg = total / length(fibs)
return total, avg
end
function print_statistics(fibs)
if length(fibs) == 0
println("No Fibonacci numbers to summarize.")
return
end
total, avg = fibonacci_statistics(fibs)
println("Total of Fibonacci numbers: $total")
println("Average of Fibonacci numbers: $avg")
end
function print_fibonacci_sequence(fibs)
if length(fibs) == 0
println("No Fibonacci numbers to display.")
return
end
println("Fibonacci Sequence: ", fibs)
end
function get_limit_from_user()
while true
println("Enter the maximum limit for Fibonacci generation (positive integer):")
limit_input = readline()
try
limit = parse(Int, limit_input)
if limit < 0
println("Please enter a non-negative integer.")
continue
end
return limit
catch e
println("Invalid input! Please enter a valid positive integer.")
end
end
end
function main()
println("Welcome to the Enhanced Fibonacci Sequence Generator!")
while true
limit = get_limit_from_user()
fibs = fibonacci(limit)
println("Fibonacci numbers up to $limit: ")
print_fibonacci_sequence(fibs)
print_statistics(fibs)
println("\nWould you like to enter another limit? (y/n)")
response = readline()
if response == "n"
println("Exiting program. Goodbye!")
break
elseif response != "y"
println("Invalid input, exiting program.")
break
end
end
end
# Run the main function
main()
# Comprehensive Statistical Analysis Script
#
# This script provides a set of functions to compute a comprehensive
# statistical summary of a numeric vector in R. The user can input
# a numeric vector, and the script will compute various statistics
# including mean, median, variance, standard deviation, minimum,
# maximum, interquartile range (IQR), and a simple histogram.
#
# The script allows multiple datasets to be analyzed and can also handle
# user input gracefully, prompting for re-entry in case of invalid data.
#
# Example usage:
# To get started, run the script and input a set of numbers when prompted.
#
# The statistical functions demonstrated in this script will help in
# understanding the distribution and behavior of numerical data, making
# it an essential tool for data analysis.
#
# Additional functionalities can be added here in the future for enhanced usability,
# such as saving results to files or comparing multiple vectors.
stat_summary <- function(numbers) {
mean_val <- mean(numbers)
median_val <- median(numbers)
variance_val <- var(numbers)
sd_val <- sd(numbers)
min_val <- min(numbers)
max_val <- max(numbers)
iqr_val <- IQR(numbers)
cat("Comprehensive Statistical Summary:\n")
cat("Mean:", mean_val, "\n")
cat("Median:", median_val, "\n")
cat("Variance:", variance_val, "\n")
cat("Standard Deviation:", sd_val, "\n")
cat("Minimum Value:", min_val, "\n")
cat("Maximum Value:", max_val, "\n")
cat("Interquartile Range (IQR):", iqr_val, "\n")
# Calling the histogram plotting function
plot_histogram(numbers)
}
# Function to plot a histogram
plot_histogram <- function(numbers) {
hist(numbers, main="Histogram of Numbers", xlab="Values", col="lightblue", border="black", breaks="FD")
abline(v=mean), col="red", lwd=2, lty=2)
legend("topright", legend=paste("Mean:", round(mean(numbers), 2)), col="red", lwd=2, lty=2)
}
# Function to get user input and convert to numeric vector
get_user_input <- function() {
cat("Please enter a set of numbers separated by spaces:\n")
input <- scan(what=numeric())
if (length(input) == 0) {
stop("No input provided.")
}
return(input)
}
# Function to validate numeric input
validate_input <- function(input) {
if (any(is.na(input)) || length(input) == 0) {
stop("Input must be a numeric vector with at least one number.")
}
}
# Main execution block
main <- function() {
repeat {
tryCatch({
numbers <- get_user_input()
validate_input(numbers)
stat_summary(numbers)
}, error=function(e) {
cat("Error:", e$message, "\n")
cat("Please try again.\n")
})
repeat {
cat("\nWould you like to analyze another set of numbers? (y/n)\n")
response <- readline()
if (response == "n") {
cat("Exiting the program. Goodbye!\n")
return()
} else if (response == "y") {
break
} else {
cat("Invalid input! Please enter 'y' or 'n'.\n")
}
}
}
}
# Running the main function
main()
"""
Full Temperature Conversion Program
This program provides a comprehensive interface for converting temperatures
between Celsius, Fahrenheit, Kelvin, and Rankine. The user can choose to
convert from one scale to another with input validation and error handling.
The program continuously prompts the user until they decide to quit.
The conversion formulas used are:
- Celsius to Fahrenheit: F = (C * 9/5) + 32
- Fahrenheit to Celsius: C = (F - 32) * 5/9
- Celsius to Kelvin: K = C + 273.15
- Kelvin to Celsius: C = K - 273.15
- Fahrenheit to Rankine: R = F + 459.67
- Rankine to Fahrenheit: F = R - 459.67
The program also handles invalid input gracefully, prompting the user to
enter a valid temperature format. This code demonstrates various Python
programming concepts such as functions, user input, loops, conditionals,
and exception handling, making it an excellent tool for learners and
programmers alike.
"""
def celsius_to_fahrenheit(celsius):
"""Convert Celsius to Fahrenheit."""
return (celsius * 9/5) + 32
def fahrenheit_to_celsius(fahrenheit):
"""Convert Fahrenheit to Celsius."""
return (fahrenheit - 32) * 5/9
def celsius_to_kelvin(celsius):
"""Convert Celsius to Kelvin."""
return celsius + 273.15
def kelvin_to_celsius(kelvin):
"""Convert Kelvin to Celsius."""
return kelvin - 273.15
def fahrenheit_to_rankine(fahrenheit):
"""Convert Fahrenheit to Rankine."""
return fahrenheit + 459.67
def rankine_to_fahrenheit(rankine):
"""Convert Rankine to Fahrenheit."""
return rankine - 459.67
def get_float_input(prompt):
"""Get a floating-point input and handle exceptions."""
while True:
try:
user_input = float(input(prompt))
return user_input
except ValueError:
print("Invalid input! Please enter a numerical valuedef main():
"""Main function to run the temperature conversion program."""
print("Welcome to the Temperature Conversion Program!")
while True:
print("\nMenu:")
print("1. Convert Celsius to Fahrenheit")
print("2. Convert Fahrenheit to Celsius")
print("3. Convert Celsius to Kelvin")
print("4. Convert Kelvin to Celsius")
print("5. Convert Fahrenheit to Rankine")
print("6. Convert Rankine to Fahrenheit")
print("7. Quit")
choice = input("Choose an option (1-7): ")
if choice == '1':
celsius = get_float_input("Enter temperature in Celsius: ")
fahrenheit = celsius_to_fahrenheit(celsius)
print(f"{celsius}°C is {fahrenheit:.2f}°F")
elif choice == '2':
fahrenheit = get_float_input("Enter temperature in Fahrenheit: ")
celsius = fahrenheit_to_celsius(fahrenheit)
print(f"{fahrenheit}°F is {celsius:.2f}°C")
elif choice == '3':
celsius = get_float_input("Enter temperature in Celsius: ")
kelvin = celsius_to_kelvin(celsius)
print(f"{celsius}°C is {kelvin:.2f} K")
elif choice == '4':
kelvin = get_float_input("Enter temperature in Kelvin: ")
celsius = kelvin_to_celsius(kelvin)
print(f"{kelvin} K is {celsius:.2f}°C")
elif choice == '5':
fahrenheit = get_float_input("Enter temperature in Fahrenheit: ")
rankine = fahrenheit_to_rankine(fahrenheit)
print(f"{fahrenheit}°F is {rankine:.2f} R")
elif choice == '6':
rankine = get_float_input("Enter temperature in Rankine: ")
fahrenheit = rankine_to_fahrenheit(rankine)
print(f"{rankine} R is {fahrenheit:.2f}°F")
elif choice == '7':
print("Exiting the program.")
break
else:
print("Invalid choice! Please choose a valid option between 1 and 7.")
if __name__ == "__main__":
main()
@wleoncio
Copy link
Author

Yes, some of them contain syntax errors.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment