CCSE0151
Module-2
Arithmetic expressions & Conditional Branching
Operator: An operator is a symbol that tells the computer to perform specific mathematical or
logical functions. Operators are broadly classified as follow-
(i) Unary Operator: The operator that operates over single operand is known as unary
operator. Examples are: Increment (++), Decrement (--), Logical NOT (!).
(ii) Binary Operator: The operator that operates over two operands is known as binary
operator. Examples are: Logical AND (&&), Logical OR (||), Relational operators.
(iii) Ternary Operator: The operator that operates over three operands is known as ternary
operator. Example is conditional operator (? :).
Types of Operators:
(i) Arithmetic Operators
(ii) Relational Operators
(iii) Logical Operators
(iv) Assignment Operators
(v) Increment and decrement Operators
(vi) Conditional Operator
(vii) Bitwise Operators
(viii) Special Operators
(i) Arithmetic Operators: C programming has five arithmetic operators.
Operator Description
+ Addition or unary plush
- Subtraction or unary minus
* Multiplication
/ Division
% Modulo division (It gives the remainder of an integer division)
Example: X=20%6;
X=2
Points:
An integer division always gives an integer value.
Modulo division operator cannot be used with floating point data.
During modulo division the sign of result is always the sign of first operand.
-14%3=-2 and 14%-3=2
(ii) Relational Operators: Relational operators are used to compare two values. The value
of a relational expression can be either zero or one.
Operator Description Example
< Is less than x=(a<b)
<= Is less than or equal to x=(a<=b)
> Is greater than x=(a>b)
>= Is greater than or equal to x=(a>=b)
1
CCSE0151
== Is equal to x=(a==b)
!= Is not equal to x=(a!=b)
(iii) Logical Operators: C programming has three logical operators.
Operator Description Example
&& Logical AND if(a>b && a>c)
|| Logical OR if(a>b || a>c)
! Logical NOT if(!a)
A logical expression always gives zero or one. Logical NOT is used to convert true (Non-zero)
value to false (Zero) and false (zero) to true (one). The logical AND and logical OR gives the
result according to following table.
Operand1 Operand2 Operand1&& Operand1 Operand1|| Operand1
Non-zero Non-zero 1 1
Non-zero 0 0 1
0 Non-zero 0 1
0 0 0 0
(iv) Assignment Operators: The assignment operators are used to assign the result of an
expression to a variable. C programming has a simple assignment operator =. C
programming also has a set of shorthand assignment operators. Shorthand assignment
operators are- +=, -=, *=, /=, %=. The left operand in an assignment expression must be a
single variable.
Statements with Shorthand Operator Description
a+=b a=a+b
a-=b a=a-b
a*=b+c a=a*(b+c)
a/=b a=a/b
a%=b a=a%b
(v) Increment and Decrement Operators: C Programming has Increment (++) and Decrement
(--) operators. ++ adds one to the operand and – subtract one from operand. Both are unary
operators.
Example: If a=5, then the value of a and x after the expression x=a++ + a-- + ++a; will be 6
and 18.
(vi) Conditional Operator: Conditional operator is also known as ternary operator. It uses the
symbol (? :). It can be used as-
Syntax: expression1 ? expression2 : expression3;
In this expression1 is calculated first. If expression1 is true then expression2 is calculated and
its value becomes the value of the expression.
2
CCSE0151
If expression1 is false then expression3 is calculated and its value becomes the value of the
expression.
Example: X=5>6 ? 5 : 6;
X=6
(vii)Bitwise Operators: Bitwise operators are used to manipulate the data at bit level. C
programming has five bitwise operators.
Operator Description Example
& Bitwise AND X=5&6 , X=101&110, X=100 i.e. X=4
| Bitwise OR X=5|6 , X=101|110, X=111 i.e. X=7
^ Bitwise XOR X=5^6 , X=101^110, X=011 i.e. X=3
<< Bitwise left shift X=5<<2 , X=101<<2, X=10100 i.e. X=20
>> Bitwise right shift X=5>>2 , X=101>>2, X=1 i.e. X=1
~ Bitwise complement X=~6, X=~00000110, X=11111001 i.e. X=-7
The table for bitwise &, |, ^ is below
Operand1 Operand2 Operand1&Operand1 Operand1|Operand1 Operand1^Operand2
1 1 1 1 0
1 0 0 1 1
0 1 0 1 1
0 0 0 0 0
(viii) Special Operators: C programming has some special operators. These special operators
are- , (comma), & (ampersand), . (dot), *(dereferencing operator) and sizeof.
sizeof: It gives the number of bytes obtained by the operand in computer memory. Operand
can be a variable, constant or data type.
Example: x=sizeof(int);
x=2
Comma Operator: The comma operator separates expressions. It can act as - operator in
the Expression and separator in variable declaration and function Call Parameter List
int a=(x=5, y=6, x+y);
a=11
Address of Operator (&): The operator that is used to extract the address of a variable is
called address of operator.
Dereferencing Operator (*) or Indirection Operator (Value at Address): The operator that
returns the value stored at an address is called dereferencing operator (*).
Precedence and Associativity:
Precedence: Precedence is used to determine the order in which different operators in a complex
expression are evaluated. The highest precedence operators are evaluated first. Precedence is
always applied before associativity.
Associativity: Associativity is used to determine the order in which operators with the same
precedence are evaluated in a complex expression. Associativity can be left to right or right to left.
Example: x=5+6*2-31/5
3
CCSE0151
x=5+12-31/5
x=5+12-6
x=17-6
x=11
Type Conversion (Type Casting): When a combination of two or more data types are used
to perform operation, the data or value is converted to any one of the data type. This process is
known as type conversion. There are two types of type conversions in C programming-
(i) Implicit type conversion
(ii) Explicit type conversion
Implicit type conversion: If the operands in an expression are of different types, the lower type is
automatically converted to the higher type before the operation proceeds. This automatic
conversion is known as implicit type conversion.
The result of an expression is converted to the type of the variable on the left of the
assignment operator before assigning the value to it.
long double
double
float
unsigned long int
long int
unsigned int
int
short or char
(Conversion Hierarchy)
Explicit type conversion: When one type is converted to another forcefully by the programmer, it
is called explicit type conversion. We can convert it as follow-
(type-name) expression
The process of such local conversion is known as explicit type conversion.
X=(int) 7.5 7.5 is converted to integer value i.e. 7
X=(int)21.3 / (int)4.5 Evaluated as 21/4 and result would be 5
X=(double)sum/n Division is done in floating point mode
X=(int) (a+b) Result of (a+b) is converted to integer
X=(int) a+b a is converted to integer and then added to b
Difference between Initialization and Assignment
1. Assignment can be done as many times as desired where as initialization can be done only
once.
2. We cannot assign to a const variable, whereas you can initialize it. For example:
const AXC d = 3; //OK! Initialization
d = 3; //WRONG! Cannot assign to const
Expressions: An expression is a combination of variables constants and operators written
according to the syntax of C language. In C, every expression evaluates to a value i.e., every
expression results in some value of a certain type that can be assigned to a variable.
4
CCSE0151
Header File: A header file is a file with extension .h which contains C function declarations and
macro definitions and to be shared between several source files. Names of header files are- stdio.h,
conio.h, math.h, string.h etc.
Formatted Input/Output: It refers to the conversion of data to and from a stream of
characters, for printing (or reading) in plain text format.
Formatted Input and Output Functions: scanf(), printf(), fscanf(), fprintf().
Unformatted Input and Output Functions: getchar(), putchar(), getch(), putch().
Escape Sequence Characters: Characters combinations consisting of a back slash (\)
followed by a symbol are known as escape sequence characters. Examples: \n, \t, \b, \r, \0, \\, \”,
etc.
Characteristics of Escape sequence characters:
They are not displayed directly.
They are interpreted at execution time.
They are used in output statements.
Comments: Comments are the statements that are ignored by the compiler and they are not
translated to machine language code. There are two types of comments- line comment and block
comment.
Line Comment: This comment is written in only one line. It uses two slashes (//).
Block Comment: A comment written in multiple lines is called a block comment. It uses opening
token (/*) and closing token (*/).
Difference between Syntax and logical Error:
Syntax Error Logical Error
These errors occur when a program does not These errors occur when a program does not
use the correct syntax of a programming do what the programmer wants to do.
language. Example:
Example: If we want to find the average of three
printf(“syntax error”) numbers and we write the following
statement-
syntax error statement missing ; avg=a+b+c/3; //logical error
This statement should be written as-
avg=(a+b+c)/3;
Structure of C Program:
5
CCSE0151
Write a program to swap the values of two variables by using third variable.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
printf(“Eneter two Numbers”);
scanf(“%d%d”,&a,&b);
printf(“Before swapping a=%d, b=%d”,a,b);
c=a;
a=b;
b=c;
printf(“After swapping a=%d, b=%d”,a,b);
getch();
}
Write a program to swap the values of two variables without using third variable.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
printf(“Eneter two Numbers”);
scanf(“%d%d”,&a,&b);
printf(“Before swapping a=%d, b=%d”,a,b);
a=a+b;
b=a-b;
a=a-b;
printf(“After swapping a=%d, b=%d”,a,b);
getch();
}
6
CCSE0151
Storage Classes: A variable storage class tells the following four thins about a variable.
(i) Where the variable value would be stored.
(ii) What will be the default initial value of variable?
(iii) What is the scope of variable?
(iv) What is the life of variable?
There are following four storage classes in C programming
(1) Automatic storage class
(2) Register storage class
(3) Static storage class
(4) External storage class
Storage Class Keyword Storage Default Value Scope Life
Automatic auto Memory Garbage Local Within the function in which it
(RAM) is declared
Register register CPU Garbage Local Within the function in which it
Register is declared
Example of Automatic Storage Class: Example of Register Storage Class:
Static static
#include<stdio.h> Memory Zero Local Variable retains its value
#include<stdio.h>
#include<conio.h> (RAM) between different function call
#include<conio.h>
External voidextern
increment();Memory Zero void increment();
Global Throughout the program
void main() void main()
(RAM) execution
{ {
increment(); increment();
increment(); increment();
increment(); increment();
getch(); getch();
} }
void increment() void increment()
{ {
auto int i=1; register int i=1;
printf(“\t%d”,i); printf(“\t%d”,i);
i++; i++;
} }
Example of Static Storage Class: Example of External Storage Class:
#include<stdio.h> file1.c
#include<conio.h> #include<stdio.h>
void increment(); int a=8;
void main() void display()
{ {
increment(); printf(“%d”,a);
increment(); a++;
increment(); }
getch(); file2.c
} #include<stdio.h>
void increment() #include<conio.h>
{ #include “file1.c”;
static int i=1; void main() 7
printf(“\t%d”,i); {
i++; extern int a;
} display();
printf(“%d”,a);
getch();
}
CCSE0151
By default, all variables declared within a function are automatic variable.
Static is the default storage class of global variables.
Conditional Statements: Conditional statements are used to execute a statement or a group
of statement based on certain conditions.
In C Language decision making capabilities are supported by following statements.
if statement
switch statement
Conditional Operator
if statements: The if statement is a decision making statements. It is two-way decision statement
and used in combination with an expression.
8
CCSE0151
Syntax:
if(test expression)
{
Statement-block;
}
Statement-X;
if else Statement: In this, the body of if is executed if the result of expression is true, otherwise the
else block is executed and then the control is transferred to the next statement.
Syntax:
if(test expression)
{
statement block-1;
}
else
{
statement block-2;
}
statement-x;
Nested if else Statement: When an if statement is written inside another if statement, it is called a
nested if statement.
9
CCSE0151
Syntax:
if(test expression-1)
{
if(test expression-2)
{
statement block-1;
}
else
{
statement block-2;
}
}
else
{
if(test expression-3)
{
statement block-3;
}
else
{
statement block-4;
}
}
Statement-x;
else if Ladder: It is a multiway branching statement. It starts by checking the first logical expression.
If the expression is true, then the body of first if is executed. Otherwise the next expression is
evaluated and so on. When an expression is found to be true, the statements associated with it are
executed and then the control is transferred.
1
0
CCSE0151
Syntax:
if(test expression-1)
{
Statement block-1
}
else if(test expression-2)
{
Statement block-2
}
else if(test expression-3)
{
Statement block-3
}
else
{
statement block-4
}
Statement-x;
Write a program to check whether a number is even or odd.
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
printf(“Enter a Number”);
scanf(“%d”,&n);
if(n%2==0)
printf(“Number is Even”);
else
printf(“Number is odd”);
getch();
}
Write a program to check whether a year is a leap year or not.
#include<stdio.h>
#include<conio.h>
void main()
{
int y;
printf(“Enter a Year”);
scanf(“%d”,&y);
if((y%4==0 && y%100!=0)||(y%400==0))
printf(“Year is a leap year”);
else
printf(“Year is not a leap year”);
getch();
1
1
CCSE0151
}
Write a program to convert an uppercase letter into lowercase and vice-versa.
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
printf(“Eneter a character”);
scanf(“%c”,&ch);
if(ch>=’A’ && ch<=’Z’ )
{
ch=ch+32;
printf(“%c”,ch);
}
else if(ch>=’a’ && ch<=’z’)
{
ch=ch-32;
printf(“%c”,ch);
}
else
printf(“Invalid Character”);
getch(); }
Write a program to find the largest number among three numbers.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
printf(“Enter three Numbers”);
scanf(“%d%d%d”,&a,&b,&c);
if(a>b && a>c)
printf(“%d is largest”,a);
else if(b>a && b>c)
printf(“%d is largest”,b);
else
printf(“%d is largest”,c);
getch();
}
Write a program to check whether a number is positive, negative or zero.
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
printf(“Enter Number”);
scanf(“%d”,&n);
if(n>0)
1
2
CCSE0151
printf(“Number is Positive”);
else if(n<0)
printf(“Number is Negative”);
else
printf(“Number is Zero”);
getch();
}
Write a program to find the largest number among three numbers using conditional
operator.
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b, c, x;
printf(“Enter three numbers”);
scanf(“%d%d%d”,&a,&b,&c);
x=a>b?a>c:a:c:b>c?b:c;
printf(“Largest number=%d”,x);
getch();
}
Switch Statement: The switch statement is a multiway decision statement. The switch
statement tests the value of a given variable or expression against a list of case values and when a
match is found a block of statement associated with that case is executed.
Syntax: switch(expression)
{
caes value1: block-1;
break;
caes value2: block-2;
break;
caes value3: block-3;
break;
default: block-4;
break;
}
Advantages of Switch
(i). Easier to debug.
(ii). Easier to read, understand, and maintain.
(iii).Faster execution.
(iv).More efficient (destination can be computed by looking up in table).
Limitations (Disadvantages) of switch statement
(i). It doesn't work with floats, strings, etc.
1
3
CCSE0151
(ii). Relational and logical operators are not allowed in switch case.
(iii).It doesn't work with variable conditions i.e. case values cannot be variable.
Write a program to simulate calculator using switch statement.
#include<stdio.h>
#include<conio.h>
void main()
{
float a,b,c;
char op;
printf(“Enter two numbers”);
scanf(“%f%f”,&a,&b);
fflush(stdin);
printf(“Enter Operator”);
scanf(“%c”,&op);
switch(op)
{
case ‘+’: c=a+b;
printf(“Addition=%f”,c);
break;
case ‘-’: c=a-b;
printf(“Subtraction=%f”,c);
break;
case ‘*’: c=a*b;
printf(“Multiplication=%f”,c);
break;
case ‘/’: c=a/b;
printf(“Division=%f”,c);
break;
default: printf(“Invalid Operator”);
break;
}
getch();
}
Write a menu driven program to calculate the area of different geometrical figures such as
rectangle, square, circle and triangle.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float a,b,c,s,area;
int n;
printf(“Enter:\n1:For rectangle\n2:For square\n3:For circle\n4:For triangle\n”);
scanf(“%d”,&n);
switch(n)
{
1
4
CCSE0151
case 1: printf(“Enter length and breadth of rectangle”);
scanf(“%f%f”,&a,&b);
area=a*b;
printf(“Area of Rectanle:%f”,area);
break;
case 2: printf(“Enter the side of square”);
scanf(“%f”,&a);
area=a*a;
printf(“Area of Square:%f”,area);
break;
case 3: printf(“Enter the radius of circle”);
scanf(“%f”,&a);
area= 3.14*a*a;
printf(“Area of Circle:%f”,area);
break;
case 4: printf(“Enter the three sides of triangle ”);
scanf(“%f%f%f”,&a,&b,&c);
s=(a+b+c)/2;
area=sqrt(s*(s-a)*(s-b)*(s-c));
printf(“Area of Triangle:%f”,area);
break;
default: printf(“Invalide Choice”);
break;
}
getch();
}
Difference between switch and if statement
switch if
1) In switch statement the condition is tested 1) In multiple if statements the conditions are to
only once and jumps to required block. be checked as many times the if statements
are written.
2) A switch statement is generally best to use
when you have more than two conditional 2) A if else statement can take any kind of value
expressions based on a single variable of in conditional expression.
numeric & character type.
3) All operators are allowed in if else statement.
3) Logical operators are not allowed in case.
1
5
CCSE0151
1
6