0% found this document useful (0 votes)
3 views47 pages

C Programming Notes

Notes of c programming

Uploaded by

manyajgowda753
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)
3 views47 pages

C Programming Notes

Notes of c programming

Uploaded by

manyajgowda753
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

@azdocuments

INTRODUCTION TO
C PROGRAMMING
SUBJECT CODE: 1BPLC205E/105E

MODULE-2

Name:

USN:

College:

AZ Documents
Your Engineering Study Partner
[Link]
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

INTRODUCTION TO C PROGRAMMING
1BPLC205E/105E
MODULE-02
Operators: Introduction to Operators, Arithmetic Operators, Relational Operators,
Logical Operators, Assignment Operators, Increment and Decrement Operators,
Conditional Operators, Precedence of Arithmetic Operators.
Decision Making, Branching, Looping: Introduction, Decision Making with IF
Statement, Simple IF Statement, The IF..ELSE Statement, Nesting of IF..ELSE
Statements, The ELSE IF Ladder, The Switch Statement, The ?: Operator, The GOTO
Statement, WHILE, DO, FOR, Jumps in LOOPS.
Textbook: Chapter 4.1 to 4.7, 4.12, Chapter 6.1 to 6.9, Chapter 7.1 to 7.5

OPERATORS IN C

C programming language provides a rich set of built-in operators that help programmers perform
various operations on data.

An operator is a symbol that instructs the computer to perform a specific operation such as:

• arithmetic calculation

• comparison

• logical decision
• bit manipulation

Operators act on operands.

Example

a+b

Here:

• + → operator

• a and b → operands
Operators are usually used in expressions.

Expression

An expression is a combination of variables, constants, and operators that produces a single value.

[Link] 1
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

Example
10 + 15

Value of expression = 25

Types of Operators in C

C operators are classified into the following categories:

1. Arithmetic operators

2. Relational operators
3. Logical operators

4. Assignment operators

5. Increment and decrement operators

6. Conditional operator
7. Bitwise operators

8. Special operators

1. Arithmetic Operators
Arithmetic operators are used to perform mathematical calculations.

List of Arithmetic Operators

Operator Meaning

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus (remainder)

Example

a+b
a-b
a*b

[Link] 2
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

a/b
a%b

Integer Arithmetic

When both operands are integers, the result is also an integer.

Example:

int a = 14;
int b = 4;

Results:

a + b = 18
a - b = 10
a * b = 56
a/b=3
a%b=2

Note:

Integer division removes the decimal part.

Real Arithmetic

If operands are floating point numbers, the operation is called real arithmetic.

Example:

6.0 / 7.0 = 0.857143


1.0 / 3.0 = 0.333333

Floating-point values are approximate values due to precision limits.

[Link] 3
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

Mixed Mode Arithmetic


When one operand is integer and the other is floating point.

Example:

15 / 10 = 1
15 / 10.0 = 1.5

If one operand is real, the result becomes real.

Program Using Arithmetic Operators

#include <stdio.h>

int main()
{
int a = 14, b = 4;

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


printf("Subtraction = %d\n", a - b);
printf("Multiplication = %d\n", a * b);
printf("Division = %d\n", a / b);
printf("Remainder = %d\n", a % b);

return 0;
}

2. Relational Operators

Relational operators are used to compare two values.

The result of relational operation is either:

• 1 (true)

• 0 (false)

List of Relational Operators

Operator Meaning

< Less than

> Greater than

[Link] 4
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

Operator Meaning

<= Less than or equal

>= Greater than or equal

== Equal to

!= Not equal

Example

10 < 20 → TRUE
20 < 10 → FALSE

Example Program

#include <stdio.h>

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

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


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

return 0;
}

3. Logical Operators

Logical operators are used when multiple conditions must be tested together.

Types of Logical Operators

Operator Meaning

&& Logical AND

! Logical NOT

[Link] 5
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

Logical AND (&&)


Returns TRUE only if both conditions are true.

Example

a > b && x == 10

Logical OR (||)

Returns TRUE if any one condition is true.

Example
number < 0 || number > 100

Logical NOT (!)

Reverses the condition.


Example

!(a > b)

Program Using Logical Operators


#include <stdio.h>
int main()
{
int age = 60;
int salary = 900;

if(age > 55 && salary < 1000)


printf("Condition satisfied\n");

return 0;
}

