0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

プログラミング練習記録 3日目:C# 基本文法:変数、条件分岐、ループ

Posted at

1.本日の作業内容

 C# 基本文法:変数、条件分岐、ループ 復習

2.作業目的

 ・基本文法の復習。
 (ちなみに案件の異動でC#使わなくなりました...)

1.変数

変数とは...「値を一時的に保存するための名前付きの記憶領域」のこと。

C#は静的型付け言語なので、変数には必ず型が付く。
 例)int sting bool など
→型によって使える演算子や、扱える値の種類が変わる。

変数には大きく分けて以下の2種類がある:

値型(Value Type):int, double, bool, struct など
 → 値そのものがスタックに格納され、代入時には値がコピーされる。
参照型(Reference Type):string, class, object, array など
 → ヒープ上に格納され、変数はその参照(アドレス)を保持する。

型推論

C#では var を使うことで型推論によって自動的に型が決まる。
型はコンパイル時に決定されており、動的ではない。

サンプル

int age = 20;
string name = "佐藤";
bool isStudent = false;
var job = "police";
var fathersAge = 45;

Console.WriteLine(age);
Console.WriteLine(name);
Console.WriteLine(isStudent);
Console.WriteLine(job);
Console.WriteLine(fathersAge);

出力結果

20
佐藤
False
police
45

2.条件分岐(if / else)

特定の条件に応じて異なる処理を実行するための制御構文

基本形は下記の通り。

  • if (条件):条件が true のときのみ実行される
  • else:if の条件が false のときに実行される
  • else if:複数の条件を順に評価する場合に使う

サンプル

int age = 20;
string name = "佐藤";
bool isStudent = false;
var job = "police";
var fathersAge = 45;

// if(条件式)
if (age == 20 && isStudent)
{
    Console.WriteLine(name);
    Console.WriteLine(age);
} 
// 条件が当てはまらないとき
else
{
    Console.WriteLine(job);
    Console.WriteLine(fathersAge);
}

出力結果

police
45

3. 繰り返し(ループ)

ある処理を繰り返し実行するための制御構文

代表的なループは下記の通り

  • for 文:回数が決まっている場合に使う
  • while 文:条件が true の間、繰り返す
  • foreach 文:コレクション(配列・リストなど)を順番に処理する

for文サンプル

for (int i = 1; i <= 3; i++ ){
    Console.WriteLine(i);
}

// 出力
1
2
3

while文サンプル

int age = 20;
while (age < 25)
{
    age++;
    Console.WriteLine(age);
}

// 出力
21
22
23
24
25

foreach文サンプル

string[] foods = { "寿司", "天ぷら", "そば" };
foreach(string food in foods)
{
    Console.WriteLine(food);
}

// 出力
寿司
天ぷら
そば

まとめ

なんとなく使わずに、ちゃんと意味と使い分けを意識したいですね。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?