In: Computer Science
Develop the pseudo code for, desk check and test the following programs. Allow the user to provide the number of elements, and initialise the array according to their input. Use functions where appropriate to ensure modularity. 1. Find the average of a list of numbers 2. Find the smallest element in a list of numbers
Solution:
I am writing the program in java language. Please comment in case of any doubt.
//Code is as follows
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
//provide the number of elements
System.out.print("Enter number of elments: ");
int n = sc.nextInt();
//initialise the array according to their input
int nums[] = new int[n];
System.out.println("Enter "+n+" numbers: ");
for(int i=0; i<n; i++)
{
nums[i] = sc.nextInt();
}
//Find the average of a list of numbers
double avg = 0.0;
for(int i=0; i<n; i++)
{
avg += nums[i];
}
avg /= n;
//Find the smallest element in a list of numbers
int smallest = nums[0];
for(int i=1; i<n; i++)
{
if(smallest>nums[i])
smallest = nums[i];
}
//print entered elements
System.out.println("Entered numbers are: ");
for(int i=0; i<n; i++)
{
System.out.print(nums[i]);
if(i!=n-1)
System.out.print(", ");
}
//print average and smallest element
System.out.printf("\nAverage is: %.2f\n", avg);
System.out.printf("Smallest Element is: %d\n",smallest);
}
}
Output:
Please give thumbsup, if you like it. Thanks.