You are on page 1of 1

Q) Distinguish between getchar and scanf functions for reading strings.

Getchar:-Reading a single character can be done by using the function getchar.
Syntax:- variable_name = getchar ( );

Variable_name is a valid µc¶ name that has been declared as char type. When this statement is encountered, the computer waits until a key is pressed and then assigns this character as a value to getchar function. Since getchar is used on the right hand side of an assignment statement, the character value of getchar is in turn assigned to the variable_name on the left. The getchar function may be called successively to read the characters contained in a line of text. Getchar accepts space character.
Scanf (³control strings´,arg1, arg2, «««« argn);

The control string specifies the field format in which the data is to be entered and the arguments arg 1, arg 2, arg n specify the address of locations where the data is stored. Scanf does not accept space character. (b) Write a program to count the number of words, lines and characters in a text.
#include<stdio.h> main( ) { char line[80],ctr; int I,c,end=0,characters=0,words=0,lines=0; printf(³\n key in text´); printf(³give one space after each word \n´); printf(³when completed press µenter¶ \n\n´); while (end==0) { c=0; while((ctr=getchar())!=µ\n¶) line[c++]=ctr; line[c]=µ\0¶; if(line[0]==µ\0¶) break; else { words++; for(i=0;line[i]!=µ\0¶;i++) if(line[i]==¶ µ || line[i]==µ\t¶) words++; }

_#% ________

__________

lines=lines+1; characters=characters+strlen(line); } printf(³\n´); printf(³\n number of lines=%d´, lines); printf(³\n number of words=%d´,words); printf(³\n number of characters=%d´,characters); }