1. 클래스의 개념 : 클래스란 객체를 만들어 내기 위한 설계 혹은 틀이다.


2. 객체의 개념 : 객체란 클래스에 선언된 모양 그대로 생성된 실체를 객체라 부르며 클래스의 인스턴스(instance)라고도 부른다. 객체와 인스턴스는 구별 없이 사용한다.


3. 객체지향이란 : 객체 지향이란 컴퓨터가 산업 전반에 활용됨에 따라 실세계에서 발생한 일들을 프로그래밍 해야 하는 경우가 많아지게 되고 이에 따라 실세계의 일을 보다 쉽게 프로그래밍 할 수 있는 방법이 절차 지향적인 언어와 비교되는 객체 지향적 언어이다.


4. 객체정의 예제


객 체

상 태

동 작

충전상태,소리,발열

발광하다,충전하다

인간

배고픔,아픔

소리지르다,섭취하다


5. 객체생성 예제(프로그램 4-1 소스코드, 실행결과, 주석: 클래스 구성, 객체 생성 순서 설명)


package exClass1;


public class Circle {


int radius; //속성

String name;

public double getArea(){ //메소드

return 3.14*radius*radius;

}



public static void main(String[] args){

//1. 객체생성

Circle pizza = new Circle(); //pizza 객체 생성

//2. 필드와 메소드에 도트 연산자.을 이용해서 접근

pizza.radius = 10;

pizza.name = "콤비네이션 피자";

double area = pizza.getArea(); //피자면적 계산

//3. 객체내용 출력

System.out.println(pizza.name + "의 면적은 " + area);

//2. 도넛을 만들어보자

Circle donut = new Circle();

donut.radius = 2;

donut.name = "까데기";

area = donut.getArea();

System.out.println(donut.name + "의 면적은 " + area);

}


}



클래스는 필드와 메소드로 구성되어지며 객체를 생성할때에는 객체를 생성한 뒤 해당 필드와 메소드에 도트 연산자 . 을 이용하여 접근하고 마지막으로 객체의 내용을 출력하면 된다.


6. 객체생성 예제2 (프로그램 4-2참조. rect객체, book객체를 생성하는 코드, 결과, 주석)


package exClass1;


public class Rectangle {

int width;

int height;

int getArea(){

return width*height;

}

public static void main(String[] args){

//1. 객체 생성

Rectangle nemo = new Rectangle();

//2. 필드와 메소드에 접근

nemo.width = 4; //너비와 높이의 초기값 지정

nemo.height = 5;

int area = nemo.getArea();

//3. 객체 내용 출력

System.out.println("해당 사각형의 면적은 " + area);

Rectangle book = new Rectangle();

book.height = 15;

book.width = 10;

System.out.println("책의 size = " + book.getArea() + "입니다.");

}


}



7. 생성자의 개념 : 생성자란 객체가 생성될 때 초기화를 위해 실행되는 메소드이다.


8. 생성자의 특징 : 

생성자의 특징은 다음과 같이 여러가지가 있다.

(1) 이름이 클래스 이름과 동일하다.

(2) 여러 개 작성할 수 있다.

ex) public class Circle{

public Circle(){...}        //매개 변수가 없는 생성자

public Circe(int r, String n){...}        //2개의 매개 변수를 가진 생성자

}

(3) 객체를 생설할 때 한 번만 호출된다.

(4) 리턴 타입을 지정할 수 없다.

(5) 생성자는 초기화 작업을 위하여 사용한다.


9. 생성자의 예제(4-3 소스코드, 결과, 주석)


package exClass1;


public class Circle {


int radius; //속성

String name;

//생성자 이름은 클래스 이름과 동일하다.

public Circle(){ //매개 변수가 없는 생성자

radius = 1; name = ""; //radius의 초기값은 1

}

//생성자는 리턴 타입이 없다. - 기본 생성자 

public Circle(int r, String n){ //매개 변수를 가진 생성자

radius = r; name = n; //생성자는 radius와 name필드 초기화

}

public double getArea(){ //메소드

return 3.14*radius*radius;

}



public static void main(String[] args){

//1. 객체생성

Circle pizza = new Circle(10,"자바피자"); //Circle 객체 생성, 반지름10

double area = pizza.getArea(); //피자면적 계산

//3. 객체내용 출력

System.out.println(pizza.name + "의 면적은 " + area);

//2. 도넛을 만들어보자

Circle donut = new Circle();//Circle 객체 생성, 반지름 1

donut.name = "도넛피자";

area = donut.getArea();

System.out.println(donut.name + "의 면적은 " + area);

}


}



10. 생성자와 this예제 (프로그램 4-5 소스코드, 결과(출력된 이유), (주석)생성자 함수 몇개, 특징(매개변수의 개수와 타입))


package mypractice;


public class Book {


String title;

String author;

void show() {

System.out.println(title + " " + author);

}

public Book(){

this("", "");

System.out.println("생성자 호출됨");

}

public Book(String title){

this(title, "작자미상");

}

public Book(String title, String author){

this.title = title;

this.author = author;

}

public static void main(String[] args) {


Book javaBook = new Book("Java", "황기태");

Book bible = new Book("Bible");

Book emptyBook = new Book();

bible.show();


}


}





생성자 함수는 매개변수의 개수와 타입을 찾아서 실행하는데 매개변수의 개수와 타입은 달라야한다.


11. static 멤버의 선언방법, 특징(표 4-2 참조)


static 멤버 선언방법 : class 내의 필드와 변수 앞에 static을 붙여서 사용

ex)    class Sample{

static int m;

static void g(){...}

}

특징 : static 멤버는 클래스당 하나 생성(공간적 특성), 클래스 로딩 시에 멤버 생성(시간적 특성), 동일한 클래스의 모든 객체들에 의해 공유된다.(공유의 특성)


12. 예제 4-11 소스코드, 실행결과


package exStatic;


class Calc{

public static int abs(int a){

return (a>0) ? a : -a;

}

public static int max(int a, int b){

return (a>b) ? a : b;

}

public static int min(int a, int b){

return (a>b) ? b : a;

}

}


public class CalEx {


public static void main(String[] args) {

/*클래스이름.멤버함수(abs) 가능한 이유 : abs 함수가 static으로 선언됨

static 멤버는 클래스 이름으로 접근이 가능함.*/

System.out.println(Calc.abs(-5));

System.out.println(Calc.max(10, 8));

System.out.println(Calc.min(-3, -8));


}


}



'basic > Java 8' 카테고리의 다른 글

[Java] Exception  (0) 2018.08.07
5. 상속  (0) 2017.05.12
3. 반복문과 배열 그리고 예외처리  (0) 2017.03.31
2. 자바 기본 프로그래밍  (0) 2017.03.14
1. 자바시작  (0) 2017.03.07

1. 반복문 (for문)

  (1) 형식 : 

for(초기식;조건식;증감식)

{

여러문장;

}

for문을 무한루프 돌리고 싶을때는 조건식을 생략하면 된다.

  (2) 예제

package exam;


public class ForSample {


public static void main(String[] args) {

// TODO Auto-generated method stub

int i, sum=0;;

for(i=1;i<=10;i++)

{

sum += i; //sum = sum + i

System.out.print(i);

if(i<=9) //1~9까지는 '+' 출력

System.out.print("+");

else{

System.out.print("="); //'='출력하고

System.out.print(sum); //덧셈 결과 출력

}

}


}


}





