Skip to content

Instantly share code, notes, and snippets.

@mokomokohitsuzi
Last active November 6, 2016 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mokomokohitsuzi/3565d3b99a880b829f9b18c847affbd5 to your computer and use it in GitHub Desktop.
Save mokomokohitsuzi/3565d3b99a880b829f9b18c847affbd5 to your computer and use it in GitHub Desktop.
新・明解Java入門 演習4-13
import java.util.Scanner;
public class En4_13 {
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
System.out.println("1からnまでの和を求めます。");
int n;
do {
System.out.print("nの値:");
n = stdIn.nextInt();
} while (n <= 0);
int sum = 0; // 合計変数sumを0で初期化
for (int i = 1; i <= n; i++) { // iを1で初期化し、nまで繰り返す。
sum += i; // sumにiを足す。
}
System.out.println("1から" + n + "までの和は" + sum + "です。");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment