1.
using System;
using System.IO;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
namespace Helloworld1
{
class App
{
public App()
{
int n = 3;
//SayHello(n);
SayHelloRecursive(n);
}
//재귀적이지 않게 정의및 구현 하세요
//매개변수로 횟수를 전달받아 Hello World를 출력하는 메서드를 정의 하고 구현
//이름 : SayHello
//매개변수명 : n
void SayHello(int n)
{
for (int i = 0; i < n; i++)
{
Console.WriteLine("Hello World!");
}
}
//재귀 함수 (메서드)
//재귀 : 자신을 정의 할때 자신을 재참조 하는 방법
void SayHelloRecursive(int n)
{
//탈출구 만들기
Console.WriteLine("Hello World!");
if (n == 1) return; //탈출구
SayHelloRecursive(n - 1); //재귀호출 하면서 매개변수를 어떻게 절달?
}
}
}
이해 연습 (메모장)
void SayHelloRecursive(3) //3을 넣었을 때
{
console.writeLine("Hello World!"); //출력
if (n == 1) return; //3을 n에 넣어서 같다면 반환(종료) 그렇지 않으면 넘어감.
SayHelloRecursive(n-1); //그렇다면 3-1이 되면 2이므로 다음으로 넘어감.
}
void SayHelloRecursive(2) //2가 들어가고
{
console.writeLine("Hello World!") //출력
if(n == 1) return; //n에 2가 들어갔지만, 1과 같지 않으므로 넘어감.
SayHelloRecursive(n-1); // n에 2가 들어가고 2-1은 1이므로 다음으로 넘어감
}
void SayHelloRecursive(1) //1이 들어가고
{
console.writeLine("Hello World!") //출력
if(n == 1) return; //n에 1이 들어가고 1과 같으므로 return 반환해버림. 종료.
SayHelloRecursive(n-1);
}
...
-----------------------------------------------------------------------------------------------------------------------------------
이해를 한 건줄 알았는데 아니었다. 일단은 기본 헬로월드를 써가면서 연습 해봐야 겠음.
'c# > 수업 내용' 카테고리의 다른 글
자료구조 Stack 복습(push, pop, peek,count) (0) | 2021.09.23 |
---|---|
자료구조 스택(stack) - 추상자료형 (0) | 2021.09.17 |
자료구조 재귀 함수 정의 (0) | 2021.09.16 |
자료구조 순서도 정의 (0) | 2021.09.15 |
자료구조 Linked List 연결리스트(Node 연습 ) (0) | 2021.09.15 |