Basic C programming 5: Array variable and for loop statement¶

Yuto Omae @ Nihon University, Japan¶

  • We use online compiler and debugger for c/c++.
  • https://www.onlinegdb.com/online_c_compiler

By using array, we can handle multiple values by a single variable.

Code 1: Array initialization¶

  • Here is the simplest code using array.
#include <stdio.h>
int main() {
    int a_arr[3] = {1, 2, 3};

    printf("a[0] = %d\n", a_arr[0]);
    printf("a[1] = %d\n", a_arr[1]);
    printf("a[2] = %d\n", a_arr[2]);

    return 0;
}

Key points¶

  • In initialization process, write a array size just after variable name like int a_arr[3].
  • By writing {...}, we can give specific values into array variable at ones.
  • We can access each value by writing variable and index like a_arr[0].

Works¶

  • Make a code including the double type array variable.

Code 2: Assigning values to array variable¶

  • Here is the code for assigining value to element of array variable.
#include <stdio.h>
int main() {
    int a_arr[3];

    a_arr[0] = 5;
    a_arr[1] = 10;
    a_arr[2] = 15;

    printf("a[0] = %d\n", a_arr[0]);
    printf("a[1] = %d\n", a_arr[1]);
    printf("a[2] = %d\n", a_arr[2]);

    return 0;
}

Key points¶

  • We can assign value by writing the element of array, index number and equal like a_arr[1] = 15.

Works¶

  • (1) By using scanf function, we can assign any values. e.g., in the case of int,
scanf("%d", &a_arr[0]);
scanf("%d", &a_arr[1]);
scanf("%d", &a_arr[2]);
  • (2) Make a code including the double type array variable. For input from keyboard, in the case of double type,
scanf("%lf", &a_arr[0]);
scanf("%lf", &a_arr[1]);
scanf("%lf", &a_arr[2]);

Code 3: For statement¶

  • The For statement is used to repeat a similar process.
#include <stdio.h>
int main() {
    int a_arr[3];

    for(int i = 0; i < 3; i++){
        a_arr[i] = (i+1)*5;
        printf("a[%d] = %d\n", i, a_arr[i]);
    }

    return 0;
}

Key points¶

  • for(int i = 0; i < 3; i++) means For statement and this condition of repeating.
  • i = 0 is initial value of i.
  • i < 3 is condition of continuance. During i < 3, the process is repeated.
  • i++ is the change statement after one process is completed.
  • For example, the first repeating process is run by i = 0, the second repeating process is run by i = 1, and the third repeating process is run by i = 2. That is, the code
for(int i = 0; i < 3; i++){
    a_arr[i] = (i+1)*5;
    printf("a[%d] = %d\n", i, a_arr[i]);
}
  • is same as the following code
a_arr[0] = (0+1)*5;
printf("a[%d] = %d\n", 0, a_arr[0]);
a_arr[1] = (1+1)*5;
printf("a[%d] = %d\n", 1, a_arr[1]);
a_arr[2] = (2+1)*5;
printf("a[%d] = %d\n", 2, a_arr[2]);

Works¶

  • Change the condition of continuance from i < 3 to i < 5, then, please check an warning message displayed. This reason is out of array range in the case of int a_arr[3].

Code 4: Define statement¶

  • The #Define statement can improve readability of code.
#include <stdio.h>
#define MAX_SIZE 3 // <- check here
int main() {
    int a_arr[MAX_SIZE];

    for(int i = 0; i < MAX_SIZE; i++){
        a_arr[i] = (i+1)*5;
        printf("a[%d] = %d\n", i, a_arr[i]);
    }
    return 0;
}

Key points¶

  • On the top of code, #define MAX_SIZE 3 represents assigning 3 as MAX_SIZE.
  • Any name can be used in stead of MAX_SIZE.
  • In general, array size and the number of repeating regarding for statement is same.
  • Therefore, by using #define statement, we can make safety code, that is, avoiding access out of range

Works¶

  • Change define name, give other values, e.g., #define ARR_MAX_SIZE 100, and check result.

Code 5: Assigning random value to array variable¶

  • Here is the code for assigning random to array variable.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_SIZE 10
int main() {
    int a_arr[MAX_SIZE];

    // random number range
    int min_n = 1;
    int max_n = 100;
    srand(time(0));

    // substituing random numbers to array
    for(int i = 0; i < MAX_SIZE; i++){
      a_arr[i] = rand() % (max_n - min_n + 1) + min_n;
    }

    // show
    for(int i = 0; i < MAX_SIZE; i++){
      printf("a[%d] = %d\n", i, a_arr[i]);
    }

  return 0;
}

Key points¶

  • For generating random number, need #include <stdlib.h>, #include <time.h>, and srand(time(0)) as preparation.
  • rand() % (max_n - min_n + 1) + min_n; is the code for generating random number from min_n to max_n (see previous lecture material).
  • Because of min_n = 1 and max_n = 100, the range of random is 1 to 100.

Works¶

  • Change value of MAX_SIZE, min_n, and max_n. After that, check result.

Code 6: Sum total of array values (not good case, pattern 1)¶

  • The following is the code for calculating sum total of array.
#include <stdio.h>
#define MAX_SIZE 5
int main() {
    int a_arr[MAX_SIZE] = {10, 20, 30, 40, 50};
    int s = 0;

    s = a_arr[0]+a_arr[1]+a_arr[2]+a_arr[3]+a_arr[4]+a_arr[5];    

    printf("Total number = %d", s);
    return 0;
}