4. Assignment Operators

Assignment operators are used to assign values to variables.

Basic Assignment

[Link] 6
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

Example
a = 10

Shorthand Assignment Operators

Operator Equivalent

+= a=a+b

-= a=a-b

*= a=a*b

/= a=a/b

%= a=a%b

Example
x += y

means

x=x+y

Program Using Assignment Operator

#include <stdio.h>

int main()
{
int x = 5;

x += 3;
printf("Value of x = %d\n", x);

return 0;
}

5. Increment and Decrement Operators


C provides two special operators:

++
--

[Link] 7
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

These are called increment and decrement operators.

Increment Operator (++)

Adds 1 to the variable.

Example

i++

Decrement Operator (--)


Subtracts 1 from the variable.

Example

i--

Prefix Increment

++i

Value is incremented before use.

Example
i=5
y = ++i
Result:

i=6
y=6

Postfix Increment

i++

Value is incremented after use.

Example

i=5
y = i++

Result:

[Link] 8
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

y=5
i=6

Program Example

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

printf("%d\n", ++a);
printf("%d\n", a++);

return 0;
}

6. Conditional Operator

The conditional operator is written as:

?:
It is also called ternary operator.

Syntax

condition ? expression1 : expression2

Example

x = (a > b) ? a : b;
Meaning:
If a > b → x = a
Else → x = b
Program Example

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

[Link] 9
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

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

return 0;
}

7. Bitwise Operators

Bitwise operators operate on individual bits of data.

They are mainly used in system programming.

Bitwise Operators

Operator Meaning

& Bitwise AND

^ Bitwise XOR

~ Bitwise NOT

<< Left shift

>> Right shift

Example

5&3
Binary
5 = 101
3 = 011
Result = 001

Program Example

#include <stdio.h>
int main()
{
int a = 5, b = 3;
printf("a & b = %d\n", a & b);
printf("a | b = %d\n", a | b);

[Link] 10
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

return 0;
}

8. Special Operators

C provides several special operators.

Comma Operator

The comma operator evaluates multiple expressions.

Example

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

Result:
value = 15

sizeof Operator

The sizeof operator returns the size of a variable or data type in bytes.

Example

sizeof(int)
sizeof(float)

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

Pointer Operators

C also supports pointer operators:

&
*

[Link] 11
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

Example
& → address operator
* → pointer operator

ARITHMETIC EXPRESSIONS IN C

Definition

An arithmetic expression is a combination of:

• constants

• variables

• arithmetic operators

arranged according to the syntax rules of C programming language.


These expressions are used to perform mathematical calculations.

Example

a+b
x*y
a*b-c
(a + b) / c

C can handle very complex mathematical expressions involving multiple operators and variables.
However, unlike some other programming languages, C does not have an exponentiation operator.

For example:


cannot be written as x^2 in C because ^ is a bitwise operator.

Instead we use functions like:

pow(x,2)

from the math library.

EVALUATION OF EXPRESSIONS

Arithmetic expressions are usually evaluated in an assignment statement.

General form:

variable = expression;

[Link] 12
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

Process of evaluation
1. The expression on the right side is evaluated first.

2. The computed result is assigned to the variable on the left side.

3. The previous value of the variable is replaced by the new value.

Example

x = a * b - c;

Evaluation steps:

1. Multiply a and b
2. Subtract c

3. Assign result to x

Example Expressions
x = a * b - c;
y = b / c * a;
z = a - b / c + d;

Before evaluating these expressions, all variables must be initialized.

Example:

a = 10;
b = 5;
c = 2;

Then expression evaluation can occur correctly.

PRECEDENCE OF ARITHMETIC OPERATORS

When an expression contains multiple operators, the order in which they are executed depends on
operator precedence.

Arithmetic Operator Precedence

Priority Operators

High */%

Low +-

This means multiplication and division are evaluated before addition and subtraction.

[Link] 13
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

Example Expression
x = a - b/3 + c*2 - 1

Let:

a=9
b = 12
c=3
Expression becomes:

x = 9 - 12/3 + 3*2 - 1

Evaluation Process

First Pass (High Priority Operators)

12/3 = 4
3*2 = 6
Expression becomes

x=9-4+6-1

Second Pass (Low Priority Operators)

9-4=5
5 + 6 = 11
11 - 1 = 10
Final result:

