In: Computer Science
Fill in the blank for this common use of the for loop in processing each character of a string. for _____________________________________________________ { char ch = str.charAt(i); // process ch } |
Insert the missing statement in the following code fragment prompting the user to enter a positive number. double value; do { System.out.print("Please enter a positive number: "); value = in.nextDouble(); } _____________________________________ |
The following for loop is executed how many times? for (x = 0; x <= 10; x++) |
Consider the following for loop: for (i = 0; i < str.length(); i++) { ... } and the corresponding while loop: i = 0; while __________________________________ { . . . i++; } Fill in the blank for the while loop condition that is equivalent to the given for loop? |
Write a for loop that is equivalent to the given while loop. i = 1; while (i <= 5) { . . . i++; } |
1. for loop to process each character of a string:
For loop is used to traverse each character of the string where the process:
i. starts from charAt(0)
ii. end at charAt(last character of the string)
Below is the highlighted code for the loop to process the string
for(int I = 0; I < str.length(); i++)
{
char ch = str.charAt(i);
// process ch
}
EXAMPLE
Suppose the string str is “Example” which is to be printed by loop having a space in each character. Below is the full code with output:
String str = "Example";
for(int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
System.out.print(ch+" ");
}
Output:
-----------------------------------------
2. Please find added while condition with do loop:
double value;
do
{
System.out.print("Please enter a positive number: ");
value = in.nextDouble();
}while(value<=0);
Example:
The above code will keep on asking the input until user enters a positive value as below, when 96 is entered the loop exists:
-----------------------------------------
3. The given loop has iterator variable x, which will be executed 11 times from 0 to 10
X’s starting value is = 0;
X’s ending value when the loop will be executed is 10
Please note 10 is included as condition is <=10
-----------------------------------------
4. Given for loop:
The for loop will traverse for each character of i from index 0 to index at its length-1.
Corresponding while loop is as below:
int i =0;
while (i< str.length())
{
. . .
i++;
}
EXAMPLE:
The sample code to print each character of string with while loop is as below:
int i =0;
while (i< str.length())
{
char ch = str.charAt(i);
System.out.print(ch+" ");
i++;
}
Scanner in = new Scanner(System.in);
-----------------------------------------
5. The given while loop will start from int i = 1 to i <=5 and increment i for each iteration.
Corresponding for loop is as below:
for(int i = 1; i <=5; i++) {
....;
}
**Kindly comment if you need any
clarification.