0% found this document useful (0 votes)
2 views59 pages

2 Control Structures

2 Control Structures of c programming

Uploaded by

shradha Linge
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)
2 views59 pages

2 Control Structures

2 Control Structures of c programming

Uploaded by

shradha Linge
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

2.

Control Structures
C if else Statement
The if-else statement in C is used to perform the
operations based on some specific condition. The
operations specified in if block are executed if and only if
the given condition is true.

There are the following variants of if statement in C


language.

o If statement
o If-else statement
o If else-if ladder
o Nested if

If Statement
The if statement is used to check some given condition
and perform some operations depending upon the
correctness of that condition. It is mostly used in the
scenario where we need to perform the different
operations for the different conditions. The syntax of the
if statement is given below.

if(expression){
//code to be executed
}

Flowchart of if statement in C
Let's see a simple example of C language if statement.

#include<stdio.h>
int main(){
int number=0;
printf("Enter a number:");
scanf("%d",&number);
if(number%2==0)
{
printf("%d is even number",number);
}
return 0;
}

Output
Enter a number:4
4 is even number
enter a number:5

Program to find the largest number of the three.


#include <stdio.h>
int main() {
int a, b, c;
printf("Enter three numbers?");
scanf("%d %d %d",&a,&b,&c);
if(a>b && a>c)
{
printf("%d is largest",a);
}
if(b>a && b > c)
{
printf("%d is largest",b);
}
if(c>a && c>b)
{
printf("%d is largest",c);
}
if(a == b && a == c)
{
printf("All are equal");
}
}

Output
Enter three numbers?
12 23 34
34 is largest

If-else Statement
The if-else statement is used to perform two operations
for a single condition. The if-else statement is an
extension to the if statement using which, we can
perform two different operations, i.e., one is for the
correctness of that condition, and the other is for the
incorrectness of the condition. Here, we must notice that
if and else block cannot be executed simiulteneously.
Using if-else statement is always preferable since it
always invokes an otherwise case with every if condition.
The syntax of the if-else statement is given below.

if(expression){
//code to be executed if condition is true
}else{
//code to be executed if condition is false
}

Flowchart of the if-else statement in C


Let's see the simple example to check whether a number
is even or odd using if-else statement in C language.

#include<stdio.h>
int main(){
int number=0;
printf("enter a number:");
scanf("%d",&number);
if(number%2==0){
printf("%d is even number",number);
}
else{
printf("%d is odd number",number);
}
return 0;
}

Output
enter a number:4
4 is even number
enter a number:5
5 is odd number

Program to check whether a person is eligible to


vote or not.
#include <stdio.h>
int main()
{
int age;
printf("Enter your age?");
scanf("%d",&age);
if(age>=18)
{
printf("You are eligible to vote...");
}
else
{
printf("Sorry ... you can't vote");
}
}

Output
Enter your age?18
You are eligible to vote...
Enter your age?13
Sorry ... you can't vote
If else-if ladder Statement
The if-else-if ladder statement is an extension to the if-
else statement. It is used in the scenario where there are
multiple cases to be performed for different conditions. In
if-else-if ladder statement, if a condition is true then the
statements defined in the if block will be executed,
otherwise if some other condition is true then the
statements defined in the else-if block will be executed,
at the last if none of the condition is true then the
statements defined in the else block will be executed.
There are multiple else-if blocks possible. It is similar to
the switch case statement where the default is executed
instea of else block if none of the cases is matched.

if(condition1)
{
//code to be executed if condition1 is true
}else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
...
else{ //code to be executed if all the conditions are false
}

Flowchart of else-if ladder statement in C


The example of an if-else-if statement in C language is
given below.

#include<stdio.h>
int main(){
int number=0;
printf("enter a number:");
scanf("%d",&number);
if(number==10){
printf("number is equals to 10");
}
else if(number==50){
printf("number is equal to 50");
}
else if(number==100){
printf("number is equal to 100");
}
else{
printf("number is not equal to 10, 50 or 100");
}
return 0;
}

Output
enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
Program to calculate the grade of the student
according to the specified marks.
#include <stdio.h>
int main()
{
int marks;
printf("Enter your marks?");
scanf("%d",&marks);
if(marks > 85 && marks <= 100)
{
printf("Congrats ! you scored grade A ...");
}
else if (marks > 60 && marks <= 85)
{
printf("You scored grade B + ...");
}
else if (marks > 40 && marks <= 60)
{
printf("You scored grade B ...");
}
else if (marks > 30 && marks <= 40)
{
printf("You scored grade C ...");
} else
{ printf("Sorry you are fail ...");
}
}