2. 반복문 (while문)

  (1) 형식 : 

초기식

while(조건식)

{

문장1; 문장2;

...

증감식;

}

while문을 무한루프 돌리려면 조건식을 참으로 만들어주면 됨 while(true)

  (2) 예제(프로그램3-2 소스코드, 실행결과)

package exam;


import java.util.Scanner;


public class ForSample {


public static void main(String[] args) {

// TODO Auto-generated method stub

//1~10 출력

Scanner sc = new Scanner(System.in);

System.out.println("정수를 입력하세요(0을 입력하면 결과가 출력됩니다) : ");

int i=0,num=0; //1.초기식

double sum = 0;

while((num = sc.nextInt()) != 0) //2.조건식

{

sum += num;

i++;

}

System.out.print("수의 개수는" + i + "개이며 ");

System.out.print("합은 "+ sum + "이며 ");

System.out.println("평균은 " + sum/i + "입니다.");

sc.close();

}


}





3. 반복문 (do~while문)

  (1) 형식


초기식

do

{

문장...

증감식

}while(조건식);


  (2) 예제 (소스코드, 결과, 주석:i가 1만 출력된 이유)


package exam;


import java.util.Scanner;


public class ForSample {


public static void main(String[] args) {

// TODO Auto-generated method stub

int i;

i=1; //1.초기식

do{

System.out.println(i);

i++; //3.증감식

}while(i>10); //2.조건식    /*i는 1만 출력된다 이유는 조건식이 거짓이 되므로 실행이 멈추기 때문.*/

}


}




4. 중첩반복문 예제(예제3-4 소스코드, 결과)


package exam;


import java.util.Scanner;


public class ForSample {


public static void main(String[] args) {

// TODO Auto-generated method stub

for(int i = 1 ; i < 10 ; i++){

for(int j=1 ; j<10 ; j++){

System.out.print(i + "*" + j + "=" + i*j);

System.out.print('\t');

}

System.out.println();

}

}


}




5. 반복문 + contnue문, break문 예제


package exam;


import java.util.Scanner;


public class ForSample {


public static void main(String[] args) {

// TODO Auto-generated method stub

Scanner sc = new Scanner(System.in);

System.out.println("정수를 5개 입력하세요.");

int i;

int sum = 0;

for(i=0 ; i<5 ; i++)

{

int n = sc.nextInt();

if (n<=0) continue;

else sum += n;

}

System.out.println("양수의 합은 " + sum);

sc.close();

}


}



continue는 해당하는 조건에 부합되면 다음 단계로 넘어가고


package exam;


import java.util.Scanner;


public class ForSample {


public static void main(String[] args) {

// TODO Auto-generated method stub

Scanner sc = new Scanner(System.in);

System.out.println("정수를 5개 입력하세요.");

int i;

int sum = 0;

for(i=0 ; i<5 ; i++)

{

int n = sc.nextInt();

if (n<=0) break;

else sum += n;

}

System.out.println("양수의 합은 " + sum);

sc.close();

}


}



break는 조건에 해당하면 반복문 자체를 빠져 나와 버리기 때문에 차이가 생긴다.


6. 배열 사용방법


1. 선언할때에는 배열의 크기를 지정하지 않는다.

2. 생성할때에는 new를 사용하여 복사하여 사용한다.

public class exArray1 {

public static void main(String[] args){

int intArray[]; //1.배열선언

intArray = new int[5]; //2.배열생성

int intArray1[] = new int[6]; //배열선언+생성 동시에 할 수 있다.

int intArray2[] = {1,2,3,4,5}; //배열을 초기화하면서 선언

int size = intArray2.length;

for(int k: intArray2)

//for~each문으로 배열 원소를 순서대로 읽어올수있음.

System.out.println(k);

for(int i=0;i<size;i++){

System.out.println("배열의 원소는 " + intArray2[i]);

}

}




7. 배열 사용예제


(1)합계,평균함수정의


package exArray;


public class exArray1 {

public static void main(String[] args){

int intArray[]; //1.배열선언

intArray = new int[5]; //2.배열생성

int intArray1[] = new int[6]; //배열선언+생성 동시에 할 수 있다.

int intArray2[] = {2,2,3,4,5}; //배열을 초기화하면서 선언

int size = intArray2.length;

for(int k: intArray2)

//for~each문으로 배열 원소를 순서대로 읽어올수있음.

System.out.println(k);

int n = sum(intArray2); //1. 배열함수 정의

System.out.println("합계는 : " + n);

double avg = avg(intArray2);

System.out.println("평균은 : " + avg);

/*for(int i=0;i<size;i++){

System.out.println("배열의 원소는 " + intArray2[i]);

}*/

}


private static double avg(int[] intArray2) {

double avg=0;

int sum=0;

for(int k : intArray2)

{

sum+=k;

avg = (double)sum/(double)intArray2.length;

}

return avg;

}


private static int sum(int[] intArray2) {

int sum=0;

for(int k : intArray2)

sum+=k;

return sum;

}


}



8. 2차원 배열예제 (소스, 결과, 주석)


package exArray;


public class ScoreAverage {


public static void main(String[] args) {

double score[][] = 

{ //행단위로 열의 값을 나열해서 사용

{3.3,3.4}, //1학년 1, 2학기 평점

{3.5,3.6}, //2학년 1, 2학기 평점

{3.7,4.0}, //3학년 1, 2학기 평점

{4.1,4.2} //4학년 1, 2학기 평점

};

double sum = 0;

/*이중 for문 year 0행 에서 term의 1열 2열 실행됨

바깥쪽의 for문의 1행이 고정되어 있을때 안쪽의 for문이 반복 실행됨.*/

for(int year=0;year<score.length;year++) //각 학년별로 반복

for(int term=0;term<score[year].length;term++) //각 학년의 학기별로 반복

sum += score[year][term]; // 전체 평점 합

int n = score.length; //배열의 행 개수, 4

int m = score[0].length; //배열의 열 개수, 2

System.out.println("4년 전체 평점 평균은 " + sum/(n*m));

}


}



9. 예외처리


개념 :  프로그램 실행 중 오동작이나 결과에 악영향을 미치는 예상치 못한 상황 발생을 예외라고 하고 이 예외를 처리하는 과정

형식 : try{예외가 발생할 가능성이 있는 실행문} catch(처리할 예외 타입 선언){예외 처리문} finally(예외 발생 여부와 상관없이 무조건 실행되는 문장) (finally 블록은 생략이 가능하다).


(1) 0으로 나눈 예외처리 예제(소스, 결과, 주석) 표3-1 예외 내용 참고


package example;


import java.util.Scanner;


public class DivideByZero {


public static void main(String[] args){

Scanner scanner = new Scanner(System.in);

int dividend; // 나뉨수

int divisor; // 나눗수

System.out.print("나뉨수를 입력하시오:"); 

dividend = scanner.nextInt(); // 나뉨수 입력

System.out.print("나눗수를 입력하시오:"); 

divisor = scanner.nextInt(); // 나눗수 입력

try{

System.out.println(dividend+"를 " + divisor + "로 나누면 몫은 "

+ dividend/divisor + "입니다.");

}

catch(ArithmeticException e){

System.out.println("0으로 나눌 수 없습니다.");

}

finally{

scanner.close();

}

}

}



예외 발생 타입(예외 클래스) 가 ArithmeticException인 경우 정수를 0 으로 나눌 때 발생함.


(2) 입력 오류를 처리하는 예제(소스, 결과, 주석) 표3-1 예외 내용 참고


package example;

import java.util.InputMismatchException;
import java.util.Scanner;

public class ex2 {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("정수 3개를 입력하세요");
int sum=0, n=0;
  for(int i=0; i<3; i++)
  {
  
  System.out.print(i+">>");
  
  try{
  n = scanner.nextInt(); // 정수 입력
  }
  catch(InputMismatchException a){
  System.out.println("정수가 아닙니다. 다시 입력하세요");
  scanner.next();
  i--;
  continue;
  }
  sum+=n;
  }
System.out.println("합은 " + sum);
scanner.close();
}

}

