Print Line and Text Using Function


Explanation

A function is a block of code that performs a specific task. It helps us avoid writing the same code multiple times. In this program, a user-defined function named line() is created to print two horizontal lines. The main() function calls line() before and after printing the text.

How It Works?

  • Step 1: Include the required header files stdio.h and conio.h.
  • Step 2: Create a user-defined function line() that prints two horizontal lines.
  • Step 3: Start the main() function and clear the screen using clrscr().
  • Step 4: Call the line() function.
  • Step 5: Display the text using printf().
  • Step 6: Call the line() function again to print the lines after the text.
  • Step 7: Stop the screen using getch().

Example Program


#include <stdio.h>
#include <conio.h>

void line()
{

    printf("\n ------------------------------");

    printf("\n ------------------------------");

}

int main()
{

    clrscr();

    line();

    printf("\n Hey");

    printf("\n How are you guys?");

    line();

    getch();

}

Output

------------------------------
------------------------------
Hey
How are you guys?
------------------------------
------------------------------

Practice Exercises

Task 1: Write a C program using a function named star() to print a line of 30 asterisks (*). Call the function before and after displaying the message "Welcome to C Programming".

Goal: Learn how to create and call a user-defined function to avoid repeating the same code.

💡 Hint: Create a function star() that prints a line of stars using printf(). Call the function twice from the main() function.
💡 Show Solution

#include <stdio.h>
#include <conio.h>

void star()
{

    printf("\n ******************************");

}

int main()
{

    clrscr();

    star();

    printf("\n Welcome to C Programming");

    star();

    getch();

}

Output
******************************
Welcome to C Programming
******************************
Explanation: The program creates a user-defined function named star() that prints a line of asterisks. The main() function calls star() before and after displaying the message, demonstrating how a function can be reused to avoid writing the same code multiple times.