Output
Enter your marks?10
Sorry you are fail ...
Enter your marks?40
You scored grade C ...
Enter your marks?90
Congrats ! you scored grade A ...

C Switch Statement
The switch statement in C is an alternate to if-else-if
ladder statement which allows us to execute multiple
operations for the different possibles values of a single
variable called switch variable. Here, We can define
various statements in the multiple cases for the different
values of a single variable.

The syntax of switch statement in c language is given


below:

switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......

default:
code to be executed if all cases are not matched;
}
Rules for switch statement in C language
1. The switch expression must be of an integer or character
type.
2. The case value must be an integer or character constant.
3. The case value can be used only inside the switch
statement.
4. The break statement in switch case is not must. It is
optional. If there is no break statement found in the case, all
the cases will be executed present after the matched case. It
is known as fall through the state of C switch statement.

Let's try to understand it by the examples. We are


assuming that there are following variables.

1. int x,y,z;
2. char a,b;
3. float f;

Valid Switch Invalid Switch Valid Case Invalid Case

switch(x) switch(f) case 3; case 2.5;

switch(x>y) switch(x+2.5) case 'a'; case x;

switch(a+b-2) case 1+2; case x+2;

switch(func(x,y)) case 'x'>'y'; case 1,2,3;


Flowchart of switch statement in C

Functioning of switch case statement


First, the integer expression specified in the switch
statement is evaluated. This value is then matched one
by one with the constant values given in the different
cases. If a match is found, then all the statements
specified in that case are executed along with the all the
cases present after that case including the default
statement. No two cases can have similar values. If the
matched case contains a break statement, then all the
cases present after that will be skipped, and the control
comes out of the switch. Otherwise, all the cases
following the matched case will be executed.

How does C switch statement work?


Let's go through the step-by-step process of how the
switch statement works in C:

Consider the following switch statement:

C Program:

#include <stdio.h>

int main() {
int num = 4;
switch (num) {
case 1:
printf("Value is 1\n");
break;
case 2:
printf("Value is 2\n");
break;
case 3:
printf("Value is 3\n");
break;
default:
printf("Value is not 1, 2, or 3\n");
break;
}
return 0;
}

Output
Value is 2

Step-by-step Process:

1. The switch variable num is evaluated. In this case, num is


initialized with the value 2.
2. The evaluated num (2) value is compared with the
constants specified in each case label inside the switch
block.
3. The switch statement matches the evaluated value
(2) with the constant specified in the second case (case
2). Since there is a match, the program jumps to the code
block associated with the matching case (case 2).
4. The code block associated with case 2 is executed, which
prints "Value is 2" to the console.
5. The "break" keyword is present in the code block of case 2.
As a result, the program breaks out of the switch statement
immediately after executing the code block.
6. The program control continues after the switch statement,
and any statements following the switch statement are
executed. In this case, there are no statements after the
switch, so the program terminates.
7. The switch statement evaluated the value of the variable
num, found a match with case 2, executed the
corresponding code block, and then exited the switch
block due to the presence of the "break" statement.
Example of a switch statement in
Let us see a simple example of a C language switch
statement.
#include<stdio.h>
int main(){
int number=0;
printf("enter a number:");
scanf("%d",&number);
switch(number){
case 10:
printf("number is equals to 10");
break;
case 50:
printf("number is equal to 50");
break;
case 100:
printf("number is equal to 100");
break;
default:
printf("number is not equal to 10, 50 or 100");
}
return 0;
}

Output
enter a number:4
number is not equal to 10, 50 or 100

enter a number:50
number is equal to 50

Switch case example 2