예외 발생 타입(예외 클래스) 가 InputMismatchException인 경우 Scanner 클래스의 nextInt()를 호출하여 정수로 입력받고자 하였으나 사용자가 정수가 아닌 다른 문자를 입력한 경우 발생한다.

'basic > Java 8' 카테고리의 다른 글

[Java] Exception  (0) 2018.08.07
5. 상속  (0) 2017.05.12
4. 클래스와 객체  (0) 2017.04.11
2. 자바 기본 프로그래밍  (0) 2017.03.14
1. 자바시작  (0) 2017.03.07

1. 자바프로그램의 기본구조

자바 프로그램은 클래스 단위로 구성된다. 그리고 그 클래스 안에 변수나 메소드 등의 프로그램 요소가 들어가있다. 

자바 프로그램은 메인 메소드부터 실행을 시작한다. 그러나 모든 클래스가 메인 메소드를 가지는 것은 아니다. 

아래의 예제 Hello 클래스에서 Hello 라는 클래스 내에 두 개의 메소드가 들어가 있는 모습이다.

아래쪽 main 메소드에서 실행이 시작된다.


 (예) Hello클래스


package example2;


public class Hello {

public static int sum(int n,int m){

return n+m;

}

public static void main(String[] args) {

int i = 20;

int s;

char a;

s = sum(i,10); //sum() 메소드 호출

a = '?';

System.out.println(a); //문자 '?' 화면 출력

System.out.println("Hello"); //"Hello" 문자열 화면 출력

System.out.println(s); //정수 s값 화면 출력


}


}





2. 자바의 키 입력 예제 2-3


package example2;


public class TypeConversion {


public static void main(String[] args) {

byte b = 127;

int i = 100;

System.out.println(b+i); //b가 int 타입으로 자동변환되어 연산됨

System.out.println(10/4); //정수/정수 = 정수 의 결과

System.out.println(10.0/4); //실수/정수 = 실수 의 결과

System.out.println((char)0x12340041); //0x로 시작한 16진수 데이터에서 char형으로 캐스팅 되고있다. char형은 2바이트, 해당 데이터의 하위 2바이트 까지만 읽을수 있으므로 0041의 아스키 코드 값 65는 문자 A

System.out.println((byte)(b+i)); //해당 데이터는 int형으로 저장되지만 byte로 캐스팅 되므로 손실되는 부분을 제외한 값 -29

System.out.println((int)2.9+1.8); //2.9가 int형으로 캐스팅 되어 2 + 1.8 = 3.8

System.out.println((int)(2.9+1.8)); //2.9+1.8 이 먼저 계산되어 4.7이라는 데이터가 int형으로 캐스팅 되어 4

System.out.println((int)2.9+(int)1.8); // 위와 마찬가지로 2.9는 2로 1.8은 1로 int형으로 각각 캐스팅 되어 결과는 3



}


}



3. 키입력 예제 2-4 소스코드, 실행결과, 주석


import java.util.Scanner;


public class exScanner1 {


public static void main(String[] args) {

// TODO Auto-generated method stub

Scanner sc = new Scanner(System.in);

System.out.println("이름, 도시, 나이, 체중, 독신여부를 빈칸으로 분리하여 입력하세요.");

String name = sc.next();                 //이름입력 ,이름은 문자열을 받는 next사용

String city = sc.next();                 //도시입력 ,도시는 문자열을 받는 next사용

int age = sc.nextInt();         //나이입력 ,나이는 정수형이므로 nextInt사용

double weight = sc.nextDouble(); //체중입력 ,체중은 실수형이므로 nextDouble사용

boolean single = sc.nextBoolean(); //독신여부입력 ,독신여부는 논리형이므로 Boolean사용

System.out.println("이름은 " + name);         //name에 입력된 값 출력

System.out.println("도시는 " + city);            //city에 입력된 값 출력

System.out.println("나이는 " + age);            //age에 입력된 값 출력

System.out.println("체중은 " + weight);        //weight에 입력된 값 출력

System.out.println("혼인여부는 " + single);    //single에 입력된 값 출력

sc.close();

}


}



4. 조건문(IF문) 예제 (프로그램2-10, 2-11)


(예제 2-10)
import java.util.Scanner;

public class Twenties {

public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
System.out.println("나이를 입력하시오 : ");
int age = scanner.nextInt(); //정수 입력
if((age>=20) && (age<30)) { //age가 20~29 사이인지 검사
System.out.print("20대입니다. ");
System.out.println("20대라서 행복합니다!");
}

else
System.out.println("20대가 아닙니다.");
scanner.close();
}

}


(예제 2-11)


package exGrade1;


import java.util.Scanner;


public class Grading1 {


public static void main(String[] args) {

// TODO Auto-generated method stub


Scanner sc = new Scanner(System.in);

System.out.print("점수를 입력하세요(0~100) : ");

int score = sc.nextInt();

if(score>=90){

System.out.println("학점은 A입니다.");

}

else if(score>=80){

System.out.println("학점은 B입니다.");

}

else if(score>=70){

System.out.println("학점은 C입니다.");

}

else if(score>=60){

System.out.println("학점은 D입니다.");

}

else

System.out.println("학점은 F입니다.");

sc.close();

}


}




package exGrade1;


import java.util.Scanner;


public class Grading1 {


public static void main(String[] args) {

// TODO Auto-generated method stub


Scanner sc = new Scanner(System.in);

//스캐너 클래스 복제

System.out.print("점수를 입력하세요(0~100) : ");

//입력받기전 입력문

int score = sc.nextInt(); //정수형으로 입력받음

char grade;

if(score>=90)

grade = 'A';

else if(score>=80)

grade = 'B';

else if(score>=70)

grade = 'C';

else if(score>=60)

grade = 'D';

else

grade = 'F';

System.out.println("학점은" + grade);

sc.close();

}


}




전자는 내가 처음에 만든것 후자는 교수님 코드 뺏긴것 
별 차이는 없지만 더 간단하고 보기좋은것 같음.


5. 조건문(switch문) 예제


package exSwitch;


import java.util.Scanner;