x = 10

ROLE OF PARENTHESES

Parentheses change the order of evaluation.

Expressions inside parentheses are evaluated first.

Example:

9 - 12/(3+3)*(2-1)
Step 1

3+3 = 6
2-1 = 1

[Link] 14
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

Expression becomes
9 - 12/6 * 1

Step 2

12/6 = 2

Step 3

9 - 2*1

Step 4

9-2=7
Final result:

NESTED PARENTHESES
Parentheses can also be nested.

Example:

9 - (12/(3+3) * 2) - 1

Evaluation starts from the innermost parentheses.


Steps:

3+3 = 6
12/6 = 2
2*2 = 4
9-4 = 5
5-1 = 4

Final result:

RULES FOR EVALUATION OF EXPRESSIONS

1. Expressions inside parentheses are evaluated first.

2. Nested parentheses are evaluated from innermost to outermost.

3. Operator precedence determines which operator is applied first.

4. Operators of same precedence follow associativity rules.

[Link] 15
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

5. Arithmetic expressions are generally evaluated left to right.

COMPUTATIONAL PROBLEMS

Certain computational problems may arise while evaluating expressions.

1 Floating Point Approximation Error

Computers store real numbers approximately.

Example:
a = 1.0/3.0
b = a * 3.0

Mathematically:
(1/3) × 3 = 1

But computer may produce

0.999999

This is called round-off error.

2 Division by Zero

If a program tries to divide by zero:


x=a/0

The program may


• terminate abnormally

• produce meaningless result

Programmers must ensure denominator is not zero.

Example:

if(b != 0)
result = a/b;

3 Overflow and Underflow


Overflow

[Link] 16
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

Occurs when a value exceeds the maximum limit of a data type.


Example:

int x = 40000

on a 16-bit system.

Underflow

Occurs when a number becomes too small to represent.

TYPE CONVERSION IN EXPRESSIONS

C allows expressions with different data types.

Example:

int + float
To evaluate such expressions, C converts data types automatically.

This is called type conversion.

IMPLICIT TYPE CONVERSION


Implicit conversion means automatic type conversion performed by the compiler.

Example:

int a = 10;
float b = 2.5;

c = a + b;

Here
a → converted to float

Result becomes float.

Conversion Hierarchy

Lower types are converted into higher types.

char

[Link] 17
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

int

long

float

double

long double

Example

int + double → double


float + double → double

FINAL ASSIGNMENT CONVERSION

After expression evaluation, the result is converted to the type of the variable on the left side.
Example:
int x;
x = 10.75;
Result:

x = 10

Fractional part is removed.

EXPLICIT TYPE CONVERSION (CASTING)


Sometimes the programmer forces type conversion manually.

This is called explicit type conversion or casting.


Syntax
(type) expression

Example

ratio = (float) female_number / male_number;

Here

female_number → converted to float

[Link] 18
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

Division becomes floating-point division.

Example Program

#include<stdio.h>

int main()
{
int a = 5, b = 2;
float result;

result = (float)a / b;

printf("Result = %f", result);

return 0;
}
Output

2.500000

Without casting result would be

ROUNDING USING CAST

Casting can also help in rounding values.


Example

x = (int)(y + 0.5);

If

y = 27.6

then

27.6 + 0.5 = 28.1

After casting
x = 28

OPERATOR PRECEDENCE AND ASSOCIATIVITY

[Link] 19
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

When an expression contains multiple operators, two rules determine evaluation:


1. Precedence

2. Associativity

Operator Precedence

Precedence determines which operator is executed first.

Example

x = 10 + 15 * 2
Multiplication has higher precedence.

So

15 * 2 = 30
10 + 30 = 40

Associativity

Associativity determines evaluation order when operators have same precedence.

Example

10 - 5 - 2

Associativity is left to right


(10 - 5) - 2
=3

Example of Precedence and Associativity

if(x == 10 + 15 && y < 10)

Step 1

10 + 15 = 25

Expression becomes

if(x == 25 && y < 10)

Step 2
Evaluate relational operators.

[Link] 20
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

x == 25
y < 10

Step 3
Evaluate logical operator &&.

MATHEMATICAL FUNCTIONS IN C

C provides several mathematical functions in the math library.

To use them:

#include <math.h>

Common Mathematical Functions

Function Purpose

sqrt(x) Square root

