0% found this document useful (0 votes)
20 views34 pages

Unit Ii

C programming

Uploaded by

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

Unit Ii

C programming

Uploaded by

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

UNIT II

Precedence and Associativity, Type Conversion with suitable illustrative programs.

Conditional/Decision Statements: if, if-else, nested if-else, else-if ladder, and switch-
statement with suitable illustrative programs.

Unconditional Statements: break, continue and goto.

Control Structures: while, do-while and for with suitable illustrative programs.

SAMPLE QUESTIONS

1) Explain about Selection Making Decision?


2) Explain about Two way selection: if-else, null else, nested if, examples,
3) Explain about Multi-way selection: switch, else-if, examples.
4) Explain about iterative/loops- while, do-while and for statements
5) Difference between while and do-while
6) Explain about breaking control statements( break, continue and goto)?
7) Explain Type conversions in C
8) Write the priority of precedence
9) Explain for loop syntax
10) Write the examples of unconditional statements
11) Explain about Nested loops

Prepared by K CHANDRAM Assistant Professor Anurag University


Precedence and Order of Evaluation
Some expressions may contain more than one operator at that time the same expression
gives the different result.
Consider the following examples:
x=4*5+2;
1)x=4*5+2 2)x=4*5+2
=20+2 =4*10
=22 =40
The expression 4*5+2 gives the two different results as 22 and 40. But getting the
different results for the same expression is not correct.
In order to overcome the above problem, consider the precedence level for operators.
Operator Precedence:

Category

Associativity

Consider the following examples:


1 )X=20/5*6
X=4*6
=24

Prepared by K CHANDRAM Assistant Professor Anurag University


2) X=30/5+20/4
=6+5
=11

3) X=3*4/5+10/5+8-2+7/8
=12/5+10/5+8-2+7/8
=2+2+8-2+0
=4+6+0
=10+0
=10

4) X=2*3+5
=6+5
=11

5) X=2*(3+5)
=2*8
=16

6) X=2*(3+5*6)
=2*(3+30)
=2*33
=66

Type Conversion in C
Type conversion in C is the process of converting one data type to another. The type
conversion is only performed to those data types where conversion is possible. Type
conversion is performed by a compiler. In type conversion, the destination data type can’t be
smaller than the source data type. Type conversion is done at compile time and it is also
called widening conversion because the destination data type can’t be smaller than the source
data type. There are two types of Conversion:
1. Implicit Type Conversion

Also known as ‘automatic type conversion’.


A. Done by the compiler on its own, without any external trigger from the user.
B. Generally takes place when in an expression more than one data type is present. In such
conditions type conversion (type promotion) takes place to avoid loss of data.

Prepared by K CHANDRAM Assistant Professor Anurag University


C. All the data types of the variables are upgraded to the data type of the variable with the
largest data type.
bool -> char -> short int -> int ->
unsigned int -> long -> unsigned ->
long long -> float -> double -> long double
D. It is possible for implicit conversions to lose information, signs can be lost (when signed is
implicitly converted to unsigned), and overflow can occur (when long is implicitly converted
to float).

Occurrences of Implicit Type Conversion in C

Implicit type conversion is also called automatic type conversion. Some of its few
occurrences are mentioned below:
 Conversion Rank
 Conversions in Assignment Expressions
 Conversion in other Binary Expressions
Example of Type Implicit Conversion
Example no 1

// An example of implicit
conversion
#include <stdio.h>
int main()
{
int x = 10; // integer x
char y = 'a'; // character c

// y implicitly converted to
int. ASCII
// value of 'a' is 97
x = x + y;

// x is implicitly converted
to float
float z = x + 1.0;

printf("x = %d, z = %f", x,


z);
return 0;
}
Output
x = 107, z = 108.000000

Prepared by K CHANDRAM Assistant Professor Anurag University


2. Explicit Type Conversion

This process is also called type casting and it is user-defined. Here the user can typecast the
result to make it of a particular data type. The syntax in C Programming:
(type) expression
Type indicated the data type to which the final result is converted.

