Describe one situation with realworld examples in which a p
• Describe one situation with real-world examples in which a programmer might want to create a loop that tests its condition in the beginning of the loop and one situation in which the condition is tested at the end of the loop.
• There are many situations where infinite loops may occur. Discuss those situations and provide best practices for each of the loop types that help avoid writing infinite loops.
Solution
//Loop
1.A program which writes into a text file till its size reaches say 2KB.in this case we cannot use do while or for loop because we don\'t know number of iterations.here we are checking condition at the end
Consider we want to take an integer input from user until user have entered a positive number. In this case we will use a do-while loop like this.Here we check the condition first.
2.
Infinite loops are loops that repeat forever without stopping.
Situations where a wrong variable is incremented,this infinite loops comes in:
Example:
int i, j=0;
for( i = 0; i < 5; j++ )
printf( \"i = %d\ \", i );
Other times infinite loops serve a useful purpose, such as this alternate means of checking user input:
while( true ) {
printf( \"Please enter a month from 1 to 12 > \" );
scanf( \"%d\", &month );
if( month > 0 && month < 13 )
break;
printf( \"I\'m sorry, but %d is not a valid month.\ Please try again.\ \", month );
}
Best practises using loops:
1.Avoid nesting of loops.Create/use methods functions in the loop
2.If your are aware of no of times loop runs,use for loop.if not sure of it go fr while loops.USe break and continue in the loops.
