getchar and putchar in C
Here, you will get a program code to use the predefined functions getchar and putchar in C programming. In this program we will reads a string character by character as input and prints it character by character as output.
What is getchar and putchar in C?
The function getchar is used for input, to read the string character by character from the keyboard till the new line character (‘\n’) is found and the function putchar is used to print it character by character on the screen till the null character (‘\0’) is found.
Difference between getchar and putchar in C
getchar() | putchar() |
getchar is an input function.This function is used to get a single character input from the console input. | putchar is an output function. This function is used to print a single character at a time on output screen. |
for example:- void main(){ char ch; ch=getchar(); printf(“the char is %c”,ch); } | for example:- void main(){ char ch; ch=getchar(); putchar(ch); } |
Algorithm
Step 1: Initialize i=0.
Step 2: Print message ‘Enter a string’.
Step 3: Input a character and store in str[i].
Step 4: Increment the value of i.
Step 5: Repeat Steps 3 and 4, until the user presses the input key.
Step 6: Assign NULL character to str[i].
Step 7: Print String(in characters).
Step 8: Repeat Step 7, till not reached to Null character.
Example Program for getchar and putchar in C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #include <stdio.h> #include <conio.h> void main( ) { char str[ 50 ], c; int i = 0; printf( "\nEnter a string:" ); while( ( c = getchar( ) ) != '\n' ) { str[ i ] = c; i++; } str[ i ] = '\0'; printf("\nThe string is :"); for(i = 0; str[ i ] != '\0'; i++) putchar( str [ i ] ); getch(); } |
Output
Enter a string: Learn coding with www.coderevise.com
The string is : Learn coding with www.coderevise.com
Check out our other C programming Examples