전공 과목 이수2👨‍💻/닷넷 c#

💯1~3장💯

천숭이 2020. 10. 15. 22:30

'대표적인 아스키코드'
0 - 48
A - 65
a - 97

// 두개의 콘솔데이터 중에서 '7'을 읽어옴. int 형으로 변환하기 위해서는 '0'을빼주어야 한다
// 모든 숫자는 0부터 시작하므로 (48 = '0')

number = int.Parse(Console.ReadLine());
// 한라인을 통째로 int형으로 변환할수있는 메소드

double.parse 는 변환할 값이 null이면 null메세지가 나와서 에러가 생기는데
Convert.ToDouble 을 사용하게 되면 null일때 0으로 처리해 준다

★실습
- (예제 3-10) 사칙연산계산기

using System; class CalculatorApp { public static void Main() { int x, y, r = 0; char opr; Console.Write("Enter an operator & two numbers = "); opr = (char)Console.Read(); x = Console.Read() - '0'; y = Console.Read() - '0'; switch (opr){ case '+': r = x + y; Console.WriteLine(x+y); break; case '-': r = x + y; Console.WriteLine(x-y); break; case '*': r = x + y; Console.WriteLine(x*y); break; case '/': r = x + y; Console.WriteLine(x/y); break; default: Console.WriteLine("Illegal operator"); break; } } }

출력:
Enter an operator & two numbers = +28
10

출력:
Enter an operator & two numbers = /42
2

★실습
- (예제1-4) 프로퍼티 값지정 셋접근자, 값참조 겟접근자

