loop Flashcards
identify what would ‘i’ be at the end of the code in:
for ( int i = 1 ; i <= 3 ; i++ )
4
correct the following:
for ( int i = 1 ; i <= 3 ; i++ );
for ( int i = 1 ; i <= 3 ; i++ ) // the for command comes without the ;
print the output of the following:
for ( int i = 1 ; i <= 3 ; i++ )
System.out.println(“Hello”);
System.out.println(“end.”);
hello
hello
hello
end.
print the output of the following:
for ( int i = 1 ; i <= 3 ; i++ )
{
System.out.println(“Hello”);
System.out.println(“end.”);
}
hello
end.
hello
end.
hello
end.
print the output of the following:
for ( int i = 1 ; i <= 3 ; i++ ) ;
{
System.out.println(“Hello”);
System.out.println(“end.”);
hello
end.
print the output of the following:
for ( int i = 1 ; ; i++ ) ;
{
System.out.println(“Hello”);
infinite loop.
it will go on forever since there is no condition statement.
print the output of the following:
for (int i = 1 ; i <= 9 ; i += 2)
System.out.println(i + “”)
1
3
5
7
9
print the output of the following:
for ( int i = 1 ; i <= 10 ; i– )
System.out.print(“*”);
- infinite
convert the following to a while code:
// read 3 grads from user then find sum and average :
102
103 int sum = 0 ;
104
105 int num ;
106
107 for(int i = 1 ; i <= 3 ; i++)
108 {
109 System.out.println(“Enter number : “);
110 num = input.nextInt() ;
111 sum = sum + num ;
112
113 }
114
115 System.out.println(“sum = “ +sum );
116 System.out.println(“Average = “ + ( sum / 3 ));
120 int sum = 0 ;
121
122 int num ;
123 int i = 1;
124
125 while( i <= 3 )
126 {
127 System.out.println(“Enter number : “);
128 num = input.nextInt()
129 sum = sum + num ;
130 i++ ;
131 }
132
133 System.out.println(sum );
134 System.out.println(“Average = “ + ( sum / 3 ));
What do you use when the question asks you to read a cont. set of numbers but asks to stop at a certain num/char/etc.
it is an essential loop.
explain why we added num = input.nextInt() twice in:
System.out.println(“Enter number, to stop enter -1”);
num = input.nextInt();
while ( num != -1)
{
sum = sum + num ;
System.out.println(“Enter number, to stop enter -1”);
num = input.nextInt();
}
we added a second num input in the while loop so that the user can keep entering a number
whereas if we only had the first one then the user wouldve only been able to enter a num once
if you were using a do-while code then you must first identify.. before the “do”
the variable that’s within the while condition statement before the do
ex:
char ch;
do(
correct the following:
do(
char ch = ‘a’;
double book = 0;
int i;
…….
)while ( int => 0 )
int i;
do(
char ch = ‘a’;
double book = 0;
…….
)while ( int => 0 )
\ you must identify the var used in the while condition statement before the “do”
T/F: a ‘break’ could make you exit an if statement.
F, it makes you exit a for or while loop
what does the break do?
it immediately takes you out of the loop