public class Banking {


public static void main(String[] args) {

// TODO Auto-generated method stub

System.out.println("1. 입금하기 2. 출금하기 3. 송금하기");

System.out.print("원하는 메뉴를 선택하세요. ");//라인이 띄워지지 않는 print문

Scanner sc = new Scanner(System.in);

//스캐너 클래스 복제

int menu = sc.nextInt();

//정수형으로 값을 반환

switch(menu)/*switch의 식부분엔 반환형이 정수형이 들어와야함

식에는 정수, 문자열(JDK1.7이상부터가능)을 지정한다.*/

{

case 1: System.out.println("입금메뉴 선택");

break;/*스위치 구문에선 브레이크가 없으면 브레이크를 만날때까지 계속 실행하므로 

브레이크 문을 사용 해주어야 한다.*/

case 2: System.out.println("출금메뉴 선택");

break;

case 3: System.out.println("송금메뉴 선택");

break;//브레이크 구문

default: System.out.println("잘못된 메뉴를 선택하였습니다.");

//디폴트 구문

}

}


}



'basic > Java 8' 카테고리의 다른 글

[Java] Exception  (0) 2018.08.07
5. 상속  (0) 2017.05.12
4. 클래스와 객체  (0) 2017.04.11
3. 반복문과 배열 그리고 예외처리  (0) 2017.03.31
1. 자바시작  (0) 2017.03.07

1. 자바의 실행환경


   (1) 왜 플랫폼 독립적인가, WORA의 개념

기존의 언어들은 프로그램을 실행하고자 할때 코드를 수정하거나 해당 플랫폼에 맞는 기계어로 프로그램을 생성해야 하는 번거로움이 따른다.

그래서 자바라는 똑똑한 언어는 플랫폼에 독립적으로 설계 되었다.

WORA란 Write Once Run Anywhere 해석 해보면 일단 작성되면 어디서든지 구동이 가능하다 라고 해석이 된다. 그 말인 즉슨 운영체제나 CPU 등 플랫폼에 상관없이 Java Virtual Machine 환경이 구축된 어떤 컴퓨터에서든지 동일하게 실행이 된다.

   (2) JVM개념, 역활

JVM : Java Virtual Machine 의 줄임말로서 자바의 바이트 코드를 해당 컴퓨터의 명령어로 해석해주는 프로그램이다.

이 JVM이 있기 때문에 자바가 플랫폼에 상관없이 어느 컴퓨터에서든 동일하게 실행을 할수있는 역할을 한다.


2. 자바프로그램의 작성부터 실행 과정을 정리해봅시다. (command창에서 실습한 내용)



자바 프로그램을 작성하기 위해 가장 간단한 방법은 메모장(notepad)을 통하여 작성하는 방법이 있습니다.


다만 주의할 점은 파일명과 자바 파일내의 클래스명이 같아야 합니다.

당연히 자바는 설치가 되어있다는 가정하에 진행하겠습니다.


자바 프로그램을 작성한 뒤 사용자가 원하는 위치에 파일을 저장합니다.



저는 C드라이브 내의 Test라는 폴더에 hellojava.java라는 자바 파일을 저장시켰습니다.


다음 cmd 창을 켜 보겠습니다.



음 자바가 아주 잘 설치되어 있군요


제 자바 파일이 설치되어 있는 경로로 들어가 dir 명령어를 친 모습입니다.



javac 이라는 자바파일을 컴파일 하는 명령어를 사용을 하면 hellojava.java 파일을 컴파일한 hellojava.class 라는 class파일이 만들어지게 됩니다. 


자 그리고 컴파일한 파일을 실행시키기 위해 java 파일명을 타이핑 하면 놀랍게도 결과가 

helloJAVA라고 출력이 됩니다.


아래의 사진은 첫 시간에 했던 자료입니다.



'basic > Java 8' 카테고리의 다른 글

[Java] Exception  (0) 2018.08.07
5. 상속  (0) 2017.05.12
4. 클래스와 객체  (0) 2017.04.11
3. 반복문과 배열 그리고 예외처리  (0) 2017.03.31
2. 자바 기본 프로그래밍  (0) 2017.03.14

1. 구조체 사용과정 (3단계)

  1. main 함수 위에 구조체를 정의함.
  2. main 함수 내에 구조체 변수를 선언함.
  3. 구조체의 맴버를 참조.
2. 구조체 변수를 이용한 예(소스, 결과, 주석)

#include <stdio.h>
#include <stdlib.h>

//1. main 함수 위에 구조체 정의
struct person
{
char id[6];
char name[10];
char tel[14];
int grade;
};

int main(int argc, char *argv[]) {

//2. 사용자 정의 자료형 : 구조체 변수 선언
struct person members;
printf("학번 : ");
scanf("%s", members.id);
 
printf("이름 : ");
scanf("%s", members.name);
 
  printf("전화 : ");
scanf("%s", members.tel);
printf("등급 : ");
scanf("%d", &members.grade);
printf("이름 : %s, 번호 : %s, 등급 : %d", members.name, members.tel, members.grade);

system("pause");
return 0;
}




3. 구조체 배열을 이용한 예(소스, 결과, 주석)

#include <stdio.h>
#include <stdlib.h>

//1. main 함수 위에 구조체 정의
struct person
{
char id[6];
char name[10];
char tel[14];
int grade;
};

int main(int argc, char *argv[]) {

//2. 사용자 정의 자료형 : 구조체 배열 선언
struct person members[3];
int i;
for(i=0;i<3;i++)
{
printf("학번 : ");
scanf("%s", members[i].id);
 
printf("이름 : ");
scanf("%s", members[i].name);
 
  printf("전화 : ");
scanf("%s", members[i].tel);
printf("등급 : ");
scanf("%d", &members[i].grade);
}
for(i=0;i<3;i++)
{
printf("\n 이름 : %s, 번호 : %s, 등급 : %d \n", members[i].name, members[i].tel, members[i].grade);
}


system("pause");
return 0;
}





20161126main1.c

main_ver2.c

ForOreport.dev

ForOreport.exe

ForOreport.layout

Makefile.win

report.c

report.o

main_ver2.c


'basic > C' 카테고리의 다른 글

7. 포인터  (0) 2016.11.10
6. 함수  (0) 2016.10.31
5. 배열  (0) 2016.10.13
4. 제어문(조건문과 반복문)  (0) 2016.10.06
3. 연산자  (0) 2016.09.22

1. 포인터의 개념

데이터가 저장된 주기억장치의 주소만 저장 (갂단히 포인터(pointer)라고도 함)


2. 포인터와 배열의 관계 예(소스코드,실행결과)


#include <stdio.h>

#include <stdlib.h>

#define N 4


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


//void print_arr(int arr[]); //3. 함수의 원형 선언 

void print_arr(int *arr);


int main(int argc, char *argv[]) {

int count[N] = {42, 37, 83, 33}; // 배열이름 = 시작주소 

//1. 출력할 함수의 이름 정의

print_arr(count); 

return 0;

}


//2. 함수 구현

//void print_arr(int arr[]) //int arr[N]배열을 다시 선언하면서 받는다. 

void print_arr(int *arr) //배열의 주소가 넘어오므로 포인터로 받는다. 

