Lesson 6. Array

Overview

  • Exploring the concept of array in C/C++

Array

  • Array is used for representing number of variables with identical variable type esily.
  • For example, when we need 100 integer values to be stored, we can simply say
    1
    int arr[100];
    

    instead of

    1
    int a1, a2, ... ,a100;
    
  • Also it is possible to compine for loops with arrays to make programming easier.
  • Basically, array is a set of same-typed variables.
  • Arrays can be made using all types of data types - int, float, double, long, unsigned, char, and more.

Using array with for loop

  • It is possible to access the array element using another variable:
    1
    2
    3
    4
    int arr[5]={1,4,3,5,9};
    int n=1;
    printf("%d\n",arr[0]); //this will print 1
    printf("%d\n",arr[n]); //this will print 4
    
  • Using the similar method, getting input from the user can be easier:
    1
    2
    3
    4
    5
    6
    7
    int arr[5];
    for(int i=0;i<5;i++){
      scanf("%d",&array[i]); //this will allow the user to inpur 5 integers seperated with a single space or a return button.
    }
    for(int i=0;i<5;i++){
      printf("%d ",arr[i]);//this will print the 5 integers that user have inputed seperated with a single space.
    }
    
  • Using this, you can build program easier and efficiently.

Multi-dimensional array

  • Arrays can be made in different dimensions.
  • The following code will create a 2D array and get input from user
    1
    2
    3
    4
    5
    6
    int arr[5][5];
    for(int i=0;i<5;i++){
      for(int j=0;j<5;j++){
          scanf("%d",&arr[i][j]);
      }
    }
    
  • The code above allows the users to input data in 2D form. For example:
    1
    2
    3
    4
    5
    1 2 3 4 5
    2 3 4 5 7
    9 5 3 6 2
    1 3 5 7 9
    0 65 3 2 6
    
  • This type of input is possible.
  • You can also create 3D and more dimensions to the array to increase the efficiency of managing datas stored in a array.

Application of array

  • With knowing array, loop, and basic knowledge of C, it is possible to create multiple types of software.
  • There are number of things that you should learn about C, but for now, you can do almost everything you can think of (except that those software may be VERY inefficient).
  • This link will take you to my program that I created using function, basic Windows operations, array, loop, and other basic knowledges you have gained throughout the posts on my blog. Since this is created many years ago, there may be inperfection and numerous software bugs in it. Consider it as a weird example, not the sample you can look into.

Next post

  • Next post will be a general post about my experience at University of Waterloo after finishing the first term of Computer Engineering.
  • Next coding post will be explaining about functions, which may take several posts to explain fully.