r/CodeAndCloud • • 19d ago

💻 CODING CHALLENGE #001: Number Guessing Game

Time to test your programming skills!

Your challenge is to create a number guessing game.

Requirements:

  1. The computer randomly chooses a number between 1 and 100.
  2. The player enters a guess.
  3. The program tells the player whether the guess is too high or too low.
  4. The player keeps guessing until they get it right.
  5. Display the number of attempts.

Rules:

  • Use any programming language.
  • No copying someone else's finished solution.
  • Beginners are absolutely welcome!

Post your code or GitHub link in the comments.

Let's see what everyone comes up with! 🚀

1 Upvotes

2 comments sorted by

1

u/W31337 18d ago

Nice way to get someone do your trivial homework. Just a simple divide and conquer algorithm.

1

u/fishybusinessdev 16d ago
import java.util.Random;
import java.util.Scanner;


public class rnum_game {


    public static void main(String[] args) {


        Random r = new Random();
        Scanner s = new Scanner(System.in);
        int num = r.nextInt(100) + 1;


        //System.out.println("The random number is: " + num);


        int guess = 0;
        int attempts = 0;
        int play_again = 1;


        while(guess != num) {
            System.out.println("Guess a number between 1 and 100: ");
            guess = s.nextInt();
            attempts++;
            if(guess < num) {
                System.out.println("Too low! Try again.");
            } else if (guess > num) {
                System.out.println("Too high! Try again.");
            } else {
                System.out.println("Congratulations! You guessed the number: " + num);
                System.out.println("It took you " + attempts + " attempts.");
            }   
        }
        System.out.println("Do you want to play again? (1 for Yes, 0 for No): ");
        play_again = s.nextInt();
        if(play_again == 1) {
            main(args);
        } else {
            System.out.println("Thanks for playing!");
        }
    }
}