Control flow statements in Programming
Last Updated :
04 Mar, 2024
Control flow refers to the order in which statements within a program execute. While programs typically follow a sequential flow from top to bottom, there are scenarios where we need more flexibility. This article provides a clear understanding about everything you need to know about Control Flow Statements.
What are Control Flow Statements in Programming?
Control flow statements are fundamental components of programming languages that allow developers to control the order in which instructions are executed in a program. They enable execution of a block of code multiple times, execute a block of code based on conditions, terminate or skip the execution of certain lines of code, etc.
Types of Control Flow statements in Programming:
Control Flow Statements Type | Control Flow Statement | Description |
---|
Conditional Statements | if-else | Executes a block of code if a specified condition is true, and another block if the condition is false. |
switch-case | Evaluates a variable or expression and executes code based on matching cases. |
Looping Statements | for | Executes a block of code a specified number of times, typically iterating over a range of values. |
while | Executes a block of code as long as a specified condition is true. |
do-while | Executes a block of code once and then repeats the execution as long as a specified condition is true. |
Jump Statements | break | Terminates the loop or switch statement and transfers control to the statement immediately following the loop or switch. |
continue | Skips the current iteration of a loop and continues with the next iteration. |
return | Exits a function and returns a value to the caller. |
goto | Transfers control to a labeled statement within the same function. (Note: goto is generally discouraged due to its potential for creating unreadable and error-prone code.) |
Conditional statements in programming are used to execute certain blocks of code based on specified conditions. They are fundamental to decision-making in programs. Here are some common types of conditional statements:
1. If Statement in Programming:
The if
statement is used to execute a block of code if a specified condition is true.
C++
#include <iostream>
using namespace std;
int main()
{
int a = 5;
if (a == 5) {
cout << "a is equal to 5";
}
return 0;
}
C
#include <stdio.h>
int main()
{
int a = 5;
if (a == 5) {
printf("a is equal to 5");
}
return 0;
}
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
int a = 5;
if (a == 5) {
System.out.println("a is equal to 5");
}
}
}
C#
using System;
public class GFG {
static public void Main()
{
int a = 5;
if (a == 5) {
Console.WriteLine("a is equal to 5");
}
}
}
JavaScript
let a = 5;
if (a === 5) {
console.log("a is equal to 5");
}
Python3
a = 5
if a == 5:
print("a is equal to 5")
2. if-else Statement in Programming:
The if-else
statement is used to execute one block of code if a specified condition is true, and another block of code if the condition is false.
C++
#include <iostream>
using namespace std;
int main()
{
int a = 10;
if (a == 5) {
cout << "a is equal to 5";
}
else {
cout << "a is not equal to 5";
}
return 0;
}
C
#include <stdio.h>
int main()
{
int a = 10;
if (a == 5) {
printf("a is equal to 5");
}
else {
printf("a is not equal to 5");
}
return 0;
}
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
int a = 10;
if (a == 5) {
System.out.println("a is equal to 5");
}
else {
System.out.println("a is not equal to 5");
}
}
}
C#
using System;
public class GFG {
static public void Main()
{
int a = 10;
if (a == 5) {
Console.WriteLine("a is equal to 5");
}
else {
Console.WriteLine("a is not equal to 5");
}
}
}
JavaScript
let a = 10;
if (a === 5) {
console.log("a is equal to 5");
} else {
console.log("a is not equal to 5");
}
Python3
a = 10
if a == 5:
print("a is equal to 5")
else:
print("a is not equal to 5")
Outputa is not equal to 5
3. if-else-if Statement in Programming:
The if-else-if
statement is used to execute one block of code if a specified condition is true, another block of code if another condition is true, and a default block of code if none of the conditions are true.
C++
#include <iostream>
using namespace std;
int main()
{
int a = 15;
if (a == 5) {
cout << "a is equal to 5";
}
else if (a == 10) {
cout << "a is equal to 10";
}
else {
cout << "a is not equal to 5 or 10";
}
return 0;
}
C
#include <stdio.h>
int main()
{
int a = 15;
if (a == 5) {
printf("a is equal to 5");
}
else if (a == 10) {
printf("a is equal to 10");
}
else {
printf("a is not equal to 5 or 10");
}
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void main(String[] args)
{
int a = 15;
if (a == 5) {
System.out.println("a is equal to 5");
}
else if (a == 10) {
System.out.println("a is equal to 10");
}
else {
System.out.println("a is not equal to 5 or 10");
}
}
}
C#
using System;
public class GFG {
static public void Main()
{
int a = 15;
if (a == 5) {
Console.WriteLine("a is equal to 5");
}
else if (a == 10) {
Console.WriteLine("a is equal to 10");
}
else {
Console.WriteLine("a is not equal to 5 or 10");
}
}
}
JavaScript
let a = 15;
if (a === 5) {
console.log("a is equal to 5");
} else if (a === 10) {
console.log("a is equal to 10");
} else {
console.log("a is not equal to 5 or 10");
}
Python3
a = 15
if a == 5:
print("a is equal to 5")
elif a == 10:
print("a is equal to 10")
else:
print("a is not equal to 5 or 10")
Outputa is not equal to 5 or 10
4. Ternary Operator or Conditional Operator in Programming:
In some programming languages, a ternary operator is used to assign a value to a variable based on a condition.
C++
#include <iostream>
using namespace std;
int main()
{
int a = 10;
cout << (a == 5 ? "a is equal to 5"
: "a is not equal to 5");
return 0;
}
C
#include <stdio.h>
int main()
{
int a = 10;
printf("%s", (a == 5 ? "a is equal to 5"
: "a is not equal to 5"));
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void main(String[] args)
{
int a = 10;
System.out.println(a == 5 ? "a is equal to 5"
: "a is not equal to 5");
}
}
C#
using System;
public class GFG {
static public void Main()
{
int a = 10;
Console.WriteLine(a == 5 ? "a is equal to 5"
: "a is not equal to 5");
}
// Code
}
JavaScript
let a = 10;
console.log(a === 5 ? "a is equal to 5" : "a is not equal to 5");
Python3
a = 10
print("a is equal to 5" if a == 5 else "a is not equal to 5")
Outputa is not equal to 5
5. Switch Statement in Programming:
In languages like C, C++, and Java, a switch
statement is used to execute one block of code from multiple options based on the value of an expression.
C++
#include <iostream>
using namespace std;
int main()
{
int a = 15;
switch (a) {
case 5:
cout << "a is equal to 5";
break;
case 10:
cout << "a is equal to 10";
break;
default:
cout << "a is not equal to 5 or 10";
}
return 0;
}
C
#include <stdio.h>
int main()
{
int a = 15;
switch (a) {
case 5:
printf("a is equal to 5");
break;
case 10:
printf("a is equal to 10");
break;
default:
printf("a is not equal to 5 or 10");
}
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void main(String[] args)
{
int a = 15;
switch (a) {
case 5:
System.out.println("a is equal to 5");
break;
case 10:
System.out.println("a is equal to 10");
break;
default:
System.out.println("a is not equal to 5 or 10");
}
}
}
C#
using System;
public class GFG {
static public void Main()
{
int a = 15;
switch (a) {
case 5:
Console.WriteLine("a is equal to 5");
break;
case 10:
Console.WriteLine("a is equal to 10");
break;
default:
Console.WriteLine("a is not equal to 5 or 10");
break;
}
}
}
JavaScript
let a = 15;
switch (a) {
case 5:
console.log("a is equal to 5");
break;
case 10:
console.log("a is equal to 10");
break;
default:
console.log("a is not equal to 5 or 10");
}
Outputa is not equal to 5 or 10
Each programming language may have its own syntax and specific variations of these conditional statements.
Looping statements, also known as iteration or repetition statements, are used in programming to repeatedly execute a block of code. They are essential for performing tasks such as iterating over elements in a list, reading data from a file, or executing a set of instructions a specific number of times. Here are some common types of looping statements:
The for
loop is used to iterate over a sequence (e.g., a list, tuple, string, or range) and execute a block of code for each item in the sequence.
C++
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 5; i++) {
cout << i << endl;
}
return 0;
}
C
#include <stdio.h>
int main()
{
for (int i = 0; i < 5; i++) {
printf("%d\n", i);
}
return 0;
}
Java
public class Main {
public static void main(String[] args)
{
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
}
}
C#
using System;
class Program {
static void Main(string[] args) {
for (int i = 0; i < 5; i++) {
Console.WriteLine(i);
}
}
}
JavaScript
for (var i = 0; i < 5; i++) {
console.log(i);
}
Python3
for i in range(5):
print(i)
The while
loop is used to repeatedly execute a block of code as long as a specified condition is true.
C++
#include <iostream>
using namespace std;
int main()
{
int count = 0;
while (count < 5) {
cout << count << endl;
count++;
}
return 0;
}
C
#include <stdio.h>
int main()
{
int count = 0;
while (count < 5) {
printf("%d\n", count);
count++;
}
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void main(String[] args)
{
int count = 0;
while (count < 5) {
System.out.println(count);
count++;
}
}
}
C#
using System;
class Program
{
static void Main(string[] args)
{
int count = 0;
while (count < 5)
{
Console.WriteLine(count);
count++;
}
}
}
JavaScript
let count = 0;
while (count < 5) {
console.log(count);
count++;
}
Python3
count = 0
while count < 5:
print(count)
count += 1
In some programming languages, such as C and Java, a do-while
loop is used to execute a block of code at least once, and then repeatedly execute the block as long as a specified condition is true.
C++
#include <iostream>
using namespace std;
int main()
{
int count = 0;
do {
cout << count << endl;
count++;
} while (count < 5);
return 0;
}
C
#include <stdio.h>
int main()
{
int count = 0;
do {
printf("%d\n", count);
count++;
} while (count < 5);
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void main(String[] args)
{
int count = 0;
do {
System.out.println(count);
count++;
} while (count < 5);
}
}
C#
using System;
public class GFG {
static public void Main()
{
int count = 0;
do {
Console.WriteLine(count);
count++;
} while (count < 5);
}
}
JavaScript
let count = 0;
do {
console.log(count); // Print the current value of count
count++; // Increment count by 1
} while (count < 5); // Continue looping as long as count is less than 5
4. Nested Loops in Programming:
Loops can be nested within one another to perform more complex iterations. For example, a for
loop can be nested inside another for
loop to create a two-dimensional iteration.
C++
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
cout << "i=" << i << " j=" << j << "\n";
}
}
}
C
#include <stdio.h>
int main()
{
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("i=%d j=%d\n", i, j);
}
}
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void main (String[] args) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
System.out.println("i=" + i + " j=" + j);
}
}
}
}
C#
using System;
public class GFG {
static public void Main()
{
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
Console.WriteLine($"i={i} j={j}");
}
}
}
}
JavaScript
for (let i = 0; i < 2; i++) {
for (let j = 0; j < 2; j++) {
console.log(`i=${i} j=${j}`);
}
}
Python3
for i in range(2):
for j in range(2):
print(f"i={i} j={j}")
Outputi=0 j=0
i=0 j=1
i=1 j=0
i=1 j=1
Each programming language may have its own syntax and specific variations of these looping statements.
Jump Statements in Programming:
Jump statements in programming are used to change the flow of control within a program. They allow the programmer to transfer program control to different parts of the code based on certain conditions or requirements. Here are common types of jump statements:
1. Break Statement in Programming:
The break
statement is primarily used to exit from loops prematurely. When encountered inside a loop, it terminates the loop's execution and transfers control to the statement immediately following the loop.
C++
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 10; i++) {
if (i == 5)
break;
cout << i << " ";
}
return 0;
}
C
#include <stdio.h>
int main()
{
for (int i = 0; i < 10; i++) {
if (i == 5)
break;
printf("%d ", i);
}
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void main(String[] args)
{
for (int i = 0; i < 10; i++) {
if (i == 5)
break;
System.out.print(i + " ");
}
}
}
C#
using System;
public class GFG {
static public void Main()
{
for (int i = 0; i < 10; i++) {
if (i == 5)
break;
Console.Write($"{i} ");
}
}
}
JavaScript
for (let i = 0; i < 10; i++) {
if (i === 5)
break;
console.log(i + " ");
}
Python3
for i in range(10):
if i == 5:
break
print(f"{i} ", end="")
2. Continue Statement in Programming:
The continue
statement is used to skip the current iteration of a loop and proceed to the next iteration.
C++
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 10; i++) {
if (i % 2 == 1)
continue;
cout << i << " ";
}
return 0;
}
C
#include <stdio.h>
int main()
{
for (int i = 0; i < 10; i++) {
if (i % 2 == 1)
continue;
printf("%d ", i);
}
return 0;
}
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
for (int i = 0; i < 10; i++) {
if (i % 2 == 1)
continue;
System.out.print(i + " ");
}
}
}
C#
using System;
public class GFG {
static public void Main()
{
for (int i = 0; i < 10; i++) {
if (i % 2 == 1)
continue;
Console.Write($"{i} ");
}
}
}
JavaScript
for (let i = 0; i < 10; i++) {
if (i % 2 === 1)
continue;
console.log(i + " ");
}
Python3
for i in range(10):
if i % 2 == 1:
continue
print(f"{i} ", end="")
3. Return Statement in Programming:
The return
statement is used to exit a function and optionally return a value to the caller.
C++
#include <iostream>
using namespace std;
bool isEven(int N) { return N % 2 == 0; }
int main()
{
int N = 5;
if (isEven(N)) {
cout << "N is even";
}
else {
cout << "N is odd";
}
return 0;
}
C
#include <stdio.h>
int isEven(int N) { return N % 2 == 0; }
int main()
{
int N = 5;
if (isEven(N)) {
printf("N is even");
}
else {
printf("N is odd");
}
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
static boolean isEven(int N) { return N % 2 == 0; }
public static void main(String[] args)
{
int N = 5;
if (isEven(N)) {
System.out.println("N is even");
}
else {
System.out.println("N is odd");
}
}
}
C#
using System;
public class GFG {
static bool IsEven(int N) { return N % 2 == 0; }
static public void Main()
{
int N = 5;
if (IsEven(N)) {
Console.WriteLine("N is even");
}
else {
Console.WriteLine("N is odd");
}
}
}
JavaScript
function isEven(N) {
return N % 2 === 0;
}
let N = 5;
if (isEven(N)) {
console.log("N is even");
} else {
console.log("N is odd");
}
Python3
def isEven(N):
return N % 2 == 0
N = 5
if isEven(N):
print("N is even")
else:
print("N is odd")
4. Goto Statement in Programming:
Some programming languages support the goto
statement, which allows transferring control to a labeled statement within the same function or block of code. However, the use of goto
is generally discouraged due to its potential for creating unreadable and unmaintainable code.
C++
#include <iostream>
using namespace std;
int main()
{
int i = 0;
loopStart:
if (i < 5) {
cout << i << " ";
i++;
goto loopStart;
}
return 0;
}
C
#include <stdio.h>
int main() {
int i = 0;
loopStart:
if (i < 5) {
printf("%d ", i);
i++;
goto loopStart;
}
return 0;
}
C#
using System;
public class GFG {
static public void Main()
{
int i = 0;
loopStart:
if (i < 5) {
Console.Write(i + " ");
i++;
goto loopStart;
}
}
}
Similar Reads
C++ Tutorial | Learn C++ Programming C++ is a popular programming language that was developed as an extension of the C programming language to include OOPs programming paradigm. Since then, it has become foundation of many modern technologies like game engines, web browsers, operating systems, financial systems, etc.Features of C++Why
5 min read
Introduction to c++
Difference between C and C++C++ is often viewed as a superset of C. C++ is also known as a "C with class" This was very nearly true when C++ was originally created, but the two languages have evolved over time with C picking up a number of features that either weren't found in the contemporary version of C++ or still haven't m
3 min read
Setting up C++ Development EnvironmentC++ is a general-purpose programming language and is widely used nowadays for competitive programming. It has imperative, object-oriented, and generic programming features. C++ runs on lots of platforms like Windows, Linux, Unix, Mac, etc. Before we start programming with C++. We will need an enviro
8 min read
Header Files in C++C++ offers its users a variety of functions, one of which is included in header files. In C++, all the header files may or may not end with the ".h" extension unlike in C, Where all the header files must necessarily end with the ".h" extension. Header files in C++ are basically used to declare an in
6 min read
Namespace in C++Name conflicts in C++ happen when different parts of a program use the same name for variables, functions, or classes, causing confusion for the compiler. To avoid this, C++ introduce namespace.Namespace is a feature that provides a way to group related identifiers such as variables, functions, and
6 min read
Writing First C++ Program - Hello World ExampleThe "Hello World" program is the first step towards learning any programming language and is also one of the most straightforward programs you will learn. It is the basic program that demonstrates the working of the coding process. All you have to do is display the message "Hello World" on the outpu
4 min read
Basics
C++ Data TypesData types specify the type of data that a variable can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared as every data type requires a different amount of memory.C++ supports a wide variety of data typ
7 min read
C++ VariablesIn C++, variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be accessed or changed during program execution.Creating a VariableCreating a variable and giving it a name is called variable definition (sometimes called variable
4 min read
Operators in C++C++ operators are the symbols that operate on values to perform specific mathematical or logical computations on given values. They are the foundation of any programming language.Example:C++#include <iostream> using namespace std; int main() { int a = 10 + 20; cout << a; return 0; }Outpu
9 min read
Basic Input / Output in C++In C++, input and output are performed in the form of a sequence of bytes or more commonly known as streams.Input Stream: If the direction of flow of bytes is from the device (for example, Keyboard) to the main memory then this process is called input.Output Stream: If the direction of flow of bytes
5 min read
Control flow statements in ProgrammingControl flow refers to the order in which statements within a program execute. While programs typically follow a sequential flow from top to bottom, there are scenarios where we need more flexibility. This article provides a clear understanding about everything you need to know about Control Flow St
15+ min read
C++ LoopsIn C++ programming, sometimes there is a need to perform some operation more than once or (say) n number of times. For example, suppose we want to print "Hello World" 5 times. Manually, we have to write cout for the C++ statement 5 times as shown.C++#include <iostream> using namespace std; int
7 min read
Functions in C++A function is a building block of C++ programs that contains a set of statements which are executed when the functions is called. It can take some input data, performs the given task, and return some result. A function can be called from anywhere in the program and any number of times increasing the
9 min read
C++ ArraysIn C++, an array is a derived data type that is used to store multiple values of similar data types in a contiguous memory location.Arrays in C++Create an ArrayIn C++, we can create/declare an array by simply specifying the data type first and then the name of the array with its size inside [] squar
10 min read
Strings in C++In C++, strings are sequences of characters that are used to store words and text. They are also used to store data, such as numbers and other types of information in the form of text. Strings are provided by <string> header file in the form of std::string class.Creating a StringBefore using s
5 min read
Core Concepts
Pointers and References in C++In C++ pointers and references both are mechanisms used to deal with memory, memory address, and data in a program. Pointers are used to store the memory address of another variable whereas references are used to create an alias for an already existing variable. Pointers in C++ Pointers in C++ are a
5 min read
new and delete Operators in C++ For Dynamic MemoryIn C++, when a variable is declared, the compiler automatically reserves memory for it based on its data type. This memory is allocated in the program's stack memory at compilation of the program. Once allocated, it cannot be deleted or changed in size. However, C++ offers manual low-level memory ma
6 min read
Templates in C++C++ template is a powerful tool that allows you to write a generic code that can work with any data type. The idea is to simply pass the data type as a parameter so that we don't need to write the same code for different data types.For example, same sorting algorithm can work for different type, so
9 min read
Structures, Unions and Enumerations in C++Structures, unions and enumerations (enums) are 3 user defined data types in C++. User defined data types allow us to create a data type specifically tailored for a particular purpose. It is generally created from the built-in or derived data types. Let's take a look at each of them one by one.Struc
3 min read
Exception Handling in C++In C++, exceptions are unexpected problems or errors that occur while a program is running. For example, in a program that divides two numbers, dividing a number by 0 is an exception as it may lead to undefined errors.The process of dealing with exceptions is known as exception handling. It allows p
11 min read
File Handling through C++ ClassesIn C++, programs run in the computerâs RAM (Random Access Memory), in which the data used by a program only exists while the program is running. Once the program terminates, all the data is automatically deleted. File handling allows us to manipulate files in the secondary memory of the computer (li
8 min read
Multithreading in C++Multithreading is a technique where a program is divided into smaller units of execution called threads. Each thread runs independently but shares resources like memory, allowing tasks to be performed simultaneously. This helps improve performance by utilizing multiple CPU cores efficiently. Multith
5 min read
C++ OOPS
Standard Template Library (STL)
Practice Problem