{

int i;

for(i=0;i<N;i++) 

printf("%3d", *(arr+i));

//printf("%3d", arr[i]);



3. 포인터를 이용한 문자열 교환 예제


#include <stdio.h>

#include <stdlib.h>

#define SIZE 5


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {


char *first = "GilDong", *last = "Hong"; // 이름 , 성 

char *temp;   // 임시 저장 포인터 변수 

   

printf("Name : %s %s \n", first, last);

    

   

   // 포인터 변수에 저장된 두 주소를 교환해 두 포인터가 가리키는 문자열 교환하기

   

temp = first;

first = last;

last = temp;

   

printf("Name : %s %s \n ", first, last); 



   return 0;

}




4. char형 배열을 이용한 문자열 교환 예제


#include <stdio.h>

#include <stdlib.h>

#define SIZE 5


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {


 char first[10] = "GilDong", last[10] = "Hong"; // 이름과 성

   char temp[10]; // 문자열을 임시로 저장할 배열


   printf("Name : %s %s\n", first, last);


 // 배열의 내용을 직접 교환하여 두 문자열을 교환하기

   strcpy(temp, first); // first 배열의 문자열을 temp 배열에 복사하기

   strcpy(first, last); // last 배열의 문자열을 first 배열에 복사하기

   strcpy(last, temp); // temp 배열의 문자열을 last 배열에 복사하기

   

   printf("Name : %s %s \n", first, last);



   return 0;

}




5. char형 2차원 배열을 이용한 정렬 예제


#include <stdio.h>

#include <stdlib.h>

#define SIZE 5


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {


char silver[SIZE][10] = {"나태희","유빈","나원빈","문건영","소지법"};

char temp[10];

int i, pass; 

printf("**은메달 리스트 ");

for(i=0;i<SIZE;i++)

printf("%s, ", silver[i]);

printf("\b\b **\n\n");

for(pass=1;pass<SIZE;pass++)

for(i=0;i<SIZE-pass;i++)

if(strcmp(silver[i], silver[i+1]) > 0 )

{

strcpy(temp, silver[i]);

strcpy(silver[i], silver[i+1]);

strcpy(silver[i+1], temp);

}

printf("**정렬한 리스트 ");

for(i=0;i<SIZE;i++)

printf("%s, ", silver[i]);

printf("\b\b **\n\n");


   return 0;

}




6. char형 포인터배열을 이용한 예제


#include <stdio.h>

#include <stdlib.h>

#define SIZE 5


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {


   char *gold[5] = {"한빛","성춘향","이몽룡","사공민국","황해"};

   char *temp;

   int size, i, j;

   

   size = sizeof(gold) / sizeof (gold[0]);

   

   printf("** 금메달 리스트 : ");

   for(i=0;i<size;i++)

      printf("%s, ", gold[i]);

      printf("\b\b ** \n\n");

   

   for(i=0;i<size;i++)

      for(j=i+1;j<size;j++)

         if(strcmp(gold[i], gold[j]) > 0 )

         {

            temp = gold[i];

            gold[i] = gold[j];

            gold[j] = temp;

         }

   

   printf("** 정렬한 리스트 : ");

   for(i=0;i<size;i++)

      printf("%s, ", gold[i]);

      printf("\b\b ** \n\n");


   return 0;

}




'basic > C' 카테고리의 다른 글

8. 구조체  (0) 2016.11.21
6. 함수  (0) 2016.10.31
5. 배열  (0) 2016.10.13
4. 제어문(조건문과 반복문)  (0) 2016.10.06
3. 연산자  (0) 2016.09.22

1. 함수의 필요성 : : 하나의 큰 문제들을 작은 문제로 쪼개어 해결함에 용이하여 사용함.


2 c함수의 종류


(1) 라이브러리 함수


예제1 : 기본적인 rand()함수 소스코드, 실행결과


rand()함수 : 0~32767 범위 안의 임의의 정수를 결과 값으로 호출


문제점 : 컴파일 시켰을때 동일한 값이 출력됨


#include <stdio.h>

#include <stdlib.h>

#include <time.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {

int i,random;

for(i=1;i<=5;i++)

{

random = rand();

printf("%d번째 난수 %5d \n",i ,random);

}

return 0;

}




예제2 : 범위를 지정한 rand()함수 소스코드, 실행결과


#include <stdio.h>

#include <stdlib.h>

#include <time.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {

int i,random;

for(i=1;i<=5;i++)

{

random = rand()%6+1;

printf("%d번째 난수 %5d \n",i ,random);

}

return 0;

}




예제3 : 씨드값 설정한 rand()함수 소스코드, 실행결과


#include <stdio.h>

#include <stdlib.h>

#include <time.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {

int i,random;

srand(time(NULL));

for(i=1;i<=5;i++)

{

random = rand();

printf("%d번째 난수 %5d \n",i ,random);

}

return 0;

}




(2) 사용자 정의함수


정의하는 순서 예제


{1} main() 함수이름 정의


(2) main() 밖 아래 함수기능 정의


(3) main() 밖 위 함수의 원형 정의

아직 정리중인 내용...


(3) 인수 : main에서 넘어가는 값


(4) 매개변수 : 넘어오는 값을 받는 변수


*main()에서 함수호출시 인수를 전달하고 정의된 함수에서 매개변수를 선언하면서 받는다.


3. 함수의 인수전달 방법


(1) 값에 의한 호출 (call by value) 예제(소스코드,실행결과)

main안의 변수 그 안의 인수를 함수(매개변수공간)에 그대로 호출하여 입력. 

원본과 복사본이 서로 독립된 공간을 가짐 여기서 원본은 main공간 안의 인수를말하고 복사본은 사용자 지정 함수안에서의 매개변수 공간을 말함.


#include <stdio.h>

#include <stdlib.h>


void sort_by_point(int first, int second); // 함수 원형정의 


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {

int point1=5000, point2=4000;

printf("함수 호출전 포인트 점수 %d, %d\n", point1, point2);

sort_by_point(point1, point2); // 값에 의한 호출. 

printf("함수 호출후 포인트 점수 %d, %d\n", point1, point2);

return 0;

}


void sort_by_point(int first, int second) //함수정의 : 값에 의한 호출


{

int temp;

if(first>second)

{

temp=first;

first=second;

second=temp;

}

printf("\n sort함수 안에서 정렬한 결과 first : %d, second : %d\n\n", first, second);

}




(2) 주소에 의한 호출 (call by address) 예제(소스코드,실행결과)


#include <stdio.h>

#include <stdlib.h>


void sort_by_point(int *first, int *second); // 함수 원형정의 


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {

int point1=5000, point2=4000;

printf("함수 호출전 포인트 점수 %d, %d\n", point1, point2);

sort_by_point(&point1, &point2);   // 주소에 의한 호출. 

printf("함수 호출후 포인트 점수 %d, %d\n", point1, point2);

return 0;

}


void sort_by_point(int *first, int *second) //주소에 의한 호출 

{

int temp;

if(*first>*second)

{

temp=*first;

*first=*second;

*second=temp;

}

printf("\n sort함수 안에서 정렬한 결과 first : %d, second : %d\n\n", *first, *second);

}




4. 값에 의한 호출의 문제점과 주소에 의한 호출의 필요성 : 호출된 함수에서 자신을 호출한 함수의 인수 내용을 수정 할 수가 없는 문제점이 있고 호출된 함수에서 자신을 호출한 함수의 인수를 변경하고 싶다면 주소에 의한 호출을 이용해야 함.