Example no 2

// C program to demonstrate explicit


type casting
#include<stdio.h>

int main()
{
double x = 1.2;

// Explicit conversion from


double to int
int sum = (int)x + 1;

printf("sum = %d", sum);

return 0;
}
Output
sum = 2

Example no 3

Prepared by K CHANDRAM Assistant Professor Anurag University


#include <stdio.h>

int main() {
float a = 1.5;
int b = (int)a;

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

return 0;
}
Output
a = 1.500000
b = 1

Control Structures

Definition:-The structure which controls the flow of execution of the statements is called
control structure.Control structures are classified into three types:
1) Sequence 2) Selection 3) Iteration
 Sequence: In this, the statements are executed one by one from start to end.
 Selection: In this, some statements are executed based on condition result only.
 Iteration: In this, some statements are executed repeatedly as long as condition is
true.
Decision making is an important part of programming. Every programming language supports
decision making statements allowing programmers to branch according to the condition. In C
programming language, if statement is used to check condition and make decision. The decisions or
statements are enclosed inside curly braces, however if only a single statement has to be executed,
curly braces are not mandatory. Depending upon the number of conditions to be checked, we have
following types of if statement:
1. if statement
2. if … else statement
3. if … else if … else statement
4. Nested if
5. switch
if statement

if statement is used for branching when a single condition is to be checked. The condition enclosed in
if statement decides the sequence of execution of instruction. If the condition is true, the statements
inside if statement are executed, otherwise they are skipped. In C programming language, any non
zero value is considered as true and zero or null is considered false.

Syntax of if statement

if (condition)

Prepared by K CHANDRAM Assistant Professor Anurag University


{

statements;

... ... ...

Flowchart of if statement

Example of if statement

Example 1: C program to print the square of a number if it is less than 10.

#include<stdio.h>

int main()

int n;

printf("Enter a number:");

scanf("%d",&n);

if(n<10)

printf("%d is less than 10n",n);

printf("Square = %dn",n*n);

Prepared by K CHANDRAM Assistant Professor Anurag University


}

return 0;

This program is an example of using if statement. A number is asked from user and stored in
variable n. If the value of n is less than 10, then its square is printed on the screen. If the condition is
false the program, execution is terminated.

Output

Enter a number:6

6 is less than 10

Square = 36

if … else statement

if … else statement is a two way branching statement. It consists of two blocks of statements each
enclosed inside if block and else block respectively. If the condition inside if statement is true,
statements inside if block are executed, otherwise statements inside else block are executed. Else
block is optional and it may be absent in a program.

Syntax of if…else statement

if (condition)

statements;

... ... ...

else

statements;

... ... ...

Flowchart of if … else statement

Prepared by K CHANDRAM Assistant Professor Anurag University


Example of if … else statement

Example 2: C program to find if a number is odd or even.

#include<stdio.h>

int main()

int n;

printf("Enter a number:");

scanf("%d",&n);

if(n%2 == 0)

printf("%d is even",n);

else

printf("%d is odd",n);

return 0;

Here, a number is entered by user which is stored in n. The if statement checks if the remainder of that
number when divided by 2 is zero or not. If the remainder is zero, the number is even which is printed
on the screen. If the remainder is 1, the number is odd.

Note: If there is only one statement inside if block, we don’t need to enclose it with curly brackets { }.

Prepared by K CHANDRAM Assistant Professor Anurag University


Output

Enter a number:18

18 is even

Enter a number:33

33 is odd

if … else if … else statement(else-if ladder)

It is used when more than one condition is to be checked. A block of statement is enclosed inside if,
else if and else part. Conditions are checked in each if and else if part. If the condition is true, the
statements inside that block are executed. If none of the conditions are true, the statements inside else
block are executed. A if … else if … else statement must have only one if block but can have as many
else if block as required. Else part is optional and may be present or absent.

Syntax of if…else if…else statement

if (condition 1)

statements;

... ... ...

else if (condition 2)

statements;

