유튜브 나도코딩의 c언어 기초 내용입니다.
#include <stdio.h>
int main(void)
{
printf("HelloWorld\n");
printf("HelloWorld\n");
printf("HelloWorld\n");
printf("HelloWorld\n");
printf("HelloWorld\n");
printf("HelloWorld\n");
printf("HelloWorld\n");
printf("HelloWorld\n");
printf("HelloWorld\n");
printf("HelloWorld\n");
return 0;
}
HelloWorld를 10번 출력하고 싶으면 이렇게 printf("HelloWorld\n"); 를 10번 반복해서 출력할 수 있다.
하지만 10번이 아니라 엄청 많이 하고싶으면 ???? 힘들잖아...
그래서 반복문을 사용하면 된다.
반복문에는 for, while, do while이 있는데 for와 while 두개를 주로 많이 쓴다.
#include <stdio.h>
int main(void)
{
for (int i = 1; i <= 5; i++)
{
printf(" <for> HelloWorld\n");
}
i = 1;
while (i <= 5)
{
printf(" <while> HelloWorld\n");
i++;
}
do
{
printf(" <do while> HelloWorld\n");
i++;
} while(i <= 5);
return 0;
}
for문은 for(선언, 조건, 증감)
while문은 while(조건)
do while문은 do () while (조건)
for 문은 괄호 안에 선언을 해주기 때문에 for 문 전에 i를 미리 선언해 줄 필요가 없다.
하지만 while 문은 괄호 안에 조건만 들어가기 때문에 while문 전에 i를 선언해줘야 하고,
한번 반복마다 i의 증감을 실행할 문장 안에 적어줘야한다.
do while 문은 예시 코드와 같이 처음에 do를 적고 중괄호 안에 실행할 코드를 적은 후 마지막에 while (조건식)을 쓰면 된다.
#include <stdio.h>
int main(void)
{
// 이중반복문
for (int i = 1; i <= 3; i++)
{
printf("첫 번째 반복문 : %d \n", i);
for (int j = 1; j <= 5; j++)
{
printf(" 두번째 반복문 : %d \n", j);
}
}
return 0;
}
for 문 안에 for문을 또 사용함으로써 이중반복문을 만들 수도 있다.
i가 1일 때 j 1~5 / i가 2일 때 j 1~5 ,,,,,, 이런식으로 된다.
#include <stdio.h>
int main(void)
{
// 프로젝트
// SSSS*
// SSS***
// SS*****
// S*******
// *********
int floor;
printf("몇 층할래 ?");
scanf_s("%d", &floor);
for (int i = 0; i < floor; i++)
{
for (int j = i; j < floor - 1; j++)
{
printf(" ");
}
for (int k = 0; k < i * 2 + 1; k++)
{
printf("*");
}
printf("\n");
}
return 0;
}
피라미드 쌓기 프로젝트
이중 for문을 이용해서 프로젝트를 만들었다.
층수를 입력받는데 3층이라면
ss*
s***
***** (s는 공백)
이런 모양이 나와야하는데 3층은 * 5개, 2층은 s 1개 * 3개, 1층은 s 2개 * 1개 ( 층수를 역순으로,,, 제일 위가 1층)
잘 보면 3층은 *이 3 + ( 3-1)개, 2층은 2 + (2-1)개, 1층은 1 + (1-1)개이다.
그래서 for 문의 i는 층수가 되고, j와 k 는 공백과 *의 갯수가 되도록 하면 입력받은 층수만큼의 피라미드를 만들 수 있다.
'c언어 기초' 카테고리의 다른 글
c언어 포인터 pointer - 나도코딩 (0) | 2022.05.30 |
---|---|
c언어 배열 array - 나도코딩 (0) | 2022.05.30 |
c언어 함수 function - 나도코딩 (0) | 2022.05.29 |
c언어 조건문 if else break continue switch~case rand 랜덤- 나도코딩 (0) | 2022.05.29 |
c언어 변수,자료형, printf, scanf - 나도코딩 (0) | 2022.05.29 |