본문 바로가기
학습/IT

[IT] C언어 입문(4) Operators, 연산자 - scanf, 산술연산자, 관계연산자, 증감연산자, 대입연산자, 동등연산자 등

by 개성공장 2021. 8. 21.
반응형

□ 기본연산자

 

 * scanf

 - Analogous to printf, but used for input

 - scanf is passed a list arguments, control_string and other arguments

 - other arguments : addresses

 - ex) scanf("%d", &x);

 => &x : the address of x, The format %d is matched with &x

 

 - When reading numbers, it skips white space (blanks, newlines, and tabs) but when reading in a character white space is not skipped.

     c : Character

     d : Decimal integer

     f : Floating-point number (float)

     LF or lf : Floating-point number (double)

     s : String

 

 * Call by value

 - Arguments to functions are always passed by value

 - The variables passed as arguments to functions are not changed

 - The expression passed as an argument to a function is first evaluated, and its value is passed to the function

 - 변수에 들어있는 값으로 수식을 계산하여 값만 넘겨주는 것

 

참고 : Call by reference : 변수를 넘겨주어 계산

 

---

#include <stdio.h>

int main(void)
{
	char c1, c2;
	int i;
	float f;
	double d;

	printf("%s%s", "Input two characters .", "an int, a float, and a double :");
	scanf("%c%c%d%f%lf", &c1, &c2, &i, &f, &d);
	printf("The data use typed in: \n");
	printf("%c%c%d%f%e\n", c1, c2, i, f, d);

	return 0;
}

---

 

 - gcc -o hello hello.c

 : hello.c라는 코드파일로 hello라는 실행파일을 만들라는 의미

 

 * 예제1

 - Use the following code to print out a list of powers of 2 in decimal, hexadecimal, and octal

 

---

#include <stdio.h>

int main(void)
{
	int i, val = 1;

	for(i=1; i <35; i = i+1;) {
		printf("%15d%15u%15x%15o\n", val, val, val, val);
		val = val *2;
	}
}

---

%15d : 정수형으로 15칸 출력

d : decimal

u : unsigned integer

x : hexadecimal 

o : octal

 

 

 * 예제2

---

#include(math.h)
#include(stdio.h)
int main(void)
{
	double two_pi = 2.0 * M_PI   //in math.h
	double h = 0.1;
	double x;
	for(x=0.0; x < two_pi; x=x+h;) {
		printf("%5.1f: %.15e\n", x, sin(x)*sin(x)+cos(x)*cos(x));
	}
	return 0;
}

---

- gcc -lm -o hello hello.c

수학함수 포함시 '-lm'을 포함시켜서 실행해주어야 함

 

 

 

□ C언어의 다양한 연산자들

 

 * Arithmetic Operators(산술연산자)

 : +, -, *, /, %

 / : 나눗셈 후 몫만 취함

 % : 나눗셈 후 나머지만 취함

 - Binary operator(이항연산자)

 

 * Increment and Decrement Operators (증감연산자)

 - Unary operators(단항연산자)

 - ++a : Increment the stored value of a, The value of ++a is the value after incrementing

 - a++ : The value of a++ is the value before incrementing

 - '--' is similar to '++'

 - Examples

int a=1, b=2, c;
a++; b--;      /* a=2, b=1 */
c = ++a + b;   /* a=3, b=1, c=4 */
c = a++ + b;   /* a=4, b=1, c=4, ++a와 a++의 차이점에 유의 */

 - 일반적으로 정수형 변수에 주로 사용. 실수형 변수에도 증감연산자가 사용될 수 있으나 별로 쓰이지 않음

 

 * Relational Operator (관계연산자)

 - <, >, <=, >=

 - relational_expression ::= expr < expr | expr > expr | expr <= expr | expr >= expr

 - Two operands, the result is 0 or 1 (int)   (다른 언어에서는 참/거짓을 boolean type으로 표현하기도 함, java)

(0은 거짓, 0이 아닌 모든 값은 참. ex) 2, 3 등도 참)

 - Precedence of the relational operators is less than that of the arithmetic operators : 산술연산이 우선

 - ex) 2 < j < 6   => (2 < j) < 6   : 관계연산자가 연달아 나오는 경우 왼쪽부터 하나씩 처리. 결과는 1

 

* Equality Operators

 - ==, !=

 - equality_expression ::= expr == expr | expr != expr

 - Two operands, the result is 0 or 1 (int)

 - 동일하게 산술연산이 우선

 - 예시

int i =1, j=2, k=3;
i == j   => 0 (두 값이 같은지, ==)
i != j   => 1 (두 값이 다른지, !=)

 - 유의할 것은 '='는 대입연산자이고, 관계연산자 '=='과 혼동하지 말아야 함

 

※ C언어 입문 시리즈
1. Introduction - C언어의 역사와 기본 개념
2. Variables - 변수, 대입연산자, 구문규칙, 데이터타입 등
3. Data types, 데이터 타입(자료형)
4. Operators, 연산자 - scanf, 산술연산자, 관계연산자, 증감연산자, 대입연산자, 동등연산자 등
5. Operators, 연산자 - 논리연산자, 단축평가, 대입연산자, if문 및 while문 활용
6. Control flow, 제어흐름 - While문, For문, If문, do-while문 등 루프문
7. Function, 함수 - Goto문, getchar와 putchar, 함수 정의와 프로토타입 선언
8. Scope rules/recursion, 변수의 영역규칙과 재귀호출, 난수생성 예시
9. Array와 Pointers, 배열과 포인터
10. Pointer, 역참조, swap 함수 활용, 배열과 포인터 비교
11. File operation 파일연산, String, 다차원 배열 예시
12. structure, union, enumerated types - 구조체, 공용체, 열거체
13. 자료구조(data structure) 예시 - 연결리스트(linked list)
14. C 전처리기(C preprocessor), 함수 포인터(function pointer)
반응형

댓글