Doit! 알고리즘 (2)

업데이트:


chap01-06

package chap01;
import java.util.Scanner;

public class Q6 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.println("1부터 n까지 합");
		System.out.print("n의 값 : ");
		int n = sc.nextInt();
		
		int sum = 0;
		int i = 1;
		
		while(i <= n) {
			sum += i;
			i++;
		}
		System.out.println(i);
	}
}



chap01-07

package chap01;
import java.util.Scanner;

public class Q7 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.print("n 입력 : ");
		int n = sc.nextInt();
		String str = "";
		int sum = 0;
		for(int i = 1; i <= n; i++) {
			if(i == n) {
				str += i + " = ";
			}else {
				str += i + " + ";
			}
			sum += i;
		}
		System.out.println(str + sum);
	}
}



chap01-08

package chap01;

import java.util.Scanner;

public class Q8 {
	
	static int sum(int n) {
		float sum = 0;
		sum = (1 + n) * ((float)n / 2);
		return (int)sum;
	}

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.print("n 값 입력 : ");
		int n = sc.nextInt();
		
		System.out.println(sum(n));
	}
}



chap01-09

package chap01;
import java.util.Scanner;

public class Q9 {
	static int sumof(int a, int b) {
		int sum = 0;
		
		if(a >= b) {
			for(int i = b; i <= a; i++) {
				sum += i;
			}
		}else {
			for(int i = a; i <= b; i++) {
				sum += i;
			}
		}
		return sum;
	}

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.print("a 입력 : ");
		int a = sc.nextInt();
		System.out.print("b 입력 : ");
		int b = sc.nextInt();
		
		System.out.println(sumof(a, b));
	}
}



chap01-10

package chap01;
import java.util.Scanner;

public class Q10 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.print("a의 값 : ");
		int a = sc.nextInt();
		int b;
		do {
			System.out.print("b의 값 : ");
			b = sc.nextInt();
			if(a >= b) System.out.println("a보다 큰 값을 입력하세요.");
		}while(a >= b);
		
		System.out.println("b-a는 " + (b-a) + "입니다.");
	}
}



chap01-11

package chap01;
import java.util.Scanner;

public class Q11 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.print("정수 입력 : ");
		int n = sc.nextInt();
		int cnt = 0;
		for(int i = 1; i <= n; i*=10) {
			cnt++;
		}
		System.out.println("그 수는 " + cnt + "자리입니다.");
	}
}



태그:

카테고리:

업데이트:

댓글남기기