Monday, July 27, 2009

Is is possible to use strings or characters in establishing conditions in loops in a c programming language?

If yes, how?


Can you site an example?

Is is possible to use strings or characters in establishing conditions in loops in a c programming language?
Yes you can. Character variables or literals can be compared directly with the standard %26lt;, %26gt;, %26lt;=, %26gt;= and = operators because C treats them as numbers based on their value in the character encoding you're using (ASCII, Unicode or whatever).





Strings can be compared with functions like strcmp(s1, s2), which returns zero if s1 and s2 are equal, a positive value value if s1 is greater than s2 (based on dictionary position) and a negative value if s1 is less than s2.





An example that prints all the lower case characters in the alphabet:





for (char c = 'a'; c %26lt;= 'z'; c++)


{


printf ("%c", c);


}
Reply:Sure you can, using a while loop.





Set a string variable inside the loop. In the while statement, see if that variable is a certain value. If it is, the loop will break.


No comments:

Post a Comment