... ... ...

... ... ...

... ... ...

else if (condition n)

statements;

Prepared by K CHANDRAM Assistant Professor Anurag University


... ... ...

else

statements;

... ... ...

Flowchart of if … else if … else statement

Example of if … else if … else statement

Example 3: C program to find if a number is negative, positive or zero.

#include<stdio.h>

int main()

int n;

Prepared by K CHANDRAM Assistant Professor Anurag University


printf("Enter a number:");

scanf("%d",&n);

if(n<0)

printf("Number is negative");

else if(n>0)

printf("Number is positive");

else

printf("Number is equal to zero");

return 0;

In this program, a number is entered by user stored in variable n. The if … else if … else statement
tests two conditions:

1. n<0: If it is true, “Number is negative” is printed on the screen.


2. n>0: If it is true, “Number is positive” is printed on the screen.
If both of these conditions are false then the number is zero. So the program will print “Number is
zero”.

Output

Enter a number:109

Number is positive

Enter a number:-56

Number is negative

Enter a number:0

Number is equal to zero

Nested if statements

When a if statement is kept inside another if statement, it is called nested if statement. Nested if
statements are used if there is a sub condition to be tested. The depth of nested if statements depends
upon the number of conditions to be checked.

Syntax of nested if statement

Prepared by K CHANDRAM Assistant Professor Anurag University


if (condition 1)

statements;

if (sub condition 1)

statements;

statements;

else if (condition 2)

statements;

if (sub condition 2)

statements;

statements;

... ... ...

... ... ...

else

statements;

if (sub condition n)

Prepared by K CHANDRAM Assistant Professor Anurag University


statements;

statements;

Flowchart of nested if statement

Example of Nested if statement

Example 4: C program to check if a number is less than 100 or not. If it is less than 100 then
check if it is odd or even.

#include<stdio.h>

int main()

int n;

printf("Enter a number:");

Prepared by K CHANDRAM Assistant Professor Anurag University


scanf("%d",&n);

if(n<100)

printf("%d is less than 100n",n);

if(n%2 == 0)

printf("%d is even",n);

else

printf("%d is odd",n);

else

printf("%d is equal to or greater than 100",n);

return 0;

This program tests two conditions:

1. If the number is less than 100 or not.


2. If the number is less than 100 then is it odd or even.
It consists of a nested if statement. The outer if statement checks whether the number is less than 100
or not. If the number is less than hundred, another condition i.e. if the number is even or odd is
checked and respective message is displayed.

Output

Enter a number:46

46 is less than 100

46 is even

Enter a number:67

67 is less than 100

67 is odd

Prepared by K CHANDRAM Assistant Professor Anurag University


Enter a number:316

316 is equal to or greater than 100

switch
The switch-case statement is used to check the multiple conditions at a time.
1) switch without break
2) switch with break.
1) switch without break;-
Syntax:- switch(expression)
{ case value-1: statement1;
case value-2: statement2;
case value-3: statement3;
case value-4: statement4;
------------------------------
[default:statement n;]
}

Execution procedure:-
 First the expression will be evaluated and it must return a constant value like numeric
or character.
 Now , the expression constant value is compared with the case constant values like
value-1, value-2, value-3,..........etc.
 If the expression constant value is match with any case value then the execution start
from that corresponding case statements to last statement of the switch block.

Write a C program to explain the concept of switch without break.


#include<stdio.h>
#include<conio.h>
void main()
{
int x,y,add,sub,mul,div,mod_div,choice;
clrscr();
printf("Enter two numbers : \n");
scanf("%d%d",&x,&y);
printf("enter choice 1.addition 2.substraction 3.multiplicatio 4.division 5.modulo
division \n");
scanf("%d",&choice);
switch(choice)
{
case 1: add=x+y; printf("addition = %d\n",add);
case 2: sub=x-y;printf("substraction = %d\n",sub);
case 3: mul=x*y;printf("multiplication = %d\n",mul);
case 4:div=x/y;printf("division = %d\n",div);
case 5:mod_div=x%y;printf("modulo division = %d\n",mod_div);
default:printf("Invalid choice you entered");
}

Prepared by K CHANDRAM Assistant Professor Anurag University


getch();
}
Output:-
1) Enter two numbers :
7 3
enter choice 1.addition 2.substraction 3.multiplication 4.division 5.modulo division
2
substraction =4
multiplication =21
division = 2
modulo division = 1
Invalid choice you entered
2) Enter two numbers :
7 3
enter choice 1.addition 2.substraction 3.multiplication 4.division 5.modulo division
4
division = 2
modulo division = 1
Invalid choice you entered