#include <stdio.h>
int main()
{
int x = 10, y = 5;
switch(x>y && x+y>0)
{
case 1:
printf("hi");
break;
case 0:
printf("bye");
break;
default:
printf(" Hello bye ");
}

Output
hi

Break and Default keyword in Switch


statement
Let us explain and define the "break" and "default"
keywords in the context of the switch statement, along
with example code and output.

1. Break Keyword:
The "break" keyword is used within the code block of
each case to terminate the switch statement
prematurely. When the program encounters a "break"
statement inside a case block, it immediately exits
the switch statement, preventing the execution of
subsequent case blocks. The "break" statement is
crucial for avoiding switch statements' "fall-
through" behavior.
Example:Let's take a program to understand the use of
the break keyword in C.

#include <stdio.h>
int main() {
int num = 3;

switch (num) {
case 1:
printf("Value is 1\n");
break; // Exit the switch statement after executing this case block

case 2:
printf("Value is 2\n");
break; // Exit the switch statement after executing this case block

case 3:
printf("Value is 3\n");
break; // Exit the switch statement after executing this case block

default:
printf("Value is not 1, 2, or 3\n");
break; // Exit the switch statement after executing the default ca
se block
}

return 0;
}

Output
Value is 3

Explanation:
In this example, the switch statement evaluates the
value of the variable num (which is 3) and matches it
with case 3. The code block associated with case 3 is
executed, printing "Value is 3" to the console.
The "break" statement within case 3 ensures that the
program exits the switch statement immediately after
executing this case block, preventing the execution of
any other cases.

2. Default Keyword:
When none of the case constants match the evaluated
expression, it operates as a catch-all case. If no
matching case exists and a "default" case exists, the
code block associated with the "default" case is run. It is
often used to handle circumstances where none of the
stated situations apply to the provided input.

Example:

Let's take a program to understand the use of


the default keyword in C.

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

switch (num) {
case 1:
printf("Value is 1\n");
break;
case 2:
printf("Value is 2\n");
break;
case 3:
printf("Value is 3\n");
break;
default:
printf("Value is not 1, 2, or 3\n");
break; // Exit the switch statement after executing the default ca
se block
}

return 0;
}

Output
Value is not 1, 2, or 3

Explanation:

In this example, the switch statement examines the


value of the variable num (which is 5). Because no case
matches the num, the program performs the code block
associated with the "default" case. The "break"
statement inside the "default" case ensures that the
program exits the switch statement after executing
the "default" case block.

Both the "break" and "default" keywords play


essential roles in controlling the flow of execution within a
switch statement. The "break" statement helps prevent
the fall-through behavior, while the "default"
case provides a way to handle unmatched cases.

C Switch statement is fall-through


In C language, the switch statement is fall through; it
means if you don't use a break statement in the switch
case, all the cases after the matching case will be
executed.

Let's try to understand the fall through state of switch


statement by the example given below.

#include<stdio.h>
int main(){
int number=0;

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

switch(number){
case 10:
printf("number is equal to 10\n");
case 50:
printf("number is equal to 50\n");
case 100:
printf("number is equal to 100\n");
default:
printf("number is not equal to 10, 50 or 100");
}
return 0;
}

Output
enter a number:10
number is equal to 10
number is equal to 50
number is equal to 100
number is not equal to 10, 50 or 100

Output
enter a number:50
number is equal to 50
number is equal to 100
number is not equal to 10, 50 or 100

Nested switch case statement


We can use as many switch statement as we want inside
a switch statement. Such type of statements is called
nested switch case statements. Consider the following
example.

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

int i = 10;
int j = 20;

switch(i) {

case 10:
printf("the value of i evaluated in outer switch: %d\n",i);
case 20:
switch(j) {
case 20:
printf("The value of j evaluated in nested switch: %d\
n",j);
}
}

printf("Exact value of i is : %d\n", i );


printf("Exact value of j is : %d\n", j );

return 0;
}

Output
the value of i evaluated in outer switch: 10
The value of j evaluated in nested switch: 20
Exact value of i is : 10
Exact value of j is : 20

Advantages of the switch statement:


There are several advantages of the switch
statement in C. Some main advantages of the switch
statement are as follows:
ADVERTISEMENT

o Readability and clarity: The switch statement provides


a concise and straightforward way to express multiway
branching in the code. Dealing with multiple cases can
make the code more organized and easier to read than
multiple nested if-else statements.
o Efficiency: The switch statement is generally more
efficient than a series of if-else statements when dealing
with multiple conditions. It works as a direct jump table,
which makes it faster and more optimized in terms of
execution time.
o Case-based logic: The switch statement naturally fits
scenarios where the program needs to make decisions based
on specific values of a single variable. It is an intuitive and
straightforward way to implement case-based logic.

The switch statement supports using a default case


which serves as a catch-all option for values that do not
match any provided cases. This default case handles
unusual inputs or circumstances that are not expressly
stated.
Disadvantages of the switch statement:
There are several disadvantages of the switch
statement in C. Some main disadvantages of the switch
statement are as follows:

o Limited expressions: The expression used in the switch


statement must result in an integral value (char, int,
enum) or a compatible data type. It cannot handle
more complex or non-constant expressions, limiting
its flexibility in some scenarios.
o Inability to compare ranges: Unlike if-else statements,
the switch statement cannot handle ranges of values
directly. Each case in the switch statement represents a
specific constant value, making it challenging to handle a
range of values efficiently.
o No support for floating-point numbers: The switch
statement only accepts integral types (integers) and
values from enums; it does not accept floating-point
numbers. It does not handle non-integral data
types like floating-point integers, which might be
problematic in some circumstances.
o Fall-through behavior: Switch statements have "fall-
through" behavior by default which implies that if a case
does not include a "break" statement, execution will "fall
through" to the following case block. If not managed
appropriately, this might result in unwanted behavior.
o Duplicate code: Using a switch statement might result in
duplicate code in some circumstances, especially when
numerous cases demand the same actions. If not properly
managed, this might result in code duplication.
o Nested switches can become complex: When dealing
with nested switch statements, the code can become
complex and less readable. It may require additional effort to
understand and maintain such nested structures.

