NIOS Computer Science: Chapter 12 – Function Part 3

Glide to success with Doorsteptutor material for IAS : Get complete video lectures from top expert with unlimited validity: cover entire syllabus, expected topics, in full detail- anytime and anywhere & ask your doubts to top experts.

Download PDF of This Page (Size: 201K)

Image of getchar() and putchar() functions

Image of Getchar() and Putchar() Functions

Image of getchar() and putchar() functions

II.) Putchar ( ) Function

The putchar( ) function takes one argument, which is the character to be sent to output device.

It also returns this character as a result. The general form of the putchar ( ) function is:

putchar (ch);

Where ch is a variable of type character

Example-1

# include < iostream.h >

# include < stdio.h>

void main ( )

{

char ch;

ch = getchar ( );

putchar (ch);

}

The above program takes a character from the keyboard and prints it on the screen.

III) . Gets ( ) Function

The gets ( ) function gets a string terminated by a newline character from the standard input stream stdin.

The gets ( ) replaces the newline by a null character (\0). It also allows input string to contain white space characters (spaces, tabs), gets return when it encounters a newline; everything upto the newline is copied into A.

gets (A) ;

Example 2

# include < stdio.h >

# include < iostream.h >

void main ( )

{

char A [ 100 ];

cout << “Input a string”;

gets (A);

puts (A);

}

Some More Functions

The Getch ( ) and Getche ( ) Functions

The general form of the getch ( ) and getche ( ) is

ch = getche ( ) ;

ch1 = getch ( ) ;

ch and ch1 are the variables of type character.

They take no argument and require the conio.h header file. On execution, the cursor blinks, the user must type a character. The value of the character returned from getche ( ) is assigned to ch.

The getche ( ) function echoes the character to the screen.

That's why there's an e in getche. Another function, getch ( ), is similar to getche ( ) but does not echo the character to the screen.

Example 3

To count the no. of characters and words in a sentence entered by the user.

# include < iostream.h >

# include < conio.h >

void main ( )

{

char ch;

int chcnt = 0, wdcnt = 1;

while ( (ch = getche ( ) ) ! = ‘\r’)

{

if (ch = = ‘ ’)

wdcnt + + ;

else

chcnt + + ;

}

cout < < “No. of characters” < < chcnt << “\n”

cout < < “No. of words” < < wdcnt;

}

The above program counts the no. of characters and no. of words in a sentence terminated by return key. The ‘\r’ reads the return key character.

Developed by: