2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【C++】基礎を学ぶ⑧~if文~

Last updated at Posted at 2022-07-09

if

分岐処理を行うプログラムである
分岐処理とは、条件判定を行いその結果によって異なる処理を実行すること
条件式は真(true)と偽(false)のどちらかになる

if文の使い方

if (条件式) {
  処理; // 条件式が真の場合に実行する処理
}

条件式について

条件式は比較演算子論理演算子で書く

比較演算子

左右の値を比較して、結果を真偽値で返す

構文 意味
x == y 等価
x != y 非等価
x > y 大なり
x < y 小なり
x >= y 大なりイコール
x <= y 小なりイコール

数値の大小を比較するプログラム

#include <iostream>

using namespace std;

int main(){
  int x = 10;
  if (x<10) {
    cout << "10より小さい" << endl;
  }
  if (x==10) {
    cout << "10と等しい" << endl;
  }
  if (x>10) {
    cout << "10より大きい" << endl;
  }
  return 0;
}
10と等しい

論理演算子

複数の条件式の統合や条件の反転を行う

構文 意味
!(条件式) 条件式の結果の反転
条件式1 && 条件式2 条件式1が真 かつ 条件式2が真
条件式1 || 条件式2 条件式1が真 または 条件式2が真

プログラム

#include <iostream>

using namespace std;

int main(){
  int x = 7;
  if (x > 5 && x < 10) {
    cout << "5より大きく、10より小さい" << endl;
  }
  return 0;
}
5より大きく、10より小さい

else

条件式が正しくなかったとき処理を実行する

else if

前のif文の条件が偽で、else ifの条件が真のときに処理を実行する

プログラム

if (条件式1) {
  処理1
}
else if (条件式2) {
  処理2
}
else {
  処理3
}

次の記事

【C++】基礎を学ぶ⑨~switch文~

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?