- C language
- Basic grammar
- here
while statement-repeating syntax
You can write iteratively using the while statement.
while (repetition condition) { }
This is a sample to calculate the total with a while statement.
#include <stdint.h> #include <stdio.h> int main (void) { // Find the total with a while statement int32_t total = 0; int32_t i = 0; while (i <10) { total + = i; i ++; } printf("%d\n", total); }
The total from 0 to 9 is output.
45 45
The above while statement can be written concisely using for statement.
Use of while statement and for statement properly
How do you use the while statement and the for statement properly?
Sample for which for statement is suitable
Processing that uses indexes such as arrays can be written in a for statement in an easy-to-understand and concise manner. If the index spacing is fixed, such as +1 or +2, the for statement is sufficient.
#include <stdint.h> #include <stdio.h> int main (void) { int32_t nums [3] = {1, 3, 5}; // Find the total with a for statement int32_t total = 0; for (int32_t i = 0; i <3; i ++) { total + = nums [i]; } printf("%d\n", total); }
Sample for which while statement is suitable
If the above does not apply, write using a while statement. This is not an absolute standard, so use it as a rough guide.
For example, while seems to be suitable for the process of finding the terminal character "\ 0" in a string.
#include <stdint.h> #include <stdio.h> int main (void) { // String constant const char * string = "abc"; // A pointer to a single character (the beginning of a string constant) const char * buf_ptr = string; // Repeat until the terminating character "\ 0" appears while (* buf_ptr! ='\ 0') { // * to extract the actual character and output it printf("%c\n", * buf_ptr); // Increment the pointer to advance the character position buf_ptr ++; } }