0% found this document useful (0 votes)
23 views46 pages

C Programming Unit - 2 Notes-1

Uploaded by

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

C Programming Unit - 2 Notes-1

Uploaded by

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

Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

UNIT -II
Operators and Expressions

C Operators & Expressions: Arithmetic operators; Relational operators; Logical operators;


Assignment operators; Increment & Decrement operators; Bitwise operators; Conditional
operator; Special operators; Operator Precedence and Associatively; Evaluation of
arithmetic expressions; Type conversion.
Control Structures: Decision making Statements - Simple if, if_else, nested if_else, else_if
ladder, Switch Case, goto, break & continue statements; Looping Statements-Entry
controlled and exit controlled statements, while, do-while, for loops, Nested loops.

C Operators & Expressions

C Operator:
Def.: In C programming, an operator is a special symbol that tells the compiler to
perform a specific mathematical operation on single or two operands or variables or
values. Operators are used to perform operations like arithmetic, comparison, logical
operations, bit manipulation, etc.

1. Unary Operator :

Def.: A unary operator is an operator that acts on only one operand to perform an
operation. It is used to modify or evaluate a single value (operand).

The Unary Operators are:

1. Unary Minus
2. Logical NOT Operator
3. Bitwise Complementation

Prof. Raju Vathari Page 1


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

Unary Minus:
 The unary minus operator is used to negate the value of its operand. It
changes the sign of a number — turning a positive number into negative and
vice versa.

For example: Let a=3,b=4 and then the expression is c=a+(-b)


c = a+(-b)
= 3+(-4)
= -1

Example:

#include <stdio.h>
int main()
{
int a = 10;
int b = -5;

printf("Original a = %d\n", a); // 10


printf("Unary minus of a = %d\n", -a); // -10

printf("Original b = %d\n", b); // -5


printf("Unary minus of b = %d\n", -b); // 5

return 0;
}

OUTPUT:

Original a = 10
Unary minus of a = -10
Original b = -5
Unary minus of b = 5

Prof. Raju Vathari Page 2


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

Binary Operators:

Definition:

 A binary operator is an operator that takes two operands and performs a


specific operation.
 They are used to perform operations like arithmetic, comparison, logical
operations, bit manipulation, etc.

Classification of Binary Operators:

Binary Operator

Arithmetic Operators Relational Operators Logical Operators Bitwise Operators

1. Arithmetic Operators:

 Def : Arithmetic operators are the operators used to perform basic


mathematical operations on variables and values (operands).
 They work on numeric data types such as int, float, double, etc.
 And Associativity indicates the order in which the operators are evaluated.
That is Left to Right

List of Arithmetic Operators in C:

Operator Meaning Precedence Example Result

+ Addition 2 10 + 5 15

- Subtraction 2 10 - 5 5

* Multiplication 1 10 * 5 50

/ Division (gives quotient) 1 10 / 5 2

% Modulus (gives remainder, works with 10 % 3 1


1
integers only)

Prof. Raju Vathari Page 3


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

Example in C: Write c program to perform the basic arithmetic operations.

#include <stdio.h>
OUTPUT
int main()
{
int a = 10, b = 3;
Addition: 13
Subtraction: 7
printf("Addition: %d\n", a + b);
printf("Subtraction: %d\n", a - b); Multiplication: 30
printf("Multiplication: %d\n", a * b); Division: 3
printf("Division: %d\n", a / b);
Modulus: 1
printf("Modulus: %d\n", a % b);

return 0;
}

Arithmetic Expression in C
 Expression: An arithmetic expression in C is a combination of operands
(constants, variables) and arithmetic operators (+, -, *, /, %) that are
evaluated to produce a value.

 It works just like mathematical expressions you write on paper, but with C’s
operator rules.

Mathematical Expression C Equivalent Expression


a + b
a - b
a * b
a / b

a % b
(power) pow(a, b)
(a + b) * c
(a + b) / (c + d)

√ sqrt(a*a + b*b)

√ (-b + sqrt(b*b - 4*a*c)) / (2*a)

Prof. Raju Vathari Page 4


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

Rules for Evaluation in C


1. Parentheses first – Anything inside () is solved first.
2. Operator precedence – Among operators, * / % have higher priority than + -.
3. Associativity – If operators have the same precedence, evaluation goes left to
right.
4. Data type matters – Integer division drops decimal part, float division keeps it.

Example 1:
Mathematical Expression: 10+20∗310 + 20 * 3
C Expression:
10 + 20 * 3
Step-by-step evaluation:
1. 20 * 3 = 60 (multiplication first)
2. 10 + 60 = 70
Result = 70

Example 2:
Mathematical Expression: (10+20)∗3(10 + 20) * 3
C Expression:
(10 + 20) * 3
Step-by-step evaluation:
1. (10 + 20) = 30 (parentheses first)
2. 30 * 3 = 90
Result = 90

Example 3: Quadratic Formula


Mathematical Expression:−

