English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Java

Contrôle de flux Java

Java Tableau

Java Programmation orientée objet (I)

Java Programmation orientée objet (II)

Java Programmation orientée objet (III)

Gestion des exceptions Java

Java Liste (List)

Java Queue (file d'attente)

Java Map (ensemble)

Java Set (ensemble)

Java Entrée/Sortie (I/O)

Java Reader/Writer

Autres sujets Java

Programme Java pour calculer la somme des nombres naturels

Java Examples Comprehensive

Dans ce programme, vous apprendrez à utiliser la boucle for et la boucle while en Java pour calculer la somme des nombres naturels.

Nombre positif1、2、3 ...sont appelés nombres naturels, et leur somme commence à1Résultat de tous les nombres jusqu'au nombre donné.

Pour n, la somme des nombres naturels est :

1 + 2 + 3 + ... + n

Example1:Utilisation de la boucle for pour la somme des nombres naturels

public class SumNatural {
    public static void main(String[] args) {
        int num = 100, sum = 0;
        for(int i = 1; i <= num; ++i)
        {
            // sum = sum + i;
            sum += i;
        }
        System.out.println("Sum = " + sum);
    }
}

When running the program, the output is:

Sum = 5050

The above program starts from1to the given num(10loop, and add all numbers to the variable sum.

You can solve this problem using a while loop as follows:

Example2: Sum of natural numbers using while loop

public class SumNatural {
    public static void main(String[] args) {
        int num = 50, i = 1, sum = 0;
        while(i <= num)
        {
            sum += i;
            i++;
        }
        System.out.println("Sum = " + sum);
    }
}

When running the program, the output is:

Sum = 1275

In the above program, unlike the for loop, we must increase the value of i within the loop body.

Although both programs are technically correct, it is best to use a for loop in this case. This is because the number of iterations (up to num) is known.

Java Examples Comprehensive