2 Control Structures
2 Control Structures
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.
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
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
}
#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
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
}
#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.
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.
1. int x,y,z;
2. char a,b;
3. float f;
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:
Output
enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
Output
hi
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:
#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:
#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
#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);
}
}
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
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.
Advantage of loops in C
1) It provides code reusability.
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).
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.
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.
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;
}
Output:
#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:
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:
Example:
#include <stdio.h>
int main() {
inti = 1;
do {
printf("Iteration %d\n", i);
i++;
} while (1); // Condition is always true
return 0;
}
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)
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;
}
Output:
Explanation:
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.
while(condition){
//code to be executed
}
#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
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
//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:
Output
1
2
3
4
5
6
7
8
9
10
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
#include<stdio.h>
void main ()
{
for(;;)
{
printf("welcome to javatpoint");
}
}
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.
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.
The nested for loop means any type of loop which is defined inside the '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");
}
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:
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.
}
#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");
}
}
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:
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
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.
o Simple Loops
o Nested Loops
o Infinite Loops
o Switch case
1. Simple Loops:
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
Example:
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.
goto Statement in C
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>
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);