5. 배열 원소 함수로 전달하는 방법->설명

(예제, 소스코드, 주석)


#include <stdio.h>

#include <stdlib.h>


//3. 함수의 원형을 작성 

int find_large(int first, int second);


int main(int argc, char *argv[]) {


// 배열의 원소를 함수로 전달하는 방법

int max, score[5] = {10,8,9,7,8};

//1. 호출할 위치에서 함수이름 정의

max = find_large(score[1], score[2]);

printf("%d, %d중 큰 수는 = %d\n", score[1], score[2], max);

return 0;

}


//2. 함수 작성

int find_large(int first, int second)

{

if (first>second)

return first;

else

return second;




6. 배열 전체를 함수로 전달하는 방법-> 설명

(예제, 소스코드, 주석)


#include <stdio.h>

#include <stdlib.h>

#define N 4


//3. 함수의 원형을 작성한다. 

void print_arr(int arr[N]);

void percentage(int arr[N]);


int main(int argc, char *argv[]) {

//예제2. 배열전체를 함수로 전달하는 방법

//함수 전달할때는 ~~~ 넘기고, 함수정의할떄는 ~~~ 받는다. 

int count[N] = {42, 37, 83, 33}; 

//1. 함수 이름을 정의한다. 

printf("인원수 : ");

print_arr(count); //배열 이름은 시작 주소를 의미하기 때문에 주소를 넘기면 배열 전체를 넘길수 있다.  

printf("\n");

printf("백분율 : ");

percentage(count); //함수는 배열의 백분율을 계산해서 출력 

print_arr(count);

return 0;

}


//2. 함수를 작성한다. 

void print_arr(int arr[N]) // int arr[]도 가능하다  

{

int i;

for(i=0;i<N;i++)

printf("%3d", arr[i]);

}


// 배열에 저장된 수치를 백분율로 변경하는 함수 

void percentage(int arr[N])// int arr[]도 가능 

{

int i, total = 0;

//전체 인원을 total에 구하기 

for(i=0;i<N;i++)

total += arr[i]; // 배열 전체를 읽으면서 total값 계산 

// 전체 인원수 total을 이용해 백분율 구하기 

for(i=0;i<N;i++)

arr[i] = (int)((double)arr[i]/total*100);

}



'basic > C' 카테고리의 다른 글

8. 구조체  (0) 2016.11.21
7. 포인터  (0) 2016.11.10
5. 배열  (0) 2016.10.13
4. 제어문(조건문과 반복문)  (0) 2016.10.06
3. 연산자  (0) 2016.09.22

1. 배열의  개념 : 자료형이 같은 여러개의 값을 연속된 기억장소에 같은 이름(배열명)으로 저장한것 주로 동일한 구조의 많은 자료등을 다룰때 사용한다.


변수는 하나의 자료를 저장하지만 배열은 여러개의 자료를 저장한다 즉 여러 변수의 모임이라고 볼수있다.


2. 배열 선언 및 주의사항 : 배열을 선언할때에 배열의 크기(배열 원소수)에는 정수형 상수만 가능하고 변수는 불가능하다.


3. 배열의 초기화 : 배열의 크기를 지정하고 초기값이 부족하다면 초깃값은 자동으로 0으로 지정된다. 배열 원소수를 명시 않으면 중괄호{} 안의 값 개수가 원소수로 결정된다.


4. 예제1 - 5명의 퀴즈점수를 배열에 저장한 후 평균 출력하기 프로그램


#include <stdio.h>

#include <stdlib.h>

#define SIZE 5


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {

/*

//배열선언 예

//1. 1000명의 나이를 저장하는 배열

int age[1000];

//2. 5명의 퀴즈점수를 저장하는 배열

int quiz[5];

//3. 100명의 평균을 저장하는 배열

double avg[100];

//4. 학생의 이름(홍길동)을 저장하는 배열

char name[10];  

*/


//배열 예제1. 5명의 퀴즈점수를 입력

int quiz[SIZE], i, count;

int sum=0;

double avg;


for(i=0;i<SIZE;i++)

{

printf("퀴즈점수 입력 : ");

scanf("%d", &quiz[i]);

sum+=quiz[i]; //sum=sum+quiz[i];

avg = (double)sum / SIZE;

//입력한 점수의 합을 출력

printf("입력한 %d명의 합 : %d\n", SIZE, sum);

printf("입력한 %d명의 평균 : %.1lf\n", SIZE, avg);

//평균미만인 수

for(i=0;i<SIZE;i++)

{

if(quiz[i] < avg)

count++;

}

//결과출력

printf("===========================\n");

printf(" 번호 점수 평균과의 차이 \n"); 

printf("===========================\n");

for(i=0;i<SIZE;i++)

printf(" %2d     %2d      %5.1lf\n", i+1, quiz[i], quiz[i]-avg);

printf("===========================\n");

printf(" 평균 : %.1lf 점 \n", avg);

printf("===========================\n");

printf(" 평균미만 : %d명 \n", count);

return 0;

}




5. 예제 2 - 배열의 원소에서 최소값, 최대값 구하기


#include <stdio.h>

#include <stdlib.h>

#define N 5

/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {

int i;

int min, max; //1. min 변수 지정 

int f[N]={3,0,-30,-20,-1};

for(i=0;i<N;i++)

{

printf("%d ", f[i]);

}

printf("\n");

//최소값 찾기

//2.첫번째 원소를 min변수에 저장

min = f[0];

for (i=1;i<N;i++)

{

if(f[i]<min) //3. 각 원소를 min변수와 비교 및 교체작업 

min = f[i];

//최소값 출력

printf("\n\n 최소값은 %d \n", min); 

//최대값 찾기

max = f[0];

for(i=1;i<N;i++)

{

if(f[i]>max)

max = f[i]; 

//최대값 출력

printf("\n\n 최대값은 %d \n", max); 

 

return 0;

}



7. 예제4 - 배열의 원소를 오름차순 정렬 소스코드, 실행결과

             (주석: 오름차순의 개념정리, 버블정렬, 개선된 버블정렬의 원리 및 차이점)


#include <stdio.h>

#include <stdlib.h>

#define SIZE 5


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {

int a[SIZE] = {5,4,3,2,1};

int repeat, i, temp;

FILE *fp;


printf("정렬 전 배열 : ");

for(i=0;i<SIZE;i++)

printf("%4d",a[i]);

printf("\n");

// 버블 정렬 시작 : 오름차순정렬 

for(repeat=1;repeat<SIZE;repeat++) // (배열 원소수-1)번 반복하기 

{

//배열의 이웃한 두 원소간의 정렬을 차례대로 반복하기 

for(i=0;i<SIZE-repeat;i++) //(i가 0부터 3까지 순서를 반복) 

{ //SIZE-repeat 개선된 이유 : 이미 정렬이 끝난 부분의 비교를 제거하여 실행속도가 빨라짐. 

if(a[i]>a[i+1])

{

temp=a[i];

a[i]=a[i+1];

a[i+1]=temp;//이웃하는 두원소 교환 

}

} //안쪽 for의 끝 

} // 바깥쪽 for의 끝 

  for(i=0;i<SIZE;i++)

printf("%4d", a[i]);

//배열원소 출력 

fp=fopen("asc.txt","w");

        for(i=0;i<SIZE;i++)

fprintf(fp, "오름차순 정렬 : %2d",a[i]);

fclose(fp);

return 0;

}





8. 예제5 - 배열의 원소를 내림차순 정렬 소스코드, 실행결과           

             (주석:  내림차순 개념정리)


#include <stdio.h>

#include <stdlib.h>

#define SIZE 5


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {

int a[SIZE] = {1,2,3,4,5};

int repeat, i, temp;


printf("정렬 전 배열 : ");

for(i=0;i<SIZE;i++)

printf("%4d",a[i]);

printf("\n");

// 버블 정렬 시작 : 내림차순정렬 

for(repeat=1;repeat<SIZE;repeat++) // (배열 원소수-1)번 반복하기 

{

//배열의 이웃한 두 원소간의 정렬을 차례대로 반복하기 

for(i=0;i<SIZE-repeat;i++) //(i가 0부터 3까지 순서를 반복) 

{ //SIZE-repeat 개선된 이유 : 이미 정렬이 끝난 부분의 비교를 제거하여 실행속도가 빨라짐. 

if(a[i]<a[i+1])

{

temp=a[i];

a[i]=a[i+1];

a[i+1]=temp;//이웃하는 두원소 교환 

}

} //안쪽 for의 끝 

} // 바깥쪽 for의 끝 

  for(i=0;i<SIZE;i++)

printf("%4d", a[i]);

//배열원소 출력 

return 0;

}




'basic > C' 카테고리의 다른 글

7. 포인터  (0) 2016.11.10
6. 함수  (0) 2016.10.31
4. 제어문(조건문과 반복문)  (0) 2016.10.06
3. 연산자  (0) 2016.09.22
2. C프로그래밍의 기초문법  (0) 2016.09.08

1. 조건문 - if문


1.1 형식1 예제(소스코드, 실행결과)


#include <stdio.h>

#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {

int score;

printf("점수입력 : ");

scanf("%d", &score);

//if문 형식1 예제

if(score>=80)

{

printf("점수는 %d, 결과는 ", score);

printf("합격"); 

}

return 0;

}



*텍스트 파일 생성


예제


#include <stdio.h>

#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {

int age;

FILE *fp; //1. FILE포인터 선언

 

printf("나이입력 : ");

scanf("%d", &age);

fp=fopen("age.txt", "w"); //2. 생성할 FILE open

fprintf(fp, "나이 : %d",age);//3. file에 내용 쓰기 : fprintf() 

fclose(fp);//4. file 닫기 : fclose() 


return 0;

}



1.2 형식2 예제(소스코드, 실행결과)


#include <stdio.h>

#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {

//if문 형식2

int score;

printf("점수 입력 : ");

scanf("%d", &score); 

if(score>=80)

{

printf("점수는 %d이고, ",score);

printf("합격입니다.\n");

}

else

{

printf("점수는 %d이고, ",score);

printf("불합격입니다.\n");

}

return 0;

}



1.3 형식3 예제(소스코드, 실행결과)

#include <stdio.h>

#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {


//if문 형식3

int score;

printf("점수입력 : ");

scanf("%d", &score);

if(score >= 90)

printf("A등급\n");

else if(score>=80) //주의 : else와 if사이에 공백이 있어야함. 

printf("B등급\n"); 

else if(score>=70)

printf("C등급\n");

else

printf("F등급\n"); 

return 0;

}



