0% found this document useful (0 votes)
16 views

Sample Program - Looping and Array

The document discusses different types of loops in Java including while, do-while, and for loops. It includes code examples to calculate the average of input numbers using these different loop structures.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Sample Program - Looping and Array

The document discusses different types of loops in Java including while, do-while, and for loops. It includes code examples to calculate the average of input numbers using these different loop structures.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

import java.util.

Scanner;
public class LabLooping1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
//while loop
int intValue=1;
Scanner sc = new Scanner (System.in);
while (intValue!=0) {
System.out.print("Enter a value: ");
intValue = sc.nextInt();//trigger user input
if (intValue!=0)
System.out.println("Your input is non-zero.");
else
System.out.println("Your input is zero.");
}*/

//do-while loop
/*int intValue;
Scanner sc = new Scanner (System.in);
do {
System.out.print("Enter a value: ");
intValue = sc.nextInt();//trigger user input
if (intValue!=0)
System.out.println("Your input is non-zero.");
else
System.out.println("Your input is zero.");
}
while (intValue!=0);*/

//for loop - This will compute for the average of 5 numbers


/*float sum=0, ave, num;
Scanner sc = new Scanner (System.in);
for (int ctr=1;ctr<=5;ctr++) {
System.out.print("Enter num" + ctr + ": ");
num=sc.nextFloat();
sum=sum+num;
}
ave=sum/5;
System.out.println("The average of the 5 numbers is " + ave +
".");*/

//for loop using array - average of n numbers;


Scanner sc=new Scanner (System.in);
int n;
System.out.print("Enter the number of inputs: ");
n=sc.nextInt();
float[] num=new float[n];
int n1=num.length;
float sum=0, ave;
for (int ctr=0;ctr<n1;ctr++) {
System.out.print("Enter num" + (ctr+1) + ": ");
num[ctr]=sc.nextFloat();
sum=sum+num[ctr];
}
ave=sum/n1;
System.out.println("The average of the " + n1 + " numbers is " +
ave + ".");
}
}

You might also like