Question
Answer and Explanation
Printing a horizontal bar in C is a straightforward task that can be accomplished using a simple loop and the printf function. Here's how you can do it:
Basic Approach:
The most common way to print a horizontal bar is by repeatedly printing a character, such as '-', '=', or ''. You can control the length of the bar by specifying the number of times the character is printed.
Example Code:
#include <stdio.h>
int main() {
int barLength = 20; // Length of the horizontal bar
char barChar = '-'; // Character to use for the bar
for (int i = 0; i < barLength; i++) {
printf("%c", barChar);
}
printf("\n"); // Move to the next line after printing the bar
return 0;
}
Explanation:
1. Include Header: The #include <stdio.h> line includes the standard input/output library, which provides the printf function.
2. Variables:
- barLength: An integer variable that determines the length of the horizontal bar. In this example, it's set to 20.
- barChar: A character variable that holds the character used to draw the bar. Here, it's set to '-'.
3. Loop: The for loop iterates barLength times. In each iteration, it prints the barChar using printf("%c", barChar).
4. Newline: After the loop completes, printf("\n") is used to move the cursor to the next line, ensuring that subsequent output doesn't appear on the same line as the bar.
Customization:
- You can change the barLength variable to adjust the length of the bar.
- You can change the barChar variable to use a different character for the bar (e.g., '=', '').
Example Output:
If you compile and run the above code, the output will be:
--------------------
This simple method allows you to easily print horizontal bars of varying lengths and using different characters in your C programs.