SWE234 Solution To Array Question
SWE234 Solution To Array Question
SWE234 Solution To Array Question
Question
A C program to find the smallest and largest number from an array?
To write a C program that finds the smallest and largest numbers in an array, you can follow these steps:
1. Initialize the array and its size.
2. Use a loop to iterate through the array elements.
3. Compare each element with the current smallest and largest values.
4. Update the smallest and largest values accordingly.
5. Print the results.
Here’s a sample code to demonstrate this:
1. #include <stdio.h>
2.
3. int main() {
4. int n, i;
5. int smallest, largest;
6.
7. // Ask user for the number of elements
8. printf("Enter the number of elements in the array: ");
9. scanf("%d", &n);
10.
11. // Declare the array
12. int arr[n];
13.
14. // Input elements into the array
15. printf("Enter %d elements:\n", n);
16. for (i = 0; i < n; i++) {
17. scanf("%d", &arr[i]);
18. }
19.
20. // Initialize smallest and largest
21. smallest = largest = arr[0];
22.
23. // Iterate through the array to find smallest and largest
24. for (i = 1; i < n; i++) {
25. if (arr[i] < smallest) {
26. smallest = arr[i];
27. }
28. if (arr[i] > largest) {
29. largest = arr[i];
30. }
31. }
32.
33. // Print the results
34. printf("Smallest number: %d\n", smallest);
35. printf("Largest number: %d\n", largest);
36.
37. return 0;
38. }
Explanation:
• Input Handling: The program first prompts the user to enter the number of elements and
then the elements themselves.
Copyright @ Eugene Tebo OCTOBER 2024
1
SWE/CSN 234 PROGRAMMING II Solution to the Questions on Array
• Initialization: The smallest and largest variables are initialized to the first element of the
array.
• Loop: A loop runs through the array starting from the second element, updating the smallest
and largest values based on comparisons.
• Output: Finally, the smallest and largest values are printed.
#include <stdio.h>
int main() {
int n, i;
float sum = 0.0, average;
float num[n];
average = sum / n;
printf("Average = %.2f\n", average);
return 0;
}
Output:
Average = 30.00
#include<stdio.h>
int main()
{
int arr[10], i;
printf("Enter any 10 array elements: ");
for(i=0; i<10; i++)
scanf("%d", &arr[i]);
printf("\nAll Even Array elements are:\n");
for(i=0; i<10; i++)
{
if(arr[i]%2==0)
{
printf("%d ", arr[i]);
}
}
return 0;
}
Provide any 10 elements for the array and press the ENTER key to see all the even numbers from the given 10
array elements, as shown in the second snapshot given here:
Program Explained
• Receive any 10 array elements.
• Create a for loop that starts from 0 to 9.
• Inside the for loop, check whether the current element is an even number or not.
• If it is an even number, print it out and continue to check for the next array element until all 10
elements gets checked and printed.
• In this way, we will see all the even array elements as output.