A repetition (or looping) statement allows you to specify that a program should repeat an
action while some condition remains true. The pseudocode statement
While there are more items on my shopping list
Purchase next item and cross it off my list
describes the repetition that occurs during a shopping trip. The condition “there are more
items on my shopping list” may be true or false. If it’s true, then the action “Purchase next
item and cross it off my list” is performed. This action will be performed repeatedly while
the condition remains true. The statement(s) contained in the While repetition statement
constitute its body, which may be a single statement or a block. Eventually, the condition
will become false (when the last item on the shopping list has been purchased and crossed
off). At this point, the repetition terminates, and the first statement after the repetition
statement executes. Here is a simple program using while loop ;
we are going to receive an input from the user as the student grade and there is 10 students and get the average of their grades ;
here is the code in java ;
import java.util.Scanner;
public class Apples {
public static void main(String[] args){
int counter = 0;
float sum = 0;
float studentGrade =0;
float average = 0;
while (counter <= 10){
System.out.println("enter student grade ");
Scanner input = new Scanner(System.in); // creating object from scanner class
studentGrade = input.nextInt();
sum += studentGrade;
counter ++;
}
System.out.printf("the sum is %f " , sum);
average = sum / counter;
System.out.printf("the average is %f " , average);
}
}
as we see the program keeps executing till it gets 10 grades and then calculate the sum of it , we will try a smarter program next .
Nested Control Statements
Nice class , looking forward to the next class :D
ReplyDelete