Create an array of size 10, input values and print the array, and search an element in the array
#include <stdio.h>
int main() {
int arr[10]; // Step 1: Declare an array of size 10
int i, search, found = 0;
// Step 2: Input 10 elements from the user
printf("Enter 10 integers:\n");
for(i = 0; i < 10; i++) {
printf("Element %d: ", i + 1);
scanf("%d", &arr[i]);
}
// Step 3: Print the array
printf("\nThe array is:\n");
for(i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
// Step 4: Search for an element
printf("\n\nEnter the number to search: ");
scanf("%d", &search);
for(i = 0; i < 10; i++) {
if(arr[i] == search) {
printf("%d found at position %d (index %d)\n", search, i + 1, i);
found = 1;
break;
}
}
if(!found) {
printf("%d not found in the array.\n", search);
}
return 0;
}
🧠Step-by-Step Explanation
🔹 Step 1: Declare an array
int arr[10];
- This line creates an integer array of size 10
- It can store 10 elements of type int
- Array indices range from 0 to 9
🔹 Step 2: Take input from the user
for(i = 0; i < 10; i++) {
scanf("%d", &arr[i]);
}
- This loop runs from 0 to 9 (10 iterations)
- We use scanf() to take user input
- Each input is stored in consecutive array indices
- &arr[i] gets the memory address of each element
🔹 Step 3: Display the array
for(i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
- Prints each element of the array
- Elements are separated by spaces
- Output appears on a single line
🔹 Step 4: Search for an element
scanf("%d", &search);
for(i = 0; i < 10; i++) {
if(arr[i] == search) {
// Print the found message
break;
}
}
- First reads the number to search for
- Linear search through the array elements
- Compares each element with search value
- If found, prints position and breaks the loop
- If not found, displays appropriate message
🖨️ Sample Output:
Enter 10 integers:
Element 1: 12
Element 2: 34
Element 3: 56
Element 4: 78
Element 5: 90
Element 6: 11
Element 7: 23
Element 8: 45
Element 9: 66
Element 10: 67
The array is:
12 34 56 78 90 11 23 45 66 67
Enter the number to search: 90
90 found at position 5 (index 4)
💡 Key Concepts:
- Array Declaration: Specifies size and type at compile time
- Zero-based Indexing: First element is at index 0
- Linear Search: Simple search algorithm checking each element sequentially
- Loop Control: for loops provide precise iteration control
- I/O Operations: printf and scanf for console input/output
No comments:
Post a Comment