C Expression:
(-b + sqrt(b*b - 4*a*c)) / (2*a)
If a = 1, b = -3, c = 2:
1. b*b = 9
2. 4*a*c = 8
3. b*b - 4*a*c = 1 So evaluation = applying
4. sqrt(1) = 1
5. -(-3) + 1 = 4
precedence + associativity +
6. 2*a = 2 parentheses rules step by step
7. 4 / 2 = 2
Result = 2 until you get a single value.

Prof. Raju Vathari Page 5


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

Increment Operator in C
Definition:

 The increment operator in C is ++.


 It increases the value of a variable by 1.
 It is mostly used with looping and repetitive tasks.

Forms of Increment Operator In simple words:

There are two types of increment operators in C:Pre-increment: "First add 1, and then use it."
 Post-increment: "First use it, and then add 1."
1. Pre-increment (++x )
2. Post-increment (x++)

1. Pre-increment (++x)

 First, the variable is increased by 1.


 Then, the new value is used in the expression.

Example:

#include <stdio.h>
int main()
{
int a = 5;
int b;

b = ++a; // a is incremented first, then assigned to b


printf("a = %d\n", a); // 6
printf("b = %d\n", b); // 6

return 0; OUTPUT
}

Explanation: a=6
b=6
 a = 5
 ++a → now a = 6
 b = 6

Prof. Raju Vathari Page 6


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

2. Post-increment (x++)

 First, the current value of the variable is used in the expression.


 Then, the variable is increased by 1.

Example:

#include <stdio.h>
int main()
{
int a = 5;
int b;

b = a++; // a is assigned first, then incremented


printf("a = %d\n", a); // 6
printf("b = %d\n", b); // 5

return 0; OUTPUT
}

Explanation: a=6
b=5
 a = 5
 b = a→b = 5
 After assignment, a++ makes a = 6

Decrement Operator in C

Definition:

 The decrement operator in C is --.


 It decreases the value of a variable by 1.
 It also has two forms:
1. Pre-decrement (--x )
2. Post-decrement (x--)

Prof. Raju Vathari Page 7


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

1. Pre-decrement (--x)

 First, the variable is decreased by 1.


 Then, the new value is used in the expression.

Example:

#include <stdio.h>
int main()
{
int a = 5;
int b;

b = --a; // a is decremented first, then assigned to b


printf("a = %d\n", a); // 4
printf("b = %d\n", b); // 4

return 0; OUTPUT
}

Explanation:
a=4
 a = 5
b=4
 --a → now a = 4
 b = 4

2. Post-decrement (x--)

 First, the current value of the variable is used in the expression.


 Then, the variable is decreased by 1.

Example:

#include <stdio.h>
int main()
{
int a = 5;
int b;

b = a--; // a is assigned first, then decremented


printf("a = %d\n", a); // 4
printf("b = %d\n", b); // 5

return 0;
} OUTPUT
Explanation:
a=4
 a = 5 b=5
 b = a→b = 5
 After assignment, a-- makes a = 4

Prof. Raju Vathari Page 8


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

Program on Increment and Decrement operator

#include <stdio.h>
int main() OUTPUT
{
int a = 5, b = 7, c;
c = 12
c = a++ + ++b - --b + a--;

printf("c = %d\n", c);

return 0;
}

Step-by-step Evaluation

Initial values:
a = 5, b = 7
Expression:
c = a++ + ++b - --b + a--;

Step 1: Break into parts

 a++ → use a=5, then a=6


 ++b → increment first → b=8, use 8
 --b → decrement first → b=7, use 7
 a-- → use a=6, then a=5

Step 2: Substitute values


c = (5) + (8) - (7) + (6)

So final result c = 12.

Prof. Raju Vathari Page 9


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

Relational Operators in C

Definition

 Relational operators in C are used to compare two values or expressions.


They always return a boolean result:
 1 (true) if the relation is correct.
 0 (false) if the relation is incorrect.

They are commonly used in decision-making statements like if, while, for.

Relational Operators Table

Operator Meaning Precedence Associativity

< Less than 1 Left to Right

> Greater than 1 Left to Right

<= Less than or equal to 1 Left to Right

>= Greater than or equal to 1 Left to Right

== Equal to 2 Left to Right

!= Not equal to 2 Left to Right

Note:

 <, >, <=, >= have higher precedence than == and !=.
 Arithmetic operators (+ - * / % ) are evaluated before relational operators.

Example Program
#include <stdio.h>
int main()
{
int a = 10, b = 20;
OUTPUT
printf("a = %d, b = %d\n", a, b);
printf("a < b : %d\n", a < b); a = 10, b = 20
printf("a > b : %d\n", a > b);
printf("a <= b : %d\n", a <= b);
a < b : 1
printf("a >= b : %d\n", a >= b); a > b : 0
printf("a == b : %d\n", a == b); a <= b : 1
printf("a != b : %d\n", a != b); a >= b : 0
a == b : 0
return 0;
}
a != b : 1

Prof. Raju Vathari Page 10


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

Logical Operators in C

Definition

 Logical operators are used to combine or invert relational/boolean


expressions.
 They return 1 (true) or 0 (false) based on logical conditions.

Logical Operators Table

Operator Meaning Precedence Associativity