C Loops
The looping can be defined as repeating the same
process multiple times until a specific condition satisfies.
There are three types of loops used in the C language. In
this part of the tutorial, we are going to learn all the
aspects of C loops.

Why use loops in C language?


The looping simplifies the complex problems into the
easy ones. It enables us to alter the flow of the program
so that instead of writing the same code again and again,
we can repeat the same code for a finite number of
times. For example, if we need to print the first 10 natural
numbers then, instead of using the printf statement 10
times, we can print inside a loop which runs up to 10
iterations.

Advantage of loops in C
1) It provides code reusability.

2) Using loops, we do not need to write the same code


again and again.

3) Using loops, we can traverse over the elements of data


structures (array or linked lists).
Types of C Loops
There are three types of loops in C language that is given
below:

1. do while
2. while
3. for

do-while loop in C
The do-while loop continues until a given condition
satisfies. It is also called post tested loop. It is used when
it is necessary to execute the loop at least once (mostly
menu driven programs).

The syntax of do-while loop in c language is given below:

do{
//code to be executed
}while(condition);
while loop in C
The while loop in c is to be used in the scenario where we
don't know the number of iterations in advance. The
block of statements is executed in the while loop until the
condition specified in the while loop is satisfied. It is also
called a pre-tested loop.
The syntax of while loop in c language is given below:

while(condition){
//code to be executed
}
for loop in C
The for loop is used in the case where we need to
execute some part of the code until the given condition is
satisfied. The for loop is also called as a per-tested loop.
It is better to use for loop if the number of iteration is
known in advance.

The syntax of for loop in c language is given below:

for(initialization;condition;incr/decr){
//code to be executed
}

do while loop in C
A loop is a programming control structure that allows you
to execute a block of code indefinitely if a specific
condition is met. Loops are used to execute repeating
activities and boost programming performance. There are
multiple loops in the C programming language, one of
which is the "do-while" loop.

A "do-while" loop is a form of a loop in C that executes


the code block first, followed by the condition. If the
condition is true, the loop continues to run; else, it
stops. However, whether the condition is originally true,
it ensures that the code block is performed at least once.

do while loop syntax


The syntax of the C language do-while loop is given
below:
do{
//code to be executed
}while(condition);
The components are divided into the following:

o The do keyword marks the beginning of the Loop.


o The code block within curly braces {} is the body of the
loop, which contains the code you want to repeat.
o The while keyword is followed by a condition enclosed in
parentheses (). After the code block has been run, this
condition is verified. If the condition is true, the loop
continues else, the loop ends.

Working of do while Loop in C


Let us look at an example of how a do-while loop works
in C. In this example, we will write a simple program that
questions the user for a password and keeps asking until
the right password is input.

Example:

#include <stdio.h>
#include <string.h>
int main() {
char password[] = "secret";
char input[20];
do {
printf("Enter the password: ");
scanf("%s", input);
} while (strcmp(input, password) != 0);
printf("Access granted!\n");
return 0;
}

The program runs as follows:


1. The following header files are included: <stdio.h> for
standard input and output routines and <string.h> for
string manipulation functions.
2. The correct password is defined as a character array (char
password[]) with the value "secret"
3. After that, we define another character array input to store
the user's input.
4. The do keyword indicates that the code block included
within the loop will be performed at least once.
5. Using the printf() function, we display a prompt requesting
the user to input their password inside the Loop.
6. Next, we read the user's input using the scanf()
function and store it in the input array.
7. After reading the input, we use the strcmp() function to
compare the input with the correct password. If the strings
are equal, the strcmp function returns 0. So, we continue
looping as long as the input and the password are not equal.
8. Once the correct password is entered, the loop terminates,
and we print "Access granted!" using the printf()
function.
9. After that, the program returns 0 to indicate successful
execution.

Output:

Let us walk through a possible scenario:


Enter the password: 123
Enter the password: abc
Enter the password: secret
Access Granted!

Explanation: In this example, the user initially enters


the wrong passwords, "123" and "abc". The loop
prompts the user until the correct password "secret" is
entered. Once the correct password is provided, the loop
terminates, and the "Access granted!" message is
displayed.

