jueves, 31 de agosto de 2023

Domina Java: 20 Ejercicios Resueltos para Impulsar tus Habilidades de Programación. Universidad. (Parte 1)

Java es uno de los lenguajes de programación más populares y ampliamente utilizados en el mundo. Su versatilidad y robustez lo convierten en una elección sólida para desarrolladores de todos los niveles. Sin embargo, para dominar Java y aprovechar al máximo su potencial, es esencial practicar y resolver una variedad de problemas. Este artículo te brindará una colección de ejercicios resueltos de Java que te ayudarán a fortalecer tus habilidades de programación y comprender mejor este lenguaje.


Ejercicio 1: Programa Java para comprobar si un número dado es par o impar

import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    System.out.println("Enter a number: ");
    Scanner sc = new Scanner(System.in);
    int number =Integer.parseInt(sc.nextLine());
    int x = number%2;
    
    if(x==0){
      System.out.println("The number is Even");
    }
    else{
      System.out.println("The number is Odd");
    }
    
  }
}


Ejercicio 2: Programa Java para convertir la temperatura en Centígrados a Fahrenheit

import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    System.out.println("Enter temperature in Centigrade: ");
    Scanner sc = new Scanner(System.in);
    int c =Integer.parseInt(sc.nextLine());
    float f = ((9f*c)/5f)+32;
    
    System.out.println("Temperature in Fahrenheit is: "+f);
    
  }
}


Ejercicio 3: Programa Java para hallar el área de un triángulo cuyos tres lados están dados

import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    Scanner sc= new Scanner(System.in);
        
         System.out.println("Enter the 1st side:");
         int a= sc.nextInt();
 
         System.out.println("Enter the 2nd side:");
          int b= sc.nextInt();
 
         System.out.println("Enter the 3rd side:");
         int c= sc.nextInt();
    
         if((a+b)>c && (a+c)>b && (b+c)>a)
          {
            double s=(a+b+c)/2.0;
            double area=Math.sqrt(s*(s-a)*(s-b)*(s-c));
            System.out.println("Area of Triangle is: " + area);    
           }
         else  
           System.out.println("Area of the triangle does not exist");
    
  }
}


Ejercicio 4: Programa Java para hallar la media de un conjunto de enteros

import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the count of numbers: ");
    int count = Integer.parseInt(sc.nextLine());
    int i = 0;
    float sum = 0;
    for(i=0;i<count;i++){
      System.out.println("Enter an integer: ");
      int x = Integer.parseInt(sc.nextLine());
      sum = sum + x;
    }
  
    float avg = sum/count;
    System.out.println("The average is: "+avg);
    
  }
}


Ejercicio 5: Programa Java para hallar el producto de un conjunto de números reales

import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the number of real numbers: ");
    int count = Integer.parseInt(sc.nextLine());
    int i = 0;
    float product = 1.0f;
    for(i=0;i<count;i++){
      System.out.println("Enter a real number: ");
      float x = Float.parseFloat(sc.nextLine());
      product = product * x;
    }
  
    System.out.println("The product of the numbers is: "+product);
    
  }
}


Ejercicio 6: Programa Java para hallar la circunferencia y el área de un círculo con un radio dado

import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    System.out.println("Input the radius of the circle: ");
    double radius = Float.parseFloat(sc.nextLine());

    double c = 2 * Math.PI * radius;
    double area = Math.PI * radius * radius;
    
    System.out.println("The circumference of the circle is: "+c);
    System.out.println("The area of the circle is: "+area);
    
  }
}


Ejercicio 7: Programa Java para comprobar si el número entero dado es múltiplo de 5

import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    System.out.println("Enter an integer: ");
    Scanner sc = new Scanner(System.in);
    int number =Integer.parseInt(sc.nextLine());
    
    if(number%5==0){
      System.out.println(number+" is a multiple of 5");
    }
    else{
      System.out.println(number+" is not a multiple of 5");
    }
    
  }
}


Ejercicio 8: Programa Java para comprobar si el número entero dado es múltiplo de 5 y de 7

import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    System.out.println("Enter an integer: ");
    Scanner sc = new Scanner(System.in);
    int number =Integer.parseInt(sc.nextLine());
    
    if((number%5==0)&&(number%7==0)){
      System.out.println(number+" is a multiple of both 5 and 7");
    }
    else{
      System.out.println(number+" is not a multiple of both 5 and 7");
    }
    
  }
}


