0428 C# (초급)실습예제들
정수형 데이터타입의 크기 출력
using System; using System.Collections.Generic; using System.Text;
namespace Consolesizeofex { class Program { static void Main(string[] args) { Console.WriteLine("Sbyte 의크기는{0} Byte입니다.", sizeof(sbyte)); Console.WriteLine("byte 의크기는{0} Byte입니다.", sizeof(byte)); Console.WriteLine("Shortbyte 의크기는{0} Byte입니다.", sizeof(short)); Console.WriteLine("Ushortbyte 의크기는{0} Byte입니다.", sizeof(ushort)); Console.WriteLine("int 의크기는{0} Byte입니다.", sizeof(int)); Console.WriteLine("uint 의크기는{0} Byte입니다.", sizeof(uint)); Console.WriteLine("long 의크기는{0} Byte입니다.", sizeof(long)); Console.WriteLine("ulong 의크기는{0} Byte입니다.", sizeof(ulong)); //정수형DATA TYPE의크기를출력해본다.
Console.ReadLine(); //사용자의입력값을대기함으로써, 결과화면이종료되지않고볼수있다.
} } } |
간단한 구구단 2단짜기
using System; using System.Collections.Generic; using System.Text;
namespace ConsoleArray { class Program { static void Main(string[] args) { int[] ar; ar = new int[10]; for (int i = 1; i < 10; i++) { ar[i] = 2 * i; } for (int i = 1; i < 10; i++) { Console.WriteLine("2*"+i+"="+ar[i]); } } } } |
진짜 구구단 짜기 |
namespace ConsoleTest2 { class Program { static void Main(string[] args) { int i, j; for (i = 1; i < 10; i++){ for (j = 1; j < 10; j++){ Console.Write("{0}" + "*" + "{1}" + "=" + "{2}\t", i, j, j*i); } } } } } |
namespace ConsoleApplication3 { class Program { static void Main(string[] args) { int[] ar; ar = new int[10]; for (int i = 1; i < 10; i=i+2) //위의 반복문은 I 값을 1씩 증가시키지만, 이 식에서는 I 값을 2씩 증가시킨다. { ar[i] = i * 2; } for (int i = 1; i < 10; i = i + 2) { Console.Write("2*"); Console.Write(i); Console.Write("="); Console.WriteLine(+ar[i]); } } } } |
Char 형 데이터 입력받기
using System; using System.Collections.Generic; using System.Text;
namespace ConsoleApplication3 { class Program { static void Main(string[] args) { char charinput;
Console.WriteLine("문자를입력하세요");
//charinput = Console.Read(); //오류CS0266: 암시적으로'int' 형식을'char' 형식으로변환할수없습니다. //명시적변환이있습니다. 캐스트가있는지확인하십시오.
charinput = Convert.ToChar(Console.Read()); Console.WriteLine("입력된문자는{0} 입니다.", charinput); } } } |
BOOL 데이터타입 입력하기
namespace ConsoleApplication3 { class Program { static void Main(string[] args) { bool a,b; a = false; b = true;
Console.WriteLine("A의논리값은" + a); Console.WriteLine("B의논리값은" + b); Console.ReadLine(); } } } |
출력물의 소수점 자릿수 결정지어 출력하기
namespace ConsoleApplication3 { class Program { static void Main(string[] args) { double d1input = 3.1415926535; double d2input = 1.23456789;
Console.WriteLine("출력형태를살펴보자"); Console.WriteLine("d1input의소수점아래를다삭제하면: {0:F0}",d1input); Console.WriteLine("d1input의소수점아래첫째자리까지보려면: {0:F1}",d1input); Console.WriteLine("d1input의소수점아래셋째자리까지보려면: {0:F3}",d1input);
Console.WriteLine();
Console.WriteLine("d2input의소수점아래첫째자리까지보려면: {0:F1}",d2input); Console.WriteLine("d2input의소수점아래넷째자리까지보려면: {0:F4}",d2input);
Console.ReadLine();
} } } |
'+' 연산자의 사용
namespace ConsoleApplication3 { class Program { static void Main(string[] args) { string strmessage = "c#초보입니다.";
Console.WriteLine("안녕하세요" + strmessage + " 잘부탁드립니다");
Console.ReadLine();
} } } |
탭기능 사용해보기
class Program { static void Main(string[] args) { Console.WriteLine("출력결과조절하기"); Console.WriteLine("1 2 3 4 5");
Console.WriteLine("=========="); Console.WriteLine("가로탭기능적용하기"); Console.WriteLine("\t1\t2\t3\t4\t5");
Console.WriteLine();
} } |
한 줄의 출력문에 여러 개의 변수 출력하기
class Program { static void Main(string[] args) { int a = 1; double b = 2; short c = 3; int d = (int)a + (int)b + (int)c; Console.WriteLine("a= "+"{0}"+" b= "+"{1}"+" c= "+"{2}",a,b,c); Console.Write("a+b+c="+"{0}", d); } } } |
값복사 하기
static void Main(string[] args) { int a = 10; int b; b = a; //값 복사 Console.WriteLine("a는"+"{0}"+"\t"+"b는"+"{1}",a,b); } |
구조체 및 값 복사 실습2
구조체란?!
|
using System;
//구조체선언 struct test { public int mom; public int age; } class Program { public static void Main() {
//구조체변수의선언 test t; t.mom=58; t.age=29;
Console.WriteLine("제몸무게는"+"{0}"+"입니다",t.mom); Console.WriteLine("그리고제나이는"+"{0}"+" 입니다",t.age);
//값복사 test y = t;
Console.WriteLine("제몸무게는" + "{0}" + "입니다", y.mom); Console.WriteLine("그리고제나이는" + "{0}" + " 입니다", y.age);
} } |
Enum 열거형 데이터타입
Enum ?! 열거형 데이터 타입을 지정. 열거형으로 만든 데이터 타입을 이용해서 변수를 만드는 것은 일반 데이터 타입과 동일하지만 열거형 변수에는 정해진 값만 넣는 것이 원칙이다. |
using System; using System.Collections.Generic; using System.Text;
//열거형선언(열거된data만입력될수있으며이값들은0,1,2,3 순의숫자값(INT)값과매치될수있다. enum DirectFlag { left, right, up=10, down };
namespace ConsoleTest2 { class Program { static void Main(string[] args) { //열거형변수선언 DirectFlag d1; d1 = DirectFlag.left; Console.WriteLine("{0}={1}",d1, d1); //int(숫자)형으로나타내어라 Console.WriteLine("{0}={1}", d1,(int)d1); //'ToString()'를사용하여문자열로나타내어라 string strDirect = d1.ToString(); Console.Write(strDirect); Console.WriteLine();
d1=(DirectFlag)Enum.Parse(typeof(DirectFlag),"left"); Console.WriteLine("d1의값은{0} ", d1);
d1 = DirectFlag.right; Console.WriteLine("{0}={1}", d1, (int)d1); Console.WriteLine();
d1 = DirectFlag.up; Console.WriteLine("{0}={1}",d1, (int)d1); Console.WriteLine();
d1 = DirectFlag.down; Console.WriteLine("{0}={1}", d1, (int)d1); } } }
|
제어문 실습(조건/반복/분기문)
조건문
첫째: (IF)
- 특정 범위별로 수행할 결과값을 지정할 때 사용하면 좋다.
class Program { public static void Main() { Console.WriteLine("당신의성적을입력해주세요");
int sungjuk = Int32.Parse(Console.ReadLine());
Console.WriteLine("너는말이야....");
if ((sungjuk <= 100) && (sungjuk >= 90)) { Console.WriteLine("너무똑똑한거아니야~"); } else if ((sungjuk < 90) && (sungjuk >= 80)) {
Console.WriteLine("제법인데~"); } else if ((sungjuk < 80) && (sungjuk >= 70)) {
Console.WriteLine("좀더노력해야긋다."); } else {
Console.WriteLine("어허... 갈길이멀구먼"); } } } |
둘째 : SWITCH
- 단일한 특정 값에 매치되는 결과가 있을 때, 그에 대한 수행을 처리한다.
namespace ConsoleTest2 { class Program { public static void Main() { Console.WriteLine("당신의성적대을입력해주세요");
int sungjuk = Int32.Parse(Console.ReadLine());
Console.WriteLine("너는말이야....");
switch (sungjuk) { case 100: Console.WriteLine("매우훌륭해요"); break; //위출력문을실행하고빠져나온다. case 90: Console.WriteLine("훌륭해요"); break; case 80: Console.WriteLine("잘하셨어요"); break; case 70: Console.WriteLine("그럭저럭~"); break; case 60:
case 50: Console.WriteLine("분발하세요"); break; } } } } | |
위의 식과 옆의 결과값에서 살펴보듯이 70과 100에 해당하는 Case 문의 경우 안에 수행해야 할 값들이 존재하므로 해당 값들을 실행한 후, 'break'문을 통해 빠져나오면 된다. 하지만 60의 경우 'case 60:'에 지정된 식이 없으므로 그 아래로 내려와 식이 지정된 값을 실행하게 된다. |
반복문 (FOR & WHILE)
첫째 :WHILE
- 조건식이 만족하면 해당 BLOCK을 계속 실행한다.
namespace ConsoleTest2 { class Program { public static void Main() { int i = 0; int sum = 0; while (i < 100) { sum = sum + i; i++; } Console.WriteLine("1부터100까지의합은=" + sum); } } } |
DO WHILE 문 |
둘째 : FOR 문
- WHILE문의 단순한 조건 반복과 달리 다양한 옵션을 줄 수 있는 진화된 반복문.
- FOR(초기화; 조건식; 스텝){문장}으로 구성.
namespace ConsoleTest2 { class Program { public static void Main() { int i = 0; int sum = 0; for (i = 0; i < 100; i++) { sum = sum + i; } Console.WriteLine("1부터100까지의합은" + sum); } } } |
- FOR 문과 WHILE 문의 차이
한계나 범위가 주어져 있을 때는 FOR문을 사용하고, 특정 조건에만 반복 수행할 때는 WHILE문을 사용한다.
public static void Main() { //문자열배열변수su에{}안의내용들을입력한다. string[] su ={ "하나", "둘", "셋", "넷", "다섯", "여섯" };
//foreach반복문으로문자열변수number를선언하고, 문자열배열in의값들을모두삽입한다. foreach (string number in su) Console.WriteLine(number);
Console.ReadLine(); } |
소설 같은 c# 3.1.5 예제파일(접근과 비접근)
/* private에 접근하기 위한 방법을 제시하는 예제 */ using System; public class TestPrivate { //지역변수 선언 private int top_secret; //전역(SetWeight)함수 선언 및 (my_weight)변수 선언 public void SetWeight(int my_weight) {//SetWeight 함수의 입력값인 my_weight가 들어오면 이를 지역변수인 top_secret에 복사하여 준다. top_secret = my_weight; } public int GetWeight() { return top_secret; } }//class
public class TestPrivateMain { public static void Main() { int s; TestPrivate we = new TestPrivate(); we.SetWeight(70); s = we.GetWeight(); Console.WriteLine("private멤버의 값은: " + we.GetWeight()); Console.WriteLine("private멤버의 값은: " + s); }//main }//class |
|
using System; public class beforeoper { private int hap; private int multi; public void oper(int x, int y) { hap = x + y; multi = x * y; } public int GetValue() { int s = hap + multi; return s; }
}
public class afteroper { public static void Main(){ beforeoper XX = new beforeoper(); XX.oper(3, 5); int s = XX.GetValue(); Console.WriteLine("두 수의 합과 곱을 다시 더한 값은" +s); } } |
최대 최소값 구하기 class Program { static void Main(string[] args) { int[] numbers = { -123, 45, 55, 33, 21, 15, 100, 89 }; int min, max, i;
min = max = numbers[0];
for (i = 0; i < 7; i++) {
if (numbers[i] < min) { min = numbers[i]; } if (numbers[i] > max) { max = numbers[i]; } } Console.WriteLine("최소값은 : {0}\n" + "최대값은 : {1}\n",min,max); Console.ReadKey(); } } |
/* SORT를 이용하여 정렬시키기 */
using System; class Program { static void Main(string[] args) { //배열 선언 및 값 할당 int[] numbers = { -123, 45, 55, 33, 21, 15, 100, 89 }; int i; //배열의 차수 확인 (Rank함수 이용) Console.WriteLine("배열의 차수는 : {0}", numbers.Rank); //입력된 배열의 입력된 값만큼 출력 (입력순서순으로 출력) for(i=0 ; i<numbers.Length ; i++) Console.Write(numbers[i]+"\t");
Console.WriteLine(" "); //배열을 오름차순으로 정렬 Array.Sort(numbers); //정렬 후의 값을 다시 출력 for (i = 0; i < numbers.Length; i++) Console.Write(numbers[i] + "\t");
Console.Read(); } } |