2) switch with break;-


Syntax:- switch(expression)
{ case value-1: statement1;break;
case value-2: statement2; break;
case value-3: statement3; break;
case value-4: statement4; break;
------------------------------
[default:statement n;]
}
Execution procedure:-
 First the expression will be evaluated and it must return a constant value like numeric
or character.
 Now , the expression constant value is compared with the case constant values like
value-1, value-2, value-3,..........etc.
 If the expression constant value is match with any case value then only that
corresponding case statements will be executed.
 If the expression constant value is not match with any case value then only the
default case will be executed .

Write a C program to explain the concept of switch with break.


#include<stdio.h>
#include<conio.h>
void main()
{
int x,y,add,sub,mul,div,mod_div,choice;
clrscr();
printf("Enter two numbers : \n");
scanf("%d%d",&x,&y);
printf("enter choice 1.addition 2.substraction 3.multiplication 4.division
5.modulo division \n");

Prepared by K CHANDRAM Assistant Professor Anurag University


scanf("%d",&choice);
switch(choice)
{
case 1: add=x+y; printf("addition = %d\n",add);break;
case 2: sub=x-y;printf("substraction = %d\n",sub);break;
case 3: mul=x*y;printf("multiplication = %d\n",mul);break;
case 4:div=x/y;printf("division = %d\n",div);break;
case 5:mod_div=x%y;printf("modulo division = %d\n",mod_div);break;
default:printf("Invalid choice you entered");break;
}
getch();
}
Output:-
1) Enter two numbers :
7 3
enter choice 1.addition 2.substraction 3.multiplication 4.division 5.modulo division
2
substraction =4
2) Enter two numbers :
7 3
enter choice 1.addition 2.substraction 3.multiplication 4.division 5.modulo division
4
division = 2

3) Enter two numbers :


7 3
enter choice 1.addition 2.substraction 3.multiplication 4.division 5.modulo division
7
Invalid choice you entered
ITERATIVE(LOOPS) STATEMENTS
Looping:-The set of instructions which are executed repeatedly as long as the condition is
true is called “looping”.

LOOPS:-

1. while loop
2. do-while loop and
3. for loop.
1) while loop:-
 while loop is also called as Entry controlled loop.

Syntax:-
.................

Flow chart:-
.................

Prepared by K CHANDRAM Assistant Professor Anurag University


while(condition)
{ ------------------
..........................
------------------ False
} cond
Statement x; i-
tion
..................... True Statement x;
.......................

While block

Procedure for executing the while loop:-


 if the condition is true then the while block is executed. At the end of execution of
while block again it check the condition. Now if the condition is true then again the
while block is executed . I t is repeated till the condition is true.
2) do-while loop:-
 do-while loop is also called as Exit controlled loop.

Syntax:-

Flow chart

Procedure for executing the do-while loop:-

Prepared by K CHANDRAM Assistant Professor Anurag University


 When the program control first comes to the do…while loop, the body of the loop is
executed first and then the test condition/expression is checked, unlike other loops
where the test condition is checked first. Due to this property, the do…while loop is
also called exit controlled or post-tested loop.
 When the test condition is evaluated as true, the program control goes to the start of
the loop and the body is executed once more.
 The above process repeats till the test condition is true.
 When the test condition is evaluated as false, the program controls move on to the
next statements after the do…while loop.

// C Program to demonstrate the use of do...while loop