&& Logical AND (true if both operands are true) 2 Left to Right

|| true if at least one condition is true. 3 Left to Right

! Logical NOT (inverts truth value) 1 Left to Right

Got it � Let’s rewrite the truth tables clearly showing that 0 = False and 1 = True.

Truth Tables of Logical Operators :

1. Logical AND (&&)

A (Input) B (Input) A && B (Result) Meaning

0 (False) 0 (False) 0 (False) Both false → false

0 (False) 1 (True) 0 (False) One false → false

1 (True) 0 (False) 0 (False) One false → false

1 (True) 1 (True) 1 (True) Both true → true

Prof. Raju Vathari Page 11


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

2. Logical OR (||)

A (Input) B (Input) A || B (Result) Meaning

0 (False) 0 (False) 0 (False) Both false → false

0 (False) 1 (True) 1 (True) One true → true

1 (True) 0 (False) 1 (True) One true → true

1 (True) 1 (True) 1 (True) Both true → true

3. Logical NOT (!)

A (Input) !A (Result) Meaning

0 (False) 1 (True) Not false = true

1 (True) 0 (False) Not true = false

Example Program:

#include <stdio.h>
int main() OUTPUT
{
int a, b, c;

a = 4; a = 1, b = 1, c = 1
b = 3;

c = a && b;
b = a || b || c;
a = a && b || c;

printf("a = %d, b = %d, c = %d\n", a, b, c);

return 0;
}

Prof. Raju Vathari Page 12


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

Bitwise Operators in C

Definition

 Bitwise operators in C are used to perform operations on individual bits of


integer values.

 They work only on integer types (int, char, long, etc.).


 Each operation is performed bit by bit (0 or 1).

Bitwise Operators Table

Operator Symbol Name Meaning / Operation

Sets each bit to 1 if both bits are 1,


& Bitwise AND
else 0

| Pipeline Bitwise OR

Sets each bit to 1 if only one bit is 1,


^ Bitwise XOR (exclusive OR)
else 0

~ Bitwise NOT (1’s Complement) Inverts all bits (0 → 1, 1 → 0)

Shifts bits to the left by given


<< Left Shift
positions, filling with 0

Shifts bits to the right by given


>> Right Shift
positions

Truth Tables (Bitwise Operators)


 Remember: Bitwise works bit by bit (0 = False, 1 = True).

1. Bitwise AND (&) 2.BitwiseOR (|) 3. Bitwise XOR

A B A&B A B A|B A B A^B

0 0 0 0 0 0 0 0 0

0 1 0 0 1 1 0 1 1

1 0 1
1 0 0 1 0 1
1 1 0
1 1 1 1 1 1

Prof. Raju Vathari Page 13


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

Example in C
#include <stdio.h>
int main()
OUTPUT
{
int a = 5, b = 3;
a = 5, b = 3
printf("a = %d, b = %d\n", a, b); a & b = 1
printf("a & b = %d\n", a & b); a | b = 7
printf("a | b = %d\n", a | b); a ^ b = 6
printf("a ^ b = %d\n", a ^ b);

return 0;
}

Shift Operators in C

Definition

 Shift operators are used to move the bits of a number left or right by a
given number of positions.

 Each shift changes the value of the number.


 Only works with integers (int, char, long, etc.).

Types of Shift Operators

Operator Symbol Name Meaning

Shifts bits to the left, filling with 0 on the right. Each left
<< Left Shift
shift multiplies the number by 2.

Shifts bits to the right, discarding bits on the right. Each


>> Right Shift right shift divides the number by 2. (For signed numbers,
behavior of negative values may depend on compiler).

Prof. Raju Vathari Page 14


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

 << → Multiply by 2 for each shift left.


 >> → Divide by 2 for each shift right.

Left Shift (<<) Operators

 The left shift(<<) is a binary operator that takes two numbers, left shifts
the bits of the first operand, and the second operand decides the number
of places to shift. In other words, left-shifting an integer "a" with an integer
"b" denoted as '(a<<b)' is equivalent to multiplying a with 2^b (2 raised to
power b).

Syntax

a << b;

where,
 a is the integer value to be shifted.
 b specifies how many positions to shift the bits.

 Example: Let's take a=21; which is 10101 in Binary Form. Now, if ―a is


left-shifted by 1‖ i.e a = a << 1 then a will become a = a * ( 2 ^ 1).
Thus, a = 21 * (2 ^ 1) = 42 which can be written as 101010.

 But if the size of the data type of a is only 5 bits, then the first bit will
be discarded we will be left with a = 10, which is 01010 in binary. It is
shown in the below image.

Prof. Raju Vathari Page 15


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM
Right Shift(>>) Operators
 Right Shift(>>) is a binary operator that takes two numbers, right shifts the
bits of the first operand, and the second operand decides the number of
places to shift. In other words, right-shifting an integer "a" with an integer "b"
denoted as '(a>>b)' is equivalent to dividing a with 2^b.

Syntax

a >> b;

where,
 a is the integer value to be shifted.
 b specifies how many positions to shift the bits.

