C
삼항연산자(조건연산자), 제어문(if, switch), 반복문(for)
김꼬알
2023. 3. 13. 17:46
삼항연산자
- 조건에 따라서 다른 명령을 수행하는 연산자
- 구조는 조건 ? 참 : 거짓
int a = 10 > 5 ? 10 : 5 // 10 > 5가 참이므로 10이 출력됨
printf("%d", a);
void main(void){
int a, b;
a = 20;
b = ( a > 10 ) ? a+a : a*a; // b = a > 10 이므로 20+20
printf("b=%d\n", b);
}
if 문
- 조건에 따라서 다른 명령어들을 수행
switch 문
- 주어진 값에 맞는 명령어들을 수행
#include<stdio.h>
int main(){
int a=0, b=1;
switch(a){
case 0 : printf("%d\n", b++); break; // a = 0이므로 case 0을 수행, b = 1 출력됨
case 1 : printf("%d\n", ++b); break; // break를 만날 때까지 연산을 수행함
default : printf("%d\n", b); break;
}
return 0;
}
반복문 종류
for
- 정해진 횟수만큼 반복
while
- 조건이 만족하는 동안 반복
do ~ while
- 무조건 한번 수행 후 조건이 만족하는 동안 반복
for 문 구조
for( 초기식; 조건식; 증감식 )
{
수행하는 작업들
}
#include<stdio.h>
int main(){
int j;
int sum = 0;
for(j = 2; j <= 70; j += 5)
sum = sum + 1;
printf("%d", sum);
}