2. 조건문 - switch문 예제


#include <stdio.h>

#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {


int menu;


printf("1. 입금하기 \t 2. 출금하기 \t 3. 송금하기 \n");

printf("메뉴 번호선택 : ");

scanf("%d", &menu);

//주의 : case문 뒤에 반드시 break문을 붙인다. 

switch(menu) //정수형 값 또는 정수형 결과 

{

case 1: printf("입금하기 화면이동...\n"); break; 

case 2: printf("출금하기 화면이동...\n"); break;

case 3: printf("송금하기 화면이동...\n"); break;

default: printf("잘못된 입력입니다. \n");

}

return 0;

}




3. 반복문 - for문 예제

#include <stdio.h>

#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {


//for문

int i, sum=0;

printf("1. 1~10출력 \n\n");

for(i=1;i<=10;i++) 

printf("%d\n", i);

printf("\n");

printf("2. 10~1출력 \n\n");

for(i=10;i>=1;i--)

printf("%d\n", i); 

printf("\n");

printf("\n------------------\n");

printf("3. 1~10합출력");

for(i=1;i<=10;i++)

{

sum = sum+i; // sum+=i;

}

printf("합 = %d\n", sum);

printf("\n");

printf("4. 1~10중 3의 배수 출력\n\n");

for(i=0;i<=10;i+=3) // i+=3 은 i=i+3과 같음

printf("%d\n", i);

printf("\n------------------\n");

printf("\n");

printf("5. 무한반복 : 합이 1000이 넘는 i값 \n\n");

for(i=1;;i++) //조건식을 생략하면 무한반복됨

{

printf("%d\n",i);

sum+=i;

if(sum>1000) break;

}

printf("합은 %d \n",sum);


return 0;

}



#include <stdio.h>

#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {


int line, star;

for(line=1;line<=5;line++)

{

for(star=1;star<=line;star++)

printf("*");

printf("\n");

}

for(line=1;line<=5;line++)

{

for(star=5;star>=line;star--)

printf("*");

printf("\n");

}



int i,j;

printf("6. 2중 for문 : 구구단\n\n");

for (i=2;i<=9;i++)

{

for(j=1;j<=9;j++)

{

printf("%d * %d = %d\n",i,j,i*j);

}

printf("\n");

}

return 0;

}





4. 반복문 - while문 예제


#include <stdio.h>

#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {


printf("7. while문 : 1~10출력 \n\n");


//while문 형식

// 1. 초기식

// 2. while문(조건식)

// { 반복실행 문장 

// 3. 증감식 

// }

int i;

i=1; //초기식 

while(i<=10)//조건식 

{

printf("%d\n",i);

i++; //증감식 

}


return 0;

}




5. 반복문 - do~while문 예제


#include <stdio.h>

#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {


printf("8. do~while문 : 1~10출력 \n\n");

//형식

// 1.초기식

//do

// {

// //3.증감식 

// } while(조건식); //2. 조건식 : 세미콜론(;) 붙인다.

int i;

i=1; //1. 초기식

do{

printf("%d\n",i);

i++; //3. 증감식 

} while(i<=10); //2. 조건식 


return 0;

}



'basic > C' 카테고리의 다른 글

6. 함수  (0) 2016.10.31
5. 배열  (0) 2016.10.13
3. 연산자  (0) 2016.09.22
2. C프로그래밍의 기초문법  (0) 2016.09.08
1. C프로그래밍의 기초  (0) 2016.09.05

1. 대입연산자


(1) 종류 : 왼 = 오 (오른쪽에서 왼쪽으로 대입)


(2) 예제 


#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {

int a = 3, b = 5, temp=0; // 변수 선언  


printf("교환전 : a= %d, b= %d\n", a, b); 

temp=b; //b를 temp에 대입 

