0

C Arrays

An array is a variable that represents a collection of the same variable types. For instance, a collection of doubles is an array. It can also declare one variable as an array. The size of an array depend on the memory size of the target computer. It can store larger array size if the memory size is bigger.

Below is the arrays declaration format:

typename arrayname[init_literal];

As you remember from previous posts, this format is the same as when declaring strings. A string is a collection of characters, which also is an array.

After an array was declared, each element in the array can be accessed individually. For example:

floatarray[5] = 3.56;

Like other programming languages, the first element of an array in C always starts with 0. Therefore for the above example, floatarray[5] refers to the sixth element of the array.

Arrays are often used with loops to operate with all elements sequentially, especially the for loop. When used inside a loop, an array of n elements always stars from 0 to n – 1. For instance, an array of 10 elements would start from 0 to 9 inside a loop.

Here is the sample code for the arrays:

/*
 *
 * array.c
 *
 * Program to illustrate the use of arrays
 *
 * by Mark Virtue, 2001.
 *
 */

#include <stdio.h>

main() {
 float array[5];
 int i, index;

 for (i = 0; i < 5; ++i) {
  printf("Please enter element number %d: ", i + 1);
  scanf("%f", &array[i]);
   while (getchar() != 'n' && getchar() != EOF)
    printf("");
 }

 printf("Which element do you want to see? ");
 scanf("%d", &index);
 while (getchar() != 'n' && getchar() != EOF)
  printf("");

 printf("Element %d is %fn", index, array[index-1]);

 fflush(stdin);
 getchar();
}

The following sample code demonstrates how to use strings with arrays:

/*
 *
 * string.c
 *
 * Program to illustrate the makeup of a string
 *
 * by Mark Virtue, 2001.
 *
 */

#include <stdio.h>

main() {
 char name[51];
 int length;

 printf("Please enter your name: ");
 scanf("%[^n]", name);
 while (getchar() != 'n' && getchar() != EOF)
   printf("");

 for (length = 0; name[length] != ''; length++) {}    // do nothing

 printf("The length of >>>%s<<< is %dn", name, length);

 fflush(stdin);
 getchar();
}

Notice the name[length] != ” statement. The slash zero inside the quotes represents a NULL character. It means that the loop will end if there is no more character to read.

Multi-dimensional Arrays

A multi-dimensional Array is an array made of multiple arrays. Here is an example:

/*
 *
 * multi.c
 *
 * Program to demonstrate multi-dimensional arrays
 *
 * by Mark Virtue, 2001.
 *
 */

#include <stdio.h>

main() {
 int grid[8][3];    // It contains 8 arrays and each array has 3 elements
 int i, j;

 for (i = 0; i < 8; i++) {
  for (j = 0; j < 3; j++) {
   grid[i][j] = (i + 1) * (j + 1);
   }
 }

 for (i = 0; i < 8; i++) {
  for (j = 0; j < 3; j++) {
   printf("%3d ", grid[i][j]);
  }
  printf("n");
 }

 fflush(stdin);
 getchar();
}

And here is the sample code for the string usage in a multi-dimensional array:

/*
 *
 * multi2.c
 *
 * Program to demonstrate multi-dimensional arrays
 * by Mark Virtue, 2001.
 *
 */

#include <stdio.h>

main() {
 char strings[5][20];    // It contains 5 strings and each has 20 characters long
 int i;

 for (i = 0; i < 5; i++) {
  printf("Please enter string %d: ", i + 1);
  scanf("%s", strings[i]);
  while (getchar() != 'n' && getchar() != EOF) {}
 }

 for (i = 0; i < 5; i++) {
  printf("String %d is %sn", i + 1, strings[i]);
 }

 fflush(stdin);
 getchar();
}

Array Initialization

Arrays can be initialized at the beginning of the program when they are declared. During the initialization, it’s unneccessay to specify the size of the array. For instance, here is the declaration of an array:

int array[40];

And here is the initialization of an array when it is declared:

int array[] = {3, 6, 9, 12};

