C UNIT 2 Notes.docx
C UNIT 2 Notes.docx
UNIT II
OPERATOR AND EXPRESSIONS
Data Input and Output statements – Operators: Arithmetic Operators, Relational
Operators, Logical Operators, Increment and Decrement Operators, Bitwise
Operators, Assignment Operators and Expressions, Precedence and Order of
Evaluation – Decision Making and Branching – Looping statements.
Input and Output statement are used to read and write the data in C
programming. These are embedded in stdio.h (standard Input/Output header
file).
Input means to provide the program with some data to be used in the program
and Output means to display data on screen or write the data to a printer or a
file.C programming language provides many built-in functions to read any
given input and to display data on screen when there is a need to output the
result.
There are mainly two of Input/Output functions are used for this purpose. These
are discussed as:
● getchar()
● putchar()
● gets()
● puts()
● getch()
● getche()
getchar()
v = getchar();
putchar()
putchar(v);
For example:
char n;
putchar(n);
A simple program is written as below, which will read a single character using
getchar() function and display inputted data using putchar() function:
gets()
gets(v);
char n[20];
gets(n);
puts()
getch()
This is also an input function. This is used to read a single character from
the keyboard like getchar() function. The character data read by this function is
directly assigned to a variable rather it goes to the memory buffer, the character
data is directly assigned to a variable without the need to press the Enter key.
Another use of this function is to maintain the output on the screen till
you have not press the Enter Key. The general syntax is as:
v = getch();
getch();
}
Output:
getche()
v = getche();
where v is the variable of character type.
Output:
Formatted I/O functions which refers to an Input or Ouput data that has
been arranged in a particular format. There are mainly two formatted I/O
functions discussed as follows:
● scanf()
● printf()
scanf()
The scanf() function is an input function. It used to read the mixed type of
data from keyboard. You can read integer, float and character data by using its
control codes or format codes. The general syntax is as:
scanf("control strings",arg1,arg2,..............argn);
(Or)
scanf("control strings",&v1,&v2,&v3,................&vn);
Example Program:
#include <stdio.h>
int main()
{
char n,name[20];
int abc;
float xyz;
printf("Enter the single character, name, integer data and real value");
scanf("\n%c%s%d%f", &n,name,&abc,&xyz);
getch();
Unit 2 C Progg
printf()
printf("control strings",&v1,&v2,&v3,................&vn);
(Or)
The control strings use some printf() format codes or format specifiers or
conversion characters. These all are discussed in the below table as:
OPERATORS IN C
C operators are one of the features in C which has symbols that can be used to
perform mathematical, relational, bitwise, conditional, or logical
manipulations. Operators are used to perform operations on variables and
values.
● Arithmetic operators
● Relational Operator
● Logical operators
● Bitwise operators
● Assignment Operators
● Misc Operators
ARITHMETIC OPERATORS
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1
Unit 2 C Progg
RELATIONAL OPERATORS
A relational operator checks the relationship between two operands. If the
relation is true, it returns 1; if the relation is false, it returns value 0. Relational
operators are used in decision making and loops.
5 == 5 is 1
5 == 10 is 0
5 > 5 is 0
5 > 10 is 0
5 < 5 is 0
5 < 10 is 1
5 != 5 is 0
5 != 10 is 1
5 >= 5 is 1
5 >= 10 is 0
5 <= 5 is 1
5 <= 10 is 1
LOGICAL OPERATORS:
Logical Operators are used to combine two or more
conditions/constraints or to complement the evaluation of the original condition
in consideration. The result of the operation of a logical operator is a boolean
value either true or false.
Unit 2 C Progg
Output:
Unit 2 C Progg
(a == b) && (c > b) is 1
(a == b) && (c < b) is 0
(a == b) || (c < b) is 1
(a != b) || (c < b) is 0
!(a != b) is 1
!(a == b) is 0
BITWISE OPERATORS
The Bitwise operators is used to perform bit-level operations on the
operands. The operators are first converted to bit-level and then the calculation
is performed on the operands. The mathematical operations such as addition,
subtraction, multiplication etc. can be performed at bit-level for faster
processing.
unsigned char p = 5, q = 9;
// The result is 00000001
printf(“p = %d, q = %d\n”, p, q);
printf(“p&q = %d\n”, p & q);
// The result is 00001100
printf(“p^q = %d\n”, p ^ q);
// The result is 00001101
printf(“p|q = %d\n”, p | q);
// The result is 11111010
printf(“~p = %d\n”, p = ~p);
// The result is 00000100
printf(“q>>1 = %d\n”, q >> 1);
// The result is 00010010
printf(“q<<1 = %d\n”, q << 1);
return 0;
}
Output:
p = 5, q = 9
p&q = 1
p^q = 12
p|q = 13
~p = 250
q>>1 = 4
q<<1 = 18
ASSIGNMENT OPERATORS
Assignment operators are used to assign value to a variable. The left side
operand of the assignment operator is a variable and right-side operand of the
Unit 2 C Progg
assignment operator is a value. The value on the right side must be of the same
data-type of variable on the left side otherwise the compiler will raise an error.
■ a = 10; b = 20; ch = 'y';
■ (a += b) can be written as (a = a + b)
■ (a -= b) can be written as (a = a - b)
■ (a /= b) can be written as (a = a / b)
// AS POSTFIX
m++
1. Pre-Increment
In pre-increment, the increment operator is used as the prefix. Also
known as prefix increment, the value is incremented first according to the
precedence and then the less priority operations are done.
Example
result = ++var1;
}
int main()
{
increment();
return 0;
}
Output:
Prefix Increment: 6
Postfix Increment: 5
Decrement Operator in C
Syntax
Just like the increment operator, the decrement operator can also be used in two
ways:
// AS PREFIX
--m
// AS POSTFIX
m—
1. Pre-Decrement Operator
Example
result = --m;
2. Post-Decrement Operator
Example
result = m--;
Postfix = 5
Prefix increment operator means the Prefix decrement operator means the
variable is incremented first and variable is decremented first and then
then the expression is evaluated the expression is evaluated using the
using the new value of the variable. new value of the variable.
?: If Condition is true ?
Conditional Expression. then value X : otherwise
value Y
Example:
// C Program To demonstrate sizeof operator
#include <stdio.h>
int main()
{
printf("%lu\n", sizeof(char));
printf("%lu\n", sizeof(int));
printf("%lu\n", sizeof(float));
printf("%lu", sizeof(double));
return 0;
}
Output
1
4
4
8
C Ternary Operator:
Unit 2 C Progg
We use the ternary operator in C to run one code when the condition is
true and another code when the condition is false.
Syntax:
Example:
#include <stdio.h>
int main()
{
int age;
// take input from users
printf("Enter your age: ");
scanf("%d", &age);
// ternary operator to find if a person can vote or not
(age >= 18) ? printf("You can vote") : printf("You cannot vote");
return 0; }
Output:
EXPRESSIONS IN C:
A C expression is a union of operators and operands. A C expression is
used to calculate a single value that is saved in a variable. The action or
operation to be carried out is indicated by the operator. The objects to which we
apply the operation are known as operands.
Unit 2 C Progg
a. Infix
When the operator lies between the operands then the expression is known as an
Infix expression. Below is the representation:
X=A+B
+ operator lies between the two operands A and B.
Y=U+N–O
+ and −− operator lies between the operands, so it is also an infix expression.
b. Postfix
When the operator lies after the operands then the expression is known as a
Postfix expression. Below is the representation:
Unit 2 C Progg
X = AB+
+ operator lies after the two operands A and B.
c. Prefix
When the operator lies before the operands then the expression is known as a
Prefix expression. Below is the representation:
X = +AB
+ operator lies before the two operands A and B.
Postfix and Prefix expressions can't be used directly while coding a program.
These expressions are generally used by the compilers during the compilation
process of a program as there is no issue of operator precedence or associativity
with postfix and prefix expressions.
d. Unary
When the expression contains only one operand and one operator then the
expression is known as a Unary expression. Below is the representation:
A++
--A
++B
B --
++ and -- are the increment and decrement operators that can lie before
and after a single operand in a unary expression. We will see more about it later
in the article using a C program.
e. Binary
When the expression contains two operands and only one operator then
the expression is known as a Binary expression. Below is the representation:
A+B
A/B
A%B
Unit 2 C Progg
Input:
Enter 4 values: 2 3 4 6
Output:
Now, a = 2, b = 3, c = 4, d = 6
Unary Expression: u1 = 2 u2 = 2
Now, a = 3, b = 2, c = 4, d = 6
Binary Expression: b1 = 5 b2 = -2
Infix Expression: i1 = 11 i2 = 50
Ternary Expression: t1 = 1
Unit 2 C Progg
a = 3 is big
● If statements
● If-else statements
● Nested-if statements
● Switch statements
● Nested switch statements
If statement
Syntax :
if(test expression)
{
Statements;
}
Unit 2 C Progg
Flow Diagram:
Example:
#include <stdio.h>
int main ()
{
if( a < 20 ) {
/* if condition is true then print the following */
printf("a is less than 20\n" );
}
printf("value of a is : %d\n", a);
return 0;
}
Output:
a is less than 20
value of a is: 10
Unit 2 C Progg
If-else Statements:
Syntax
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
else
{
/* statement(s) will execute if the boolean expression is false */
}
If the Boolean expression evaluates to true, then the if block will be executed,
otherwise, the else block will be executed.
Flow Diagram:
Example:
#include <stdio.h>
Unit 2 C Progg
int main ( )
{
/* local variable definition */
int a = 100;
Output:
NESTED-IF STATEMENTS:
Syntax
if( boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
if(boolean_expression 2) {
/* Executes when the boolean expression 2 is true */
}
}
Unit 2 C Progg
Example:
#include <stdio.h>
int main () {
return 0;
}
Output:
Example:
#include <stdio.h>
int main()
{
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num > 0)
{
printf("%d is positive.\n", num);
}
Unit 2 C Progg
else
{
if (num < 0)
{
printf("%d is negative.\n", num);
}
else
{
printf("%d is zero.\n", num);
}
}
return 0;
}
Output:
Enter a number: 10
10 is positive.
Enter a number: -5
-5 is negative.
Enter a number: 0
0 is zero.
Unit 2 C Progg
SWITCH STATEMENTS:
Syntax
switch(expression) {
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
Example:
Unit 2 C Progg
#include <stdio.h>
int main ( ) {
/* local variable definition */
char grade = 'B';
switch(grade) {
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well done\n" );
break;
case 'D' :
printf("You passed\n" );
break;
case 'F' :
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
}
printf("Your grade is %c\n", grade );
return 0;
}
Output:
Well done
Your grade is B
switch(ch2)
{
case 'A':
printf("This A is part of inner switch" );
break;
case 'B': /* case code */
}
break;
case 'B': /* case code */
}
Flow Diagram
Example:
#include <stdio.h>
int main () {
/* local variable definition */
int a = 100;
Unit 2 C Progg
int b = 200;
switch(a) {
case 100:
printf("This is part of outer switch\n", a );
switch(b) {
case 200:
printf("This is part of inner switch\n", a );
}
}
printf("Exact value of a is : %d\n", a );
printf("Exact value of b is : %d\n", b );
return 0;
}
Output:
BRANCHING STATEMENTS
A branch is an instruction in a computer program that can
cause a computer to begin executing a different instruction sequence and thus
deviate from its default behavior of executing instructions in order. Common
branching statements include,
● break,
● continue,
● return,
● goto
break
The break is used in one of two ways; with a switch to make it act like a
case structure or as part of a looping process to break out of the loop. The
following gives the appearance that the loop will execute 8 times, but the break
statement causes it to stop during the fifth iteration.
counter = 0;
Unit 2 C Progg
continue
The following gives the appearance that the loop will print to the monitor
8 times, but the continue statement causes it not to print number 4.
return
The return statement exits a function and returns to the statement where
the function was called.
Function Documenting
statements
Return <optional return value>
goto
Key Terms
branching statements
Allow the flow of execution to jump to a different part of the program.
Unit 2 C Progg
break
A branching statement that terminates the existing structure.
continue
A branching statement that causes a loop to stop its current iteration and
begin the next one.
exit
A predefined function used to prematurely stop a program and return to
the operating system.
goto
An unstructured branching statement that causes the logic to jump to a
different place in the program.
return
A branching statement that causes a function to jump back to the function
that called it.
LOOPING STATEMENTS
Loops in programming are used to repeat a block of code until
the specified condition is met. A loop statement allows programmers to execute
a statement or group of statements multiple times without repetition of code.
Unit 2 C Progg
for Loop
Syntax:
for (initialize expression; test expression; update expression)
{
body of for loop
}
Example:
for(int i = 0; i < n; ++i)
{
printf("Body of for loop which will execute till n");
}
In for loop, a loop variable is used to control the loop. Firstly we initialize the
loop variable with some value, then check its test condition. If the statement is
true then control will move to the body and the body of for loop will be
executed. Steps will be repeated till the exit condition becomes true. If the test
condition will be false then it will stop.
● Initialization Expression: In this expression, we assign a loop
variable or loop counter to some value. for example: int i=1;
● Test Expression: In this expression, test conditions are performed. If
the condition evaluates to true then the loop body will be executed and
then an update of the loop variable is done. If the test expression
becomes false then the control will exit from the loop. for example,
i<=9;
● Update Expression: After execution of the loop body loop variable is
updated by some value it could be incremented, decremented,
multiplied, or divided by any value.
{
int i = 0;
for (i = 1; i <= 5; i++)
{
printf( "Hello World\n");
}
return 0;
}
Output
Hello World
Hello World
Hello World
Hello World
Hello World
While Loop
While loop does not depend upon the number of iterations. In for loop the
number of iterations was previously known to us but in the While loop, the
execution is terminated on the basis of the test condition. If the test condition
will become false then it will break from the while loop else body will be
executed.
Syntax:
initialization_expression;
while (test_expression)
{
// body of the while loop
update_expression;
}
Unit 2 C Progg
Example:
// C program to illustrate while loop //
#include <stdio.h>
int main()
{
// Initialization expression
int i = 2;
// Test expression
while(i < 5)
{ // loop body
printf( "Hello World\n");
// update expression
i++;
}
return 0; }
Output
Hello World
Hello World
Unit 2 C Progg
DO-WHILE LOOP
The do-while loop is similar to a while loop but the only difference lies in
the do-while loop test condition which is tested at the end of the body. In the
do-while loop, the loop body will execute at least once irrespective of the test
condition.
Syntax:
initialization_expression;
do
{
// body of do-while loop
update_expression;
} while (test_expression);
{ // loop body
printf( "Hello World\n");
// Update expression
i++;
// Test expression
} while (i < 1);
return 0; }
Output
Hello World