using System; namespace PropertyApp { class PropertyClass { private int privateValue; public int PrivateValue { get { return privateValue; } // get-accessor set { privateValue = value; } // set-accessor } public void PrintValue() { Console.WriteLine("Hideen Value =" + privateValue); } } class PropertyApp { public static void Main() { int n; PropertyClass obj = new PropertyClass(); obj.PrivateValue = 100; // invoke set-accessor obj.PrintValue(); n = obj.PrivateValue; // invoke get-accessor Console.WriteLine(" Value =" + n); } } }

출력:
Hideen Value =100
Value =100

★실습
- (예제 1-5) 연산자중복(operatoroverloadingapp.cs)

using System; class Even { int evenNumber; public Even(int n) { evenNumber = (n % 2 == 0) ? n : n + 1; } public static Even operator++(Even e) { e.evenNumber += 2; return e; } public static Even operator--(Even e) { e.evenNumber -= 2; return e; } public void PrintEven() { Console.WriteLine("Even Number =" + evenNumber); } } class OperatorOverloadingApp{ public static void Main() { Even e = new Even(4); e.PrintEven(); ++e; e.PrintEven(); // e++라고 작성할 수 있음 --e; e.PrintEven(); } }

출력:
Even Number =4
Even Number =6
Even Number =4

★실습
- (예제 1-6) 델리게이트

using System; delegate void SampleDelegate(); // 델리게이트 정의 class DelegateClass { public void DelegateMethod() // 델리게이트할 메소드 { Console.WriteLine("In the DelegateClass.DelegateMethod ..."); } } class DelegateApp { public static void Main() { DelegateClass obj = new DelegateClass(); SampleDelegate sd = new SampleDelegate(obj.DelegateMethod); sd(); // invoke obj.DelegateMethod() indirectly. // 객체 obj로 해당클래스(DelegateClass) 간접적으로 } } 


출력 :
In the DelegateClass.DelegateMethod ...

- (예제 1-7)
델리게이트를 이용해 이벤트 처리

using System; // 1. delegate void MyeventHandler(); // system.EventHandler를 사용한다면 이 과정 생략 가능 class EventApp{ public EventHandler MyEvent; // 2. 이벤트 선언 void MyEventHandler(object sender, EventArgs e){ // 3. 이벤트 처리기 작성 Console.WriteLine("Hello World"); } public EventApp(){ // 생성자 this.MyEvent += new EventHandler(MyEventHandler); // 4. 이벤트 처리기 등록 } public void InvokeEvent(){ if (MyEvent != null) MyEvent(this, null); // 5. 이벤트 발생 } public static void Main() { new EventApp().InvokeEvent(); } } 

출력:
Hello World

- (예제 1-8) 제네릭,자료형을 매개변수로 가질 수 있음

using System; class Stack<StackType> { private StackType[] stack = new StackType[100]; // 이때 힙에 메모리 할당 private int sp = -1; public void Push(StackType element) { stack[++sp] = element; } public StackType pop() { return stack[sp--]; } } class GenericClassApp { public static void Main() { Stack<int> stk1 = new Stack<int>(); // 정수형 스택 stk1.Push(1); stk1.Push(2); stk1.Push(3); Console.WriteLine("integer stack :" + stk1.pop() + "" + stk1.pop() + "" + stk1.pop() + "" + stk1.pop()); } }

출력:

- (예제 1-8) p.32

★실습
- 예제 1-9 스레드

using System; using System.Threading; // 반드시 포함!!! class ThreadApp { static void ThreadBody() // 스레드 몸체 { Console.WriteLine("In the Thread body..."); } public static void Main() { ThreadStart ts = new ThreadStart(ThreadBody); // 델리게이트 객체 생성 Thread t = new Thread(ts); // 스레드 객체 생성 Console.WriteLine("*** Start of Main"); t.Start(); // 스레드 바디 실행 -> 스레드 실행시작 Console.WriteLine("***End of Main"); } } /* t.Start(); // 스레드 바디 실행 -> 스레드 실행시작 for (int i = 0; i < 100; i++) { if (i % 10 == 0) { Console.WriteLine("반복문"); } } Console.WriteLine("***End of Main"); */

출력:
*** Start of Main
***End of Main
In the Thread body...

출력:
*** Start of Main
In the Thread body...
반복문내부
반복문내부
반복문내부
반복문내부
반복문내부
반복문내부
반복문내부
반복문내부
반복문내부
반복문내부
***End of Main

p.43 연습문제 1.5.(1)

using System; delegate void Delegate (); class ExerciseCh1_5_1 { public static void Method1() { Console.WriteLine("In the Method 1..."); } public static void Method2() { Console.WriteLine("In the Method 2..."); } public static void Main() { Delegate d = new Delegate(Method1); d += new Delegate(Method2); d(); } }

출력:
In the Method 1...
In the Method 2...


★실습
- (예제 2-9) enum 열거형

using System; enum Color {Red, Green, Blue}; class EnumTypeApp { public static void Main() { Color c = Color.Red; c++; int i = (int)c; Console.WriteLine("Cardinality of" + c + "=" + i); } }

출력:
Cardinality ofGreen=1

- (예제2-10) 배열 선언, 객체 생성 , 값 저장 3단계

using System; class ArrayTypeApp { public static void Main() { int[] ia = new int[3]; // 배열선언 , 배열 객체 생성 int[] ib = { 1, 2, 3 }; int i; for (i= 0; i < ia.Length; i++) //배열에 값저장 ia[i] = ib[i]; for (i = 0; i < ia.Length; i++) Console.Write(ia[i] + " "); Console.WriteLine(); } }

출력:
1 2 3

- (예제 2-11) 이차원배열, array of array

using System; class ArrayOfArrayApp { public static void Main() { int[][] arrayOfArray = new int[3][]; // 객체 선언 int i, j; for (i = 0; i < arrayOfArray.Length; i++) arrayOfArray[i] = new int[i + 3]; for (i = 0; i < arrayOfArray.Length; i++) for (j = 0; j < arrayOfArray[i].Length; j++) arrayOfArray[i][j] = i * arrayOfArray[i].Length + j; for (i = 0; i < arrayOfArray.Length; i++) { for (j = 0; j < arrayOfArray[i].Length; j++) Console.Write(" " + arrayOfArray[i][j]); Console.WriteLine(); } } }

출력:
0 1 2
4 5 6 7
10 11 12 13 14

p.68 스트링형, 클래스이름 출력, 파일이름출력
- (예제 2-12)

using System; using System.Text; class StringApp { public static void Main() { StringApp obj = new StringApp(); string str = "class name is "; Console.WriteLine(str + obj.ToString()); StringBuilder sb = new StringBuilder(); sb.Append(str); sb.Append(obj.ToString()); Console.WriteLine(sb); } }

출력:
class name is StringApp
class name is StringApp

- (예제 2-17) 산술연산자, 다항연산자, 연산자 여러개

using System; class LogicalOperatorApp { public static void Main() { int x = 3, y = 5, z = 7; bool b; b = x < y && y < z; Console.WriteLine("Result = " + b); b = x == y | x < y && y > z; Console.WriteLine("Result = " + b); } }

출력:
Result = True
Result = False

★실습★ 중요!!
- (예제 2-21) 정수형 - '0' = 문자열
정수형 - '0' = 문자형

using System; class ConditionalOperatorApp { public static void Main() { int a, b, c; int m; Console.Write("Enter three numbers : "); a = Console.Read() - '0'; b = Console.Read() - '0'; c = Console.Read() - '0'; m = (a > b) ? a : b; m = (m > c) ? m : c; Console.WriteLine("The largest number = " + m); } }

출력:
Enter three numbers : 526
The largest number = 6

정수형을 출력하려면 문자열에서 정수형으로 변환. Convert.Toint()
또 다른 방법

using System; namespace Example { class Conversion { static void Main(string[] args) { char Character = '9'; Console.WriteLine("The character is: " + Character); int integer = Character - '0'; Console.WriteLine("The integer is: {0}", integer); } } }


- (예제 2-23) 복합배정 연산자
간격 조정 출력

using System; class CompoundAssingnmentApp { public static void Main() { int x, y = 2; x = 10; x += y; Console.Write("1. x = " + x + ","); x = 10; x -= y; Console.Write("\t2. x = " + x + ","); x = 10; x *= y; Console.Write("\t3. x = " + x + ","); x = 10; x /= y; Console.Write("\t4. x = " + x + ","); x = 10; x %= y; Console.WriteLine("\t5. x = " + x ); x = 10; x &= y; Console.Write("6. x = " + x + ","); x = 10; x = y; Console.Write("\t7. x = " + x + ","); x = 10; x ^= y; Console.Write("\t8. x = " + x + ","); x = 10; x <<= y; Console.Write("\t9. x = " + x + ","); x = 10; x >>= y; Console.Write("\t10. x = " + x + ","); } }

출력:
1. x = 12, 2. x = 8, 3. x = 20, 4. x = 5, 5. x = 0
6. x = 2, 7. x = 2, 8. x = 8, 9. x = 40, 10. x = 2

- (예제 2-24 , p. 84) 캐스트 연산자

using System; class CastOperatorApp { public static void Main() { int i = 0Xffff; short s; s = (short)i; Console.WriteLine("i + " + i); Console.WriteLine("s = " + s); } }

출력 :
i + 65535
s = -1

- (예제 2-25) 형 검사 연산자 (is , as)

using System; public class IsAsOperatorApp { static void IsOperator(object obj) { Console.WriteLine(obj + " is int:"+(obj is int)); Console.WriteLine(obj + " is string: " + (obj is string)); } static void AsOperator(object obj) { Console.WriteLine(obj + " as string == null: " + (obj as string == null)); } public static void Main() { IsOperator(10); IsOperator("ABC"); AsOperator(10); AsOperator("ABC"); } }

출력:
10 is int: True
10 is string: False
ABC is int:False
ABC is string: True
10 as string == null: True
ABC as string == null: False

- (예제 2-26) 지정어 연사자
foreach : 크기 지정하지않고 내부 인덱스를 순회하면 반환하는 형식

using System; public class IsAsOperatorApp { static void IsOperator(object obj) { Console.WriteLine(obj + " is int:"+(obj is int)); Console.WriteLine(obj + " is string: " + (obj is string)); } static void AsOperator(object obj) { Console.WriteLine(obj + " as string == null: " + (obj as string == null)); } public static void Main() { IsOperator(10); IsOperator("ABC"); AsOperator(10); AsOperator("ABC"); } }

출력:
all AppleMembers :
Void Ripen()
//System.Type GetType()
System.String ToString()
Boolean Equals(System.Object)
Int32 GetHashCode()
Void .ctor()
Int32 nSeeds


-2장 연습문제 2.9 (4)

출력:

설명:
함수 WriteLocations 은 매개변수 byte형인 배열 ba를 받아서 실행시키는 함수이며 C#
에서 포인터를 활용하기 위하여 unsafe구문을 사용하여야한다. fixed라는 구문을 써서 변
수를 고정을 한다. byte *pElem = pAray;라고 선언하여 포인터 pAElm가 배열 pAray
를 가리키도록 한다. for문을 이용하여 byte value에 배열의 첫번째 원소를 넣고 그 원소
의 인덱스와 주소값과 원소값을 출력한다. 여기서 주소값인 pElem를 uint(unsigned int)
형으로 형변환을 하여 출력한다. 그리고 pElem+을 하여 두번째 원소로 넘어가여 또 출
력하고 이것을 5번 반복한다. byte형으로 선언한 ba을 1,2,3,4,5 로 초기화를 하고 WriteLocations함수에 넣는다.

- 2장 연습문제 2.10 (2)
cardinality : 대응수

using System; enum Color {Red, Green, Blue, Max=Blue}; class ExerciseCh2_10_2 { public static void Main() { Color c = Color.Red; int i = (int)++c; Console.WriteLine(" Color = " + (Color)i); c = Color.Blue; Console.WriteLine("Cardinality of" + c + " = " + (int)c); c = Color.Max; Console.WriteLine("Cardinality of" + c + " = " + (int)c); } }

출력:
Color = Green
Cardinality ofBlue = 2
Cardinality ofBlue = 2

설명:
enum(열거형)을 이용하여 Color인스턴스를 참조하는 참조변수 Red, Gren, Blue, Max 를 선언하다. c에 Red를 넣어주고 c값을 하나 증가시킨 값을 i에 저장한다. 원래 c값인 0(Red의 순서값)에서 하나 증가한 1이 i에 저장된다. 따라서 i값을 Color형으로 출력하면 Gren이 출력된다. 다시 c에 Color.Blue값을 넣어주고 int형으로 c를 출력하면 2가 출력 된다. 다시 c에 Color.Max값을 넣어주면 Max에 Blue를 넣어줬기 때문에 int형으로 c를 출력하면 똑같이 2가 출력된다.

-2장 연습문제 2.10 (4)

using System; class ExerciseCh2_10_4 { public static void Main() { short i = 0; Console.WriteLine("i = " + (i + 1) * (i = 1)); } }

출력:
i=1

- 2장연습문제 2.10 (5)

using System; class ExerciseCh2_11 { int @int, i; int[] vector = new int[100]; int[,] matrix = new int[10, 10]; static int get = 2; static int add { get { return get + 2258; } } static void set(int v) { get = v; } public static void Main() { object o = get; int i = (short)0; Console.WriteLine("ExerciseCh2_11.get={0}", ExerciseCh2_11.get); Console.WriteLine("ExerciseCh2_11.add={0}", ExerciseCh2_11.add); ExerciseCh2_11.set(3342+1); Console.WriteLine("ExerciseCh2_11.get={0}", ExerciseCh2_11.get); } }

출력:

설명:

1. @i와 i는 같은 명칭으로 같이 선언할 수 없고 지정어에 @기호를 붙이면 명칭으로 사용 할 수 있기 때문에 @i를 지정어 int에 @기호를 붙여 @int로 바꾸어 명칭으로 사용한다.  
2. C#에서 배열을 선언할때 1차원 배열은 int[] vector; 라고 선언하여야 하고 new연산자 를 통해서 vector = new int[10]; 라고 적어 동적으로 생성하여야 한다.  
3. 2차원 배열을 선언할때는 int[,] matrix = new int [10,10]; 라고 선언하여야한다. 콤마로 구분하여 원소개수를 적어주어야 한다.
4. object o = get; 이러는 문장에서 박싱을 하고 int i에 언박싱을 하려고 하는데 박싱 될때 자료형인 정수형으로 언박싱이 이루어져야하므로 short를 int로 바꾸어야한다.  
5. 증가 연산자는 변수가 아닌 식에는 사용될 수 없으므로 1를 증가하고 싶다면 342+1 으로 수정하여 1를 증가시키거나 변수에 342를 담고 그 변수를 증가연산자를 이용하여 증가시킨다.  
변수와 배열을 선언하고 static으로 get을 int형으로 초기화하고 2값을 넣어준다. get에 값 을 return해주는 static int add를 선언한다. v값을 받아 get에 저장하는 함수 set을 선언 한다. object o 를 선언하여 힙에 box를 생성하고 거기에 get의 데이터를 복사한다. 그리 고 i를 선언하여 박싱된 o를 다시 int값으로 형변환 하여 언박싱한다. 먼저 get를 출력하 면 static으로 선언한 2의 값이 출력되고 add를 출력하면 2에 258가 더해진 값이 반환되 어 출력되고 set함수에 343를 넣으면 get에 343이 할당되기때문에 get을 출력하면 343값이 나온다.

p. 105 연습문제 2.12
(1) 삼각형의 세 변의 길이를 읽고 다음 공식에 의해 삼각형의 넓이를 구하는 프로그램

using System; class ExerciseCh2_12_1 { static void Main(string[] args) { Console.WriteLine("삼각형의 세 변의 길이를 입력하시오."); string inputString = Console.ReadLine(); string[] inputArr = inputString.Split(' '); double[] inputInts = new double[inputArr.Length]; double a, b, c, s; for(int index = 0; index < inputInts.Length; index++) { inputInts[index] = double.Parse(inputArr[index]); } a = inputInts[0]; b = inputInts[1]; c = inputInts[2]; double l = (a + b + c) * 0.5; s = Math.Sqrt(l * (l - a) * (l - b) * (l - c)); Console.WriteLine("삼각형의 넓이는 " + s + "입니다."); } }

출력:
삼각형의 세 변의 길이를 입력하시오.
3 7 9
삼각형의 넓이는 8.78564169540279입니다.

설명:

삼각형의 세 변의 길이를 입력받는다. 입력 받은 string 값을 ‘ ’ 단위로 구분해주는 Split 함수를 써서 inputAr[] 배열에 하나씩 넣는다. inputAr길이만큼 새로운 배열 inputInts 을 선언하다. inputInts에 Parse함수를 이용하여 inputAr값을 double값으로 바꾸어 넣 어준다. 이 값을 각각 a, b, c 에 넣어준다. l를 구하는 공식 s=~~을 이용하여 l 값을 저장하고 s를 구하는 공식 l=~~ 를 이용하기 위하여 루트값 을 구할 수 있는 Math.Sqrt 함수를 이용하여 넓이 s 값을 구하여 출력한다.


2.12 (2)
2번 절댓값 문제

using System; class ExerciseCh2_12_2 { static void Main(string[] args) { string inputString = Console.ReadLine(); string[] inputArr = inputString.Split(' '); double x, y, z; double[] input = new double[inputArr.Length]; for(int index = 0; index < input.Length; index++) { input[index] = double.Parse(inputArr[index]); } x = input[0]; y = input[1]; z = Math.Abs(Math.Pow(x, 2) - Math.Pow(y, 2)); Console.WriteLine(z); } }

출력:
-1 3
8

Console.ReadLine()을 이용하여 string을 입력받고 그 string을 ‘ ’단위로 잘라서 배열 inputAr에 넣는다. 이것을 double형으로 변환하고 x에 input[0]값을 넣고 y에 input[1] 값을 넣는다. Math.Pow함수를 이용하여 x의 제곱과 y의 제곱을 구하고 이 둘의 차의 절 댓값을 구하기 위하여 Math.Abs라는 함수를 이용하여 z값을 구하여 결과를 출력한다.

2.12 (2) 3번 루트

using System; class ExerciseCh2_12_2_3 { static void Main(string[] args) { string inputString = Console.ReadLine(); string[] inputArr = inputString.Split(' '); double x, y, z; double[] input = new double[inputArr.Length]; for (int index = 0; index < input.Length; index++) { input[index] = double.Parse(inputArr[index]); } x = input[0]; y = input[1]; z = Math.Sqrt((Math.Pow(x, 2) + Math.Pow(y, 2))); Console.WriteLine(z); } }

출력:
3 5
5.830951894845301

설명:

Console.ReadLine()을 이용하여 string을 입력받고 그 string을 ‘ ’단위로 잘라서 배열 inputAr에 넣는다. 이것을 double형으로 변환하고 x에 input[0]값을 넣고 y에 input[1] 값을 넣는다. Math.Pow함수를 이용하여 x의 제곱과 y의 제곱을 구하고 이 둘의 합의 루 트값을 구하기 위하여 Math.Sqrt라는 함수를 이용하여 z값을 구하여 결과를 출력한다.

2.12 (3) 원금과 이율, 기간을 입력받아 복리법에 의해 원리합계 구하는 프로그램

using System; class ExercisCh2_12_3 { static void Main(string[] arges) { Console.WriteLine("원금과 이율, 기간을 입력하시오."); string inputString = Console.ReadLine(); string[] inputArr = inputString.Split(" "); double[] inputInts = new double[inputArr.Length]; for(int index = 0; index < inputInts.Length; index++) { inputInts[index] = double.Parse(inputArr[index]); } double S = inputInts[0] * Math.Pow((1 + inputInts[1]), inputInts[2]); Console.Write("원리합계는 {0} 입니다.",S); } }

출력:
원금과 이율, 기간을 입력하시오.
500000 0.2 10
원리합계는 3095868.211199999 입니다.

설명:
원금과 이율, 기간을 입력받는다. 입력 받은 string 값을 ‘ ’ 단위로 구분해주는 Split 함
수를 써서 inputAr[] 배열에 하나씩 넣는다. inputAr길이만큼 새로운 배열 inputInts을
선언하다. inputInts에 Parse함수를 이용하여 inputAr값을 double값으로 바꾸어 넣어
준다. 복리법에 의해 원리합계를 구하는 공식 s=원금(1+이율)^기간 를 이용하여 원리
합계를 출력한다.

2.12 (4) 섭씨 온도값을 읽어서 화씨 온도값을 구하는 프로그램

using System; namespace ExerciseCh2_12_4 { class ExerciseCh2_12_4 { static void Main(string [] args) { Console.WriteLine("섭씨 온도값을 입력하세요."); string inputString = Console.ReadLine(); double Celsius = double.Parse(inputString); double Fahrenheit =Celsius*1.8 + 32; Console.WriteLine("화씨 온도값은 {0} 입니다.", Fahrenheit); } } }

출력:
섭씨 온도값을 입력하세요.
18
화씨 온도값은 64.4 입니다.

설명:

섭씨 온도값을 입력받는다. 입력 받은 string 값을 Parse함수를 이용하여 Celsius에 double값으로 바꾸어 넣어준다. 섭씨 온도값을 이용해 화씨 온도값을 구하는 공식 을 이용하여 화씨 온도값을 출력한다.


2.12 (6)
세개의 저항값을 읽어 직렬로 연결된 회로의 저항과 병렬로 연결된 회로의 저항을 구하는 c#프로그램을 작성하시오.

using System; class ForStApp { public static void Main() { int i, n; double h = 0.0; Console.Write("Enter a number = "); n = Console.Read() - '0'; for (i = 1; i <= n; ++i) h += 1 / (double)i; Console.WriteLine("n={0},h={1}", n, h); } }

출력:
3 4 5
직렬연결 : 12
병렬연결 : 1.2765957446808514

출력:
30 40 50
직렬연결 : 120
병렬연결 : 12.76595744680851

2.12 (7)

using System; namespace ExerciseCh2_17_7_1 { class ExerciseCh2_17_7_1 { static void Main(string[] args) { Console.WriteLine("반지름을 입력하시오 "); string inputString = Console.ReadLine(); int r = int.Parse(inputString); double V = (4 / 3) * Math.PI * Math.Pow(r, 3); double S = 4 * Math.PI * r * r; Console.WriteLine("V = {0} S = {1}", V, S); } } }

출력:
반지름을 입력하시오
5
V = 392.6990816987241 S = 314.1592653589793

Console.ReadLine()을 이용하여 저항값 3개를 입력한 string을 입력받고 그 string을 ‘ ’ 단위로 잘라서 배열 inputAr에 넣는다. 이것을 double형으로 변환하고 표면적을 구하는 식을 이용하여 표면적값을 출력하여 결과를 얻는다.

 


3장 문장
P.112

- (예제 3-2) 혼합문

using System; class AssignmentStApp { public static void Main() { short s; int i; float f; double d; s = 526; d = f = i = s; Console.WriteLine("s = " + s + " i = " + i); Console.WriteLine("f = " + f + " d = " + d); } }

출력:
s = 526 i = 526
f = 526 d = 526

★실습
예제3-2 혼합문

using System; class CompoundStApp { public static void Main() { int n; Console.Write("Enter one digit = "); n = Console.Read() - '0'; if (n < 0) Console.WriteLine("Negative number !"); else { Console.WriteLine(n + " wquared is " + (n * n)); Console.WriteLine(n + " cubed is " + (n * n * n)); } } }

출력:
Enter one digit = 5
5 wquared is 25
5 cubed is 125

★실습
(예제3-5) 짝수판별 프로그램

using System; class CompoundStApp { public static void Main() { int n; Console.Write("Enter a number = "); n = Console.Read() - '0'; if (n % 2 == 0) Console.WriteLine(n + " is an even number."); if (n % 2 != 0) //else가능 Console.WriteLine(n + "is an odd number."); } }

출력:
Enter a number = 8
8 is an even number.

★실습
(예제3-7)

using System; class NestedIfApp { public static void Main() { int day; Console.Write("Enter the day number 1~7: "); day = (int)Console.Read() - '0'; if (day == 1) Console.WriteLine("Sunday"); else if (day == 2) Console.WriteLine("Monday"); else if (day == 3) Console.WriteLine("Tuesday"); else if (day == 4) Console.WriteLine("Wednesday"); else if (day == 5) Console.WriteLine("Thursday"); else if (day == 6) Console.WriteLine("Friday"); else if (day == 7) Console.WriteLine("Saturday"); else Console.WriteLine("Illegal day"); } }

출력:
Enter the day number 1~7: 4
Wednesday

★실습
- (예제 3-8) swtich, case 숫자입력 요일출력

using System; class SwitchApp { public static void Main() { Console.WriteLine("Enter the day number 1~7 : "); string day = Console.ReadLine(); switch (day[0]) { case '1': Console.WriteLine("Sunday"); break; case '2': Console.WriteLine("Monday"); break; case '3': Console.WriteLine("Thesday"); break; case '4': Console.WriteLine("Wednesday"); break; case '5': Console.WriteLine("Thursday"); break; case '6': Console.WriteLine("Friday"); break; case '7': Console.WriteLine("Saturday"); break; } } }

출력:
Enter the day number 1~7 :
6
Friday

★중요
★실습
-(예제3-10) 계산기

using System; class CalculatorApp { public static void Main() { int x, y, r = 0; char opr; Console.Write("Enter an operator & two numbers = "); opr = (char)Console.Read(); x = Console.Read() - '0'; y = Console.Read() - '0'; switch (opr) { case '+': r=x+y; Console.WriteLine(x + " + " + y + " = " + r); break; case '-': r=x-y; Console.WriteLine(x + " - " + y + " = " + r); break; case '*': r=x*y; Console.WriteLine(x + " * " + y + " = " + r); break; case '/': r=x/y; Console.WriteLine(x + " / " + y + " = " + r); break; default: Console.WriteLine("Illegal operator "); break; } } }

출력:
Enter an operator & two numbers = /42
4 / 2 = 2

예제3-10 응용 : 사칙연산

★실습
예제 3-11 for문

using System; class ForStApp { public static void Main() { int i, n; double h = 0.0; Console.Write("Enter a number = "); n = Console.Read() - '0'; for (i = 1; i <= n; ++i) h += 1 / (double)i; Console.WriteLine("n={0},h={1}", n, h); } }

출력:
Enter a number = 5
n=5,h=2.283333333333333

-(예제 3-12) 2차원 배열(다차원배열) 생성하고 출력

using System; class PrintMatrixApp { public static void Main() { int[,] m = { { 1,2,3}, {4,5,6 }, {7,8,9 }}; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { Console.WriteLine("m[" + i + "," + j + "]=" + m[i, j] + ""); } Console.WriteLine(); } } }

출력:
m[0,0]=1
m[0,1]=2
m[0,2]=3

m[1,0]=4
m[1,1]=5
m[1,2]=6

m[2,0]=7
m[2,1]=8
m[2,2]=9

- (예제 3-13)

using System; class WhileStApp { public static void Main() { int i, n; double h = 0.0; Console.Write("Enter a number = "); n = Console.Read()-'0'; i = 1; while (i <= n) { h += 1 / (double)i; i++; } Console.WriteLine("n = {0}, h= {1}", n, h); } }

출력:
Enter a number = 7
n = 7, h= 2.5928571428571425

- (예제3-15) foreach

using System; class ForeachStApp { public static void Main() { string[] color = { "red", "green", "blue" }; foreach (string s in color) Console.WriteLine(s); } }


출력:
red
green
blue

- (예제 3-17) for~continue~

using System; class ContinueStApp { public static void Main() { int n, s, i; Console.Write("Enter a number = "); for(; ; ) { n = Console.Read() - '0'; if (n == 0) break; else if (n < 0) continue; for (s = 0, i = 1; i <= n; ++i) s += i; Console.WriteLine("n = " + n + ", sum = " + s); } Console.WriteLine("End of Main"); } }

출력:
n = 9, sum = 45
590
n = 5, sum = 15
n = 9, sum = 45
End of Main

-(예제 3-18) brea, continue

using System; class JumpStApp { public static void Main() { int n, s, i; for(; ; ) { Console.Write("Enter a number : "); n = Int32.Parse(Console.ReadLine()); if (n == 0) break; else if (n < 0) continue; for (s = 0, i = 1; i <= n; ++i) { s = sum(s, i); } Console.WriteLine("n = {0}, sum = {1}", n, s); } Console.WriteLine("End of Main"); static int sum(int s,int i) { return s + i; } } }

출력:
Enter a number : 5
n = 5, sum = 15
Enter a number : 0
End of Main

- (예제 3-20)

using System; class SimpleIoApp { public static void Main() { int i; char c; Console.Write("Enter a digit ans a character = "); //7 A i = Console.Read() - 48; // 두개의 콘솔데이터 중에서 '7'을 읽어옴. int 형으로 변환하기 위해서는 '0'을빼주어야 한다 // 모든 숫자는 0부터 시작하므로 (48 = '0') c = (char)Console.Read(); // 원래 char형인데 확실하게 캐스트연산자로 형변환 Console.Write("i = " + i); Console.WriteLine(", c= " + c); } }

Enter a digit ans a character = 7A
i = 7, c= A

중요!!!! int.parse
- (예제 3-21)

using System; class ReadLineApp { public static void Main() { int time, hour, minute, second; Console.WriteLine("*** Enter an integral time : "); time = int.Parse(Console.ReadLine()); // int.Parse 사용할줄 알아야함 hour = time / 10000; minute = time / 100 % 100; second = time % 100; Console.WriteLine("*** Time is " + hour + ":" + minute + ":" + second); } }

출력:
*** Enter an integral time :
102030
*** Time is 10:20:30

p.143 3-23
포매팅 (자릿수, 왼쪽정렬 오른쪽 정렬)
Console.WriteLine("1) {0,-5},{1,-5},{2,5}", 1.2, 1.2, 123.45);

출력:
1) 1.2 ,1.2 ,123.45

3장 연습문제3.6(1)



3장 연습문제 3.6(2)

using System; class Exercise3_6 { public static void Main() { int i = 0, n; char[] s = { '3', '5', '6', '\0' }; n = 0; while (s[i] >= '0' && s[i] <= '9') { n = 10 * n + (s[i] - '0'); i++; } Console.WriteLine("n = " + n); } } 




n = 356

연습문제 3.9(1) 소수구하기 for문

using System; using System.Collections.Specialized; using System.Globalization; using System.Security.Cryptography.X509Certificates; class Exercise3_9_1 { public static void Main() { int i, j; for (i = 2; i <= 100; i++) { for (j = 2; j <= 100; j++) { if (i%j == 0) break; } if (i == j) Console.Write(i + " , "); } } }


3.9(2) 완전수

using System; using System.Collections.Specialized; using System.Globalization; using System.Net.Mail; using System.Security.Cryptography.X509Certificates; class Exercise3_9_2 { public static void Main() { for (int i = 1; i <= 500; i++) { int sum = 0; for (int j = 1; j < i; j++) { if (i % j == 0) sum += j; } if (i == sum) Console.WriteLine(i); } } }

출력:
6
28
496

설명:
완전수란 자기 자신을 제외한 약수의 합이 자기 자신과 같은 수이기 때문에 이를 판별하
기 위하여 어떤 수의 약수를 구하여 약수들의 합을 저장하여 수와 비교하여야한다. 약수인
지 판별하기 위하여 2중 for문을 이용하여 i는 1부터 500까지(1부터 500사이의 수이기 때
문) j는 1부터 i까지(자기 자신을 제외한 수까지 비교하면 되기 때문) 반복문을 돌려 만약
i가 j로 나누어 떨어지면(j가 i의 약수이면) sum에 j를 더한다. 반복문을 실행시켜 저장된
sum값(약수들의 합)이 i값(완전수인지 판별할 수)과 같으면 완전수이므로 출력한다.


- 실습

using System; namespace ConsoleApp1 { class Program { static void Main(string[] args) { // 1. math 라이브러리 사용법 // 2. 콘솔환경에서 사용자 입력 받는법( scanf, cin) double r2 = Math.Sqrt(2.0); double a = Math.Pow(r2, 2); double b = Math.Abs(-1); Console.WriteLine("r2={0}, pow(r2) = {1}", r2,a); Console.WriteLine("abs(-1) = {0}", b); // 세개의 정수형 입력을 사용자로부터 입력받고 출력하는 프로그램 //1,2,3 string buffer = Console.ReadLine(); // buffer = 1,2,3 string[] bufferArray = buffer.Split(" "); // bufferarray = {"1","2","3"} int c = int.Parse(bufferArray[0]); // bufferarray[0] = "1" a="1" -> 1 Console.WriteLine("c = {0}", c); // parse = 분석하다 int[] intArr = new int[bufferArray.Length]; // intarr의 크기는 bufferarra의 길이만큼 할당 for (int i = 0; i < bufferArray.Length; i++) { intArr[i] = int.Parse(bufferArray[i]); } for (int i = 0; i < intArr.Length; i++) { Console.Write(intArr[i] + " "); } Console.WriteLine(); foreach (int i in intArr) { Console.Write(i + " "); } } } }