Note that it’s also possible to initialize the array when the size of the array is specified, but as stated above, it’s not necessary. For example:

int array[10] = {3, 6, 9, 12};

In the above example, the first four elements in the array got initialized, while the rest of the elements were set to 0.

Here is the sample code to show how the multi-dimensional arrays are initialized:

/*
 *
 * multi3.c
 *
 * Program to demonstrate initializing multi-dimensional arrays
 *
 * by Mark Virtue, 2001.
 *
 */

#include <stdio.h>

main() {
 char grid[8][8] =
 {
  {'r', 'h', 'b', 'k', 'q', 'b', 'h', 'r'},
  {'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'},
  {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
  {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
  {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
  {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
  {'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'},
  {'r', 'h', 'b', 'k', 'q', 'b', 'h', 'r'}
 };
 int i, j;

 for (i = 0; i < 8; i++) {
  for (j = 0; j < 8; j++) {
   printf("%c", grid[i][j]);
  }
  printf("n");
 }

 fflush(stdin);
 getchar();
}

And here is for the multi-dimensional arrays for strings:

/*
 *
 * multi4.c
 *
 * Program to demonstrate multi-dimensional arrays
 *
 * by Mark Virtue, 2001.
 *
 */

#include <stdio.h>

main() {
 char name[50] = "Mark Virtue";
 char strings[][20] = {"This", "is", "how", "to", "initialize"};
 int i;

 for (i = 0; i < 5; i++) {
  printf("Please enter string %d: ", i + 1);
  scanf("%s", strings[i]);
 }

 for (i = 0; i < 5; i++) {
  printf("String %d is %sn", i + 1, strings[i]);
 }

}

Note that strings in the multi-dimensional arrays can only have one set of arrays that has non-specified size, notably the arrays in the first dimension. The size of arrays in other dimensions needs to be specified.

1

C Special Loops

There are two special loops in C:

  • Nested loop – a loop inside of another loop, also called a loop within a loop.
  • The forever loop – a controlled infinite loop

Here is a sample code for the nested loop:

/*
 *
 * nested.c
 * Program to demonstrate the use of nested loops
 * by Mark Virtue, 2001.
 *
 */

#include <stdio.h>

main() {
 int i, j;

 for (i = 1; i <= 5; i = i + 1)
   for (j = 1; j <= 3; j = j + 1)    // nested loop
   printf("Here we are in the inner loop with i = %d and j = %dn", i, j);

 fflush(stdin);
 getchar();
}

Nested loops are often used in the multi-dimensional arrays.

And here is the forever loop:

/*
 *
 * forever.c
 * Program to demonstrate the use of the "forever" loop
 * by Mark Virtue, 2001.
 *
 */

#include <stdio.h>

main() {
 char type;
 int album;    // boolean

 for (;;) {    // A for loop that has no arguments will repeat the loop forever
   printf("Album or single (a for album, s for single)? ");
   scanf("%c", &type);
   while (getchar() != 'n' && getchar() != EOF)    // nested loop
     printf("");
   if (type == 'a' || type == 's')
     break;
   printf("Errorn");
 }

 album = type == 'a';

 if (album)
   printf("Albumn");
 else
   printf("Singlen");

 fflush(stdin);
 getchar();
}

The forever loops can only used in the for loops, and it’s similar to the while loop for input validation.

0

C break and continue

break and continue are two keywords that used in loops. They control the flow inside the loops. Below shows how these keywords work inside a block of code:

  // break
while (condition1) {
  statements...;

  if (condition2)
    break;

  statements...;
}

  // continue
while (condition1) {
  statements...;

  if (condition2)
    continue;

  statements...;
}

The break statement is used to skip a certain condition in a loop, discard the statements below the break statement and end the loop. For example, the loop continues to execute normally in the above code until the condition increases to condition2, it discards the “statements…” below the break statement and ends the loop on condition2.

Just as the break statement, the continue statement skips a certain condition in a loop and discards the statement below the continue statement. The difference from the break statement is that the continue statement continues to executed the loop once the specified condition is skipped. For example, the loop continues to execute normally in the above code until the condition increases to condiion2, it discards the “statements…” below the continue statement and continues the execution at condition3.

0

C do…while Loop

The do…while loop is the third type of loop for C and other programming languages. This type of loop is not very often used. It’s similar to the while loop. Here is the format of the do…while loop:

do {
  statements...;
}
while (condition);

Below are the execution steps:

  1. All the statements are executed
  2. The condition is checked
  3. The statements are executed one more time if the condition is true
  4. Repeat the above steps until the condition becomes false

The difference between do…while loop and while loop is that while loop checks the condition before the statements are executed whereas the do…while loop checks the condition after the statement are executed. This means that do…while loop executes the statements at least once, while the while loop might not execute the statements at all based on its condition.

The following is the sample code for the do…while loop:

/*
 *
 * dowhile.c
 *
 * Program to demonstrate the use of the do...while loop
 *
 * by Mark Virtue, 2001.
 *
 */

#include <stdio.h>

main() {
 char type;
 int album;    // Boolean

 do {
   printf("Album or single (a for album, s for single)? ");
   while (getchar() != 'n' && getchar() != EOF)
     printf("");
   scanf("%c", &type);
   if (type != 'a' && type != 's')
     printf("Errorn");
 }
 while (type != 'a' && type != 's');

 album = type == 'a';    // Convert to boolean

 if (album)
   printf("Albumn");
 else
   printf("Singlen");

 fflush(stdin);
 getchar();
}

Note that it’s the same code as the while loop. The difference is that the type variable is not initialized anymore since it uses do…while loop.

0

C for Loop

The for loop is used when the number of time the loop repeated is specified. The format of the for loop is:

for (initialization; condition; increment) {
  statements;
}

The following steps show how the for loop is executed:

  1. Initialize variable, the value usually is 0
  2. Check the condition
  3. If the condition is true, statements are executed
  4. The value of the variable increased by 1
  5. Loop from #2 to #4 until the condition becomes false

Here is the sample code for the for loop:

/*
 *
 * for.c
 *
 * Program to demonstrate the use of the for loop
 *
 * by Mark Virtue, 2001.
 *
 */

#include <stdio.h>

main() {
 int counter;
 int total = 0;

 for (counter = 1; counter <= 100; counter = counter + 1) {
   total = total + counter;
 }

 printf("The sum of all numbers from 1 to 1000 is %dn", total);

 fflush(stdin);
 getchar();
}

Note that the increment of the for loop can also be counter++ instead of counter = counter + 1.

2

C while Loop

The while loop is often used when it doesn’t know how many time the loop will be repeated. Here is the sample code for the while loop:

/*
 *
 * while.c
 *
 * Program to demonstrate the use of the while loop
 *
 * by Mark Virtue, 2001.
 *
 */

#include <stdio.h>

main() {
 char type = 'x';
 int album;    // Boolean

 while (type != 'a' && type != 's') {
  printf("Album or single (a for album, s for single)? ");
  scanf("%c", &type);
  album = type == 'a';    // Determine if type is equal to 'a'
  if (type != 'a' && type != 's')
   printf("Errorn");

   // Dummy statement to flush the input
  while (getchar() != 'n' && getchar() != EOF) {
   printf("");
  }
 }

 if (album)
  printf("Albumn");
 else
  printf("Singlen");

 fflush(stdin);
 getchar();
}

As you can see in the code above, format of the while loop is the same as the format of the if statement, except the condition is repeatedly used until the condition is true instead of used only once.

Below is the sample code for the while loop which is specified the number of repeated loops:

/*
 *
 * while2.c
 *
 * Program to demonstrate the use of the while loop
 *
 * by Mark Virtue, 2001.
 *
 */

#include <stdio.h>

main() {
 int counter = 1;
 int total = 0;

 while (counter <= 1000) {
  total = total + counter;
  counter = counter + 1;
 }

 printf("The sum of all numbers from 1 to 1000 is %dn", total);

 fflush(stdin);
 getchar();
}