You are here:

C++/Which loop is the better?

Advertisement


Question
i want to print "Hello" 100 times,
Which of the following is more efficient loop?

Or both are same ??
Please , submit ur comment with explaination...

1)

for (i = 0 ; i < 100 ; i++ )
{
printf( "Hello" );
}

2)

for ( i = 100 ; i > 0 ; i-- )
{
printf( "Hello" );
}

Answer
Hello Jai, thank you for the question.

Both of those loops do the exact same thing, in the exact same  time O(n). Another way to do that would be the following:

int i = 0;
while(i < 100)
{
printf("Hello");
++i;
}

But all of these are of the same complexity and do the exact same thing. It will take an iterative 100 times to produce the desired results, thus the loops are the same.

I hope this information was helpful.

- Eddie

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Eddie

Expertise

I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by ExpertRating.com. I also know a good deal about graphics via OpenGL, and GUIs.

Experience

I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2016 About.com. All rights reserved.