pow(x,y) x raised to power y

sin(x) Sine

cos(x) Cosine

log(x) Natural logarithm

exp(x) Exponential

Example Program

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

int main()
{
double x = 16;

printf("Square root = %lf", sqrt(x));

return 0;
}
Output

[Link] 21
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

Square root = 4.000000


DECISION MAKING AND BRANCHING IN C

In programming, it is often necessary to make decisions and execute different statements depending on
certain conditions. Real-world problems frequently require programs to evaluate conditions and take
appropriate actions based on the results of those conditions.

For example:
• If a student scores more than 40 marks, the student passes the examination.

• If the bank balance is zero, the user must borrow money.

• If a room is dark, the light should be turned on.

Such situations require decision-making capabilities in programs.

The C programming language supports several statements that allow programs to make decisions and
control the flow of execution. These statements evaluate conditions and decide which part of the
program should execute.

These statements are known as decision-making statements or control statements because they
control the execution flow of the program.

Decision Making Statements in C

C language provides the following statements for decision making:

1. if statement

2. if...else statement
3. nested if...else statement

4. else-if ladder

5. switch statement

6. conditional operator (? :)

7. goto statement

Each of these statements allows the program to choose between alternative actions depending on the
result of a condition.

Decision Making with if Statement

The if statement is the most fundamental and powerful decision-making statement in C programming.

[Link] 22
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

It allows the program to test a condition and execute a statement or group of statements only when the
condition is true.

General Syntax
if (test_expression)
{
statement-block;
}

Working of if Statement

1. The condition inside the parentheses is evaluated first.

2. If the condition is true (non-zero), the statements inside the block are executed.

3. If the condition is false (zero), the statements inside the block are skipped.
Thus, the program execution follows one of two possible paths depending on the result of the condition.

Simple if Statement

The simple if statement is the simplest form of decision control.

Syntax

if (condition)
{
statement-block;
}
statement-x;
Explanation

• If the condition is true, the statements inside the block are executed.

• If the condition is false, the block is skipped and the program continues with the next statement.

Example

if (marks >= 40)


{
printf("Student Passed");
}
If marks are greater than or equal to 40, the message is printed.

Program Example

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

[Link] 23
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

int marks = 75
if(marks >= 40)
{
printf("Student Passed");
}
return 0;
}

Output:
Student Passed

Use of if Statement in Counting

The if statement is often used in counting operations.

Example:

if(weight < 50 && height > 170)


count = count + 1;

This checks two conditions simultaneously:

• Weight must be less than 50

• Height must be greater than 170


If both conditions are true, the count variable increases.

Applying De Morgan's Rule

Sometimes conditions become complicated and difficult to understand.


Example:

!(x && y || !z)

This expression is difficult to read.


To simplify such expressions, De Morgan's Rule is applied.

De Morgan's Rule

!(A && B) = !A || !B
!(A || B) = !A && !B

Example:

!(x <= 0 || !condition)

[Link] 24
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

becomes
x > 0 && condition

This makes the logic clearer.

The if...else Statement

The if...else statement extends the simple if statement by providing an alternative action when the
condition is false.

Syntax

if(condition)
{
true-block;
}
else
{
false-block;
}

Working

• If the condition is true, the statements in the true block execute.

• If the condition is false, the statements in the false block execute.

Only one block is executed.

Example

if(number % 2 == 0)
printf("Even Number");
else
printf("Odd Number");

Program Example
#include<stdio.h>
int main()
{
int number;
printf("Enter a number: ");
scanf("%d",&number);

[Link] 25
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

if(number % 2 == 0)
printf("Number is Even");
else
printf("Number is Odd");
return 0;
}

Nested if...else Statements

When more than one decision must be made, nested if statements are used.

A nested if statement is an if statement placed inside another if statement.

Syntax

if(condition1)
{
if(condition2)
{
statement1;
}
else
{
statement2;
}
}
else
{
statement3;
}

Working

1. First condition1 is tested.

2. If it is true, condition2 is tested.


3. Based on condition2, the corresponding statement executes.

4. If condition1 is false, statement3 executes.

Example
Suppose a bank offers a bonus to account holders:

• Everyone receives 2% bonus.

[Link] 26
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

• Female customers with balance greater than 5000 receive 5% bonus.


Example logic:

if(sex == 'F')
{
if(balance > 5000)
bonus = balance * 0.05;
}
else
{
bonus = balance * 0.02;
}

Dangling Else Problem


A common issue with nested if statements is the dangling else problem.

This occurs when it is unclear which if statement the else belongs to.

Example:

if(condition1)
if(condition2)
statement1;
else
statement2;

Here the else is associated with the nearest unmatched if.

Rule:
else always matches with the closest if

To avoid confusion, braces { } should be used.

Else-if Ladder

When multiple conditions must be tested sequentially, the else-if ladder is used.

Syntax

if(condition1)
statement1;
else if(condition2)
statement2;

[Link] 27
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

else if(condition3)
statement3;

else
default-statement;

Working

1. Condition1 is tested.

2. If true, statement1 executes.

3. If false, condition2 is tested.

4. The process continues until a true condition is found.

5. If none of the conditions are true, the default statement executes.

Example: Student Grading

if(marks >= 90)


grade = 'A';

else if(marks >= 75)


grade = 'B';

else if(marks >= 50)


grade = 'C';

else
grade = 'F';

Program Example

#include<stdio.h>
int main()
{
int marks;
printf("Enter marks: ");
scanf("%d",&marks);

if(marks >= 90)


printf("Grade A");

else if(marks >= 75)

[Link] 28
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

printf("Grade B");
else if(marks >= 50)
printf("Grade C");

else
printf("Fail");

return 0;
}

Switch Statement

When many alternatives must be selected, the switch statement is used.

It provides a multi-way branching mechanism.


Syntax

switch(expression)
{
case value1:
statements;
break;

case value2:
statements;
break;

default:
statements;
}

Working
1. The expression is evaluated.

2. Its value is compared with each case label.

3. When a matching case is found, the corresponding statements execute.

4. The break statement terminates the switch block.

5. If no match is found, the default case executes.

[Link] 29
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

Example
switch(day)
{
case 1:
printf("Monday");
break;

case 2:
printf("Tuesday");
break;

default:
printf("Invalid Day");
}

Program Example
#include<stdio.h>

int main()
{
int day;

printf("Enter day number: ");


scanf("%d",&day);

switch(day)
{
case 1: printf("Monday"); break;
case 2: printf("Tuesday"); break;
case 3: printf("Wednesday"); break;
case 4: printf("Thursday"); break;
case 5: printf("Friday"); break;
case 6: printf("Saturday"); break;
case 7: printf("Sunday"); break;
default: printf("Invalid Day");
}

return 0;
}

[Link] 30
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

Rules for Switch Statement


1. Switch expression must be an integer or character.

2. Case labels must be constant values.

3. Case labels must be unique.

4. Each case label ends with a colon.

5. Break statement exits the switch block.

6. Default case is optional.

7. Nested switch statements are allowed.

Conditional Operator (? :)

C provides a special operator called the conditional operator.

This operator replaces simple if...else statements.


Syntax

condition ? expression1 : expression2

Working

• If condition is true → expression1 executes.


• If condition is false → expression2 executes.

Example

max = (a > b) ? a : b;

This selects the larger number.

Program Example
#include<stdio.h>
int main()
{
int a = 10, b = 20, max;
max = (a > b) ? a : b;
printf("Maximum = %d", max);
return 0;
}

[Link] 31
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

Goto Statement
The goto statement transfers control unconditionally to another part of the program.

Syntax

goto label;

label:
statement;

Example
#include<stdio.h>

int main()
{
int i = 1;

start:
printf("%d\n",i);
i++;

if(i <= 5)
goto start;

return 0;
}

Output

1
2
3
4
5

Forward and Backward Jump

Forward Jump

Control jumps forward in the program.

Backward Jump

Control jumps to a previous statement forming a loop.

[Link] 32
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

Disadvantages of goto
• Makes program difficult to understand

• Breaks structured programming

• Creates infinite loops

Therefore goto should be used carefully and rarely.

Decision-making statements allow programs to execute different instructions depending on specific


conditions. These statements are essential for controlling program execution and implementing logical
operations. C provides several powerful constructs such as if, if-else, nested if, else-if ladder, switch,
conditional operator, and goto to implement decision-making effectively.

LOOPING IN C (ITERATION STATEMENTS)

In many programs it becomes necessary to execute a group of statements repeatedly. Such repeated
execution of a sequence of statements is known as looping or iteration.

