0% found this document useful (0 votes)
31 views48 pages

C Launguage 2 Unit

The document discusses different types of operators in C including arithmetic, relational, logical, assignment, and increment/decrement operators. It explains the meaning and usage of each operator type with examples and covers concepts like operator precedence and associativity.

Uploaded by

Manda Vaishnavi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views48 pages

C Launguage 2 Unit

The document discusses different types of operators in C including arithmetic, relational, logical, assignment, and increment/decrement operators. It explains the meaning and usage of each operator type with examples and covers concepts like operator precedence and associativity.

Uploaded by

Manda Vaishnavi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 48

Unit-2

Operators & Expressions: C operators and expressions, Type-conversion methods, Operators


Precedence and Associativity.
Operator specifies which operation we need to perform.
Operands are the values that we perform operation on those values.

Precedence:
If there is more than one operator in an expression, which operation we need to perform first
is specified by precedence.

Associativity:
If more than one operator has the same precedence which operation we need to perform is
specified by associativity.

Types of operators based on number of operands:


We have three types of operators
1. Unary Operators – require one operand.
2. Binary Operators- require two operands.
3. Ternary Operators – require three operands.

• An operator is a symbol that tells the compiler to perform certain mathematical or


logical manipulations.
• Operators are used in programs to manipulate data and variables.
• They usually form a part of the mathematical of logical expressions.

'C' operators can be classified into 8 categories.


1. Arithmetic operators.
2. Relational operators.
3. Logical operators.
4. Assignment operators.
5. Increment and decrement operators.
6. Conditional operators.
7. Bitwise operators.
8. Special operators.

Arithmetic operators:

'C' provides all the basic arithmetic operators.


Rao’s Degree and PG College Page |1
M.Vaishnavi
Operator Meaning
+ Addition or Unary plus
- Subtraction or Unary minus
* Multiplication
/ Division
% Modulo division
Unary minus example: -2, 2*-1

Note: Modulo division operator (%) is used only for integral values and cannot be used on
floating point data.

*, /, % ------ highest precedence


+, - ------ lowest precedence

Arithmetic operator’s associativity is from Left to Right.

i. In integer arithmetic, all operands are integer.


Example: 15/4=3 ii. In real arithmetic,
all operands are real.
Example: 15.0/4.0=3.75 iii. In mixed mode arithmetic, one operand is real and another
operand is integer then that expression is called mixed mode arithmetic.

If either operand is of the real type, then only the real operation is performed and the result is
always a real number.
Example: 15.0/4=3.75 or
15/4.0=3.75

Example program:
#include<stdio.h> main()
{
int a,b;
floatc,d;
printf("enter 2 integer values\n");
scanf("%d%d",&a,&b);
printf("enter 2 float values\n");
scanf("%f%f",&c,&d);
printf("Integer Arithmetic %d/%d=%d\n",a,b,a/b);
printf("real Arithmetic %f/%f=%f\n",c,d,c/d);
printf("Mixed mode Arithmetic %f/%d=%f\n",c,b,c/b);

Rao’s Degree and PG College Page |2


M.Vaishnavi
}

Relational operators:

• These operators are used to compare the quantities.


• These operators are used to identify the relation between quantities.

Operator Meaning
< is less than
<= is less than or equal
> is greater than
>= is greater than or equal
== is equal to
!= is not equal to

Form:

ae-1 relational operator ae-2

Where ae-1 and ae-2 are arithmetic expressions, which may be simple constants, variables,
or combination of them.

The expression containing a relational operator is termed as relational expression.


The value of the relational expression is either one or zero.
It is one if the specified relation is true and zero if the relation is false. Examples:
Relational Expression Result
10<20 1(true)
20<=10 0(false)
10>5 1(true)
10>=4 1(true)
10==10 1(true)
10!=10 0(false)

<, <=, >, >= ---------------- highest precedence


==,!= ---------------- lowest precedence

Relational expressions are used in decision statements such as, if and while to decide the
course of a running program.
Rao’s Degree and PG College Page |3
M.Vaishnavi
Arithmetic operators have a higher priority than relational operators. Associativity is
from Left to Right.