#include <stdio.h>
int main(){
// loop variable declaration and initialization
int i = 0;
// do while loop
do
{
printf("Geeks\n");
i++;
}
while (i < 3);
return 0;
}
Output

Geeks
Geeks
Geeks

// C Program to print multiplication table using do...while loop


#include <stdio.h>
int main()
{
int N = 5, i = 1;
do
{
printf("%d\tx\t%d\t=\t%d\n", N, i, N * i);
}
while(i++ < 10);
return 0;
}

Output

5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45

Prepared by K CHANDRAM Assistant Professor Anurag University


5 x 10 = 50

Difference between while and do…while Loop in C

while Loop do…while Loop

The test condition is checked before the loop


The test condition is checked after executing the body.
body is executed.

When the condition is false, the body is not The body of the do…while loop is executed at least
executed not even once. once even when the condition is false.

It is a type of pre-tested or entry-controlled


It is a type of post-tested or exit-controlled loop.
loop.

Semicolon is not required. Semicolon is required at the end.

for loop

The for loop in C Language provides a functionality/feature to repeat a set of statements a defined
number of times. The for loop is in itself a form of an entry-controlled loop.
Unlike the while loop and do…while loop, the for loop contains the initialization, condition, and
updating statements as part of its syntax. It is mainly used to traverse arrays, vectors, and other data
structures.
Syntax of for Loop
for(initialization; check/test expression; updation)
{
// body consisting of multiple statements
}

Procedure for executing the for loop:-

 Step 1: Initialization is the basic step of for loop this step occurs only once during the start of the
loop. During Initialization, variables are declared, or already existing variables are assigned some
value.
 Step 2: During the Second Step condition statements are checked and only if the condition is the
satisfied loop we can further process otherwise loop is broken.
 Step 3: All the statements inside the loop are executed.
 Step 4: Updating the values of variables has been done as defined in the loop.
Continue to Step 2 till the loop breaks.

Prepared by K CHANDRAM Assistant Professor Anurag University


Different formats (syntaxes) of for loop are:-

for(i=0;k<10;i++)
{
printf(“%d “,i);
}

for(i=0;k<10;)
{
printf(“%d “,i);
i++;
}

