C Programming for the Absolute Beginner phần 6

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 demonstrates why it is necessary to initialize arrays because old data may already exist in each element. In the case of Figure you can see leftover data not assigned nor initialized by me stored in the cArray s elements. figure 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 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 . 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 demonstrates the output of the searching program. Figure Searching the contents of an array. Remember that .

Không thể tạo bản xem trước, hãy bấm tải xuống
TÀI LIỆU MỚI ĐĂNG
15    22    4    29-11-2024
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.