Chapter 15

 

Single character input

 

The basic operation done in input output is to read characters from the standard input device such as the keyboard and to output or writing it to the output unit usually the screen. The gerchar() function is used to read a character from the dtandard input device. The getchar() has the following form;

variable_name=getchar();

 

Example: program to illustrate te use of getchar()

#include<stdio.h>

#include<conio.h>

 

void main()

{

char ch;

printf(“type on char”);

ch=getchar();

printf(“The character u typed is %c”,ch);

getch();

}

 

 

Single character output:

 

The putchat function which in analogous to getchar function and printf() are used to write characters one at a time to the output terminal. The general form is of putchar() is:

 

putchar(variable name);

 

Example:

#include<stdio.h>

#include<conio.h>

void main()

{

char ch;

clrscr();

printf(“enter one character\n”);

ch=getchar();

putchar(ch);

getch();

}

 

String input and output:

The gets() function receives the string from the standard input device while puts outputs the string to the standard output device, A string is an array o r set of characters. The function gets accepts the name of the string as a parameter, and fills the string with characters that are input from the keyboard till new line character is encountered.

 

Program to illustrate the use of gets() and puts()

 

#include<stdio.h>

#include<conio.h>

void main()

{

char s[80];

printf(“Type a string less than 80 characters\n”);

gets(s);

printf(“The string type is :\n”);

puts(s);

getch();

}

 

 

 

External variable:

 

The variable which are both active and alive are known as external variables. The external variable declaration looks normal, but is located outside any of the program’s functions and can be accessed any of the function of same program. Therefore, it is also called global variable. When we want such variable that can be accessed from any function without passing arguments, then we declare a variable as global.

 

Example:

#include<stdio.h>

#include<conio.h>

void f1();

void f2();

void main()

{

int x=1;

clrscr();

f1();

printf(“It is in main function,x=%d\n”,x);

getch();

}

 

void f1(()

{

int x=2;

f2();

printf(“It is in f1 function,x=%d\n”,x);

}

void f2()

{

int x=3;

printf(“  it is in f2 function,x=%d\n”,x);

}

 

 

Program for sorting f string

 

#include<stdio.h>

#include<conio.h>

#include<string.h>

 

void main()

{

int i,j,n;

char str[20][20],temp[20];

clrscr();

puts(“Enter the number of string to be sorted”);

scanf(“%d”,&n) ;

for(i=0;i<=n;i++)

gets(str[i]);

for(i=0;i<=n;i++)

 

for(j=0;j<=n;j++)

{

if(strcmp(str[i],str[j])>0)

{

strcpy(temp,str[i]);

strcpy(str[i],str[j]);

strcpy(str[j],temp);

}

}

printf(“The sorted string\n”);

for(i=0;i<=n;i++)

puts(str[i]);

getch();

}

 

 Full Width

 


Post a Comment

0 Comments