Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Tham khảo tài liệu 'c programming for the absolute beginner phần 6', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | C Programming for the Absolute Beginner Second Edition printf nInitialized character array n for x 0 x 6 x printf c cName x end main Figure 6.4 demonstrates why it is necessary to initialize arrays because old data may already exist in each element. In the case of Figure 6.4 you can see leftover data not assigned nor initialized by me stored in the cArray s elements. figure 6.4 Initializing a character-based array. Searching One-Dimensional Arrays One of the most common practices with arrays is searching their elements for contents. Once again you will use looping structures such as the for loop to iterate through each element until the search value is found or the search is over. The concept of searching an array is demonstrated in the next program which prompts a user to enter a numeric search value. include stdio.h main int x int iValue int iFound -1 int iArray 5 Chapter 6 Arrays for x 0 x 5 x iArray x x x initialize array printf nEnter value to search for scanf d iValue for x 0 x 5 x if iArray x iValue iFound x break end for loop if iFound -1 printf nI found your search value in element d n iFound else printf nSorry your search value was not found n end main As the preceding program shows I use two separate loops one for initializing my integerbased array to the counting variable plus itself iArray x x x and the other which searches the array using the user s search value. Valid values for each preceding array element are shown in Table 6.1. Table 6. I Valid Element Values for iArray x x x Element Number Value after Initialization 0 0 1 2 2 4 3 6 4 8 140 C Programming for the Absolute Beginner Second Edition If a match is found I assign the element to a variable and exit the loop with the break keyword. After the search process I alert the user if the value was found and at which element number. If no match was found I also alert the user. Figure 6.5 demonstrates the output of the searching program. Figure 6.5 Searching the contents of an array. Remember that .