Coding - C

First-dimensional Arrays

네레이션 2022. 5. 27. 23:51

Arrays: Set of multiple data with the same data type. Each values are called elements and the location of each element are called indexes, starting from 0. 

 

The main form of array is Datatype Arrayname[Arraylength]. In this case, it is int grade[3]. 

http://www.tcpschool.com/c/c_array_oneDimensional

 

We can initialize the array as soon as we declare it. The form is same, but just add elements to it, like

int grade[3] = {85, 90, 45}. 

 

But setting the length of the array is boring, so we can just make the program set the array length based on the number of elements, like int arr[] = {1, 2, 3}, whcih the length will automatically be 3. We can also initialize the value of array wtihout mentioning, like how we just declared grade[0], grade[1], grade[2], but after we declared grade[3], even thoough the length is 3. However, this can cause errors, unlike python.

http://www.tcpschool.com/c/c_array_oneDimensional

 

We can get the memory size of the array by using this function: Array length * sizeof(data type). 

We can get the length of array by using this function: sizeof(array name) / sizeof (array name[0]).

The answer will be 3 for the example because sizeof(grade) is 12 bits and sizeof(grade[0]) is 4, so divide, which will give 3 as answer. 

http://www.tcpschool.com/c/c_array_oneDimensional

 

PRACTICE PROBLEM: REARRANGE {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} IN ASCENDING ORDER

 

This is the answer for the rearrangement, called bubble sorting.

When the next item in array is smaller, then the if statement would start. For example, when int i = 1 and j = 1, since 0 is smaller than 10, temp <-- 0, then 0 <-- 10, and 10 <-- temp (0), ultimately switching the places of the item.

 

The inner loop of int i would only push back 10, causing the sequence to be {0, 7, 1, 5, 6, 3, 8, 4, 9, 2, 10}, because as the 10's place would become switched constantly as the loop goes on for 10 times. For example, when int i = 1, it would be {0, 10, 7, 1, 5, 6, 3, 8, 4, 9, 2}, then when in 2, {0, 7, 10, 1, 5, 6, 3, 8, 4, 9, 2}, and so on. 

 

The outer loop of int j would repeat this entire process to switching places 10 times another 10 times, so for example, if we run the outer loop 3 times, the last three items in the array would be 8, 9, and 10 because they are the largerst three numbers. 

 

If I wanted to make this descending order, I can just switch the < in the if statement to >.