8
11

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言語入門

Last updated at Posted at 2017-10-11

C言語の超基本

基本的な記述

#include <stdio.h>

int main(void){
    printf("Hello World!\n");
    return 0;
}
  • まず「main関数」から実行される
  • 「return 0;」の行が実行されるとプログラムが終了(「main関数」が終了)

変数宣言

// 変数宣言してから代入
int a;
a = 0;

// 変数宣言と同時に導入
int b = 0;

配列の宣言

int a[10]; // int型の要素を10個持つ配列の宣言

int a[5] = {5, 4, 3, 2, 1}; // 宣言と同時に初期化

int a[] = {1, 2, 3, 4}; // 初期値の個数に応じて配列の要素数を決めたい時
int a[4] = {1, 2, 3, 4}; // 上記と同様

int a[10] = {0}; // すべて0で初期化したい時のみ可能

for文

int i;
for(i = 0; i < 10; i++){
    printf("Hello World!");
}

if文

if (a > 1000){
    printf("a は 1000 より大きい\n");
}else if (a > 500){
    printf("a は 1000以下で500より大きい\n");
}else{
    printf("a は 500以下\n");}

ポインタ

ポインタ型の変数を宣言するというのことは住所を住所を指し示す値を入れる箱を用意することを意味する。

#include <stdio.h>

void main() {
    int data;
    int *ptr;

    data = 5;

    printf("整数型の変数dataの値= %d\n", data);
    printf("整数型の変数dataのアドレス= %08X\n", &data);

    ptr = &data;

    printf("ポインタ型の変数ptr = %08X\n", ptr);
    printf("ptrが指す場所に保存されている値= %d\n", *ptr);
}

/* 
結果:
整数型の変数dataの値= 5
整数型の変数dataのアドレス= 0012FF7C
ポインタ型の変数ptr = 0012FF7C
ptrが指す場所に保存されている値= 5 
*/
整数 住所
int data; と宣言 data &data
int *data; と宣言 *data data
参考: 初級C言語講座

記憶クラス指定子

指定子 意味  
auto オブジェクトに自動記憶クラスを与える。関数内でのみ使用可。 
register 変数の使用頻度が高いことをコンパイラに知らせる。ほかはautoと同じ。 
static オブジェクトに静的な記憶クラスを与える。関数の中でも外でも使用可。 
extern オブジェクト用のメモリが他のどこかで定義されていることを示す。 
typedef 型に別名をつける。構文の便宜上記憶クラス指定子に分類されている。 
参考: C言語のstatic指定子について

サンプルプログラム

2整数の最大公約数を求める関数(m>nと仮定)

GCD.c
int GCD(int m, int n){
    int r;
    r = m % n;
    if(r==0)
        return n;
    else
        return GCD(n, r)
}

平成28年度総合分析情報学コース第3問

char* F(int n, int b){
    static char outb[66] = {0};
    int i = 64;
    for(; n > 0 && i > 0 ; --i, n /= b)
        outb[i] = "0123456789abcdefghijkl"[n % b];
    return &outb[i+1];
}
8
11
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
8
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?