Example of do while loop in C:


Example 1:Here is a simple example of a "do-while"
loop in C that prints numbers from 1 to 5:

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

Output:
1
2
3
4
5

Explanation:

In this example, the code block within the do loop will be


executed at least once, printing numbers from 1 to 5.
After each iteration, the i value is incremented, and the
condition i<= 5 is checked. If the condition is still true,
the loop continues; otherwise, it terminates.

Example 2:
Program to print table for the given number using do
while Loop

#include<stdio.h>
Int main(){
Int i=1,number=0;
printf("Enter a number: ");
scanf("%d",&number);
do{
printf("%d \n",(number*i));
i++;
}while(i<=10);
return 0;
}

Output:
Enter a number: 5
5
10
15
20
25
30
35
40
45
50
Enter a number: 10
10
20
30
40
50
60
70
80
90
100

Example 3:
Let's take a program that prints the multiplication table of
a given number N using a do...while Loop:

#include <stdio.h>
int main() {
int N;
printf("Enter a number to generate its multiplication table: ");
scanf("%d", &N);
inti = 1;
do {
printf("%d x %d = %d\n", N, i, N * i);
i++;
} while (i<= 10);
return 0;
}

Output:

Let us say you enter the number 7 as input:


Please enter a number to generate its multiplication table: 7
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

The program calculates and prints the multiplication table


for 7 from 1 to 10.

Infinite do while loop


An infinite loop is a loop that runs indefinitely as its
condition is always true or it lacks a terminating
condition. Here is an example of an infinite do...while
loop in C:

Example:

#include <stdio.h>
int main() {
inti = 1;
do {
printf("Iteration %d\n", i);
i++;
} while (1); // Condition is always true

return 0;
}

In this example, the loop will keep


running indefinitely because condition 1 is
always true.

Output:

When you run the program, you will see that it continues
printing "Iteration x", where x is the iteration
number without stopping:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
... (and so on)

To interrupt an infinite loop like this, you generally use


a break statement within the loop or some external
condition you can control, such as hitting a specific key
combination. In most desktop settings, the keyboard
shortcut Ctrl+C can escape the Loop.
Nested do while loop in C
In C, we take an example of a nested do...while loop.
In this example, we will write a program that
uses nested do...while loops to create a numerical
pattern.

Example:

#include <stdio.h>
int main() {
int rows, i = 1;
printf("Enter the number of rows: ");
scanf("%d", &rows);
do {
int j = 1;
do {
printf("%d ", j);
j++;
} while (j <= i);
printf("\n");
i++;
} while (i<= rows);
return 0;
}

In this program, we use nested do...while loops to


generate a pattern of numbers. The outer loop controls
the number of rows, and the inner loop generates the
numbers for each row.

Output:

Let us say you input five as the number of rows:


Enter the number of rows: 5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Explanation:

In this example, the program generates a pattern of


numbers in a triangular shape. The outer loop iterates
over the rows, and the inner loop iterates within each
row, printing the numbers from 1 up to the current row
number.

Difference between while and do while Loop


Here is a tabular comparison between the while loop and
the do-while Loop in C:

Aspect while loop do-while loop

Syntax while (condition) { ... } do { ... } while (condition);

Loop Body Condition is checked The body is executed befor


Execution before execution. the condition.

First The condition must be The body is executed at leas


Execution true initially. once.

Loop May execute zero or more Will execute at least once.


Execution times.

