From 7c8e99f5aa9a7bee32ac95f92aff6645151116a7 Mon Sep 17 00:00:00 2001 From: pro100ton Date: Thu, 12 Dec 2024 22:55:25 +0300 Subject: [PATCH] Add example for local and global variables --- .../ProgramOrganization/global_variables.c | 61 +++++++++++++++++++ .../static_local_variables.c | 18 ++++++ 2 files changed, 79 insertions(+) create mode 100644 c_modern_approach/ProgramOrganization/global_variables.c create mode 100644 c_modern_approach/ProgramOrganization/static_local_variables.c diff --git a/c_modern_approach/ProgramOrganization/global_variables.c b/c_modern_approach/ProgramOrganization/global_variables.c new file mode 100644 index 0000000..3fb3ca0 --- /dev/null +++ b/c_modern_approach/ProgramOrganization/global_variables.c @@ -0,0 +1,61 @@ +#include +#include +#include + +#define MAX_NUMBER 100 + +/* External variable */ +int secret_number; + +// Prototypes +void initialize_number_generator(void); +void choose_new_secret_number(void); +void read_guess(void); + +int main() { + char command = 'y'; + printf("Guess the secret number between 1 and %d. \n\n", MAX_NUMBER); + initialize_number_generator(); + do { + choose_new_secret_number(); + printf("New number has been chosen.\n"); + read_guess(); + printf("Play again? (Y/N)\n"); + while (getchar() != '\n') + ; // Discard any leftover input + scanf("%c", &command); + printf("\n"); + } while (command == 'y' || command == 'Y'); + exit(0); +} + +/** + * @brief Initializing random number generator based on current time + * time(NULL) returns current time in `time_t` format + */ +void initialize_number_generator(void) { srand((unsigned)time(NULL)); } + +/** + * @brief Here we are using rand() function and getting the remaining value of + * deletion by MAX_NUMBER + 1 to get random value between 0 and 100 + */ +void choose_new_secret_number(void) { + secret_number = rand() % MAX_NUMBER + 1; +}; + +void read_guess(void) { + int guess, num_guesses = 0; + for (;;) { + num_guesses++; + printf("Enter guess: "); + scanf("%d", &guess); + if (guess == secret_number) { + printf("You guessed the number after %d attempts!\n\n", num_guesses); + return; + } else if (guess < secret_number) { + printf("Missed! Secret value is lower than your value\n"); + } else { + printf("Missed! Secret value is higher than your value\n"); + } + } +}; diff --git a/c_modern_approach/ProgramOrganization/static_local_variables.c b/c_modern_approach/ProgramOrganization/static_local_variables.c new file mode 100644 index 0000000..302b75d --- /dev/null +++ b/c_modern_approach/ProgramOrganization/static_local_variables.c @@ -0,0 +1,18 @@ +#include +#include +/** + * @brief Function for demonstration static local variables + */ +void test_static() { + static int static_var; + static_var += 1; + printf("%d\n", static_var); +} + +int main() { + test_static(); + test_static(); + test_static(); + test_static(); + exit(0); +}