Change text color in C using conio.h – Old School C

In C programming, when we are dealing with console applications, the conio.h provides several functions to enhance user interaction by manipulating the console screen. One of the most important functions is textcolor(), that allows us to change the text foreground color of text displayed in the console.

Overview of conio.h

conio.h stands for console input/output. Among C and C++, it is widely used for functions suited to DOS-based systems, as well as early Windows environments. It contains functions for handling console I/O, including reading keyboard input, manipulating text, and controlling the cursor.

Syntax of textcolor()

The textcolor() function is used to set the background color of text in the console. Here is the basic syntax:

void textcolor(int color);

Parameters

  • color: An integer value representing the color to be set. The color can be one of the predefined constants available in conio.h.

Color Constants and Their Numeric Codes

The color parameter can take the following predefined constants along with their corresponding numeric codes:

  • BLACK (0)
  • BLUE (1)
  • GREEN (2)
  • CYAN (3)
  • RED (4)
  • MAGENTA (5)
  • BROWN (6)
  • LIGHTGRAY (7)
  • DARKGRAY (8)
  • LIGHTBLUE (9)
  • LIGHTGREEN (10)
  • LIGHTCYAN (11)
  • LIGHTRED (12)
  • LIGHTMAGENTA (13)
  • YELLOW (14)
  • WHITE (15)

For example, to set the background color to blue, you would use textcolor(BLUE); or textcolor(1);

Example

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

int main() {

    // Set the text color to white for better contrast
    textcolor(BLUE);
    
    // Print some text
    cprintf("Coding Dots...");
    
    // Wait for a key press
    getch();
    
    return 0;
}

Output:

Change textcolor using numeric color constant

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

int main() {
    
	textbackground(4); // RED
    
    // Clear the screen to apply the background color
    clrscr();
    
    // Set the text color to white for better contrast
    textcolor(14); // YELLOW
    
	// Print some text
    cprintf("Coding Dots...");
    
    // Wait for a key press
    getch();
    
    return 0;
}

Output:

Another example of textcolor()

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

int main()
{
    
 int i;
				
 for(i=1;i<=15;i++)
 {
	textcolor(i);
 	gotoxy(1,i);
	cprintf("Coding Dots...");
 }
 getch();
 return 0;
}

Output:

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.