In real-life programming problems, many operations must be repeated multiple times. For example:

• Calculating the sum of numbers from 1 to 100

• Printing multiplication tables

• Processing marks of students

• Searching for a particular item in a list


Earlier, repetition could be achieved by using if statements and goto statements, but this method was
inconvenient and made programs difficult to understand.
Consider a program that calculates the sum of squares of numbers from 1 to 10. The statement

sum = sum + n*n;

must be executed 10 times.

To perform such repeated tasks efficiently, C provides special looping constructs.

Looping structures allow programmers to write concise programs that perform repetitive operations
without using multiple goto statements.

[Link] 33
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

Concept of Loop

A loop is a program structure that repeats a block of statements until a specified condition becomes
false.

A typical loop consists of two major parts:

1. Body of the loop

2. Control statement

Body of the loop


This contains the statements that must be executed repeatedly.

Control statement

This tests a condition to determine whether the loop should continue or terminate.

LOOP CONTROL STRUCTURES

[Link] 34
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

Depending on the position of the test condition, loops are classified into two types:
1 Entry-Controlled Loop (Pre-test Loop)

In this type of loop, the condition is tested before entering the loop body.

If the condition is false, the loop body will not execute even once.

Examples:

• while loop

• for loop

2 Exit-Controlled Loop (Post-test Loop)

In this type of loop, the condition is tested after executing the loop body.

Therefore the loop body executes at least once, regardless of the condition.

Example:
• do-while loop

Steps Involved in Looping

A loop normally contains the following steps:


1. Initialization of the control variable

2. Execution of the loop body

3. Testing the loop condition

4. Updating the control variable

These steps continue until the termination condition is satisfied.

Types of Loop Control Based on Variable


Loops can also be classified based on how the loop is controlled.

1 Counter Controlled Loops

In a counter controlled loop, the number of repetitions is known in advance.

A variable called counter variable is used to control the number of loop executions.

Example

for(i = 1; i <= 10; i++)

[Link] 35
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

This loop executes exactly 10 times.


These loops are also known as definite loops.

2 Sentinel Controlled Loops

In a sentinel loop, repetition continues until a special value called sentinel value is encountered.

Example

while(number != -1)

Here -1 acts as a sentinel value indicating the end of input.


These loops are also known as indefinite loops because the number of repetitions is unknown.

Looping Statements in C

C provides three main looping constructs:


1. while loop

2. do-while loop

3. for loop

The while Statement

The while loop is the simplest looping structure in C.

It is an entry-controlled loop, meaning the condition is tested before the loop body executes.

Syntax

while (test_condition)
{
statements;
}

Working of while Loop

1. The test condition is evaluated first.

2. If the condition is true, the loop body executes.

3. After executing the loop body, the condition is tested again.

4. This process continues until the condition becomes false.

When the condition becomes false, control transfers to the statement immediately following the loop.

[Link] 36
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

Example: Sum of Squares Using while Loop


#include<stdio.h>
int main()
{
int n = 1, sum = 0;
while(n <= 10)
{
sum = sum + n*n;
n++;
}
printf("Sum = %d", sum);
return 0;
}
This loop executes 10 times, calculating the sum of squares.

Sentinel Loop Example using while

char character = ' ';


while(character != 'Y')
{
character = getchar();
}

This loop continues until the user enters Y.

Here:
• Y is the sentinel value

• character is the sentinel variable

Example: Calculating Power using while Loop

[Link] 37
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

y = 1;
count = 1;

while(count <= n)
{
y = y * x;
count++;
}

This loop computes xⁿ by multiplying x repeatedly.

THE DO-WHILE STATEMENT


The do-while loop is an exit-controlled loop.

In this loop, the body executes first and the condition is tested afterward.

Syntax
do
{
statements;
}
while(condition);

Characteristics
• Loop body executes at least once

• Condition is tested after executing the loop body

[Link] 38
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

Example Program
#include<stdio.h
int main()
{
int number;

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

}while(number > 0);


return 0;
}

This loop continues until the user enters zero or negative number.

NESTED DO-WHILE EXAMPLE

Nested loops occur when one loop exists inside another loop.

Example: printing multiplication table.

Outer loop controls rows and inner loop controls columns.

[Link] 39
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

THE FOR STATEMENT


The for loop is the most commonly used loop in C.

