HIDE NAV

C Array Basics

This source shows the basic use of arrays including declaration, assignment using loops and reference using loops.

ArrayBasics.c


#include <stdio.h>
#include <stdlib.h>

int main(void) {

	// typical char variables
	char cOne = 'a';
	char cTwo = 'b';
	char cThree = 'z';

	printf("cOne holds: %c\n", cOne);
	printf("cTwo holds: %c\n", cTwo);
	printf("cThree holds: %c\n", cThree);
	printf("---------------\n");

	// char variables in an array
	// Array declaration. The value in [] is the size.
	// The size is the number of variables declared.
	char c[3];


	// array assignments. When [n] follows the array name you are
	// referring to a single variable of whatever type the array is.
	// Valid indices are [0, size - 1]
	c[0] = 'd';
	c[1] = 'e';
	c[2] = 'f';

	// literal index access to array variables
	printf("c[0] holds: %c\n", c[0]);
	printf("c[1] holds: %c\n", c[1]);
	printf("c[2] holds: %c\n", c[2]);

	// array access in a loop with an index variable
	printf("---------------\n");
	int i = 0;
	while (i < 3){
		printf("c[%d] holds: %c\n", i, c[i]);
		i++;
	}

	printf("---------------\n");

	//array assignment and access in a while loop
	char alpha[26];

	i = 0;
	while (i < 26) {
		alpha[i] = 65 + i;
		i++;
	}

	i = 0;
	while (i < 26) {
		printf("alpha[%d] = %c\n", i, alpha[i]);
		i++;
	}

	printf("---------------\n");
	//array assignment and access in a for loop
	char lower[26];
		//assignments
	for (int n = 0; n < 26; n++) {
		lower[n] = 97 + n;
	}
		//access
	for (int n = 0; n < 26; n++) {
		printf("lower[%d] = %c\n", n, lower[n]);
	}


	return 0;
}