Example: Let's take a=21; which is 10101 in Binary Form. Now, if a is right shifted
by 1 i.e a = a >> 1 then a will become a=a/(2^1). Thus, a = a/(2^1) = 10 which can
be written as 1010.

Example Program OUTPUT


#include <stdio.h>
int main() a = 5
{ a << 1 = 10
int a = 5;
a << 2 = 20
a >> 1 = 2
a >> 2 = 1
printf("a = %d\n", a);
printf("a << 1 = %d\n", a << 1); // Left shift (multiply by 2)
printf("a << 2 = %d\n", a << 2); // Left shift by 2 (multiply by 4)
printf("a >> 1 = %d\n", a >> 1); // Right shift (divide by 2)
printf("a >> 2 = %d\n", a >> 2); // Right shift by 2 (divide by 4)

return 0;
}

Prof. Raju Vathari Page 16


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

Conditional Operator in C

Definition

 The conditional operator in C is also called the ternary operator because it


uses three operands.
 It is a shorthand way of writing an if-else statement.

General form:

condition ? expression1 : expression2;

Working:

 If condition is true, the result is expression1.


 If condition is false, the result is expression2.

Example 1: Find maximum of two numbers


#include <stdio.h>
int main() OUTPUT
{
int a = 10, b = 20, max;
Maximum = 20
max = (a > b) ? a : b;

printf("Maximum = %d\n", max);


return 0;
}

OUTPUT
Example 2: Even or Odd
#include <stdio.h>
int main()
{ Odd
int num = 7;

(num % 2 == 0) ? printf("Even\n") : printf("Odd\n");

return 0;
}

Prof. Raju Vathari Page 17


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

Special Operators in C

Definition

 Special operators in C are operators that do not fall under the usual categories
(arithmetic, relational, logical, etc.) but have special purposes like handling
memory, structures, or evaluation of expressions.

Operator Meaning / Use

, (Comma) Separates expressions, evaluates left to right, last value is result

sizeof() Gives size (in bytes) of data type or variable

& Address-of operator (gives memory address)

* Dereference operator (gives value at address)

. Access structure member

-> Access structure member using pointer

Types of Special Operators

1. Comma Operator (,)

 Used to separate multiple expressions in a single statement.


 Expressions are evaluated from left to right, but the result of the rightmost
expression is taken as the final value.

Example:
OUTPUT
#include <stdio.h>
int main()
{ Before swapping: a = 20, b = 30
int a, b, c, temp;
After swapping: a = 30, b = 20
b = (a = 20, a + 10);

printf("Before swapping: a = %d, b = %d\n", a, b);


temp = a, a = b, b = temp;
printf("After swapping: a = %d, b = %d\n", a, b);
return 0;
}

Prof. Raju Vathari Page 18


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

2. sizeof() Operator

 Used to find the size (in bytes) of a data type OUTPUT


or variable.
Example:
Size of int = 4
#include <stdio.h>
Size of float = 4
int main()
{
printf("Size of int = %lu\n", sizeof(int));
printf("Size of float = %lu\n", sizeof(float));
return 0;
}

 That means both int and float take 4 bytes (32 bits) of memory.
 Note: On some systems, int may vary (2, 4, or even 8 bytes), but nowadays it’s
almost always 4 bytes.

Perfect � You want a well-structured table like the one in the image (with Precedence, Type,
Operators, and Associativity).
Here’s the complete C Operator Precedence & Associativity Table in that format:

Prof. Raju Vathari Page 19


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

C Operator Precedence, Associativity Table


Precedence Type Operators Associativity

1 Postfix () , [] , -> , . , ++ , -- Left to Right

2 Unary + , - , ! , ~ , ++ , -- , (type) , * , & , sizeof Right to Left

3 Multiplicative * , / , % Left to Right

4 Additive +,- Left to Right

5 Shift << , >> Left to Right

6 Relational < , <= , > , >= Left to Right

7 Equality == , != Left to Right

8 Bitwise AND & Left to Right

8 Bitwise XOR ^ Left to Right

9 Logical AND && Left to Right

10 Conditional ?: Right to Left

= , += , -= , *= , /= , %= , <<= , >>= , &= ,


