putchar('\n');
We will take one input char by using getchar and then will display the same bit by putchar function here is the code.
printf( "Enter any char from keyboard ");
putchar ('\n'); // Move the crusher to next line
var = getchar();
putchar(var);
Using the basics of above code we will develop a program to display lowercase letter if user enters uppercase letter and vise versa. For this program we will use toupper() and tolower() function which are part of the ctype library so we will include ctype.h ( header file ) at the starting of the program. Here is the complete code.
#include <stdio.h>
#include <ctype.h>
int main(void){
char var;
printf( "Enter any char from keyboard ");
putchar ('\n'); // Move the crusher to next line
var = getchar();
if(islower(var))
{
putchar(toupper(var));
}
else
{
putchar(tolower(var));
}
return 0;
}
This example demonstrates how to use putchar() to print each character of a string individually.
#include <stdio.h>
int main() {
char str[] = "plus2net";
int i = 0;
while (str[i] != '\0') {
putchar(str[i]);
i++;
}
return 0;
}
Output:
plus2net
---
Print the alphabet using a loop and putchar().
#include <stdio.h>
int main() {
for (char c = 'A'; c <= 'Z'; c++) {
putchar(c);
putchar(' '); // Adding space for readability
}
return 0;
}
Output:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
---
This example demonstrates how to replace printf() with putchar() to print characters one by one.
#include <stdio.h>
int main() {
printf("With printf():\n");
printf("Hello\n");
printf("With putchar():\n");
putchar('H');
putchar('e');
putchar('l');
putchar('l');
putchar('o');
putchar('\n');
return 0;
}
Output:
With printf():
Hello
With putchar():
Hello