배열 array
int [] array;
array = new int [5];
for ( int i=0; i< array.Length; i++ )
{
array[i] = i; // 0 ~ 4
}
다차원 배열
// 2 차원 배열 선언
int[,] array;
// 배열에메모리 할당
array = new int [3,3];
// 배열에값 할당, 인덱스 범위 array [0..2, 0..2]
array[0,0] = 100;
int value = array[0,0];
길이가 다른 다차원 배열
2차원 배열의 경우 다음과 같이 선언
int[][] array; // 2차원 배열 선언
각 열마다 사용하는 요소 개수가 다른 경우이기때문에 필요한 만큼 메모리를 할당
각 열마다 갖는 행 개수에 따라 다음과 같이필요한 메모리를 할당
첫 번째 열은 5개, 두 번째 열은 4개 요소를 할당
array[0] = new int [5];
array[1] = new int [4];
is/as
is 연산자는 생성한 object 객체가 원하는 객체인지 확인할 때 사용
// is 연산자
object obj = "문자열입니다.";
if ( obj is string ) //string 형인가요?
Console.WriteLine ("obj is string");
as 연산자는 object 객체가 원하는 객체인지 확인하고 틀리면 null 값을 리턴하
고 맞으면 해당하는 객체로 변환해서 리턴
// as 연산자
string s = obj as string; // string 형 변환
if ( s != null )
Console.WriteLine ( "'" + s + "'" );
checked/unchecked
checked 연산자를 다음과 같이 써주면 할당할 변수에 값이 들어갈 수 없는 경우, 예외 처리가 일어난다
int n = 300;
byte b = checked( (byte)n );
코드에 checked 연산자를 넣는 대신 컴파일러 옵션을 지정할 수도 있다
다음과 같이 컴파일하면 코드에 있는 모든 명시적 형 변환에서 값을확인
csc /checkedcheck1.cs
checked 컴파일러 옵션을 주는 경우, 모든 명시적 변환을 확인
반대로 확인하고 싶지않은 변환은 다음과 같이 unchecked연산자연산자를 사용
If 문
switch 문
switch() case :~~~; break; default
while
int count = 0;
while(count < 3 )
{
Console.WriteLine( "count ={0}", count ); // 0, 1, 2
count++;
}
int count = 3;
do
{
Console.WriteLine( "count ={0}", count); // 3
count++;
} while(count < 3 );
foreach 문
배열이나 콜렉션에서 순서대로 값을 가져와 바복해서 수행할때
배열이 가지고있는 값을 이용해서 반복실행하는 예
배열에 들어있는 값을 순서대로 가져오다가 마지막 값을 가져오면 반복을 종료
static void Main()
{
string [] arr = { "Apple","Banana", "Orange" };
foreach ( string str in arr ) // in 뒤에는 루프의 대상이온다 //
{
Console.WriteLine( "{0}, ", str );
}
// Apple, Banana, Orange,
}
단순하게 배열에서 값을 가져온다면 foreach 문을 쓰는 것이 좋다
continue 문은 루프를 벗어나는 것이 아니라, 다음 반복으로 이동
현재 실행중인 반복을 중간에 끝내고 다음 반복을계속 진행
for ( int count = 0; count <10; count++ )
{
if ( count % 2 == 0 ) // 짝수인 경우
continue;
Console.Write( "{0}",count ); // 1 3 5 7 9
}
using System;
class sumtest
{
public static void Main()
{
int korean=89, english=78, math=93;
int sum = korean+english+math;
Console.WriteLine("국어 점수 : {0}",korean);
Console.WriteLine("영어 점수 : {0}",english);
Console.WriteLine("수학 점수 : {0}",math);
Console.WriteLine("--------------");
Console.WriteLine("세과목의 총점은 : {0}",sum);
float avg=(float)sum / 3;
Console.Write("세과목의 평균은 :");
Console.WriteLine(" {0:f1}",avg);
}
}
using System;
class familytest
{
public static void Main()
{
int cofee = 20;
int newspaper =10;
int TV = 15;
int milk = 5;
int adultTime = ((cofee*60)+(newspaper*60));
int childTime = ((TV*60)+(milk*60));
Console.WriteLine("가족구성원 모두가 사용한시간 {0} 초",adultTime+childTime);
int avgTime =(adultTime+childTime) /5;
Console.WriteLine("구성원이 평균 사용한 시간이 : {0}",avgTime);
Console.WriteLine("구성원중에 {0}이 사용했다",(adultTime > childTime)? "어른" :"아이" );
/* if (adultTime > childTime)
{
Console.WriteLine("어른들이 {0}초를 사용했다",adultTime);
}
if (adultTime < childTime)
{
Console.WriteLine("아이들이 {0}초를 사용했다", childTime);
} */
}
}
//////////////////////////////////// 학점 출력하기 ////////////////////////////////
//////////////////////////////////// IF 문 ///////////////////////////////////
using System;
class test
{
public static void Main()
{
// do
//{
int strwhile =1; // 나가는 값
while(strwhile == 1)
{
Console.Write("학점을 입력하세요 : ");
string str = Console.ReadLine();
Console.WriteLine("{0}",str);
int a=1;
if (str == "a" || str == "A")
{
Console.WriteLine("당신은 A학점 당신은 졸라 잘함");
}else if (str == "b" || str == "B")
{
Console.WriteLine("당신은 B학점 당신은 조금 잘함");
}else if (str == "c" || str == "C")
{
Console.WriteLine("당신은 C학점 당신은 보통 잘함");
}else if (str == "d" || str == "D")
{
Console.WriteLine("당신은 D학점 당신은 아주조금 잘함");
}else if (str == "f" || str == "F")
{
Console.WriteLine("당신은 F학점 당신은 졸라조금 잘함");
}
else if (str == "end")
{
Console.WriteLine("당신은 나간다");
strwhile=0;
}else
{
Console.WriteLine("당신은 잘못입력하였음");
}
}
//}while();
}
}
//////////////////////////////////// 학점 출력하기 ////////////////////////////////
//////////////////////////////////// switch 문 ///////////////////////////////////
using System;
class teststr
{
public static void Main()
{
int i = 0;
while(i == 0)
{
Console.Write("학점을 입력하세요 : ");
string str = Console.ReadLine();
switch (str)
{
case "a":
case "A":
Console.WriteLine("학점은 A입니다");
break;
case "b":
case "B":
Console.WriteLine("학점은 B입니다");
break;
case "c":
case "C":
Console.WriteLine("학점은 C입니다");
break;
case "d":
case "D":
Console.WriteLine("학점은 D입니다");
break;
case "f":
case "F":
Console.WriteLine("학점은 F입니다");
break;
case "end":
Console.WriteLine("나갑니다");
i = 1;
break;
default :
Console.WriteLine("잘못입력");
break;
}
}
Console.WriteLine("마지막");
}
}