Example program:
#include<stdio.h> main()
{
int a,b; printf("enter a,b\n");
scanf("%d%d",&a,&b); printf("%d<
%d=%d\n",a,b,a<b); printf("%d<=%d=
%d\n",a,b,a<=b); printf("%d>%d=%d\
n",a,b,a>b); printf("%d>=%d=%d\
n",a,b,a>=b); printf("%d==%d=%d\
n",a,b,a==b); printf("%d!=%d=%d\
n",a,b,a!=b);
}
Logical operators:

Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT

The logical operators && and || are used when we want to test more than one condition and
make decisions.

The logical expression:

An expression which combines 2 or more relational expressions is termed as a logical or


compound relational expression.

Logical expression yields a value of one or zero, according to the truth table.

Truth Table:

op1 op2 op1 && op2 op1 || op2


Non-zero Non-zero 1 1
Non-zero 0 0 1
0 Non-zero 0 1
0 0 0 0
Rao’s Degree and PG College Page |4
M.Vaishnavi
Example program:
#include<stdio.h> main()
{
int marks,a,b;
printf("enter marks\n");
scanf("%d",&marks);
printf("enter 2 int values\n"); scanf("%d
%d",&a,&b);
printf("marks>=90 && marks<=100: %d\n",marks>=90 &&
marks<=100);
printf("a>=b || b>=a=%d\n",a>=b || b>=a);
printf("!a=%d\n",!a);
}
Local NOT ---------- highest precedence, Associativity from Right-> Left
Logical AND ------------- next highest precedence, Associativity from Left -> Right Logical
OR ------------- lowest precedence, Associativity from Left -> Right

Assignment operators:
Assignment operators are used to assign the result of an expression to a variable. Assignment
operator is '='.

Example: a=10;
Left hand side must be a variable; Right hand side may be a variable/constant or combination
of these two.

'C' has a set of 'shorthand' assignment operators of the form

v op=exp;

Where v is a variable, exp is an expression and op is C binary arithmetic operator.


The operator op=is known as the shorthand assignment operator. The
assignment statement vop= exp;
is equivalent to v
= v op (exp); Associativity is from Right to Left.

Statement with simple Statement with shorthand


assignment operator operator
a =a + 100 a += 100

Rao’s Degree and PG College Page |5


M.Vaishnavi
a = a - 20 a -= 20
a = a * (n+1) a *= (n+1)
a = a / (n+1) a /= (n+1)
a=a%b a %= b

The use of shorthand assignment operators has three advantages:


1. What appears on the left hand side need not be repeated and therefore it becomes
easier to write.
2. The statement is more concise and easier to read.
3. The statement is more efficient.

Example program:
#include<stdio.h> main()
{
int a,n;
printf("enter a,n values\n");
scanf("%d%d",&a,&n); a +=
100; printf("a=%d\n",a); a -=
20; printf("a=%d\n",a); a *=
(n+1); printf("a=%d\n",a);
a /= (n+1); printf("a=
%d\n",a); a %= n;
printf("a=%d\n",a);
}
Increment and Decrement operators:

• 'C' has two very useful operators not generally found in other languages.  These are
increment and decrement operators: ++ and --
• The operator ++ adds 1 to the operand.
• The operator -- subtracts 1 from the operand.
• Both are unary operators.
• We use the increment and decrement statements in for and while loops extensively.

Statement with
Meaning
Operator
++a Pre increment
a++ Post increment
--a Pre decrement
a-- Post decrement
Rao’s Degree and PG College Page |6
M.Vaishnavi
• Both ++a and a++ mean the same thing when they form statements independently.
• They behave differently when they are used in expressions on the R.H.S. of an
assignment statement.

Statement with
Operator used in Meaning Explanation
assignment
First adds1 to a and then the
b = ++a Pre increment
result is assigned value of a to b
First assigns the value of a to b
b = a++ Post increment
and then add 1 to a
First subtracts 1 to a and then the
b = --a Pre decrement result is assigned value of a
to b
First assigns the value of a to b
b = a-- Post decrement
and then subtract 1 to a

Associativity is from Right -> Left.

Example Program:
#include<stdio.h> main()
{
int a,n;
printf("enter a value\n");
scanf("%d",&a); n=a++;
printf("a=%d\tn=%d\n",a,n);
n=++a;
printf("a=%d\tn=%d\n",a,n); n=a--;
printf("a=%d\tn=%d\n",a,n); n=--a;
printf("a=%d\tn=%d\n",a,n);
}
Output:
enter a value
4 a=5 n=4
a=6 n=6 a=5
n=6 a=4 n=4

Conditional operator:

Rao’s Degree and PG College Page |7


M.Vaishnavi
A ternary operator pair "?:"is available in C to construct conditional expressions. Form is
exp1 ? exp2 : exp3;

Where exp1, exp2, exp3 are expressions.


Working of conditional operator "?:" :
i. exp1 is evaluated first. If it is non-zero (true), then the expression exp2 is evaluated
and that is the value of the expression.
ii. If exp1 is zero (false), exp3 is evaluated and it is the value of the expression iii.
Note that only one of the expressions (either exp2 or exp3) is evaluated.

Example:
int a=10, b=15, x; x=(a<b) ?
a : b;

Here, (10<15) evaluates to True, then x=a=10

Result:
x=10
Associativity is from Right -> Left.

//Program to find whether the given number is even or odd using conditional operator
#include<stdio.h> main()
{ int n;
printf("enter n value\n"); scanf("%d",&n);
(n%2==0)?printf("%d is even number\n",n):printf("%d is odd number\n",n);
}

Output 1: enter n
value
4
4 is even number

Output 2: enter n
value
5
5 is odd number

Example: #include<stdio.h>
main()
{

Rao’s Degree and PG College Page |8


M.Vaishnavi
float a,b,c,d; printf("enter a,b,c,d
values\n"); scanf("%f%f%f
%f",&a,&b,&c,&d);
(c-d!=0)?printf("%f",(a+b)/(c-d)):printf("c-d is 0");
}

Output 1:
entera,b,c,d values
3
4
5
2
2.333333 Output 2:
entera,b,c,d values
3
4
5 5 c-d is
0

Bitwise operators:

• For manipulation of data at bit level, a special operators known as bitwise operators
are introduced.
• These operators are used for testing the bits or shifting them right or left.
• Bitwise operators may not be applied to float or double.

Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
<< Shift Left
>> Shift Right
~ One’s Complement

Truth table for Bitwise AND, Bitwise OR and Bitwise Exclusive OR:

op1 op2 op1 & op2 op1 | op2 op1 ^ op2


1 1 1 1 0
1 0 0 1 1

Rao’s Degree and PG College Page |9


M.Vaishnavi
0 1 0 1 1
0 0 0 0 0

Truth table for Bitwise NOT:


op1 ! op1
1 0
0 1

Bitwise AND (&):

Example 1:
x=9
y=7
First convert given decimal number to binary number and then perform bitwise operation.

x=1001 y=0111
---------- z=
0001

Next convert the binary number to decimal number to get final result

z = 9 & 7=1

Example2:

x=4
y=14

x=0100 y=1110
----------
z=0100 = 4

z = 4 & 14=4

Bitwise OR (|):

Rao’s Degree and PG College P a g e | 10


M.Vaishnavi
Example 1:
x=8
y=7
First convert given decimal number to binary number and then perform bitwise operation.

x=1000 y=0111
----------
z=1111

Next convert the binary number to decimal number to get final result

z = 8| 7=15

Example2:

x=4
y=14

x=0100 y=1110
----------
z=1110 = 14
z = 4 | 14=4

Bitwise Exclusive-OR (^):

Example 1:
x=5
y=7
First convert given decimal number to binary number and then perform bitwise operation.
x=101 y=111
---------- z=010
Next convert the
binary number to
decimal number
to get final result

z = 5 ^ 7=2

Example2:

Rao’s Degree and PG College P a g e | 11


M.Vaishnavi
x=4
y=14

x=0100 y=1110
----------
z=1010 = 10

z = 4 ^ 14=4

Bitwise Complement Operator (~):

Example 1:
Find complement of 5 (~5)

Step1:
Convert decimal 5 into binary and take 8 bits.
0000 0101
First perform bits complement means change 1’s as 0’s and 0’s as 1’s (1’s complement).

1111 1010
MSB LSB

Step2:
If the MSB bit of result of bits complement is 1, then the final result contains –ve sign.
Always negative numbers in the system are represented using 2’s complement form.

Finding 2’s complement means 1’s complement + 1.

0000 0101 ------------- 1’s complement


+1 (in binary addition 1+1 = 10 means 1 as carry and 0 as sum)
--------------
0000 0110 ------------- 6

Therefore final result is -6

Note:
(In binary addition 1+1 = 10 means 1 as carry and 0 as sum, 1+0=1, 0+0=0)

Example 2:
Find complement of -5 (~-5)

Rao’s Degree and PG College P a g e | 12


M.Vaishnavi
Step1:
Always negative numbers in the system are represented using 2’s complement form.

First take +5 in binary form, find 2’s complement of that number.

0000 0101
1111 1010
+1
--------------
1111 1011 ------------- -5 binary equivalent

Step2:

Perform bits complement (1’s complement) on step1 result.


0000 0100 ------------- 4
If the MSB bit of the result contains 0, then the resulting number have the + sign. (~-5)=+4

Bitwise Shift operators:

The shift operators are used to move bit patterns either to the left or to the right.

Left shift: v << n


Right shift: v >> n

Where v is the integer expression (value) that is to be shifted and n is the number of bit
positions to be shifted.

Left shift:
Left shift means given number multiply by 2 per each shift.
Example:
6<<1 or x=6, x<<1
First convert decimal 6 to binary and take 8 bits.
MSB LSB
87654321
0000 0110

0000 0 110
87654321

Rao’s Degree and PG College P a g e | 13


M.Vaishnavi
Here, 12345678 are bit positions for understanding purpose.
• First move 1stbit as 2ndbit, 2nd bit as 3rdbit, 3rd bit as 4th bit, 4th bit as 5th bit, 5th bit as
6thbit, 6th bit as 7th bit, 7th bit as 8th bit.
• Here, 1st bit is empty, make it as 0. Remove 8th bit because it position exceeds 8 bit
positions.

0000 1110
87654321

This is the final bit result. Convert binary to decimal and it is equal to decimal 12.
6 << 1 = 12

Special operators:

C supports some special operators of interest such as:


i. Comma operator (,)
ii. sizeof operator
iii. pointer operators (&, *) iv. member selection operators (., ->)
v. function call symbol ()
vi. array subscript operator []

Comma operator:
• This can be used to link the related expressions together.
• Comma liked lists of expressions are evaluated from left to right. And the value of
right most expression is the value of the combined expression.
• Comma operator has the lowest precedence of all operators, the parenthesis are
necessary.

Example:

value=(x=10, y=5, x+y) Therefore


value=15.

The sizeof operator:

• The sizeof operator is a compile time operator.


• When used with an operand, it returns the number of bytes the operand occupies.
• The operand may be a variable, a constant or a data type qualifier.
• This is normally used to determine the lengths of arrays and structures.

Rao’s Degree and PG College P a g e | 14


M.Vaishnavi
& ------- address operator or reference operator, it is unary operator.
* -------- dereference operator or pointer reference or indirection operator.

Expressions:

Arithmetic expressions:

An arithmetic expression is a combination of variables, constants, and operators arranged as


per the syntax of the language.

Examples:

Algebraic expression C expression


a×b–c a*b-c
(m + n)(x + y) (m+n)*(x+y)
ab
a*b/c
c
2
3x +2x+1 3*x*x+2*x+1
x
+c x/y+c
y

Evaluation of expressions:
Expressions are evaluated using an assignment statement.

variable = expression
Where variable is any valid 'C' variable name.
Example:
a=9, b=12, c=3 x = a – b / 3 + c *
2 – 1 x = 9 – 12 / 3 + 3 * 2 – 1

Here, /, * having the same priority and highest priority, so follow the associativity, it is Left -
> Right.

Step1: evaluate 12 / 3 = 4

x=9–4+3*2–1

Step 2: evaluate 3 * 2 = 6

Rao’s Degree and PG College P a g e | 15


M.Vaishnavi
x=9–4+6–1

Next, -, + having the same priority, so follow the associativity, it is from Left -> Right.

Step3: 9 – 4 = 5

x=5+6–1

Step4: 5 + 6 = 11

x = 11 – 1

Step5: 11 – 1 = 10

Finally x = 10

Type conversion:

char
shortint int
longint float
double
long double

Conversion of small data type to big is broadening.


Conversion of big data type to small is narrowing.
(small and big in terms of number of bytes)

Conversions are of two types:


1. Implicit type conversion
2. Explicit type conversion

Implicit type conversion:

• Computer considers one operator at a time, involving 2 operands.


• If the operands are of different types, the ‘lower’ type is automatically converted to the
‘higher’ type before the operation proceeds.
• The result is of the ‘higher’ type.
• The final result of an expression is converted to the type of the variable on the left of
the assignment sign before assigning the value to it.

Rao’s Degree and PG College P a g e | 16


M.Vaishnavi
• The following rules are followed:
i. float to int causes truncation of the fractional part.
ii. double to float causes rounding of digits.
iii. longint to int causes dropping of the excess higher order bits.

Example:
#include<stdio.h> main()
{
int a;
floatb,c;
printf("enter a,b values\n");
scanf("%d%f",&a,&b); c=a/b;
printf("c=%f\n",a/b);
}
Output:
entera,b values
4
5
c=0.800000
Explicit type conversion or casting a value:
For example,
#include<stdio.h> main()
{
int a,b;
float c;
printf("enter a,b values\n");
scanf("%d%d",&a,&b); c=a/b;
printf("c=%f\n",a/b);
}
Output:
entera,b values
4
5
c=0.000000
Consider the statement c=a/b;
• Here a, b are integer data type, so integer division is performed. The result of this
division is 0. So, the decimal part of the division would be lost and the result is not
correct.
• This problem can be solved by converting locally one of the variables to the floating
point.

Rao’s Degree and PG College P a g e | 17


M.Vaishnavi
c=(float)a/b;

• The operator (float) converts the 'a' to floating point for the purpose of evaluation of
the expression.
• Then automatically conversion is done and then the division is performed in floating
point mode.
• This process of such a local conversion is known as casting a value.
• Form is

(type name) expression

Where type name is one of the valid ‘C’ data types and the expression may be a constant,
variable or an expression.

// Example program using explicit type conversion


#include<stdio.h>
main()
{
int a,b;
float c;
printf("enter a,b values\n");
scanf("%d%d",&a,&b); c=(float)a/b;
printf("c=%f\n",c);
}
Output:
enter a,b values
4
5
c=0.800000

Usage of type conversion:

Example Action
x = (int) 4.78 4.78 is converted to integer by

Rao’s Degree and PG College P a g e | 18


M.Vaishnavi
truncation and result would be 4
Evaluated as 13/4 and the result
a=(int)13.4/4
would be 3
Division is done in floating point
d=(double)12/5
mode and result would be 2.400000

Operators Precedence and Associativity Table:


Operator Description Associativity Rank
() Function call
Left to Right 1
[] Array element reference
+ Unary plus
- Unary minus
++ Increment
-- Decrement
! Logical NOT
Right to Left 2
~ Ones complement
* Pointer reference (indirection)
& Address
sizeof Size of an object
(type) Type cast (conversion)
* Multiplication
/ Division Left to Right 3
% Modulo division (modulus)
+ Addition
Left to Right 4
- Subtraction
<< Left Shift
Left to Right 5
>> Right Shift
< Less than
<= Less than or equal to
Left to Right 6
> Greater than
>= Greater than or equal to
== ! Is equal to
Left to Right 7
= Not equal to
& Bitwise AND Left to Right 8
^ Bitwise XOR (Exclusive OR) Left to Right 9
| Bitwise OR Left to Right 10
&& Logical AND Left to Right 11
|| Logical OR Left to Right 12
Rao’s Degree and PG College P a g e | 19
M.Vaishnavi
?: 13
=
*=, /=,
%= +=, -=
Assignment operators Right to Left 14
&=, ^=, |
=
<<=, >>=
, Comma operator Left to Right 15

C Arithmetic Operators Precedence


When multiple arithmetic operators are used in a C expression, their precedence
determines the order in which they are evaluated. This is crucial for understanding
how an expression's result is computed.

Rules and Examples of C Arithmetic Operators Precedence


The precedence rules for C arithmetic operators are as follows:

1. Operators within parentheses are evaluated first.


2. Unary operators (++ and --) have higher precedence than other arithmetic
operators.
3. Multiplication, division, and modulus operators have higher precedence than
addition and subtraction operators.
4. If operators have the same precedence, they are evaluated from left to right.

Consider the following example to understand these precedence rules:

#include

int main() {
int a = 10, b = 20, c = 5, result;

result = a + b * c / 2;
printf("Result: %d\n", result);

Rao’s Degree and PG College P a g e | 20


M.Vaishnavi
return 0;
}
In this example, the expression is evaluated as follows:

1. b * c is executed: 20 * 5 = 100
2. The result is divided by 2: 100 / 2 = 50
3. The result is added to a: 10 + 50 = 60

So, the final result is 60, following the precedence rules mentioned above.
Understanding the precedence of C arithmetic operators is essential for accurate and
efficient calculations in your programs.

C Arithmetic Operations - Key takeaways

 C Arithmetic Operations: Allow mathematical calculations in C programming.


 Arithmetic Operators in C: Symbols used for basic and advanced mathematical
operations on data.
 Hierarchy of Arithmetic Operations in C: Determines the order in which
operations are executed, following a conventional hierarchy.
 Pointer Arithmetic Operations in C: Involves manipulating pointer values with
arithmetic operators, allowing calculations on memory addresses directly.
 C Arithmetic Operators Precedence: Determines the order in which multiple
arithmetic operators are evaluated following specific rules.

Rao’s Degree and PG College P a g e | 21


M.Vaishnavi
Managing Input and Output operations

Constructs for getting input Constructs for displaying output


1)scanf( ) 1)scanf( )
2)putchar() 2)getchar()
3)puts() 3)gets( )