b=a; // a를 b에 대입 

a=temp; // temp를 a에 대입 

printf("교환후 : a= %d, b= %d\n",a ,b);

return 0;

}




2. 산술연산자


(1) 종류 : + 더하기     - 빼기     * 곱하기     / 나누기     % 나머지 구하기(정수만 가능) 


(2) 예제1(소스코드, 실행결과, 주석)


#include <stdio.h>

#include <stdlib.h>


int main(int argc, char *argv[]) {


int a, b;


printf("두개의 숫자를 입력하시오\n");


scanf("%d%d", &a, &b);


printf("%d + %d =%d\n", a, b, a + b);// 더하기 연산

printf("%d - %d =%d\n", a, b, a - b);// 빼기 연산


printf("%d * %d =%d\n", a, b, a*b);// 곱하기 연산


printf("%d / %d =%d\n", a, b, a / b);// 나누기 연산


printf("%d %% %d = %d\n\n", a, b, a%b);// 나머지 구하기



return 0;

}



(3) 예제2 : 형변환 연산 (소스코드, 실행결과, 주석)

#include <stdio.h>

#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {

char ch = 'A'; // A라는 문자의 아스키 코드값을 저장

 

int x = 10, y = 4, sum = 0; 

double pi = 3.14, avg;

sum = ch + 2; //자동형 넓힘 변환. char형(1byte) 에서 int형(4byte)으로 들어가면서 자동으로 모양이 넓혀짐. 

printf("sum = %d = %c \n", sum, sum);

sum = pi; // 자동형 좁힘 변환. double형(8byte) 에서 int형(4byte)으로 컴파일러가 자동으로 모양을 좁혀서 넣음. 

printf("sum = %d \n", sum);

printf("x/y = %d", x/y); // 정수/정수 = 정수 

// 강제형변환 : 실수/실수 = 실수 

printf("x/y = %lf", (double)x/(double)y); //강제적으로 자료형을 변환시킬수있음 

sum = (double)x/(double)y; // 강제형변환 후 자동 형좁힘 ( 실수형 -> 정수형 ) 

printf("잘못된 나눗셈 = %d\n", sum);

avg = (double)(x/y); // 2.5가 아닌 2.0으로 나온 이유 x,y가 이미 정수형으로 연산된 후의 값에 강제형변환을 해서 정확한 값이 안나옴. 

printf("avg = %lf\n", avg);


avg = (double)x/y;

printf("정확한 나눗셈 = %lf\n", avg); 

 

return 0;




3. 복합대입연산자


  (1) 종류 : +=, -+, *=, /=, %/, >>=, <<=, &=, |=, ^=


  (2) 예제 (소스코드, 실행결과, 주석)


#include <stdio.h>

#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {

// 복합대입연산자 

int x,y;

x = y = 5;

printf("x = %d, y = %d\n", x, y);

printf("x += y의 결과는 %d\n", x+=y); // x = x + y

printf("x -= y의 결과는 %d\n", x-=y); // x = x - y

printf("x *= y의 결과는 %d\n", x*=y); // x = x * y

printf("x /= y의 결과는 %d\n", x/=y); // x = x / y

printf("x %%= y의 결과는 %d\n", x%=y); // x = x % y

return 0;

}




4. 관계연산자

  

  (1) 종류 : >, <, >=, <=, ==, !=


  (2) 예제 (소스코드, 실행결과, 주석)

#include <stdio.h>

#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {

// 관계연산자 

int x,y;

printf("두정수 입력 : ");

scanf("%d%d", &x, &y);

printf("%d > %d 의 결과는 %d입니다.\n", x, y, x>y); // 결과가 참인 경우 리턴값이 1 

printf("%d == %d 의 결과는 %d입니다.\n", x, y, x==y); 

// 결과가 거짓인 경우 리턴값이0 


return 0;

}




5. 논리연산자

 

  (1) 종류 : &&, || !


  (2) 예제 (소스코드, 실행결과, 주석)

#include <stdio.h>

#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {


int x,y,z;

x = 5; y = 10; z;

z = (x+=2) || (y+=1);

printf("x=%d,y=%d\n", x, y); 

printf("z=%d\n", z); // z = (x+=2) || (y+=1) 에서 x = 7이 되고 y = 11이 됨 0이 아닌 수는 참이므로 or 연산에서 참이 하나라도 있으면 결과값이 1 


return 0;

}




6. 조건연산자

  (1) 종류 : ?:

  (2) 예제 (소스코드, 실행결과, 주석)


 /*조건연산자 (조건식? 참: 거짓) 


#include <stdio.h>

#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {


int n1,n2,max,min; 

 

printf("두정수 입력 : "); 


scanf("%d%d", &n1, &n2); 

 

(n1>n2) ? (max=n1 , min=n2) : (max=n2 , min=n1); 

 

printf("\n>> 큰 수 / 작은 수 = %d\n", max / min); 


printf(">> 큰 수 %% 작은 수 = %d\n", max % min); 


return 0;

}





7. 증감연산자

 

(1) 종류 : ++, --


(2) 예제 (소스코드, 실행결과, 주석)


//증감연산자 ++, --

// ++x (진위형, prefix) : x값 1증가후 연산수행

// --x 

// x++ (후위형, postfix) : x값 연산후 1증가 

// x-- 

//int x=5;

/*

int y=x++; // x는 y에 대입연산후 1증가 

printf("x=%d\n", x);

printf("y=%d\n", y);  

*/

/*

int y=++x; // x가 1증가후 y에 대입연산됨 

printf("x=%d\n", x);

printf("y=%d\n", y); 

*/

int a = 10, b = 20;

printf("a=%d\n", a++); // a에 10의 값이 대입연산후 1증가 

printf("a=%d\n", ++a); // 1의 값이 증가한후 a에 대입연산 

printf("a=%d\n", b--); // b에 20의 값이 대입연산후 1감소 

printf("a=%d\n", --b); // 1의 값이 감소한후 b에 대입연산 


return 0;

}




8. 비트연산자


(1) 종류 : &, |, ^, ~, <<, >>


(2) 예제 (소스코드, 실행결과, 주석)


#include <stdio.h>

#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {

int x;

printf("정수입력 : ");

scanf("%d", &x);

printf("%d>>3=%d\n", x, x>>3); // 비트를 3번 이동한뒤 나누는 연산 (피연산자 나누기 2^3이 결과값으로 나옴) 

printf("%d<<3=%d\n", x, x<<3); // 비트를 3번 이동한뒤 곱하는 연산 (피연산자 곱하기 2^3이 결과값으로 나옴)

return 0;

}




9. 연산자의 우선순위


연산자 분류에 따른 우선순위 : 단항 > 산술 > 이동 > 관계 > 비트 > 논리 > 조건 > 대입 > 콤마 순이다.


연산자의 우선순위가 기억이 나지않는다면 괄호를 사용하여 강제로 우선순위를 지정할수있다.




'basic > C' 카테고리의 다른 글

6. 함수  (0) 2016.10.31
5. 배열  (0) 2016.10.13
4. 제어문(조건문과 반복문)  (0) 2016.10.06
2. C프로그래밍의 기초문법  (0) 2016.09.08
1. C프로그래밍의 기초  (0) 2016.09.05

+ Recent posts