Iterating Over a C-Style String
Write a program that declares a null-terminated C-style string and
prints each character on a seperate line using a loop, stopping at the null character ('\0').
Answer
#include <iostream>
int main() {
// Declare a null-terminated C-style string
char cString[] = "Hello, World!";
// Iterate over the string using a for loop
for (int i = 0; cString[i] != '\0'; ++i) {
std::cout << cString[i] << "\n";
}
std::cout << std::endl;
}
The program starts by declaring a C-style string, which will automatically end with a null character. A
forloop is used to iterate through each character of the string. The loop continues until the active character is the null character ('\0').