4) getche( )

5) fgets( ) 4)fputs( )
6)fscanf( ) 5)fprint( )

C Input and Output

Input means to provide the program with some data to be used in the program

Output means to display data on screen or write the data to a printer or a file.

1. Single character input and output[getchar( ) and putchar()]

 input- getchar()
 output- putchar()

The int getchar(void) function reads the next available character from the screen and returns it as an
integer. This function reads only single character at a time.

The int putchar(int c) function puts the passed character on the screen and returns the same
character. This function puts only single character at a time.

program
#include <stdio.h> int main( )
{
int c;
output $./a.out
Enter a value : this is DS class
printf( "Enter a value :"); c = You entered: t
getchar( );

printf( "\nYou entered: "); putchar( c


);

return 0;
}

2. String input and output[gets() and puts()

Rao’s Degree and PG College P a g e | 22


M.Vaishnavi
 Input--- gets (str)
 Output---puts (str)

The gets( ) function reads a line from stdin into the buffer pointed to by s until either a terminating
newline or EOF (End of File).

The puts( ) function writes the string 's' and 'a' trailing newline to stdout.

Program

#include <stdio.h> int main( ) { char Output


str[100];
$./a.out
printf( "Enter a value :"); gets( str ); Enter a value : this is DS class
printf( "\nYou entered: "); puts( str ); You entered: this is DS class
return 0;

3. Formatted Input [ scanf ( ) ] and Formatted Output [ printf ( ) ]


Specifier Meaning
%c – Print a character
%d – Print a Integer
%i – Print a Integer
%u-- Unsigned int
%ld-- Long int
%e – Print float value in exponential form.
%f – Print float value
%g – Print using %e or %f whichever is smaller %lf --
Double
%lf-- Long double
%o – Print octal value
%s – Print a string
%x – Print a hexadecimal integer (Unsigned) using lower case a – f %X –
Print a hexadecimal integer (Unsigned) using upper case A – F %a – Print a
unsigned integer.
%p – Print a pointer value
%hx – hex short

scanf()
scanf() is a predefined function in "stdio.h" header file. It can be used to read the input value from the
keyword.
Syntax of scanf() function
1. & ampersand symbol is the address operator specifying the address of the variable
2. control string holds the format of the data
3. variable1, variable2, ... are the names of the variables that will hold the input value.

scanf("control string", &variable1, &variable2, ...);

Example

Rao’s Degree and PG College P a g e | 23


M.Vaishnavi
int a; float b;
scanf("%d%f",&a,&b);

Example

double d; char c;
long int l;
scanf("%c%lf%ld",&c&d&l);

o Printf
o Printf is a predefined function in "stdio.h" header file, by using this function, we can print the data or user defined
message on console or monitor. While working with printf(), it can take any number of arguments but
first argument must be within the double cotes (" ") and every argument should separated with comma
( , ) Within the double cotes, whatever we pass, it prints same, if any format specifies are there, then
value is copied in that place.

Program

#include <stdio.h> //This is needed to run printf() function.


int main()
{ printf("C Programming"); //displays the content inside quotation return 0;
}
Output
C Programming
Program(integer and float)
#include <stdio.h> #include
<conio.h> void main();
{ int a; float b;
clrscr();
printf("Enter any two numbers: "); scanf("%d
%f",&a,&b); printf("%d %f \n",a,b); getch();
}

Output: Enter any two numbers:10 3.5


10
3.5

Rao’s Degree and PG College P a g e | 24


M.Vaishnavi
Program
#include <stdio.h> int
main()
{

int integer = 9876; float


decimal = 987.6543;
printf("4 digit integer right justified to 6 column: %6d\n", integer); printf("4

digit integer right justified to 3 column: %3d\n", integer);

printf("Floating point number rounded to 2 digits: %.2f\n",decimal);

printf("Floating point number rounded to 0 digits: %.f\n",987.6543);

printf("Floating point number in exponential form: %e\n",987.6543);

return 0; Output

4 digit integer right justified to 6 column: 9876


4 digit integer right justified to 3 column: 9876
Floating point number rounded to 2 digits: 987.65
Floating point number rounded to 0 digits: 988
Floating point number in exponential form: 9.876543e+02

FILE INPUT and OUTPUT

4. File string input and output using fgets( )and fputs( )


The fgets() function
The fgets() function is used to read string(array
of fgets(char str[],int n,FILE *fp); characters) from the file.
Syntax

The fgets() function takes three arguments, first is the string read from the file, second is size of
string(character array) and third is the file pointer from where the string will be read.

Example
File*fp; Str[80];
fgets(str,80,fp)

Example
#include<stdio.h> void
main()
{
FILE *fp; char
str[80];

Rao’s Degree and PG College P a g e | 25 M.Vaishnavi


fp = fopen("file.txt","r"); // opens file in read mode (“r”)

hile((fgets(str,80,fp))!=NULL) printf("%s",str);
//reads content from file
fclose(fp);
}
Data in file...
C is a general-purpose programming language.
It is developed by Dennis Ritchie.

C is a general-purpose programming language.


It is developed by Dennis Ritchie.

Output :

The fputs() function


The fputs() function is used to write string(array of characters) to the file.

 The fputs() function takes two arguments, first is the string to be written to the file and
second is the file pointer where the string will be written. Syntax:
fputs(char str[], FILE *fp);
# int include < stdio.h >
main
()
{
FILE *fp;
fp = fopen("proverb.txt", "w+"); //opening file in write mode
fputs("Cleanliness is next to godliness.", fp); fputs("Better
late than never.", fp); fputs("The pen is mightier than the
sword.", fp); fclose(fp); return(0);
}
Output
Cleanliness is next to godliness.
Better late than never.
The pen is mightier than the sword.
4. File string input and output using fgets( )and
fputs( ) The fscanf() function
The fscanf() function is used to read mixed type(characters, strings and integers) form the file. The fscanf() function is
similar to scanf() function except the first argument which is a file pointer that specifies the file to be read. Syntax:
Example program

#include<stdio.h> fscanf(FILE *fp,"format-string",var-list);

void main()
{
FILE *fp; char ch;
int roll;
char name[25];

Rao’s Degree and PG College P a g e | 26 M.Vaishnavi


fp = fopen("file.txt","r"); printf("\n Reading from file...\n");
while((fscanf(fp,"%d%s",&rollno,&name))!=NULL) printf("\n %d\t
%s",rollno,name);//reading data fclose(fp);
}

Output :

Reading from file...


6666 keith
7777 rose

The fprintf() function:


 The fprintf() function is used to write mixed type(characters, strings and integers) in the file.
The fprintf() function is similar to printf() function except the first argument which is a file pointer
specifies the filename to be written. Syntax

fprintf(FILE *fp,"format-string",var-list);
Examp
le
progr am #incl
ude<s tdio. h>
void main()
{ FILE *fp; introll; char name[25]; Output fp =
fopen("file.txt","w"); scanf("%d",&roll);
scanf("%s",name); fprintf(fp,"%d%s%",roll,name); 6666 john
close(fp);
}

Rao’s Degree and PG College P a g e | 27 M.Vaishnavi


In C programming language the reading and writing characters are as follows −

 The simplest of the console I/O functions are getche (), which reads a character from the keyboard,
and putchar (), which prints a character to the screen.
 The getche () function works on until a key is pressed and then, returns its value. The key pressed is
also echoed to the screen automatically.
 The putchar () function will write its character argument to the screen at the current cursor position.
 The declarations for getche () and putchar () are −
int getche (void);
int putchar (int c);
 The header file for getche () and putchar () is in CONIO.H.
Example

Here is an example which reads characters from the keyboard and prints them in
reverse case. This means that the uppercase prints as lowercase and the lowercase
prints as uppercase.

The program halts whenever a period is typed. The header file CTYPE.H is required by
the islower() library function, which returns true if its argument is lowercase and false
if it is not.

Following is the C program for the reading and writing characters −


# include <stdio.h>
# include <conio.h>
# include <ctype.h>
main(void){
char ch;
printf (“enter chars, enter a period to stop
”);
do{
ch = getche ();
if ( islower (ch) )
putchar (toupper (ch));
else
putchar (tolower (ch));
} while (ch! = ‘.’); /* use a period to stop */
return 0;
}

Rao’s Degree and PG College P a g e | 28 M.Vaishnavi


Output

When the above program is executed, it produces the following result −

enter chars, enter a period to stop


tTuUtToOrRiIaAlLsS..

There are two important variations on getche(), which are as follows −

The first one is as follows −

 The trouble with getchar() is that it buffers input until a carriage return is entered.
 The getchar() function uses the STDIO.H header file.

The second one is as follows −

 A second, more useful, variation on getche() is getch(), which operates precisely like getche () except
that the character you type is not echoed to the screen. It uses the CONIO.H header.

Formatted And Unformatted Input/Output Functions In C With Examples


Formatted IO Functions

Formatted I/O functions are essential for handling user inputs and displaying
outputs in a user-friendly way. They enable programmers to:

S.NO Format
Type Description
. Specifier

Rao’s Degree and PG College P a g e | 29 M.Vaishnavi


int/signed
1 %d used for I/O signed integer value
int

2 %c char Used for I/O character value

3 %f float Used for I/O decimal floating-point value

4 %s string Used for I/O string/group of characters

5 %ld long int Used for I/O long signed integer value

6 %u unsigned int Used for I/O unsigned integer value

7 %i unsigned int used for the I/O integer value

8 %lf double Used for I/O fractional or floating data

9 %n prints prints nothing

1. Present Data to Users: Formatted output functions allow programs to


present data to users in various formats. Format specifiers are used to control
how data is displayed, making it more readable and visually appealing.
2. Support Multiple Data Types: These I/O functions are versatile and support
a wide range of data types, including integers, floating-point numbers,
characters, and more. Each data type has corresponding format specifiers for
precise formatting.
3. Formatting Control: Programmers can use format specifiers to control the
alignment, width, precision, and other formatting aspects of displayed data,
ensuring it’s presented as intended.

Rao’s Degree and PG College P a g e | 30 M.Vaishnavi


Why they are called Formatted I/0 Functions

These functions are called formatted I/O functions as they can use format specifiers
in these functions. Moreover, we can format these functions according to our needs.

Here are the list of some specifiers

The following formatted I/O functions will be discussed in this section-

1. printf()
2. scanf()
3. sprintf()
4. sscanf()

1. printf():
In C, printf() is a built-in function used to display values like numbers, characters,
and strings on the console screen. It’s pre-defined in the stdio.h header, allowing
easy output formatting in C programs.

Syntax 1

printf(“Format Specifier”, var1, var2, …., varn);

Example

// C program to implement

// printf() function

#include <stdio.h>

// Driver code

int main()

Rao’s Degree and PG College P a g e | 31 M.Vaishnavi


// Declaring an int type variable

int a;

// Assigning a value in a variable

a = 20;

// Printing the value of a variable

printf("%d", a);

return 0;

Output

20

Syntax 2:

printf(“Enter the text which you want to display”);

Example

// C program to implement

// printf() function

#include <stdio.h>

Rao’s Degree and PG College P a g e | 32 M.Vaishnavi


// Driver code

int main()

// Displays the string written

// inside the double quotes

printf("This is a string");

return 0;

Output

This is a string

2. scanf():

scanf(): In C, scanf() is a built-in function for reading user input from the

keyboard. It can read values of various data types like integers, floats,
characters, and strings. scanf() is a pre-defined function declared in
the stdio.h header file. It uses the & (address-of operator) to store user input
in the memory location of a variable.
Syntax

scanf(“Format Specifier”, &var1, &var2, …., &varn);

Example

// C program to implement

// scanf() function

#include <stdio.h>

Rao’s Degree and PG College P a g e | 33 M.Vaishnavi


// Driver code

int main()

int num1;

// Printing a message on

// the output screen

printf("Enter a integer number: ");

// Taking an integer value

// from keyboard

scanf("%d", &num1);

// Displaying the entered value

printf("You have entered %d", num1);

return 0;

Output

Enter a integer number: You have entered 0

Rao’s Degree and PG College P a g e | 34 M.Vaishnavi


Output

Enter a integer number: 56

You have entered 56

3. sprintf():

sprintf(): Short for “string print,” sprintf() is similar to printf() but it stores the
formatted string into a character array instead of displaying it on the console screen.

Syntax

// C program to implement

// the sprintf() function

#include <stdio.h>

// Driver code

int main()

char str[50];

int a = 2, b = 8;

// The string "2 and 8 are even number"

// is now stored into str

sprintf(str, "%d and %d are even number",

a, b);

Rao’s Degree and PG College P a g e | 35 M.Vaishnavi


// Displays the string

printf("%s", str);

return 0;

Output

2 and 8 are even number

4. sscanf():

sscanf(): Abbreviated for “string scanf,” sscanf() resembles scanf() but reads

data from a string or character array rather than from the console screen.
Syntax

sscanf(array_name, “format specifier”, &variable_name);

Example

// C program to implement

// sscanf() function

#include <stdio.h>

// Driver code

int main()

char str[50];

int a = 2, b = 8, c, d;

Rao’s Degree and PG College P a g e | 36 M.Vaishnavi


// The string "a = 2 and b = 8"

// is now stored into str

// character array

sprintf(str, "a = %d and b = %d",

a, b);

// The value of a and b is now in

// c and d

sscanf(str, "a = %d and b = %d",

&c, &d);

// Displays the value of c and d

printf("c = %d and d = %d", c, d);

return 0;

Output

c = 2 and d = 8

Unformatted Input/Output functions

 Unformatted I/O Functions: These functions are used exclusively for character data types or
character arrays/strings. They are designed for reading single inputs from the user at the console
and for displaying values on the console.

Rao’s Degree and PG College P a g e | 37 M.Vaishnavi


 Why “Unformatted”?: They are referred to as “unformatted” I/O functions because they do not
support format specifiers. Unlike formatted I/O functions like printf() and scanf(), you
cannot use format specifiers to control the formatting of the data. They display or read data as-is
without formatting options.

The following are unformatted I/O functions

1. getch()
2. getche()
3. getchar()
4. putchar()
5. gets()
6. puts()
7. putch()

1. getch():
getch(): In C, getch() reads a single character from the keyboard without
displaying it on the console screen. It immediately returns without requiring the
user to press the Enter key. This function is declared in the conio.h header file and
is often used for controlling screen display.

Syntax

getch();

or

variable-name = getch();

Example

// C program to implement

// getch() function

Rao’s Degree and PG College P a g e | 38 M.Vaishnavi


#include <conio.h>

#include <stdio.h>

// Driver code

int main()

printf("Enter any character: ");

// Reads a character but

// not displays

getch();

return 0;

Output

Enter any character:

2. getche():

In C, getche() reads a single character from the keyboard, displays it on the console
screen, and immediately returns without requiring the user to press the Enter key.
This function is declared in the conio.h header file.

Syntax

Rao’s Degree and PG College P a g e | 39 M.Vaishnavi


getche();

or

variable_name = getche();

Example

// C program to implement

// the getche() function

#include <conio.h>

#include <stdio.h>

// Driver code

int main()

printf("Enter any character: ");

// Reads a character and

// displays immediately

getche();

return 0;

Rao’s Degree and PG College P a g e | 40 M.Vaishnavi


Output

Enter any character: g

3. getchar():

In C, getchar() reads a single character from the keyboard and waits until the Enter
key is pressed. It processes one character at a time. This function is declared in
the stdio.h header file

Syntax

Variable-name = getchar();

Example

// C program to implement

// the getchar() function

#include <conio.h>

#include <stdio.h>

// Driver code

int main()

// Declaring a char type variable

char ch;

Rao’s Degree and PG College P a g e | 41 M.Vaishnavi


printf("Enter the character: ");

// Taking a character from keyboard

ch = getchar();

// Displays the value of ch

printf("%c", ch);

return 0;

Output

Enter the character: a

4. putchar():

In C, putchar() is used to display a single character at a time, either by passing the


character directly or by using a variable that stores the character. This function is
declared in the stdio.h header file.

Syntax

putchar(variable_name);

Example

// C program to implement

// the putchar() function

Rao’s Degree and PG College P a g e | 42 M.Vaishnavi


#include <conio.h>

#include <stdio.h>

// Driver code

int main()

char ch;

printf("Enter any character: ");

// Reads a character

ch = getchar();

// Displays that character

putchar(ch);

return 0;

Output

Enter any character: Z

5. gets():

In C, gets() reads a group of characters or strings from the keyboard, and these
characters are stored in a character array. It allows you to input space-separated
texts or strings. This function is declared in the stdio.h header file. However,

Rao’s Degree and PG College P a g e | 43 M.Vaishnavi


please note that gets() is considered unsafe due to the risk of buffer overflow and is
generally discouraged in favor of safer alternatives like fgets().

Syntax

char str[length of string in number]; //Declare a char type variable of any length

gets(str);

Example

// C program to implement

// the gets() function

#include <conio.h>

#include <stdio.h>

// Driver code

int main()

// Declaring a char type array

// of length 50 characters

char name[50];

printf("Please enter some texts: ");

// Reading a line of character or

Rao’s Degree and PG College P a g e | 44 M.Vaishnavi


// a string

gets(name);

// Displaying this line of character

// or a string

printf("You have entered: %s",

name);

return 0;

Output

Please enter some texts: Skill Vertex

You have entered: Skill Vertex

6. puts():

In C programming, puts() is used to display a group of characters or strings that are already stored in a
character array. This function is declared in the stdio.h header file.

Syntax

puts(identifier_name );

Example

// C program to implement

Rao’s Degree and PG College P a g e | 45 M.Vaishnavi


// the puts() function

#include <stdio.h>

// Driver code

int main()

char name[50];

printf("Enter your text: ");

// Reads string from user

gets(name);

printf("Your text is: ");

// Displays string

puts(name);

return 0;

Output

Enter your text: Skill Vertex

Rao’s Degree and PG College P a g e | 46 M.Vaishnavi


Your text is: Skill Vertex

7. putch():

In C, putch() is used to display a single character provided by the user, and it prints
the character at the current cursor location. This function is declared in
the conio.h header file

Syntax

putch(variable_name);

Example

// C program to implement

// the putch() functions

#include <conio.h>

#include <stdio.h>

// Driver code

int main()

char ch;

printf("Enter any character:\n ");

// Reads a character from the keyboard

ch = getch();

Rao’s Degree and PG College P a g e | 47 M.Vaishnavi


printf("\nEntered character is: ")

// Displays that character on the console

putch(ch);

return 0;

Output

Enter any character:

Entered character is: d

Formatted I/O vs Unformatted I/O

S
Formatted I/O functions Unformatted I/O functions
No.

Whereas, Unformatted I/O functions won’t


These Formatted I/O functions will provide input
1 allow to take input or display output in user
or display output in the user’s desired format.
desired format.

2 They will support format specifiers. They will support format specifiers.

3 These will store data more user-friendly These functions are notuser-friendly.

In Formatted I/0 Functions, we can use all


4 These functions are not user-friendly.
data types.

Examples -printf(), scanf, sprintf() and Example-getch(), getche(), gets() and


5
sscanf() puts()

Rao’s Degree and PG College P a g e | 48 M.Vaishnavi

You might also like