Key points¶

  • This code can work, but, large problem.
  • When the size of array is large, it is very ugly code.
  • For example, when MAX_SIZE is 100, then, s = a_arr[0]+a_arr[1]+a_arr[2]+ ... +a_arr[98]+a_arr[99];
  • It is too long horizontally.

Code 7: Sum total of array values (not good case, pattern 2)¶

  • The following is the code for calculating sum total of array.
#include <stdio.h>
#define MAX_SIZE 5
int main() {
    int a_arr[MAX_SIZE] = {10, 20, 30, 40, 50};
    int s = 0;

    s = s + a_arr[0]; // s = 0 + 10 = 10
    s = s + a_arr[1]; // s = 10 + 20 = 30
    s = s + a_arr[2]; // s = 30 + 30 = 60
    s = s + a_arr[3]; // s = 60 + 40 = 100
    s = s + a_arr[4]; // s = 100 + 50 = 150

    printf("Total number = %d", s);

    return 0;
}

Key points¶

  • This code can work, but, big problem.
  • When the size of array is large, it is very ugly code.
  • For example, when MAX_SIZE is 100, then, s = s + a_arr[0]; s = s + a_arr[1]; ... s = s + a_arr[99];;
  • It is too long vertically.

Code 8: Sum total of array values (good case)¶

  • The following is the code for calculating sum total of array.
#include <stdio.h>
#define MAX_SIZE 5
int main() {
    int a_arr[MAX_SIZE] = {10, 20, 30, 40, 50};
    int s = 0;

    for(int i = 0; i < MAX_SIZE; i++){
        s = s + a_arr[i];
    }

    printf("Total number = %d", s);

    return 0;
}

Key points¶

  • By using For statement, we can make the simple code for calculating sum total.
  • Code 8 is same as Code 7.
  • In general, code consisting of vertically arranging similar statements like code 7 can be simply expressed by using For statement.

Works¶

  • Change size of array and assign any values to all element. Check the result of sum total.

Code 9: Count up¶

  • Here is the code for counting values that satisfy the specific condition (greater than 20).
#include <stdio.h>
#define MAX_SIZE 5
int main() {
    int a_arr[MAX_SIZE] = {10, 20, 30, 40, 50};
    int counter = 0;

    for(int i = 0; i < MAX_SIZE; i++){
        // when greater than 20, counting up
        if(a_arr[i] > 20){
            counter = counter + 1;
        }
    }

    printf("No. of over than 20 = %d", counter);

    return 0;
}

Key points¶

  • Values that is greater than 20 is counted by the code if(a_arr[i] > 20){counter = counter + 1;} and changing i from 0 to MAX_SIZE.
  • That is, the above code is same as
countr = 0;
if(a_arr[0] > 20){counter = counter + 1;}
if(a_arr[1] > 20){counter = counter + 1;}
if(a_arr[2] > 20){counter = counter + 1;}
if(a_arr[3] > 20){counter = counter + 1;}
if(a_arr[4] > 20){counter = counter + 1;}
  • Therefore, the code can count the number of values greater than 20.
  • The combination of For and If statements is useful not only c programming but other many programming.

Works¶

  • Change MAX_SIZE and the condition for counting. Check output result.

Code 10: Flag¶

  • Here is the code for checking whether the specific condition is satisfied or not.
  • When the condition is satisfied, set 1 as a flag.
  • By using Flag, we can make the code easy to read.
#include <stdio.h>
#define MAX_SIZE 10
int main() {
    int age_arr[MAX_SIZE] = {10, 20, 60, 20, 30, -200, 50, 92, 20, 31};
    int err_flag = 0;

    // age check. whether invalid value or not
    for(int i = 0; i < MAX_SIZE; i++){
        if(age_arr[i] < 0){
            err_flag = 1;
        }
    }

    // result
    if(err_flag == 0){
        printf("No problem.");
    }else if(err_flag == 1){
        printf("Warning: including invalid value!");
    }

    return 0;
}

Key points¶

  • There are many systems that require input the person's age.
  • Check whether including invalid values or not is important.
  • In the above code, when including invalid age, err_flag = 1. When not including invalid age, err_flag = 0
  • The invalid condition is minus age.
  • After that, depending on err_flag value, whether output error message or not is decided.
  • The first half is the creation of the flag, and the second half is processing based on the flags. That is, very readable code. In general, many IT engineers prefer flag-based programming since flag-based code is readable.

Works¶

  • Change invalid condition, e.g.,
if(age_arr[i] < 0 || age_arr[i] > 100){...}
  • In this case, when including ages that are less than 0 or greater than 100, flag is given 1. See Or ( | | ) operator in previous lecture material.

Assignments¶

  • (1) Prepare int-type array of size 5. Input value into array by using scanf and for statement. Not use equal symbol for assignment like a[0] = 3.
  • (2) Generate random numbers from -100 to 100 and input these random values into int-type array's element. After that calculate these sum total by using For statement.
  • (3) Prepare double type array of size 100. After that, substitute random number from 1 to 100 into array's element. Finally, calculate average value of the all array's elements.
  • (4) Write the code for input age of 10 persons by scanf and substituting them to array. After that, when including "minus" or "over 100", output warning message.
  • (5) Roll the 6-sided dice 100 times, and assign them to array. And count the number of 1.
  • (6) Roll the 6-sided dice 100 times, and assign them to array. And count the number of values that are greater than 2.
  • (7) Roll the 6-sided dice 100 times, and assign them to array. And count the numbers of each value. e.g., 1: 30times, 2: 20times, 3: 10times, 4: 10times, 5: 20times, 6: 10times (total 100 times).