int i=0;
for(; i<10;i++)
{
printf(“%d “,i);

int i=0;
for(; i<10;)
{
printf(“%d “,i);
i++;
}

// C program to demonstrate for loop


#include <stdio.h>

int main()

Prepared by K CHANDRAM Assistant Professor Anurag University


{
int i = 0;

// i <= 5 is the check/test expression


// The loop will function if and only if i' is less
// than 5
// i++ will increments it's value by this so that the
// loop can iterate for further evaluation

// conditional statement
for (i = 1; i <= 5; i++)
{
// statement will be printed
printf("Anurag University\n");
}

// Return statement to tell that everything executed


// safely
return 0;
}
Output
Anurag University
Anurag University
Anurag University
Anurag University

Breaking control statements


The statements which are used to break the sequential execution of the statements. Breaking
control statements are classified into 3 ways:

break statement
continue statement and
goto statement.

Break statement:- The break statement is used for terminating the loop or block . That
means when the break statement is occurred at that time the loop gets the termination.

switch with break example explain this concept.

Write a C program to explain the concept of switch with break.


#include<stdio.h>
#include<conio.h>
void main()
{
int x,y,add,sub,mul,div,mod_div,choice;
clrscr();
printf("Enter two numbers : \n");

Prepared by K CHANDRAM Assistant Professor Anurag University


scanf("%d%d",&x,&y);
printf("enter choice 1.addition 2.substraction 3.multiplication 4.division
5.modulo division \n");
scanf("%d",&choice);
switch(choice)
{
case 1: add=x+y; printf("addition = %d\n",add);break;
case 2: sub=x-y;printf("substraction = %d\n",sub);break;
case 3: mul=x*y;printf("multiplication = %d\n",mul);break;
case 4:div=x/y;printf("division = %d\n",div);break
case 5:mod_div=x%y;printf("modulo division = %d\n",mod_div);break;
default:printf("Invalid choice you entered");break;
}
getch();
}
Output:-
1) Enter two numbers :
7 3
enter choice 1.addition 2.substraction 3.multiplication 4.division 5.modulo division
2
substraction =4

continue statement:- The functionality of continue is skips the remaining statements in


while , do-while and for body.

Examples:-
while(condition) do for(init;cond;inc/dec)
{ {statement1; { statement1;
Statement1; if(condition) if(condition)
if(condition) {satement2; { statement2;
{ statement2; continue; continue;
continue; }while(condition); }
} }
}
Write a C program for displaying numbers from 1 to n except which are divisible by 3.
#include<stdio.h>
#include<conio.h>
void main( )
{
int i,n;
clrscr( ) ;
printf(“Enter n value:\n”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
if(i%3= =0)
{ i=i+1;
continue;

Prepared by K CHANDRAM Assistant Professor Anurag University


}
else
{ printf(“%d ”, i);
}
} }
getch();
}

goto statement:- It is used for transferring the control from one location to another location
of the program.
Syntax:-
goto label;

un-conditional goto

goto
conditional goto

un-conditional goto:-Without checking any condition the control transfer to another


location.
Example program:-
#include<stdio.h>
#include<conio.h>
void main( )
{
clrscr();
printf(“hai 1\n “);
printf(“hai 2 \n”);
goto A;
printf(“hai 3\n”);
printf(“hai 4 \n”);
A:
printf(“ hai 5\n”);
printf(“hai 6\n”);
getch( );
}
Out put:-
hai 1
hai 2
hai 5
hai 6

conditional goto:- Based on condition the control transfer to another location.


Example program:-

// C program to check if a number is


// even or not using goto statement
#include <stdio.h>

Prepared by K CHANDRAM Assistant Professor Anurag University


// function to check even or not
void checkEvenOrNot(int num)
{
if (num % 2 == 0)
// jump to even
goto even;
else
// jump to odd
goto odd;

even:
printf("%d is even", num);
// return if even
return;
odd:
printf("%d is odd", num);
}

int main()
{
int num = 26;
checkEvenOrNot(num);
return 0;
}

Output

26 is even

// C program to print numbers


// from 1 to 10 using goto
statement
#include <stdio.h>

// function to print numbers


from 1 to 10
void printNumbers()
{
int n = 1;
label:
printf("%d ", n);
n++;
if (n <= 10)
goto label;
}

// Driver program to test above


function
int main()
{
printNumbers();

Prepared by K CHANDRAM Assistant Professor Anurag University


return 0;
}

Nested Loops in C with Examples


A nested loop means a loop statement inside another loop statement. That is why nested loops are
also called “loop inside loops“. We can define any number of loops inside another loop.
1. Nested for Loop
Nested for loop refers to any type of loop that is defined inside a ‘for’ loop. Below is the equivalent
flow diagram for nested ‘for’ loops:

Nested for loop in C


Syntax:
for ( initialization; condition; increment ) {

for ( initialization; condition; increment ) {

// statement of inside loop

Prepared by K CHANDRAM Assistant Professor Anurag University


}

// statement of outer loop


}
Example: Below program uses a nested for loop to print a 3D matrix of 2x3x2.

 C
// C program to print elements of Three-Dimensional Array
// with the help of nested for loop
#include <stdio.h>

int main()
{
// initializing the 3-D array
int arr[2][3][2]
= { { { 0, 6 }, { 1, 7 }, { 2, 8 } },
{ { 3, 9 }, { 4, 10 }, { 5, 11 } } };

// Printing values of 3-D array


for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 2; ++k) {
printf("Element at arr[%i][%i][%i] = %d\n",
i, j, k, arr[i][j][k]);
}
}
}
return 0;
}
Output
Element at arr[0][0][0] = 0
Element at arr[0][0][1] = 6
Element at arr[0][1][0] = 1
Element at arr[0][1][1] = 7
Element at arr[0][2][0] = 2
Element at arr[0][2][1] = 8
Element at arr[1][0][0] = 3
Element at arr[1][0][1] = 9
Element at arr[1][1][0] = 4
Element at arr[1][1][1] = 10
Element at arr[1][2][0] = 5
Element at arr[1][2][1] = 11
2. Nested while Loop
A nested while loop refers to any type of loop that is defined inside a ‘while’ loop. Below is the
equivalent flow diagram for nested ‘while’ loops:

Prepared by K CHANDRAM Assistant Professor Anurag University


Nested while loop in C
Syntax:
while(condition) {

while(condition) {

// statement of inside loop


}

// statement of outer loop


}
Example: Print Pattern using nested while loops

 C
// C program to print pattern using nested while loops
#include <stdio.h>

Prepared by K CHANDRAM Assistant Professor Anurag University


int main()
{
int end = 5;

printf("Pattern Printing using Nested While loop");

int i = 1;

while (i <= end) {


printf("\n");
int j = 1;
while (j <= i) {
printf("%d ", j);
j = j + 1;
}
i = i + 1;
}
return 0;
}
Output
Pattern Printing using Nested While loop
1
12
123
1234
12345
3. Nested do-while Loop
A nested do-while loop refers to any type of loop that is defined inside a do-while loop. Below is the
equivalent flow diagram for nested ‘do-while’ loops:

Prepared by K CHANDRAM Assistant Professor Anurag University


do while loop in C
Syntax:
do{

do{

// statement of inside loop


}while(condition);

// statement of outer loop


}while(condition);
Note: There is no rule that a loop must be nested inside its own type. In fact, there
can be any type of loop nested inside any type and to any level.
Syntax:
do{

while(condition) {

Prepared by K CHANDRAM Assistant Professor Anurag University


for ( initialization; condition; increment ) {

// statement of inside for loop


}

// statement of inside while loop


}

// statement of outer do-while loop


}while(condition);
Example: Below program uses a nested for loop to print all prime factors of a number.

 C
// C Program to print all prime factors
// of a number using nested loop

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

// A function to print all prime factors of a given number n


void primeFactors(int n)
{
// Print the number of 2s that divide n
while (n % 2 == 0) {
printf("%d ", 2);
n = n / 2;
}

// n must be odd at this point. So we can skip


// one element (Note i = i +2)
for (int i = 3; i <= sqrt(n); i = i + 2) {
// While i divides n, print i and divide n
while (n % i == 0) {
printf("%d ", i);
n = n / i;
}
}

// This condition is to handle the case when n


// is a prime number greater than 2
if (n > 2)
printf("%d ", n);
}

/* Driver program to test above function */


int main()
{

Prepared by K CHANDRAM Assistant Professor Anurag University


int n = 315;
primeFactors(n);
return 0;
}
Output:
3357
Break Inside Nested Loops
Whenever we use a break statement inside the nested loops it breaks the innermost loop and program
control is inside the outer loop.
Example:

 C
// C program to show working of break statement
// inside nested for loops
#include <stdio.h>

int main()
{

int i = 0;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 3; j++) {
// This inner loop will break when i==3
if (i == 3) {
break;
}
printf("* ");
}
printf("\n");
}
return 0;
}
Output
***
***
***

***
In the above program, the first loop will iterate from 0 to 5 but here if i will be equal to 3 it will break
and will not print the * as shown in the output.
Continue Inside Nested loops
Whenever we use a continue statement inside the nested loops it skips the iteration of the innermost
loop only. The outer loop remains unaffected.
Example:

 C

Prepared by K CHANDRAM Assistant Professor Anurag University


// C program to show working of continue statement
// inside nested for loops
#include <stdio.h>

int main()
{

int i = 0;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 3; j++) {
// This inner loop will skip when j==2
if (j==2) {
continue;
}
printf("%d ",j);
}
printf("\n");
}
return 0;
}

Prepared by K CHANDRAM Assistant Professor Anurag University

You might also like