Ejercicio 9: Programa Java para hallar la media de 5 números usando un bucle while

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    
    int count = 0;
    int sum = 0;
    Scanner sc = new Scanner(System.in);
    while(count<5){
      System.out.println("Enter an integer: ");
      int number =Integer.parseInt(sc.nextLine());
      sum = sum+number;
      count++;
      }
    
double avg = ((double) sum) / 5.0;
System.out.println("Average is: "+avg);
    
  }
}


Ejercicio 10: Programa Java para mostrar el número entero dado en el orden inverso

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter an integer: ");
    int number =Integer.parseInt(sc.nextLine());
    int rev = 0;
    
    while(number!=0){
      int digit = number%10;
      rev = (rev*10)+digit;
      number = number/10;
      }
    
System.out.println(rev);
    
  }
}


Ejercicio 11: Programa Java para hallar la media geométrica de n números

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    int c = 0;
    double p = 1.0;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the number of values: ");
    int count =Integer.parseInt(sc.nextLine());
    
    while((c<count)){
      System.out.println("Enter a real number: ");
      double x =Double.parseDouble(sc.nextLine());
      c = c+1;
      p = p * x;
      }
    double gm = Math.pow(p,1.0/count);
    System.out.println("The geometric mean is: "+gm);
    
  }
}


Ejercicio 12: Programa Java para hallar la suma de los dígitos de un número entero utilizando un bucle while

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    int sum = 0;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter an integer: ");
    int number =Integer.parseInt(sc.nextLine());
    
    while(number!=0){
      int digit = number%10;
      sum = sum+digit;
      number = number/10;
    }
    
    System.out.println(("Sum of digits is: "+ sum));
    
  }
}


Ejercicio 13: Programa Java para mostrar todos los múltiplos de 3 dentro del intervalo de 10 a 50

import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    for(int i=10;i<50;i++){
      if(i%3==0)
        System.out.println(i);
    }
    
  }
}


Ejercicio 14: Programa Java para mostrar todos los números enteros dentro del rango 100-150 cuya suma de dígitos sea un número par

import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    for(int i=100;i<150;i++){
      int num = i;
      int sum = 0;
      while(num!=0){
        int digit = num%10;
        sum = sum + digit;
        num = num/10;
      }
      if(sum%2==0){
          System.out.println(i);
        }
    }
    
  }
}


Ejercicio 15: Programa Java para comprobar si el número entero dado es un número primo o no

import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    System.out.println("Enter an integer greater than 1: ");
    Scanner sc = new Scanner(System.in);
    int number =Integer.parseInt(sc.nextLine());

    int isprime = 1;

    for(int i=2;i<(number/2);i++){
      if(number%i==0){
        isprime = 0;
        break;
      }
    }
    
    if(isprime==1){
      System.out.println(number+" is a prime number");
    }
    else{
      System.out.println(number+" is not a prime number");
    }
    
  }
}


Ejercicio 16: Programa Java para generar los números primos de 1 a N

import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    System.out.println("Enter the range: ");
    Scanner sc = new Scanner(System.in);
    int number =Integer.parseInt(sc.nextLine());

    for (int num = 2; num <= number; num++)
        {
            boolean isPrime = true;
            for (int i=2; i <= num/2; i++)
            {
                if ( num % i == 0)
                {
                    isPrime = false;
                    break;
                }
            }
 
            if ( isPrime == true )
                System.out.println(num);
        }
    
  }
}


Ejercicio 17: Programa Java para encontrar las raíces de una ecuación cuadrática

import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    System.out.println("Enter the first coefficient: ");
    Scanner sc = new Scanner(System.in);
    double a = Integer.parseInt(sc.nextLine());
    System.out.println("Enter the second coefficient: ");
    double b = Integer.parseInt(sc.nextLine());
    System.out.println("Enter the third coefficient: ");
    double c = Integer.parseInt(sc.nextLine());

    if(a!=0.0){
      double d = (b*b)-(4*a*c);
      if (d==0.0){
        System.out.println("The roots are real and equal.");
        double r = -b/(2*a);
        System.out.println("The roots are "+ r+"and"+ r);
      }else if(d>0.0){
        System.out.println("The roots are real and distinct.");
        double r1 = (-b+(Math.sqrt(d)))/(2*a);
        double r2 = (-b-(Math.sqrt(d)))/(2*a);
        System.out.println("The root1 is: "+ r1);
        System.out.println("The root2 is: "+ r2);
      }else{
        System.out.println("The roots are imaginary.");
        double rp = -b/(2*a);
        double ip = Math.sqrt(-d)/(2*a);
        System.out.println("The root1 is: "+ rp+ "+ i"+ip);
        System.out.println("The root2 is: "+ rp+ "- i"+ip);
      }   
    }else{
      System.out.println("Not a quadratic equation.");
    }
  }
}


