56日目

配列の確認

やさしいC p.301のソースコードを改変。

#include <stdio.h>

main()
{
	int i;
	int test[5] = {80, 60, 55, 22, 75};

	printf("int test[5] = {");
	for(i = 0; i < 5; i++){
		if(i < 5-1)
			printf("%d, ", test[i]);
		else
			printf("%d", test[i]);
	}
	printf("};\n\n");
	printf("test[0]の値は%dです。\n", test[0]);
	printf("test[0]のアドレスは%pです。\n\n", &test[0]);
	
	printf("test[1]の値は%dです。\n", test[1]);
	printf("test[1]のアドレスは%pです。\n\n", &test[1]);

	printf("int型のサイズは%dバイトです。\n", sizeof(int));

return 0;
}

実行結果

test[5] = {80, 60, 55, 22, 75};

test[0]の値は80です。
test[0]のアドレスは0017FD10です。

test[1]の値は60です。
test[1]のアドレスは0017FD14です。

int型のサイズは4バイトです。

int型配列の中身が1ずれるとアドレスが4加算されることを確認。

なんぞこれ

#include <stdio.h>

main()
{
	int i;
	for(i = 0; i < 10; i++)
	printf("%c ", i);
}

実行結果

加算とか二通り以上で

#include <stdio.h>

main()
{
	int i, ans = 0;
	for(i = 0; i < 10; i++){
		ans += i;
		printf("n = %2d, ans = %2d\n", i, ans);
	}
}

実行結果

n =  0, ans =  0
n =  1, ans =  1
n =  2, ans =  3
n =  3, ans =  6
n =  4, ans = 10
n =  5, ans = 15
n =  6, ans = 21
n =  7, ans = 28
n =  8, ans = 36
n =  9, ans = 45

関数化。

#include <stdio.h>

add(){
	int i, ans=0;
	for(i = 0; i < 10; i++){
		ans += i;
	}
		printf("n = %2d, ans = %2d\n", i, ans);
}

main()
{
	int i = 0;
	add(i);
}
<||
実行結果
>|c|
n = 10, ans = 45

nの値がおかしい。なぜだ。