Input Output Statements
In ‘C’ language, two types of Input/Output statements are available and all input and output operations are carried out through function calls. These function collectively known as standard I/O library.
1.unformated Input/Output statements
2.Formated Input/Output statements
Unformatted Input/Output statemetns
These statements are used to Input/Output a single/group of characters from/to the input/output devices.Here the user cannot specify the type of data i.e, going to be input/output.
Unformatted Input/output statements
Input Output
getc();getchar();
gets();
putc();putchar();
puts();
Input/output Functions
Formated Input/output statements
Input Output
scanf();fscanf();
printf();Fprintf();
The following are the unformatted Input/output statements available in c:
Single Character Input-getchar() function
A single character can be given to the computer using ‘C’ input library function getchar().
The getchar() function is written in standard I/O library. It reads a single character from a standard input device.
Input Output
getchar();getc();gets();
putchar();putc()puts();
Synatx char variable=getchar();
Description char:datatype;Variable:Any vlid ‘c’ variable
Example char x;X=getchar();
Example:
/* Program for testing character type */
#include<stdio.h>
void main()
{
char ch;
printf(“Enter any character/digit”);
ch=getchar();
if(isalpha(ch)>0)
printf(“It is a alphabet”);
else if(isdigit(ch)>0)
printf(“It a digit”);
else
printf(“It is alphanumeric”);
}
Single Character Input-putchar() function
The putchar() function is used to display one character at a time on the standard output device.
Example:#include<stdio.h>
void main()
{
char ch;
printf(“Enter any alphabet either in Lowercase or Uppercase”);
ch=getchar();
if(islower(ch))
putchar(toupper(ch));
else
putchar(tolower(ch));
}
Syntax putchar(character variable);
Description Character variable is the valid ‘c’ variable of the type of char data type.
Example char x;putchar(x);
getc() function
This is used to accept a single character from the standard input to a character variable.
Syntax:
putc() function
This is used to display a single character in a character variable to standard output device.
Syntax character variable=getc();
Description Character variable is the valid ‘c’ variable of the type of char data type
Example char c;c=getc();
Syntax putc(character variable);
Description Character variable is the valid ‘c’ variable of the data type.
Example char c;putc(c);
gets() and puts() function:
The gets() function is used to read the string(string is a group of characters) from the standard input device(keyboard).
The putc() function is used to display/write the string to the standard output device(Monitor).
Syntax gets(char type of array variable);
Description Valid ‘c’ variable declared as one dimension char type.
Example gets(s);
Syntax puts(char type of array variable);
Description Valid ‘c’ variable declared as one dimension char type.
Example Puts(s);
Example
#include<stdio.h>
void main()
{
char name[40];
puts(“Enter Name:”);
gets(name);
puts(“Print Name:”);
put(name);
}
Formated Data Input Output Functions:Formated Input/output that has been arranged in a particular formatExample : LAK 397
The following are the formatted Input/Output statements:
scanf() Function
The scanf() function is used to read information from the standard input device(keyboard),scanf() function starts with a string argument and may contain additional arguments.
Input Output
scanf() printf()
fscanf() fprintf()
Syntax Scanf(“control string”,&var1,&var2,….&varn)
Description The Control String consists f character groups.
Example scanf(“%d”,&n)
Control String: The below table illustrates code formats(control strings) in Input/Output statements.
Each variable name(argument) must be proceeded by an ampersand(&).The ‘&’ symbol “address of” the variable.
Format Code Meaning
%c To read a single character
%d To read a decimal number
%e To read a floating point value
%f To read a floating point value
%g To read a floating point value
%o To read an octal value
%x To read hexadecimal value
%s To read a sting
%u To read an unsigned integer
Rules for writing scanf() function
1.The control string must be preceded with(%) sign and must be within quotations.
2.If there is a number of input data items, items must be separated by commas and must be preceded with(&) sign.
3.The control string and the variables going to input should match with each other.
4.It must have termination with semicolon.
5.The scanf() reads the data values until the blank space n numeric input or maximum number of character have been read, or error is detected.
printf() Function: The function is used to output any combination of data. It is similar to the input function scanf().
Rules for writing printf() function
a)Place appropriate headings in the output.
b)The variable must be separated by commas, and need not be preceded with ‘&’ sign.
c)The control string ad the variables must match in their order.
d)The control string must be in quotations and there we can also use any other text to print with data.
e)Print special messages wherever required in output.
Syntax printf(“control string”,var1,var2,…varn);
Description Control string is one of the following:a)Format code characterb)Execution characterc)Characters/String will be displayed
Example printf(“Result is…%d”,n);printf(%f”,f);Printf(“%s”,s);
CONTROL STRUCTURE
When a program is given to a computer, it carries out the instructions in the sequential order. This is called the normal flow of control.The C statements used to change the control flow are called thee C control statements or control structures.The following control structures:
Logical IF structureIF-ELSE structureNested if…else statementIf…else ladderUnconditional GOTO statementSwitch structure
Logical IF Structure
The logical IF statement is a decision making statement. It is used to control the flow of execution of the statements and also used to test logically the condition is true or false.
Syntax
if(condition is true)
{
true statements;
}
Where
condition->is a logical condition
statement->executable statement
Properties of an If statement:
1.If the condition is true, then the simple or compound condition statements are executed.
2.If the condition is false, it does not do any thing.
3.The condition is given in parenthesis and must be evaluated as true(non-zero value) or false(zero value)
4.If a compound structure is provided, it must be enclosed in opening and closing braces.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int x=10,y;
clrscr();
if(x==10)
printf("TRUE");
getch();
}
If-else statementIt is used to control the flow of execution and also used to carry out the logical test then pickup one of the two actions depending on the logical test.
Syntax:
if(condition)
{
True statement;
}
else
{
False statement;
}
#include<stdio.h>
#include<conio.h>
void main()
{
int num,rem;
clrscr();
printf(“Enter your number:”);
scanf(“%i”,&num);
rem=num%2;
if(rem==0)
printf(“The entered number is even.”);
else
printf(“The entered number is odd.”);
}
Nested if…else statement: When series of if…else statements are occurred in a program entire if…else statement in another if…else statement called nesting,& the statement is called nested if.
if(condition 1)
{
if(condition 2)
{
True statement2;
}
else
{
False statement2;
}
}
else
{
False statement1;
}
Condition1
Condition2
False statement 1
True statement2 False statement2
F
T
T F
if…else Ladder: Nested if statements can become quite complex. If there are more than three alternatives & indentation.
Syntax:if(condition 1)
{
statement 1;
}
else if(condition 2)
{
statement 2;
}
else if(condition 3)
{
statement 3;
}
else
{
default-statements;
}
Condition 1
Condition 2
Condition 2
Statement 1
Statement 2
Statement 3 Default statement
T F
T F
T F
goto statement
C Provides the goto statement to transfer control unconditionally from one place to another place in the program.A goto statement can cause program control almost anywhere in the program unconditionally.The goto statement requires a label to identify the place to move the execution.A label is a valid variable name and must be ended with colon(:).
Syntax:
goto label; label:
…… …….
…… …….
label: goto label;
Example:#include<stdio.h>void main(){ int a,b; printf(“\n Enter the number”); scanf(“%d %d”,&a,&b); if(a==b) goto equal; else { printf(“\n A and b are not equal”); exit(0); }equal: printf(“A and B are equal”);}
switch statement
The switch statement is used to pickup or execute a particular group of statements from several available group of statements.It is multiway decision statement it test the value of given variable or expression a list of case values & when a match is found, a block of statements associated with case is executed.
Syntax:
switch(expression)
{
case label1:
statements;
break;
case label2:
statements;
break;
default:
statements;
break;
}
Rules for writing switch() statement
1.The expression in switch statement must be an integer value or a character constant.
2.No real numbers are used in an expression.
3.Each case block and default blocks must be terminated with break statements.
4.The default is optional and can be placed anywhere, but usually placed at end.
5.The case keyword must terminate with colon(:).
6.No two case constants are identical.
7.The case labels must be constants.
8.The value of switch expression is compared with the case constant expression in the order specified.
9.In the absence of break statement, all statement that are followed by matched by matched cases are executed.
Example:
#include<stdio.h>
void main()
{
int a=1;
switch(a)
{
case 1:
printf(“I am in case 1 \n”);
break;
case 2:
printf(“I am in case 2 \n”);
break;
case 3:
printf(“I am in case 3 \n”);
break;
}
}
Comparison of switch() case and Nested if
Switch() Case nested if
The switch() can test only constant values.
The if can evaluate relational or logical expression
No two case statement have identical constants in the same switch.
Same conditions may be repeated for number of times
Character constants are automatically converted to integers.
Character constants are automatically converted to integers.
In switch() case statement nested if can be used.
In nested if statements, switch case can be used.
Branching and LoopingRepeat a set of instructions in specified number of times or until a particular condition is statified.This reparation is known as Looping.The loop in a program consists of 2 parts:
1.body of the loop
2.Control statementThe control statement is used to test a condition and the body of the loop executed repeatedly.In C there are 3 looping constructs:
1.for loop2.while loop3.do…while loop
while loopIn while, used to execute the statements within the body until the condition becomes false.The while loop statement, the condition is evaluated first if it is true, the body of the loop evaluated. The process is repeated until the test condition false, then the control is transferred out of the loop.
Condition True statement
T
F
Syntax
while(text expression)
{
sequence of statements;
}
Example: /* Addition of numbers upto 10 using while loop
#include<stdio.h>
void main()
{
int i=1,sum=0;
while(i<10)
{
sum=sum+i;
i++;
printf(“The sum of numbers upto 10 is %d”,sum);
}
do…while loop“do-while” is an exit control loop statement i.e., condition is tested only after executing a loop. In some situations it may be necessary to execute the body of the loop before the test condition is performed, in such a situation do…while loop is useful.
Syntax:
do
{
body of the loop;
}while (condition);
Body of the loop
Condition
T
F
/*Addition of numbers using do…while loop */
#include<stdio.h>
void main()
{
int i=1,sum=0;
do
{
sum=sum+i;
i++;
}while(i<10);
printf((“The sum of numbers upto 10 is %d”,sum);
}
/* Program to print n numbers using do…while loop */#include<stdio.h>
#include<conio.h>
void main()
{
int i,n;
printf(“Enter the number”);
scanf(“%d”,&n);
i=0;
do
{
printf(“the number are %d \n”,i);
i=i+1;
}
while(i<n);
}
Comparison between while and do while statements.
while do…while
This is the top tested loop This is the bottom tested loop
The condition is first tested, if the condition is true then the block is executed until the condition becomes false.
It executes the body once, after it checks the condition, if it is true the body is executed until
the condition
Loop will not be executed if the condition is false.
Loop will be executed atleast once even though the condition
is false.
for loop
The for loop is another repetitive control structure. and is used to execute set of instructions repeatedly until the condition becomes false.
The assignment,incrementation or decrementation and condition checking is done in for statement only, where other control structures are
Syntax:
for(initialization; text-expression; updation)
{
statements;
}
1.Initialization statement is executed.
2.Test-expression is evaluated.
3.If the test-expression evaluates to true, the statements in the body of the loop would get executed.
4.Control goes to the updation statement, the updation statement is executed, which changes the value of the loop variable.
5.Test-expression is again evaluated.
6.If it evaluates to true, again the statements in the body of the loop would get executed.
7.Conrol once again goes back to the updation statement, which updates the looping variable.
The sequence is repeated as long as the test-expression to true. Once the test-expression evaluates to false, the loop is exited and the control is transferred to the first statement following the looping construct.
/* To find sum of N natural numbers using for-loop */
#include<stdio.h>
void main()
{
int n,i,sum;
printf(“Enter a number \n”);
scanf(“%d”,&n);
sum=0;
for(i=1;i<=n;i++)
sum+=i;
printf(“Sum=%d \n”,sum);
}
/* To Print numbers from 1 to 10 and their squares */
#include<stdio.h>
void main()
{
int i;
printf(“Number \t Squares \n”);
for(i=1;i<=10;i++)
printf(“%d \t\t %d \n”,i*i);
printf(“\n Press any key to continue”);
}
Nested Loops
Any loop can be placed within another loop. Such loops are called nested loops.
Rules for implementing the nested for loop:
1.Each loop should have a unique index variable.
2.The loops should not overlap each other.
3.The loops should be completely embedded within each other.
4.The loop can have any number of exit points inside the range, but should not permit entry to it.Syntax:
for(initialization; text-expression; updation)
{
for(initialization;text-expression;updation)
{
statements;
}
statements; }
/* Program for Pascaline triangle */
#include<stdio.h>
void main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("%d\t",i);
}
printf("\n\n");
}
}
Comma OperatorThe (,).comma operator is used primarily in association with the ‘for’ statement. This operator permits two different expressions to appear .Two or more variables van be initialized and used in the ‘for’ statement using a comma operator.
Syntax 1:
for(expression1a,expression1b;expression2;expression3)
{
statements;
}
where expression1a and expression1b are two expressions separated by the comma operator. These two expressions initialize two separate indices that would be simultaneously used within the for loop.
/* Program prints the numbers from 1 to 10 and 10 to 1 */
void main()
{
int a,b;
for(1=1,b=10;a<=10;a++,b--)
printf(“a=%d,b=%d”,a,b);
}
Syntax 1:
for(expression1;expression2;expression3a,expression3b)
{
statements;
}
where expression 3a and expression 3b separated by the comma operator.
/* Program for print numbers from 1 to 10 */
#include<stdio.h>
void main()
{
int a,b;
for(a=0,b=10;a!=b;a++,b--)
printf(“a=%d,b=%d”,a,b);
}
break statementThe break statement is used to terminate loops or exit from a switch.It can be used within a do-while,for and switch statement.When used within a switch-case statement, control is transferred to the end of the construct.
Example:#include<stdio.h>
void main()
{
int x=1;
while(x<=10)
{
printf(“x=%d \n”,x);
if(x==5)
break;
x++;
} }
Continue StatementThe continue statement can be used to skip the rest of the body of an iterative loop.
Syntax:
continue;
The continue statement can be included only in a while,do-while or for statement. It is simply written as continue.
/* To print odd numbers using coninue statement */
#include<conio.h>
void main()
{
unsigned x;
x=0;
clrscr();
while(x<10)
{
++x;
if(x%2==0)
{
continue;
}
printf("%i is an odd number. \n",x);
}
}
Difference between While-loop & Do-while-loop
While-Loop Do-While Loop
Entry-Controlled Loop Exit-Controlled Loop
Loop Condition has to be initiallyTRUE for body to be executed.
Loop body will be executed at-least once
If the condition is false then the statement block will not be executed even once.
In the test condition is false then the statement block will be executed at least once.
Syntax : exp1; while(exp2) { statement... statement... exp3 }
Syntax : do { statement... statement... } while(condition);
The semicolon is not necessary after the test condition.
The semicolon is must after the test condition.
Library Functions Library functions are also known as pre-defined functions (or) build-
in functions.Pre-defined functions are functions not to be written by the programmer.
A library function is accessed simply by writing the function name, followed by a list of arguments. The arguments must be enclosed in parentheses.
A library function can be categorized with 4 types:
1.Mathematical functions
2.Character functions
3.Input and Output functions
4.String functions
Mathematical functions:
In C Programming mathematical functions reside in math.h header files.
Function Description Example
pow() This function is used to compute the x raised to y.Syntax: pow(x,y)
pow(3,4)=64
sin() It is used to find the sine of angle in radians.Syntax: sin()
sin(30)=0.5
cos() It is used to find the cosine value of angle in radians.Syntax: cos()
cos(30)=0.866
tan() It is used to compute the tangent value of angle in radians.Syntax: tan()
tan(30)=0.577
exp() This function computes the exponent value of x.Syntax: exp()
exp(30)=1.6876
Function Description Example
sqrt() It is used to compute the square root value of x.
sqrt(25)=5
abs() It is used to find the absolute value of a number as an integer.
abs(-15)=15abs(15)=15
ceil() This function is used to return the smallest integer valued greater than or equal to x.
ceil(15.99)=16ceil(15.01)=16
floor() This function is used to returns the greatest integer value lesser than or equal to x.
floor(15.99)=15floor(15.01)=15
log10() This function return the logarithms to the base 10 of x.
log10(10)=1
Example:
#include<stdio.h>
#include<math.h>
void main()
{
printf(“pow(4,3)=%f”,pow(4,3));
printf(“sin(30)=“%f”,sin(30*3.14/180.0));
printf(“sqrt(25)=%f”,sqrt(25));
printf(“abs(-15)=%d”,abs(-15));
printf(“ceil(15.99)=%f”,ceil(15.99));
printf(“floor(15.99)=%f”,floor(15.99));
printf(“log10(10)=%f”,log10(10));
}
Character functions:
In C Programming character functions reside in ctype.h header files.
Function Description Example
isalnum() This function is used to check whether a character is an alphanumeric(i.e A to Z or a to z) or (0 to 9).
isalnum(‘a’)=True(True means non zero value).isalnum(‘&’)=False
isalpha() This function is used to test whether the given character is alphabetic character or not.
isalpha(‘a’)=True(1)isalpha(‘5’)=False(0)
isdigit() This function is used to check whether or not it is a digit(0 to 9).
isdigit(‘9’)=Trueisdigit(‘a’)=False
islower() This function is used to check whether the given character is lower case or not(a to z).
islower(‘a’)=Trueislower(‘A’)=False
isupper() This function is used to check whether the given character is uppercase letter or not(A to Z).
isupper(‘a’)=FalseIsupper(‘A’)=True
Function Description Example
isspace() This function is used to check whether a given character is white space or not.
isspace(‘ ‘)=TrueIsspace(‘a’)=False
isascii() This function is used to test if the parameter is between 0 to 127.
isascii(97)=TrueIsascii(200)=False
tolower() If the character is an uppercase character(A to Z),then it is converted to lower case.
Tolower(‘a’)=A
toupper() If the character is an lower case character(a to z),then it is converted to upper case(A to Z).
toupper(‘a’)=A
toascii() This function is used to convert the character to its equivalent ascii value.
toascii(‘A’)=65toascii(‘a’)=97
Example:
#include<stdio.h>
#include<ctype.h>
void main()
{
printf(“isalnum(‘a’)=%d”,isalnum(‘a);
printf(“isalpha(‘a’)=%d”,isalpha(‘a’));
printf(“isdigit(‘9’)=%d”,isdigit(‘9’));
printf(“isupper(‘a’)=%d”,isupper(‘a’));
printf(“isspace(‘’)=%d”,isspace(‘’));
printf(“isascii(97)=%d”,isascii(97));
printf(“tolower(‘A’)=%c”,tolower(‘A’));
printf(“toupper(‘a’)=%c”,toupper(‘a’));
printf(“toascii(‘A’)=%d”,toascii(‘A’));
}
Input/Output functions: In C Programming character functions reside in stdio.h header files. The functions are scanf,printf,putc,getc.
String functions: In C Programming string functions reside in string.h header files. The following string manipulations are,
1.String Copy(strcpy) function
2.String Lengrh(strlen) function
3.String Concatenation(strcat) function
4.String Compare(strcmp) function
5.String Reverse(strrev) function
6.String Upper(strupr) function
1.String Copy(strcpy) function
This function is used to copy the content of one string into another string.
Syntax
strcpy(string1,string2);
Where,
Here,the contents of the string str2 is copied into the string str1
The str2 remains unchanged.
Example:
#include<stdio.h>
#include<string.h>
void main()
{
char name[20];
strcpy(name,"Vels University");
puts(name);
}
2.String Lenth(strlen) functionThis function is used to find out the number of characters in the given string.
Syntax
n=strlen(str);
where, n-is an integer variable which receives the length of string
str-valid string variable or constant.
Example:
#include<stdio.h>
#include<string.h>
void main()
{
char a[100];
int length;
printf(“Enter a string to calculate it’s length”);
gets(a);
length=strlen(a);
printf(“Length of entered string is=%d \n”,length);
}
3.String Concatenation(strcat) function
This function is used to join two strings.
Syntax: strcat(str1,str2)
This function is executed, the contents of str2 are joined with str1 and the character ‘\0’ is placed at the end of the new string str1.The string str2 remains unchanged.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[30],str2[10];
printf(“Enter string1 \n”);
gets(str1);
printf(“Enter string2 \n”);
gets(str2);
strcat(str1,str2);
printf(“Sting1=\n”);
puts(str1); }
4.String Compare(strcmp) function
This function strcmp() is used to compare two strings.
Syntax:
strcmp(str1,str2);
IF the two strings str1 and str2 are equal then the value of the function returns the value zero. If str1 is greater than str2 the function returns positive integer else it returns negative integer.
Example:
#include<stdio.h>
#include<string.h>
void main()
{
char word1[20],word2[20];
int i;
printf(“Enter the first string \n”);
scanf(“%s”,word1);
printf(“Enter the second string \n”);
scanf(“%s”,word2);
if(i==0)
printf(“The words are identical \n”);
else
printf(“Words are not identical \n”);
}
5.String Reverse(strrev) functionThis function is used to reverse a string.
Syntax
strrev(str);
#include<stdio.h>
void main()
{
char s1;
printf(“Enter the string:”);
gets(s1);
strrev(s1);
printf(“\n The reversed string is..%s”,s1);
}
6.String Upper(strupr) functionThis function is used converts S to all uppercase characters.
Syntax
strupr(str);
Example
#include<stdio.h>
void main()
{
char s1;
printf(“\n Enter the string1 in lower case or in combination of upper
lower case:\n”);
gets(s1);
strupr(s1);
printf(“\n The entered string is..%s”,s1);
}
TokensA token is an entity in a program. Whenever the program is submitted for compilation,te compiler identifies and splits the program into a sequence of tokens.A token may be a single character and a set of characters with a specific meaning.The following are tokens available in ‘C’.
1.Keyword
2.Constants
3.Identifiers
4.Punctuation symbols(separators)
5.Operators
Top Related