Home > Net >  Can any one help changing this do-while loop to for loop
Can any one help changing this do-while loop to for loop

Time:10-29

        do
        {
            Character_Output(string[i]);
            
        }while(string[  i] !='\0'); 

i wanted to change this form to for loop.

CodePudding user response:

Assuming i to be initialized with 0.

 for(int i=0;str[i]!='\0';  i)
 {
     Character_Output(string[i]);
 }

Remember one thing for-loop is an entry control loop whereas do-while is an exit control loop.

CodePudding user response:

This do while loop

do
{
    Character_Output(string[i]);
    
}while(string[  i] !='\0'); 

can invoke undefined behavior when the outputted string is empty because in this case the terminating zero of the string will be skipped due to the condition

string[  i] !='\0'
       ^^^^ 

A correct for loop for this code snippet can look the following way

for ( size_t i = 0; string[i] != '\0'; i   )
{
    Character_Output(string[i]);
}

Pay attention to that in general you should use the type size_t instead of the type int for the variable that is used as an index of a string because an object of the type int can be not large enough to store the length of an arbitrary string. Moreover the function strlen that returns the length of a string has the return type size_t.

An alternative approach to write the for loop can look the following way

for ( const char *p = string; *p != '\0';   p )
{
    Character_Output( *p );
}

Also the same task can be done using the while loop. For example

size_t i = 0;

while ( string[i] != '\0' )
{
    Character_Output( string[i  ] );
}

Or using a pointer

const char *p = string;

while ( *p != '\0' )
{
    Character_Output( *p   );
}
  • Related