Ejercicio 18: Programa Java para imprimir los números desde un número dado n hasta 0 usando recursividad

class Main {
  public static void main(String[] args) {
    print_till_zero(8);
    
  }

  public static void print_till_zero(int n){
      if(n==0)
        return;
      System.out.println(n);
      n=n-1;
      print_till_zero(n);
    }
}


Ejercicio 19: Java program to find the factorial of a number using recursion

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    
    System.out.println("Enter an integer:  ");
    Scanner sc = new Scanner(System.in);
    int a = Integer.parseInt(sc.nextLine());
    int result = fact(a);
    System.out.println("The factorial of"+ a + " is: "+ result);
    
  }

  public static int fact(int n){
    int f;
    if(n==1)
      f=1;
    else
      f = n * fact(n-1);
    return f;
    }
}


Ejercicio 20: Java program to display the sum of n numbers using an array

import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    System.out.println("How many numbers: ");
    Scanner sc = new Scanner(System.in);
    int num = Integer.parseInt(sc.nextLine());
    int[] numbers = new int[num];
    int sum=0;
    
    for(int n=0;n<num;n++){
      System.out.println("Enter number: ");
      int x = Integer.parseInt(sc.nextLine());
      numbers[n] = x;
    }

    for(int i = 0; i < numbers.length; i++) {  
        sum = sum + numbers[i];  
      }  
    System.out.println("Sum of all the elements of the array: " + sum);  
    
  }
}


Consulta más de mis artículos relacionados con JAVA

viernes, 25 de agosto de 2023

ChatGPT post: Exploring the Exciting Possibilities of Quantum Computing

 Hello Internet!

Today I decided to ask ChatGPT for help to generate a post in the news log and give the IA the opportunity to choose the topic.



Hello Blobber community,

I hope this message finds you all well. Today, I want to dive into one of the most fascinating and rapidly evolving areas of technology - quantum computing.

Quantum Computing: A Brief Overview

For those unfamiliar with the concept, quantum computing represents a paradigm shift in the world of computation. While classical computers use bits as the fundamental unit of information (0 or 1), quantum computers leverage qubits, which can exist in multiple states simultaneously due to the principles of superposition and entanglement. This unique property enables quantum computers to solve complex problems exponentially faster than classical counterparts in certain domains.

Current State of Quantum Computing

Quantum computing is no longer a distant dream; it's becoming a reality. Tech giants like IBM, Google, and Microsoft are investing heavily in quantum research and have made significant breakthroughs. We're seeing the emergence of quantum processors with increasing qubit counts, making it possible to tackle more complex problems.

Applications and Implications

The potential applications of quantum computing are mind-boggling. From optimizing supply chains to cracking currently unbreakable encryption, quantum computers promise to revolutionize various industries. Researchers are working on quantum algorithms for drug discovery, climate modeling, and even simulating quantum chemistry, which could lead to the development of new materials with unprecedented properties.

However, with great power comes great responsibility. The advent of quantum computing also raises cybersecurity concerns. It could render today's encryption methods obsolete, prompting the need for new, quantum-resistant cryptographic techniques.

Challenges and Future Outlook

While quantum computing holds immense promise, it's not without its challenges. Qubits are incredibly delicate and prone to errors, necessitating the development of error-correcting codes. Moreover, building practical and scalable quantum computers is an ongoing struggle.

Despite these challenges, the field of quantum computing is advancing rapidly, thanks to the collaborative efforts of researchers, tech companies, and governments worldwide.

Join the Discussion

I encourage all tech enthusiasts to join in the discussion. What are your thoughts on the current state of quantum computing? Are you excited about its potential, or do you have concerns about its implications? Have you come across any recent breakthroughs or interesting applications?

Let's explore this exciting frontier of technology together. Share your insights, questions, or any relevant news articles you've come across in the comments section below. The future of quantum computing is unfolding before our eyes, and your perspective is valuable.

Stay curious and stay connected!

Best regards,

CHATGPT