Example while (i< 5) { printf("%d\ do { printf("%d\n", i); i++;


n", i); i++; } while (i< 5);
Common Use When the loop may not When you want the loop t
Cases run at all. run at least once.

While Loop: The loop body is executed before the


condition is checked. If the condition is initially false, the
loop may not execute.

Do-while Loop: The loop body is executed at least


once before the condition is checked. This guarantees
that the loop completes at least one iteration.

When you want the loop to run based on a condition that


may be false at first, use the while loop, and when you
want the loop to run at least once regardless of the
starting state, use the do-while loop.

Features of do while loop


The do-while loop in C has several fundamental
characteristics that make it an effective programming
technique in certain situations. The following are the
significant characteristics of the do-while loop:

o Guaranteed Execution: Unlike other loop structures,


the do-while oop ensures that the loop body is executed at
least once. Because the condition is assessed after the loop
body, the code within the loop is performed before the
condition is verified.
o Loop after testing: The do-while loop is a post-tested
loop which implies that the loop condition is assessed after
the loop body has been executed. If the condition is true, the
loop body is run once again. This behavior allows you to
verify the condition for repetition before ensuring that a
given activity is completed.
o Conditionally Controlled: The loop continues to execute
as long as the condition specified after the while keyword
remains true. When the condition evaluates to false, the
loop is terminated, and control shifts to the sentence after
the loop.
o Flexibility: The do-while loop may be utilized in several
contexts. It is typically used in cases where a piece of code
must be executed at least once, such as menu-driven
programs, input validation, or repetitive
computations.
o Nesting Capability: Similar to other loop constructs,
the do-while loop can be nested inside
other loops or control structures to create more complex
control flow patterns. It allows for the creation of nested
loops and the implementation of intricate repetitive tasks.
o Break and Continue: The break statement can be used
within a do-while loop to terminate the loop execution and
exit the loop prematurely. The continue statement can
skip the remaining code in the current iteration and jump to
the next iteration of the loop.
o Local Scope: Variables declared inside the do-while
loop body have local scope and are accessible only within
the loop block. They cannot be accessed outside the loop
or by other loops or control structures.
o Infinite Loop Control: It is crucial to ensure that the loop's
condition is eventually modified within the loop body. This
modification is necessary to prevent infinite loops where the
condition continually evaluates to true. Modifying the
condition ensures that the loop terminates at some point.

while loop in C
While loop is also known as a pre-tested loop. In general,
a while loop allows a part of the code to be executed
multiple times depending upon a given boolean condition.
It can be viewed as a repeating if statement. The while
loop is mostly used in the case where the number of
iterations is not known in advance.

Syntax of while loop in C language

The syntax of while loop in c language is given below:

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

Example of the while loop in C language


Let's see the simple program of while loop that prints
table of 1.

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

Program to print table for the given number


using while loop in C
#include<stdio.h>
int main(){
int i=1,number=0,b=9;
printf("Enter a number: ");
scanf("%d",&number);
while(i<=10){
printf("%d \n",(number*i));
i++;
}
return 0;
}
Output
Enter a number: 50
50
100
150
200
250
300
350
400
450
500
Enter a number: 100
100
200
300
400
500
600
700
800
900
1000
Properties of while loop
o A conditional expression is used to check the condition. The
statements defined inside the while loop will repeatedly
execute until the given condition fails.
o The condition will be true if it returns 0. The condition will be
false if it returns any non-zero number.
o In while loop, the condition expression is compulsory.
o Running a while loop without a body is possible.
o We can have more than one conditional expression in while
loop.
o If the loop body contains only one statement, then the
braces are optional.

Example 1
#include<stdio.h>
void main ()
{
int j = 1;
while(j+=2,j<=10)
{
printf("%d ",j);
}
printf("%d",j);
}
Output
3 5 7 9 11
Example 2
#include<stdio.h>
void main ()
{
while()
{
printf("hello Javatpoint");
}
}
Output
compile time error: while loop can't be empty
Example 3
#include<stdio.h>
void main ()
{
int x = 10, y = 2;
while(x+y-1)
{
printf("%d %d",x--,y--);
}
}
Output
infinite loop

Infinitive while loop in C


If the expression passed in while loop results in any non-
zero value then the loop will run the infinite number of
times.
while(1){

//statement
}

for loop in C
The for loop in C language is used to iterate the
statements or a part of the program several times. It is
frequently used to traverse the data structures like the
array and linked list.
Syntax of for loop in C
The syntax of for loop in c language is given below:

for(Expression 1; Expression 2; Expression 3){


//code to be executed
}
Flowchart of for loop in C

C for loop Examples


Let's see the simple program of for loop that prints table
of 1.
#include<stdio.h>
int main(){
int i=0;
for(i=1;i<=10;i++){
printf("%d \n",i);
}
return 0;
}

Output
1
2
3
4
5
6
7
8
9
10

C Program: Print table for the given number


using C for loop
#include<stdio.h>
int main(){
int i=1,number=0;
printf("Enter a number: ");
scanf("%d",&number);
for(i=1;i<=10;i++){
printf("%d \n",(number*i));
}
return 0;
}

Output
Enter a number: 2
2
4
6
8
10
12
14
16
18
20
Enter a number: 1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000

Properties of Expression 1
o The expression represents the initialization of the loop
variable.
o We can initialize more than one variable in Expression 1.
o Expression 1 is optional.
o In C, we can not declare the variables in Expression 1.
However, It can be an exception in some compilers.

Example 1

#include <stdio.h>
int main()
{
int a,b,c;
for(a=0,b=12,c=23;a<2;a++)
{
printf("%d ",a+b+c);
}
}
Output
35 36

Example 2

#include <stdio.h>
int main()
{
int i=1;
for(;i<5;i++)
{
printf("%d ",i);
}
}

Output
1 2 3 4

Properties of Expression 2
o Expression 2 is a conditional expression. It checks for a
specific condition to be satisfied. If it is not, the loop is
terminated.
o Expression 2 can have more than one condition. However,
the loop will iterate until thelast condition becomes false.
Other conditions will be treated as statements.
o Expression 2 is optional.
o Expression 2 can perform the task of expression 1 and
expression 3. That is, we can initialize the variable as well as
update the loop variable in expression 2 itself.
o We can pass zero or non-zero value in expression 2.
However, in C, any non-zero value is true, and zero is false
by default.

Example 1
#include <stdio.h>
int main()
{
int i;
for(i=0;i<=4;i++)
{
printf("%d ",i);
}
}

output
0 1 2 3 4

Example 2

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

Output
0 0 0
1 2 3
2 4 6
3 6 9
4 8 12

Example 3
#include <stdio.h>
int main()
{
int i;
for(i=0;;i++)
{
printf("%d",i);
}
}

Output
infinite loop

Properties of Expression 3
o Expression 3 is used to update the loop variable.
o We can update more than one variable at the same time.
o Expression 3 is optional.

Example 1

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

Output
0 2
1 4
2 6
3 8
4 10

Loop body
The braces {} are used to define the scope of the loop.
However, if the loop contains only one statement, then
we don't need to use braces. A loop without a body is
possible. The braces work as a block separator, i.e., the
value variable declared inside for loop is valid only for
that block and not outside. Consider the following
example.

#include<stdio.h>
void main ()
{
int i;
for(i=0;i<10;i++)
{
int i = 20;
printf("%d ",i);
}
}

Output
20 20 20 20 20 20 20 20 20 20

Infinitive for loop in C


To make a for loop infinite, we need not give any
expression in the syntax. Instead of that, we need to
provide two semicolons to validate the syntax of the for
loop. This will work as an infinite for loop.

#include<stdio.h>
void main ()
{
for(;;)
{
printf("welcome to javatpoint");
}
}

If you run this program, you will see above statement


infinite times.

Nested Loops in C
C supports nesting of loops in C. Nesting of loops is the feature in C that
allows the looping of statements inside another loop. Let's observe an
example of nesting loops in C.

Any number of loops can be defined inside another loop, i.e., there is no
restriction for defining any number of loops. The nesting level can be defined
at n times. You can define any type of loop inside another loop; for example,
you can define 'while' loop inside a 'for' loop.

Syntax of Nested loop

Outer_loop
{
Inner_loop
{
// inner loop statements.
}
// outer loop statements.
}

Outer_loop and Inner_loop are the valid loops that can be a 'for' loop,
'while' loop or 'do-while' loop.

Nested for loop

The nested for loop means any type of loop which is defined inside the 'for'
loop.

for (initialization; condition; update)


{
for(initialization; condition; update)
{
// inner loop statements.
}
// outer loop statements.
}

Example of nested for loop

#include <stdio.h>
int main()
{
int n;// variable declaration
printf("Enter the value of n :");
// Displaying the n tables.
for(int i=1;i<=n;i++) // outer loop
{
for(int j=1;j<=10;j++) // inner loop
{
printf("%d\t",(i*j)); // printing the value.
}
printf("\n");
}

Explanation of the above code

First, the 'i' variable is initialized to 1 and then program control passes to the
i<=n.

o The program control checks whether the condition 'i<=n' is true or not.
o If the condition is true, then the program control passes to the inner
loop.
o The inner loop will get executed until the condition is true.
o After the execution of the inner loop, the control moves back to the
update of the outer loop, i.e., i++.
o After incrementing the value of the loop counter, the condition is
checked again, i.e., i<=n.
o If the condition is true, then the inner loop will be executed again.
o This process will continue until the condition of the outer loop is true.

Output:

Nested while loop

The nested while loop means any type of loop which is defined inside the
'while' loop.

while(condition)
{
while(condition)
{
// inner loop statements.
}
// outer loop statements.
}

Example of nested while loop

#include <stdio.h>
int main()
{
int rows; // variable declaration
int columns; // variable declaration
int k=1; // variable initialization
printf("Enter the number of rows :"); // input the number of rows.
scanf("%d",&rows);
printf("\nEnter the number of columns :"); // input the number of columns.
scanf("%d",&columns);
int a[rows][columns]; //2d array declaration
int i=1;
while(i<=rows) // outer loop
{
int j=1;
while(j<=columns) // inner loop
{
printf("%d\t",k); // printing the value of k.
k++; // increment counter
j++;
}
i++;
printf("\n");
}
}

Explanation of the above code.

o We have created the 2d array, i.e., int a[rows][columns].


o The program initializes the 'i' variable by 1.
o Now, control moves to the while loop, and this loop checks whether the
condition is true, then the program control moves to the inner loop.
o After the execution of the inner loop, the control moves to the update
of the outer loop, i.e., i++.
o After incrementing the value of 'i', the condition (i<=rows) is checked.
o If the condition is true, the control then again moves to the inner loop.
o This process continues until the condition of the outer loop is true.

Output:
C break statement
The break is a keyword in C which is used to bring the program control out of
the loop. The break statement is used inside loops or switch statement. The
break statement breaks the loop one by one, i.e., in the case of nested loops,
it breaks the inner loop first and then proceeds to outer loops. The break
statement in C can be used in the following two scenarios:

1. With switch case


2. With loop

Syntax:
1. //loop or switch case
2. break;
Flowchart of break in c

Example
#include<stdio.h>
#include<stdlib.h>
void main ()
{
int i;
for(i = 0; i<10; i++)
{
printf("%d ",i);
if(i == 5)
break;
}
printf("came outside of loop i = %d",i);

Output

0 1 2 3 4 5 came outside of loop i = 5


How does the break statement work?
The "break" statement works similarly to other programming languages in
C programming. A control flow statement is used to exit a loop or switch
statement early when a specific condition is met. The "break"
statement is beneficial when you want to terminate a loop early or exit
a switch block before it ends. The process of the "break"
statement works in C is the same as in other programming languages:

ADVERTISEMENT

o The loop (while or for) or the switch (or a series of "if-else" statements)
begins execution.
o The program analyzes the condition within the "if" statement that includes
the "break" statement throughout each iteration of the loop or each check in
the switch.
o If the condition is "true", the "break" statement is performed.
o When a "break" statement is found, the program immediately quits the loop
or switch block, skipping any remaining iterations or checks.
o The program continues to execute the code following the loop or switch

Note: The "break" statement only affects the innermost loop or switch block which
is contained within the statement. If there are nested loops or switch statements, the
nearest one that includes the "break" statement will be broken out of.

Without the "break" statement, the loop or switch would continue its normal
execution and process all the remaining iterations or checks, even if the
desired condition has already been met. The "break" statement provides an
efficient way to exit loops or switch blocks when you no longer need to
perform further iterations or checks.

Use of break statements in different cases with


their examples:
Let us go through each use case of the "break" statement in C with
detailed explanations and examples:

o Simple Loops
o Nested Loops
o Infinite Loops
o Switch case

1. Simple Loops:

When a specific condition is fulfilled, the "break" statement is widely used in


simple loops like "while" and "for" to stop the loop early. It is helpful when
you wish to terminate the loop early due to a condition.

Syntax:

It has the following syntax:

While loop

while (condition) {
// Code block inside the loop
if (some_condition) {
break; // Exit the loop if this condition is met
}
// Rest of the loop's code
}

For loop

for (initialization; condition; increment) {


// Code block inside the loop
if (some_condition) {
break; // Exit the loop if this condition is met
}
// Rest of the loop's code
}

Example:

Let's take an example to understand the use of the break


statement in simple loops in C:

// Using break in a while loop


#include <stdio.h>
int main() {
inti = 1;
while (i<= 10) {
if (i == 5) {
break; // Exit the loop when i becomes 5
}
printf("%d ", i);
i++;
}
printf("\n");
return 0;
}

Output

1 2 3 4

Explanation:

In this example, the "while" loop outputs the digits 1 through 4. When i
equals 5, the "if" condition if (i == 5) is true, and the "break"
expression is performed, forcing the loop to finish early.

Continue
The continue statement breaks one iteration (in the loop), if a specified condition
occurs, and continues with the next iteration in the loop.

This example skips the value of 4:


Example
int i;

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


if (i == 4) {
continue;
}
printf("%d\n", i);
}

goto Statement in C


The C goto statement is a jump statement which is sometimes also referred to as


an unconditional jump statement. The goto statement can be used to jump from
anywhere to anywhere within a function.

Syntax
The syntax for a “goto” statement in C is shown below
goto label;
...
...
label:
// Code to execute after the goto statement
The label is a unique identifier followed by a colon, and a statement is the code
executed when the “goto” statement jumps to that label.
The “goto” statement can be placed anywhere in the code and, when executed, will
transfer control to the labelled statement.
// C program to check if a number is
// even or not using goto statement
#include <stdio.h>

// 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);
}

Example 2

#include <stdio.h>
int main() {
int start = 1, end = 10;
int curr = start;

print_line:
printf("%d ", curr);

if (curr < end) {


curr++;
goto print_line;
}
return 0;
}

You might also like