It is an entry-controlled loop and provides a compact way to write loops.

Syntax

for(initialization; condition; increment)


{
statements;
}

Working of for Loop

1. Initialization is executed first.

2. The test condition is evaluated.

3. If true, the loop body executes.


4. After execution, increment/decrement statement runs.

5. The condition is tested again.

This process repeats until the condition becomes false.


Example: Print Numbers 0 to 9

for(i = 0; i < 10; i++)


{
printf("%d", i);
}

Output:

0123456789

[Link] 40
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

Negative Increment Example


for(i = 9; i >= 0; i--)
{
printf("%d", i);
}

Output

9876543210

Example: Sum of Squares using for

for(n = 1; n <= 10; n++)


{
sum = sum + n*n;
}

Additional Features of for Loop

The for loop has several advanced capabilities.


Multiple Initialization

for(i = 0, j = 10; i < j; i++, j--)

Two variables are initialized simultaneously.

Complex Test Conditions

for(i = 1; i < 20 && sum < 100; i++)

The loop continues while both conditions are true.

Expressions in Initialization

for(x = (m+n)/2; x > 0; x = x/2)

Infinite Loop

If the condition is omitted:

for(;;)

This creates an infinite loop.

[Link] 41
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

Time Delay Loop


for(j = 1000; j > 0; j--)
;
The semicolon represents a null statement.

Nested for Loops

A loop inside another loop is called a nested loop.

Example:

for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
{
printf("*");
}
printf("\n");
}

This prints a square pattern.

C allows up to 15 levels of loop nesting.

Selecting the Appropriate Loop


When choosing a loop, consider the following:

1. If the loop condition must be checked before execution → use while or for.

2. If the loop must execute at least once → use do-while.

3. If number of iterations is known → use for loop.

4. If loop termination depends on a special value → use while loop.

[Link] 42
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

JUMP STATEMENTS IN LOOPS


Sometimes we may want to alter the normal flow of loops.

C provides several jump statements:

1. break

2. continue

3. goto

Break Statement
The break statement terminates the loop immediately.

Control transfers to the statement following the loop.

Example

for(i=1;i<=10;i++)
{
if(i == 5)
break;

printf("%d", i);
}

Output

1234

Continue Statement

The continue statement skips the remaining part of the loop and starts the next iteration.
Example

for(i=1;i<=5;i++)
{
if(i == 3)
continue;

printf("%d", i);
}

Output

1245

[Link] 43
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

Use of Continue Example

If a program calculates square roots:

• Negative numbers must be skipped.

if(number < 0)
{
printf("Negative number");
continue;
}

Exit Function
A program can terminate completely using:

exit(0);

This function is defined in

#include<stdlib.h>

exit(0) indicates normal termination.

Structured Programming
Structured programming is a disciplined programming technique that improves program readability and
maintainability.
It is based on three fundamental control structures:

1. Sequence – statements executed one after another

2. Selection – decision making (if, switch)

3. Repetition – loops (while, for, do-while)

Structured programming discourages the use of goto statements.

Programs designed using structured programming are:

• easier to understand

• easier to debug
• easier to maintain

[Link] 44
INTRODUCTION TO C PROGRAMMING MODULE-02 AZ Documents

Concise Test Expressions


In C, any integer expression can act as a condition.

Example

if(expression != 0)

can be written as

if(expression)

Similarly

if(expression == 0)
can be written as

if(!expression)

Example

if(m%5 == 0 && n%5 == 0)


can also be written as

if(!(m%5) && !(n%5))

Looping statements are essential for performing repetitive tasks efficiently in C programs. The three
looping constructs—while, do-while, and for—provide flexible ways to control repetition. Additional
control mechanisms such as break, continue, and exit allow programmers to alter the flow of loops
when necessary. Proper use of structured programming techniques ensures that programs remain
readable, maintainable, and logically organized.

[Link] 45
Thank You
We’re glad to be part of your engineering journey.
Keep exploring, keep innovating, and keep growing.

AZ Documents
Your Engineering Study Partner
[Link]

Quality notes, simplified explanations, and


student-focused resources for every semester.

Connect With Us:


[Link] [Click Here]

@azdocuments [Click Here]


Join Our Student Community: [Click Here]

© 2025 AZ Documents. All rights reserved.


This material is intended for educational purposes only.
Redistribution without permission is prohibited.

You might also like