11 Assignment Right to Left
^= , `

12 Comma , Left to Right

Prof. Raju Vathari Page 20


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

Shorthand Assignment Operators in C


Definition
 In C, assignment operators are used to assign values to variables.
 The shorthand assignment operators are a combination of an
arithmetic/bitwise operator with the assignment operator =.
 They provide a shorter way of writing statements.
Example:
 a = a + b; // long form
 a += b; // shorthand form

Syntax
variable operator= expression;
 This is equivalent to:
 variable = variable operator expression;

Table: Shorthand Assignment Operators :

Suppose we have two variables: int a = 10, b = 5;


Operator Long Form (Normal Assignment) Shorthand Assignment
+= a = a + b; a += b;
-= a = a - b; a -= b;
*= a = a * b; a *= b;
/= a = a / b; a /= b;
%= a = a % b; a %= b;
&= a = a & b; a &= b;
^= a = a ^ b; a ^= b;
<<= a = a << b; a <<= b;
>>= a = a >> b; a >>= b;

Example Program
#include <stdio.h>
int main() OUTPUT
{
int x = 3, y = 4, z = 1;
x += y; x = 3, y = 4, z = 1
y -= x;
z *= x;
printf("x = %d, y = %d, z = %d\n", x, y, z);
return 0;
}

Prof. Raju Vathari Page 21


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

Data Type Conversion in C

Definition

 Data type conversion means changing the type of a variable or expression


from one data type to another.

 In C, it can happen automatically (implicit conversion) or manually (explicit


conversion).

1.Implicit Type Conversion (Type Casting)

 Done automatically by the compiler.


 Smaller data types are converted into larger compatible types to avoid loss
of data.

Rule of Promotion Order:


char → int → float → double → long double

Example (Implicit Conversion)

#include <stdio.h>
int main()
{
int a = 10;
float b = 2.5;

float result = a + b;
printf("Result = %f", result);
return 0;
}

Here:

 a (int) is promoted to float.


 Then addition happens: 10.0 + 2.5 = 12.5

Output:

Result = 12.500000

Prof. Raju Vathari Page 22


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM
2. Explicit Type Conversion (Type Casting)

 Also called type casting.


 Programmer forces the conversion from one type to another.
 Syntax:
 (datatype) expression;

Example (Explicit Conversion)

#include <stdio.h>
int main()
{
float pi = 3.14159;
int value;

value = (int) pi; // explicit conversion from float → int


printf("Value = %d", value);
return 0;
}

Here:

 (int) pi converts 3.14159 into 3.


 Decimal part is truncated.

Output:

Value = 3

Prof. Raju Vathari Page 23


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

Mathematical Built-in Functions in C

Definition

 Mathematical functions are predefined (library) functions in C that perform


mathematical calculations such as power, square root, logarithm,
trigonometric operations, etc.

They are defined in the math.h header file.


To use them:
#include <math.h>

Table of Common Math Functions

Function Name Return Type Action / Purpose

sqrt(x) double Returns the square root of x

pow(x, y) double Returns x raised to the power y

ceil(x) double Rounds x up to the nearest integer (as double)

floor(x) double Rounds x down to the nearest integer (as double)

fabs(x) double Returns the absolute value of x (for float/double)

fmod(x, y) double Returns the remainder of x / y

sin(x) double Returns sine of x (in radians)

cos(x) double Returns cosine of x (in radians)

tan(x) double Returns tangent of x (in radians)

log(x) double Returns natural logarithm of x (base e)

log10(x) double Returns logarithm of x (base 10)

exp(x) double Returns exponential value of e^x

Prof. Raju Vathari Page 24


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

Example Program
#include <stdio.h>
#include <math.h>
int main()
{
double a = 16.0, b = 2.0;

printf("Square root of %.2f = %.2f\n", a, sqrt(a));


printf("%.2f raised to %.2f = %.2f\n", a, b, pow(a, b));
printf("Ceil of 3.4 = %.2f\n", ceil(3.4));
printf("Floor of 3.9 = %.2f\n", floor(3.9));
printf("Absolute value of -8.5 = %.2f\n", fabs(-8.5));
printf("Remainder of 17/3 = %.2f\n", fmod(17, 3));
return 0;
}

OUTPUT

Square root of 16.00 = 4.00


16.00 raised to 2.00 = 256.00
Ceil of 3.4 = 4.00
Floor of 3.9 = 3.00
Absolute value of -8.5 = 8.50
Remainder of 17/3 = 2.00

Prof. Raju Vathari Page 25


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

Header File in C

Definition

 A header file in C is a file that contains predefined functions, macros,


constants, and definitions that we can use in our program.
 Instead of writing all functions ourselves, we include the header file using
#include .

Syntax:
#include <headerfile.h>

Why use Header Files?

1. To reuse code (no need to rewrite common functions).


2. To organize code into libraries.
3. To make programs shorter and easier to read.
4. To access standard library functions like printf(), scanf(), sqrt(), etc.

Types of Header Files

1. Standard Library Header Files → provided by C itself (e.g., <stdio.h>, <math.h>)


2. User-defined Header Files → created by the programmer for specific projects

Common C Header Files Table

Header File Used For

<stdio.h> Standard Input and Output functions ( printf, scanf, gets, puts)

<stdlib.h> Memory allocation, process control, conversions ( malloc, free, exit, atoi)

<math.h> Mathematical functions (sqrt, pow, ceil, floor, sin, cos)

<string.h> String handling functions (strlen, strcpy, strcmp, strcat)

<ctype.h> Character handling (isdigit, isalpha, toupper, tolower)

<time.h> Date and time functions (time, clock, difftime, strftime)

<conio.h>* Console I/O (non-standard, Turbo C only: clrscr, getch)

<stdbool.h> Boolean data type (true, false)

Prof. Raju Vathari Page 26


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

Example Program Using Header Files


#include <stdio.h>
#include <math.h>
#include <string.h>

int main()
{
char str1[] = "Hello", str2[] = "World";
printf("Length of str1 = %lu\n", strlen(str1));
printf("Square root of 25 = %.2f\n", sqrt(25));
return 0;
}
Output:
Length of str1 = 5
Square root of 25 = 5.00

Preprocessor Directives in C

Definition

 Preprocessor directives are instructions to the compiler that are processed


before actual compilation of the program starts.
 They begin with # symbol and do not end with semicolon.

Types of Preprocessor Directives

1. Macro substitution → #define PI 3.14


2. File inclusion → #include <stdio.h>
3. Conditional compilation → #if, #ifdef, #ifndef, #endif
4. Other directives → #undef, #pragma

Example
#include <stdio.h> // File inclusion
#define PI 3.1416 // Macro definition
int main()
{
printf("Value of PI = %.2f", PI);
return 0;
}
Output:
Value of PI = 3.14

Prof. Raju Vathari Page 27


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

Control Structures: Decision making Statements - Simple if, if_else, nested if_else, else_if ladder,
Switch Case, goto, break & continue statements; Looping Statements-Entry controlled and exit
controlled statements, while, do-while, for loops, Nested loops.

Control Structures in C

Definition

A control structure in C is a programming construct that determines the flow of


execution of statements in a program.

 By default, C executes instructions sequentially (one after another).


 Using control structures, we can alter(control) this normal flow — for
decision making, looping, and branching.

Types of Control Structures in C


1. Decision-Making / Selection Control Structure
2. Looping / Iterative Control Structure
3. Jump / Branching Control Structure

1. Decision-Making Statements :

Definition

Decision-making statements in C are used to control the flow of execution based


on a condition.

 A condition is an expression that evaluates to either true (non-zero) or false


(0).
 Depending on whether the condition is true or false, different parts of code
execute.

Prof. Raju Vathari Page 28


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

1. if Statement

Definition
 Executes a block of code only if the condition is true.
 The if statement is used for deciding between two paths based on a True or
False outcome. It is represented by the following flowchart −

Syntax FLOWCHART
if(condition)
{
// statements if condition is true
}

Example
#include <stdio.h>
int main()
{
int num = 10;
if(num > 0)
{
printf("Number is positive");
}
return 0;
}

Output:
Number is positive

2. if-else Statement

Definition
 Executes one block if the condition is true, else executes another block.
 The statements inside the body of the if block get executed if and only if the
given condition is true.

Syntax
if(condition)
{
// statements if true
}
else
{
// statements if false
}

Prof. Raju Vathari Page 29


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

Example

#include <stdio.h>
int main() FLOWCHART
{
int num = 7;
if(num % 2 == 0)
{
printf("Even number");
}
else
{
printf("Odd number");
}
return 0;
}

Output:
Odd number

3. Nested if Statement

Definition

 An if inside another if. Useful for multiple level checks.


 A nested if-else means using one if-else statement inside another if-else block.
 It is used when decisions are multi-level (one decision depends on another).
 Helps when you need to check multiple conditions step by step.

Syntax FLOWCHART
if(condition1)
{
if(condition2)
{
// statements if both true
}
}

Prof. Raju Vathari Page 30


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

Example #1
#include <stdio.h>
int main()
{
int num = 25;
if(num > 0)
{
if(num % 5 == 0)
{
printf("Positive and divisible by 5");
}
}
return 0;
}
Output:
Positive and divisible by 5

Program: Largest Among Three Numbers (Nested if-else)

#include <stdio.h>
int main()
{
int a, b, c;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);

if(a > b)
{ OUTPUT
if(a > c)
{
printf("Largest = %d", a);
}
else Enter three numbers: 12 45 30
{
printf("Largest = %d", c); Largest = 45
}
}
else
{
if(b > c)
{
printf("Largest = %d", b);
}
else
{
printf("Largest = %d", c);
}
}
return 0;
}

Prof. Raju Vathari Page 31


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

4. if-else-if Ladder

Definition

 Used when we need to test multiple conditions, one after another.


 The program tests each condition from top to bottom.
 As soon as one condition is true, the corresponding block executes, and the
ladder ends.
 If none of the conditions are true, the else part (if present) executes.

Syntax
if(condition1) FLOWCHART
{
// statements
}
else if(condition2)
{
// statements
}
else if(condition3)
{
// statements
}
else
{
// default statements
}
Example
#include <stdio.h>
int main()
{
int marks = 72;
if(marks >= 90)
{
printf("Grade A");
}
else if(marks >= 75)
{
printf("Grade B");
}
else if(marks >= 50)
{
printf("Grade C"); OUTPUT
}
else
{
printf("Fail"); Grade C
}
return 0;
}

Prof. Raju Vathari Page 32


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

5. switch Statement

Definition

 C switch statement is a conditional statement that allows you to execute


different code blocks based on the value of a variable or an expression. It is
often used in place of if-else ladder when there are multiple conditions.

 Allows a variable to be tested against multiple values (cases).

 It is an alternative to if-else-if ladder when checking equality.

Syntax FLOWCHART
switch(expression)
{
case value1:
// statements
break;

case value2:
// statements
break;
...

default:
// statements if no case matches
}

Example
#include <stdio.h>
int main()
{
int day = 3;
switch(day)
{
case 1: printf("Monday"); break;
case 2: printf("Tuesday"); break;
case 3: printf("Wednesday"); break;
case 4: printf("Thursday"); break;
default: printf("Invalid day");
OUTPUT
}
return 0;
} Wednesday

Prof. Raju Vathari Page 33


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

Example #2:

#include <stdio.h>
int main()
{
int marks, grade;
printf("Enter percentage of marks: ");
scanf("%d", &marks);
grade = marks / 10;
switch(grade)
{
case 10: // For 100
case 9: // 90–99
printf("Excellent! Grade A");
break;
case 8: // 80–89
printf("Very Good! Grade B");
break;
case 7: // 70–79
printf("Good! Grade C");
break;
case 6: // 60–69
OUTPUT
printf("Average! Grade D"); Enter percentage of marks:89
break; Very Good! Grade B
case 5: // 50–59
printf("Pass! Grade E");
break;
default: // Below 50
printf("Fail! Better luck next time.");
}
return 0;
}

Prof. Raju Vathari Page 34


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

Looping Statements in c:

What is looping statement in c?

Def: A loop is used when you want to execute a block of code repeatedly until a
certain condition is met.

There are two main types of loops:

1. Entry-controlled loops → Condition is checked before entering the loop.


(Example: for, while)
2. Exit-controlled loops → Condition is checked after executing the loop once.
(Example: do-while)

1. For Loop
Definition:

 A for loop is an entry-controlled loop that allows you to execute a block of code
repeatedly with initialization, condition, and increment/decrement in a single
line.

Syntax:

for(initialization; condition; increment/decrement)


{
// Loop body (statements to execute)
}

 Initialization → executed once at the beginning (e.g., int i = 1;)


 Condition → checked before every iteration (loop continues if true)
 Increment/Decrement → updates the loop variable after each iteration

Example Program (Simple For Loop)


#include <stdio.h>

int main() OUTPUT


{
int i;
1
for(i = 1; i <= 5; i++)
{ 2
printf("%d\n", i); 3
} 4
return 0; 5
}

Prof. Raju Vathari Page 35


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

More Examples on for loop:

Example 1: Print Numbers from 1 to 10


#include <stdio.h>

int main() OUTPUT


{
int i;
for(i = 1; i <= 10; i++) 1 2 3 4 5 6 7 8 9 10
{
printf("%d ", i);
}
return 0;
}

Example 2: Print Even Numbers up to 20


#include <stdio.h>

int main()
{ OUTPUT
int i;
for(i = 1; i <= 20; i++)
{ 2 4 6 8 10 12 14 16 18 20
if(i%2==1)
{
printf("%d ", i);
}
}
return 0;
}

Example 3: Sum of First 10 Natural Numbers


#include <stdio.h>

int main()
{ OUTPUT
int i, sum = 0;
for(i = 1; i <= 10; i++)
{
sum = sum + i;
Sum = 55
}
printf("Sum = %d", sum);
return 0;
}

Prof. Raju Vathari Page 36


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

Example 4: Multiplication Table of 5 OUTPUT


#include <stdio.h> 5x1=5
5 x 2 = 10
int main() 5 x 3 = 15
{
5 x 4 = 20
int i;
5 x 5 = 25
for(i = 1; i <= 10; i++)
5 x 6 = 30
{
printf("5 x %d = %d\n", i, 5*i); 5 x 7 = 35
} 5 x 8 = 40
return 0; 5 x 9 = 45
} 5 x 10 = 50

Example 5: Print Numbers in Reverse Order


OUTPUT
#include <stdio.h>

int main() 10 9 8 7 6 5 4 3 2 1
{
int i;
for(i = 10; i >= 1; i--)
{
printf("%d ", i);
}
return 0;
}

Prof. Raju Vathari Page 37


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

2. Nested For Loop


Definition:

 A nested loop means having one loop inside another loop. The inner loop runs
completely for every single iteration of the outer loop.

Syntax:
for(initialization; condition; increment/decrement)
{
for(initialization; condition; increment/decrement)
{
// Inner loop body
}
// Outer loop body
}

Example Program (Pattern Printing)


#include <stdio.h>

int main() OUTPUT


{ * * * *
int i, j; * * * *
for(i = 1; i <= 3; i++) // Outer loop * * * *
{
for(j = 1; j <= 4; j++) // Inner loop
{
printf("* ");
}
printf("\n"); // Move to next line after inner loop ends
}
return 0;
}

Prof. Raju Vathari Page 38


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

Example 2: Right-Angle Triangle


#include <stdio.h>
int main()
{
int i, j; OUTPUT
for(i = 1; i <= 5; i++)
{ *
for(j = 1; j <= i; j++) * *
{ * * *
printf("* "); * * * *
} * * * * *
printf("\n");
}
return 0;
}

Example 3: Number Triangle


#include <stdio.h>
int main()
{
int i, j;
for(i = 1; i <= 5; i++)
{
for(j = 1; j <= i; j++)
{
printf("%d ", j);
}
printf("\n"); OUTPUT
}
return 0; 1
} 1 2
1 2 3
1 2 3 4
1 2 3 4 5

Prof. Raju Vathari Page 39


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

While Loop:

Definition of while loop

 A while loop is a control flow statement that repeatedly executes a block of


code as long as a given condition is true. It is commonly used when the
number of iterations is not known in advance.

Syntax (in C programming)

while (condition)
{
// code to be executed
}

 condition → an expression that evaluates to true (non-zero) or false (0).


 The loop continues running as long as the condition is true.

Example

Let’s write a simple program that prints numbers from 1 to 5 using a while loop:

#include <stdio.h>
int main()
{
int i = 1;

while (i <= 5)
{ OUTPUT
printf("%d\n", i);
i++; 1
} 2
3
return 0; 4
} 5

Prof. Raju Vathari Page 40


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

Lab #6) Program to read a number, find the sum of the digits, reverse the number
and check it for palindrome.
Program:
#include <stdio.h>
void main()
{
int num, temp, digit, sum = 0, reverse = 0;

// Read number from user


printf("Enter a number: ");
scanf("%d", &num);

temp = num;

while (num > 0)


{
digit = num % 10;
sum = sum + digit;
reverse = reverse * 10 + digit;
num =num / 10;
}

// Display results
printf("Sum of digits = %d\n", sum);
printf("Reversed number = %d\n", reverse);

// Check palindrome
if (temp == reverse)
{
printf("The number is a palindrome.\n");
}
else
{
printf("The number is not a palindrome.\n");
}
}

OUTPUT #1 OUTPUT #2

Enter a number: 456 Enter a number: 121


Sum of digits = 15 Sum of digits = 4
Reversed number = 654 Reversed number = 121
The number is not a palindrome. The number is a palindrome.

Prof. Raju Vathari Page 41


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

Do - while Loop:

Definition of do...while loop

A do...while loop is similar to a while loop, but the difference is that it executes the
block of code at least once before checking the condition. After the first
execution, it keeps repeating as long as the condition is true.

Usage of do...while loop

 When you want the loop body to run at least once, no matter what.
 Useful in menu-driven programs, input validation, or cases where the action
must happen first and then the condition is checked.

do Intialization
Syntax {OR OR do
// code to be executed {
// code to be executed
} while (condition); Increment/decrement
} while (condition);

Example

Program to print numbers from 1 to 5 using do...while:

#include <stdio.h>
int main()
{
int i = 1;
OUTPUT
do
{ 1
printf("%d \n", i); 2
i++; 3
} while (i <= 5); 4
5
return 0;
}

Prof. Raju Vathari Page 42


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

Difference Between while and do while loop in table format

while loop do...while loop

Condition is checked first, then statements Statements are executed at least once,
are executed. then the condition is checked.

Statements may execute zero times if the Statements execute at least once,
condition is false initially. regardless of the condition.

No semicolon after the while(condition)


Requires a semicolon after while(condition);
statement.

The variable used in the condition must be The variable may be initialized before or
initialized before the loop starts. inside the loop.

It is an entry-controlled loop (condition It is an exit-controlled loop (condition


checked before entry). checked after execution).

Syntax: Syntax:
while (condition) do
{ {
statement(s); statement(s);
} } while (condition);

Prof. Raju Vathari Page 43


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

Unconditional or Jump Control Statement in C

Definition

Unconditional or jump control statements in C are used to transfer the control of


program execution directly to another part of the program, without checking any
condition.
These statements break the normal sequential flow of execution.

C provides four jump statements:

1. break
2. continue
3. goto
4. return

1. break Statement

Definition: Immediately terminates the loop or switch statement and transfers


control to the statement following it.

Syntax:

break;

Example:

#include <stdio.h>
int main()
{
for (int i = 1; i <= 5; i++)
{
if (i == 3)
{
break; // exit loop when i == 3
}
OUTPUT
printf("%d\n", i);
}
1
return 0;
} 2

Prof. Raju Vathari Page 44


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM
2. continue Statement

Definition: Skips the current iteration of a loop and jumps to the next iteration.

Syntax:

continue;

Example:

#include <stdio.h>
int main()
{
for (int i = 1; i <= 5; i++)
{
if (i == 3)
{
continue; // skip when i == 3
}
printf("%d\n", i);
}
return 0; OUTPUT
}
1

3. goto Statement
Definition: Transfers control unconditionally to a labeled statement in the same function.

Syntax:

Prof. Raju Vathari Page 45


Department of BCA UNIT – II OPERATORS AND EXPRESSIONS I-SEM

Example:
#include <stdio.h>
int main()
{
int i = 1;
loop:
printf("%d\n", i);
i++;
if (i <= 3)
{
goto loop; // jump to label
OUTPUT
}
return 0; 1

} 2

4. return Statement

Definition: Ends the execution of a function and optionally returns a value to the
caller.

Syntax:

return value; // for functions with a return type

Example:
OUTPUT
#include <stdio.h>
int add(int a, int b)
{
return a + b; Result = 8
}

int main()
{
int result = add(5, 3);
printf("Result = %d\n", result);
return 0;
}

Prof. Raju Vathari Page 46

You might also like