‹ Back to the paper
A student had written the following method to display “Hello World” four times on the output…
A student had written the following method to display “Hello World” four times on the output screen.
void displayMessage( )
{
System.out.println("Hello World");
System.out.println("Hello World");
System.out.println("Hello World");
System.out.println("Hello World");
}The student modified the code later to reduce the number of lines in the code. void displayMessage( )
{
int i = 1;
while(i <= 4)
{
System.out.println("Hello World");
i++;
}
}Compare the above code snippets with respect to the time complexity.Answer
Answer
AIBoth versions have the same time complexity, $O(1)$ (constant time): the first has 4 fixed print statements and the while loop also always executes exactly 4 times, so in both cases the number of operations does not depend on any input size and stays constant.
From ISC Computer Science - Competency Focused Practice Questions (CISCE, August 2024), question 42.