Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
1 views

Unit 2(Programmingincnotes)

The document covers I/O statements and control statements in C programming, detailing formatted and unformatted input/output functions, including examples of printf(), scanf(), sprintf(), and sscanf(). It also introduces control statements, explaining their types (selection, iteration, and jump) and providing examples of their usage in C code. Key characteristics and differences between formatted and unformatted I/O functions are highlighted, along with the importance of control statements in managing program flow.

Uploaded by

Pat Rick
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Unit 2(Programmingincnotes)

The document covers I/O statements and control statements in C programming, detailing formatted and unformatted input/output functions, including examples of printf(), scanf(), sprintf(), and sscanf(). It also introduces control statements, explaining their types (selection, iteration, and jump) and providing examples of their usage in C code. Key characteristics and differences between formatted and unformatted I/O functions are highlighted, along with the importance of control statements in managing program flow.

Uploaded by

Pat Rick
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

UNIT-2

I/O Statements, Control Statements

I/O Statements:-

Formatted and Unformatted Input/Output functions in C:-

 Formatted I/O Functions.

 Unformatted I/O Functions.

 Formatted I/O Functions vs Unformatted I/O Functions.


Formatted I/O Functions
 Formatted I/O functions are used to take various inputs from the user and
display multiple outputs to the user. These types of I/O functions can help
to display the output to the user in different formats using the format
specifiers. These I/O supports all data types like int, float, char, and many
more.
 Why they are called formatted I/O?
 These functions are called formatted I/O functions because we can use
format specifiers in these functions and hence, we can format these
functions according to our needs.
 List of some format specifiers-
S Format
Type Description
NO. Specifier

int/signed
1 %d used for I/O signed integer value
int

2 %c char Used for I/O character value

3 %f float Used for I/O decimal floating-point value

Used for I/O string/group of


4 %s string
characters

5 %ld long int Used for I/O long signed integer value
unsigned
6 %u Used for I/O unsigned integer value
int

7 %i unsigned int used for the I/O integer value

8 %lf double Used for I/O fractional or floating data

9 %n prints prints nothing

The following formatted I/O functions will be discussed in this section-

1. printf()

2. scanf()

3. sprintf()

4. sscanf()

printf():
printf() function is used in a C program to display any value like float, integer, character, string, etc
on the console screen. It is a pre-defined function that is already declared in the stdio.h(header
file).

Syntax 1:

To display any variable value.

printf(“Format Specifier”, var1, var2, …., varn);

Example:

 C

// C program to implement

// printf() function

#include <stdio.h>

// Driver code

int main()

{
// Declaring an int type variable

int a;

// Assigning a value in a variable

a = 20;

// Printing the value of a variable

printf("%d", a);

return 0;

Output

20

Syntax 2:

To display any string or a message

printf(“Enter the text which you want to display”);

Example:

 C

// C program to implement

// printf() function

#include <stdio.h>

// Driver code

int main()

// Displays the string written

// inside the double quotes

printf("This is a string");

return 0;
}

Output

This is a string

scanf():

scanf() function is used in the C program for reading or taking any value from the keyboard by the
user, these values can be of any data type like integer, float, character, string, and many more. This
function is declared in stdio.h(header file), that’s why it is also a pre-defined function. In scanf()
function we use &(address-of operator) which is used to store the variable value on the memory
location of that variable.

Syntax:

scanf(“Format Specifier”, &var1, &var2, …., &varn);

Example:

 C

// C program to implement

// scanf() function

#include <stdio.h>

// Driver code

int main()

int num1;

// Printing a message on

// the output screen

printf("Enter a integer number: ");

// Taking an integer value

// from keyboard

scanf("%d", &num1);
// Displaying the entered value

printf("You have entered %d", num1);

return 0;

Output

Enter a integer number: You have entered 0

Output:

Enter a integer number: 56

You have entered 56

sprintf():
sprintf stands for “string print”. This function is similar to printf() function but this function prints
the string into a character array instead of printing it on the console screen.

Syntax:

sprintf(array_name, “format specifier”, variable_name);

Example:

 C

// C program to implement

// the sprintf() function

#include <stdio.h>

// Driver code

int main()

char str[50];

int a = 2, b = 8;

// The string "2 and 8 are even number"

// is now stored into str


sprintf(str, "%d and %d are even number",

a, b);

// Displays the string

printf("%s", str);

return 0;

Output

2 and 8 are even number

sscanf():

sscanf stands for “string scanf”. This function is similar to scanf() function but this function reads
data from the string or character array instead of the console screen.

Syntax:

sscanf(array_name, “format specifier”, &variable_name);

Example:

 C

// C program to implement

// sscanf() function

#include <stdio.h>

// Driver code

int main()

char str[50];

int a = 2, b = 8, c, d;

// The string "a = 2 and b = 8"

// is now stored into str

// character array
sprintf(str, "a = %d and b = %d",

a, b);

// The value of a and b is now in

// c and d

sscanf(str, "a = %d and b = %d",

&c, &d);

// Displays the value of c and d

printf("c = %d and d = %d", c, d);

return 0;

Output

c = 2 and d = 8

Unformatted Input/Output functions


Unformatted I/O functions are used only for character data type or character array/string and
cannot be used for any other datatype. These functions are used to read single input from the user
at the console and it allows to display the value at the console.

Why they are called unformatted I/O?


These functions are called unformatted I/O functions because we cannot use format specifiers in
these functions and hence, cannot format these functions according to our needs.

The following unformatted I/O functions will be discussed in this section-

1. getch()

2. getche()

3. getchar()

4. putchar()

5. gets()

6. puts()

7. putch()

getch():
getch() function reads a single character from the keyboard by the user but doesn’t display that
character on the console screen and immediately returned without pressing enter key. This
function is declared in conio.h(header file). getch() is also used for hold the screen.

Syntax:

getch();

or

variable-name = getch();

Example:

 C

// C program to implement

// getch() function

#include <conio.h>

#include <stdio.h>

// Driver code

int main()

printf("Enter any character: ");

// Reads a character but

// not displays

getch();

return 0;

Output:

Enter any character:

getche():

getche() function reads a single character from the keyboard by the user and displays it on the
console screen and immediately returns without pressing the enter key. This function is declared in
conio.h(header file).
Syntax:

getche();

or

variable_name = getche();

Example:

 C

// C program to implement

// the getche() function

#include <conio.h>

#include <stdio.h>

// Driver code

int main()

printf("Enter any character: ");

// Reads a character and

// displays immediately

getche();

return 0;

Output:

Enter any character: g

getchar():

The getchar() function is used to read only a first single character from the keyboard whether
multiple characters is typed by the user and this function reads one character at one time until and
unless the enter key is pressed. This function is declared in stdio.h(header file)

Syntax:

Variable-name = getchar();

Example:

 C
// C program to implement

// the getchar() function

#include <conio.h>

#include <stdio.h>

// Driver code

int main()

// Declaring a char type variable

char ch;

printf("Enter the character: ");

// Taking a character from keyboard

ch = getchar();

// Displays the value of ch

printf("%c", ch);

return 0;

Output:

Enter the character: a

putchar():

The putchar() function is used to display a single character at a time by passing that character
directly to it or by passing a variable that has already stored a character. This function is declared
in stdio.h(header file)

Syntax:

putchar(variable_name);

Example:

 C
// C program to implement

// the putchar() function

#include <conio.h>

#include <stdio.h>

// Driver code

int main()

char ch;

printf("Enter any character: ");

// Reads a character

ch = getchar();

// Displays that character

putchar(ch);

return 0;

Output:

Enter any character: Z

gets():
gets() function reads a group of characters or strings from the keyboard by the user and these
characters get stored in a character array. This function allows us to write space-separated texts or
strings. This function is declared in stdio.h(header file).

Syntax:

char str[length of string in number]; //Declare a char type variable of any length

gets(str);

Example:

 C
// C program to implement

// the gets() function

#include <conio.h>

#include <stdio.h>

// Driver code

int main()

// Declaring a char type array

// of length 50 characters

char name[50];

printf("Please enter some texts: ");

// Reading a line of character or

// a string

gets(name);

// Displaying this line of character

// or a string

printf("You have entered: %s",

name);

return 0;

Output:

Please enter some texts: geeks for geeks

You have entered: geeks for geeks

puts():

In C programming puts() function is used to display a group of characters or strings which is already
stored in a character array. This function is declared in stdio.h(header file).
Syntax:

puts(identifier_name );

Example:

 C

// C program to implement

// the puts() function

#include <stdio.h>

// Driver code

int main()

char name[50];

printf("Enter your text: ");

// Reads string from user

gets(name);

printf("Your text is: ");

// Displays string

puts(name);

return 0;

Output:

Enter your text: GeeksforGeeks

Your text is: GeeksforGeeks

putch():

putch() function is used to display a single character which is given by the user and that character
prints at the current cursor location. This function is declared in conio.h(header file)
Syntax:

putch(variable_name);

Example:

 C

// C program to implement

// the putch() functions

#include <conio.h>

#include <stdio.h>

// Driver code

int main()

char ch;

printf("Enter any character:\n ");

// Reads a character from the keyboard

ch = getch();

printf("\nEntered character is: ");

// Displays that character on the console

putch(ch);

return 0;

Output:

Enter any character:

Entered character is: d

Formatted I/O vs Unformatted I/O


S
Formatted I/O functions Unformatted I/O functions
No.

These functions do not allow to take


These functions allow us to take input or
1 input or display output in user desired
display output in the user’s desired format.
format.

These functions do not support format


2 These functions support format specifiers.
specifiers.

These are used for storing data more user These functions are not more user-
3
friendly friendly.

Here, we can use only character and


4 Here, we can use all data types.
string data types.

printf(), scanf, sprintf() and sscanf() are getch(), getche(), gets() and puts(), are
5
examples of these functions. some examples of these functions.

Control Statements:-

Introduction to Control Statements in C

Control statements are an essential aspect of programming languages like C, as they allow
programmers to control the flow of execution of their programs. In C, there are three types of
control statements: selection statements, iteration statements, and jump statements.

Control statements in C are programming constructs that are used to control the flow of execution
in a program. They allow a programmer to specify conditions that determine which statements are
executed and which are skipped, to loop through statements until a condition is met, or to jump to
a different part of the program.

Characteristics:

o Control statements serve to control the execution flow of a program.

o Control statements in C are classified into selection statements, iteration statements, and
jump statements.

o Selection statements serve to execute code based on a certain circumstance.

o Iteration statements loop through a code block until a condition is met.

o Jump statements serve to move control from one section of a program to another.
o The if statement, for loop, while loop, switch statement, break statement, and continue
statement are C's most widely used control statements.

Usage:

Control statements are used extensively in programming, especially in more complex programs. By
managing the flow of execution based on particular conditions, they enable a programmer to
design more efficient and understandable code.

C Code:

Here is an example of how control statements can be used in C:

1. #include <stdio.h>

2.

3. int main() {

4. int num = 10;

5.

6. if (num > 0) {

7. printf("The number is positive\n");

8. } else {

9. printf("The number is negative\n");

10. }

11.

12. for (int i = 0; i < 5; i++) {

13. printf("%d\n", i);

14. }

15.

16. int i = 0;

17. while (i < 5) {

18. printf("%d\n", i);

19. i++;

20. }

21.

22. switch (num) {

23. case 0:

24. printf("The number is zero\n");


25. break;

26. case 10:

27. printf("The number is ten\n");

28. break;

29. default:

30. printf("The number is not zero or ten\n");

31. break;

32. }

33.

34. return 0;

35. }

Test it Now

Output

The number is positive

The number is ten

The above C code demonstrates the use of different control statements such as if-else statements,
switch statements, for loops, while loops and return statements. The code initializes a variable
'num' to 10 and then proceeds to use different control statements to manipulate the flow of the
program based on the value of 'num'.

The first control statement is an if-else statement that examines whether 'num' is greater than
zero. If it is, the program prints to the console, "The number is positive." If not, it displays "The
number is negative." This shows how to utilize selection statements in C.
The for loop is the second control statement used, which sets a variable 'i' to 0 and then performs
a block of code as long as 'i' is less than 5. The program prints the value of 'i' to the console within
the code block. This shows how to utilize iteration statements in C.

The while loop is the third control statement used. It sets a variable 'i' to 0 and then performs a
code block if 'i' is less than 5. The program within the block of code prints the value of 'i' to the
console and increments 'i' by 1. This also shows how to utilize iteration statements in C.

The fourth control statement used is the switch statement, which checks the value of 'num' and
executes different blocks of code depending on its value. If 'num' is 0, the program prints "The
number is zero". If 'num' is 10, the program prints "The number is ten". If 'num' is neither 0 nor 10,
the program prints "The number is not zero or ten". This demonstrates the use of switch
statements in C.

Finally, the program ends with a return statement, which returns the value 0 to the operating
system to indicate that the program ran successfully.

In conclusion, the above C code provides a simple example of how different control statements can
be used in a program to manipulate the flow of execution based on certain conditions. It is a good
starting point for beginners to understand the basic concepts of control statements in C.

Advantages:

o Control statements allow programmers to control the flow of execution in their programs,
enabling it to be simple to develop efficient and understandable code.

o They allow programmers to handle different scenarios and conditions in their programs.

Disadvantages:

o Overuse of control statements can make code difficult to read and maintain.

o Complex control statements can be difficult to debug and can introduce bugs in the code.

The conditional statements (also known as decision control structures) such as if, if else, switch,
etc. are used for decision-making purposes in C programs.

They are also known as Decision-Making Statements and are used to evaluate one or more
conditions and make the decision whether to execute a set of statements or not. These decision-
making statements in programming languages decide the direction of the flow of program
execution.

Need of Conditional Statements

There come situations in real life when we need to make some decisions and based on these
decisions, we decide what should we do next. Similar situations arise in programming also where
we need to make some decisions and based on these decisions we will execute the next block of
code. For example, in C if x occurs then execute y else execute z. There can also be multiple
conditions like in C if x occurs then execute p, else if condition y occurs execute q, else execute r.
This condition of C else-if is one of the many ways of importing multiple conditions. To learn how
to use these control structures alongside data structures in C, the C Programming Course Online
with Data Structures provides detailed lessons on program control and logic.
Types of Conditional Statements in C

Following are the decision-making statements available in C:

1. if Statement

2. if-else Statement

3. Nested if Statement

4. if-else-if Ladder

5. switch Statement

6. Conditional Operator

7. Jump Statements:

 break

 continue

 goto

 return

Let’s discuss each of them one by one.

1. if in C

The if statement is the most simple decision-making statement. It is used to decide whether a
certain statement or block of statements will be executed or not i.e if a certain condition is true
then a block of statements is executed otherwise not.

Syntax of if Statement

if(condition)
{
// Statements to execute if
// condition is true
}

Here, the condition after evaluation will be either true or false. C if statement accepts boolean
values – if the value is true then it will execute the block of statements below it otherwise not. If
we do not provide the curly braces ‘{‘ and ‘}’ after if(condition) then by default if statement will
consider the first immediately below statement to be inside its block.

Flowchart of if Statement
Flow Diagram of if Statement

Example of if in C

// C program to illustrate If statement

#include <stdio.h>

int main()

int i = 10;

if (i > 15) {

printf("10 is greater than 15");

printf("I am Not in if");


}

Output

I am Not in if

As the condition present in the if statement is false. So, the block below the if statement is not
executed.

2. if-else in C

The if statement alone tells us that if a condition is true it will execute a block of statements and if
the condition is false it won’t. But what if we want to do something else when the condition is
false? Here comes the C else statement. We can use the else statement with the if statement to
execute a block of code when the condition is false. The if-else statement consists of two blocks,
one for false expression and one for true expression.

Syntax of if else in C

if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}

Flowchart of if-else Statement


Flow Diagram of if else

Example of if-else

// C program to illustrate If statement

#include <stdio.h>

int main()

int i = 20;

if (i < 15) {

printf("i is smaller than 15");

}
else {

printf("i is greater than 15");

return 0;

Output

i is greater than 15

The block of code following the else statement is executed as the condition present in
the if statement is false.

3. Nested if-else in C

A nested if in C is an if statement that is the target of another if statement. Nested if statements


mean an if statement inside another if statement. Yes, C allow us to nested if statements within if
statements, i.e, we can place an if statement inside another if statement.

Syntax of Nested if-else

if (condition1)
{
// Executes when condition1 is true
if (condition_2)
{
// statement 1
}
else
{
// Statement 2
}
}
else {
if (condition_3)
{
// statement 3
}
else
{
// Statement 4
}
}

The below flowchart helps in visualize the above syntax.


Example of Nested if-else

// C program to illustrate nested-if statement

#include <stdio.h>

int main()

int i = 10;

if (i == 10) {

// First if statement

if (i < 15)

printf("i is smaller than 15\n");

// Nested - if statement

// Will only be executed if statement above

// is true

if (i < 12)

printf("i is smaller than 12 too\n");

else

printf("i is greater than 15");

else {

if (i == 20) {

// Nested - if statement

// Will only be executed if statement above

// is true

if (i < 22)

printf("i is smaller than 22 too\n");

else
printf("i is greater than 25");

return 0;

Output

i is smaller than 15

i is smaller than 12 too

4. if-else-if Ladder in C
The if else if statements are used when the user has to decide among multiple options. The C if
statements are executed from the top down. As soon as one of the conditions controlling the if is
true, the statement associated with that if is executed, and the rest of the C else-if ladder is
bypassed. If none of the conditions is true, then the final else statement will be executed. if-else-if
ladder is similar to the switch statement.

Syntax of if-else-if Ladder


if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;

Flowchart of if-else-if Ladder


Flow Diagram of if-else-if

Example of if-else-if Ladder

// C program to illustrate nested-if statement

#include <stdio.h>

int main()

int i = 20;

if (i == 10)

printf("i is 10");

else if (i == 15)

printf("i is 15");

else if (i == 20)

printf("i is 20");

else
printf("i is not present");

Output

i is 20

5. switch Statement in C

The switch case statement is an alternative to the if else if ladder that can be used to execute the
conditional code based on the value of the variable specified in the switch statement. The switch
block consists of cases to be executed based on the value of the switch variable.

Syntax of switch

switch (expression) {
case value1:
statements;
case value2:
statements;
....
....
....
default:
statements;
}

Note: The switch expression should evaluate to either integer or character. It cannot evaluate any
other data type.

Flowchart of switch
Flowchart of switch in C

Example of switch Statement

// C Program to illustrate the use of switch statement

#include <stdio.h>

int main()
{

// variable to be used in switch statement

int var = 2;

// declaring switch cases

switch (var) {

case 1:

printf("Case 1 is executed");

break;

case 2:

printf("Case 2 is executed");

break;

default:

printf("Default Case is executed");

break;

return 0;

Output

Case 2 is executed

6. Conditional Operator in C

The conditional operator is used to add conditional code in our program. It is similar to the if-else
statement. It is also known as the ternary operator as it works on three operands.

Syntax of Conditional Operator

(condition) ? [true_statements] : [false_statements];

Flowchart of Conditional Operator


Flow Diagram of Conditional Operator

Example of Conditional Operator

// C Program to illustrate the use of conditional operator

#include <stdio.h>

// driver code

int main()

int var;

int flag = 0;

// using conditional operator to assign the value to var

// according to the value of flag

var = flag == 0 ? 25 : -25;


printf("Value of var when flag is 0: %d\n", var);

// changing the value of flag

flag = 1;

// again assigning the value to var using same statement

var = flag == 0 ? 25 : -25;

printf("Value of var when flag is NOT 0: %d", var);

return 0;

Output

Value of var when flag is 0: 25

Value of var when flag is NOT 0: -25

7. Jump Statements in C

These statements are used in C for the unconditional flow of control throughout the functions in a
program. They support four types of jump statements:

A) break

This loop control statement is used to terminate the loop. As soon as the break statement is
encountered from within a loop, the loop iterations stop there, and control returns from the loop
immediately to the first statement after the loop.

Syntax of break

break;

Basically, break statements are used in situations when we are not sure about the actual number
of iterations for the loop or we want to terminate the loop based on some condition.
Example of break

// C program to illustrate

// to show usage of break

// statement
#include <stdio.h>

void findElement(int arr[], int size, int key)

// loop to traverse array and search for key

for (int i = 0; i < size; i++) {

if (arr[i] == key) {

printf("Element found at position: %d",

(i + 1));

break;

int main()

int arr[] = { 1, 2, 3, 4, 5, 6 };

// no of elements

int n = 6;

// key to be searched

int key = 3;

// Calling function to find the key

findElement(arr, n, key);

return 0;

Output
Element found at position: 3

B) continue

This loop control statement is just like the break statement. The continue statement is opposite to
that of the break statement, instead of terminating the loop, it forces to execute the next iteration
of the loop.
As the name suggests the continue statement forces the loop to continue or execute the next
iteration. When the continue statement is executed in the loop, the code inside the loop following
the continue statement will be skipped and the next iteration of the loop will begin.

Syntax of continue

continue;

Flowchart of Continue

Flow Diagram of C continue Statement

Example of continue

// C program to explain the use

// of continue statement

#include <stdio.h>

int main()

// loop from 1 to 10

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

// If i is equals to 6,

// continue to next iteration

// without printing

if (i == 6)

continue;

else

// otherwise print the value of i


printf("%d ", i);

return 0;

Output

1 2 3 4 5 7 8 9 10

If you create a variable in if-else in C, it will be local to that if/else block only. You can use global
variables inside the if/else block. If the name of the variable you created in if/else is as same as
any global variable then priority will be given to the `local variable`.

#include <stdio.h>

int main()

int gfg = 0; // local variable for main

printf("Before if-else block %d\n", gfg);

if (1) {

int gfg = 100; // new local variable of if block

printf("if block %d\n", gfg);

printf("After if block %d", gfg);

return 0;

Output

Before if-else block 0

if block 100

After if block 0

C) goto
The goto statement in C also referred to as the unconditional jump statement can be used to jump
from one point to another within a function.

Syntax of goto

Syntax1 | Syntax2
----------------------------
goto label; | label:
. | .
. | .
. | .
label: | goto label;

In the above syntax, the first line tells the compiler to go to or jump to the statement marked as a
label. Here, a label is a user-defined identifier that indicates the target statement. The statement
immediately followed after ‘label:’ is the destination statement. The ‘label:’ can also appear before
the ‘goto label;’ statement in the above syntax.

Flowchart of goto Statement

Examples of goto

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

return 0;

Output

1 2 3 4 5 6 7 8 9 10

D) return

The return in C returns the flow of the execution to the function from where it is called. This
statement does not mandatorily need any conditional statements. As soon as the statement is
executed, the flow of the program stops immediately and returns the control from where it was
called. The return statement may or may not return anything for a void function, but for a non-void
function, a return value must be returned.

Flowchart of return

Flow Diagram of return

Syntax of return

return [expression];

Example of return

// C code to illustrate return


// statement

#include <stdio.h>

// non-void return type

// function to calculate sum

int SUM(int a, int b)

int s1 = a + b;

return s1;

// returns void

// function to print

void Print(int s2)

printf("The sum is %d", s2);

return;

int main()

int num1 = 10;

int num2 = 10;

int sum_of = SUM(num1, num2);

Print(sum_of);

return 0;

Output

The sum is 20
Looping Statements:-

Loops in programming are used to repeat a block of code until the specified condition is met. A
loop statement allows programmers to execute a statement or group of statements multiple times
without repetition of code.

// C program to illustrate need of loops

#include <stdio.h>

int main()

printf( "Hello World\n");

printf( "Hello World\n");

printf( "Hello World\n");

printf( "Hello World\n");

printf( "Hello World\n");

printf( "Hello World\n");

printf( "Hello World\n");

printf( "Hello World\n");

printf( "Hello World\n");

printf( "Hello World\n");

return 0;

Output

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World
Hello World

Hello World

Hello World

There are mainly two types of loops in C Programming:

1. Entry Controlled loops: In Entry controlled loops the test condition is checked before
entering the main body of the loop. For Loop and While Loop is Entry-controlled loops.

2. Exit Controlled loops: In Exit controlled loops the test condition is evaluated at the end of
the loop body. The loop body will execute at least once, irrespective of whether the
condition is true or false. do-while Loop is Exit Controlled loop.

Loop Type Description

first Initializes, then condition check, then executes the body and at last, the
for loop
update is done.

first Initializes, then condition checks, and then executes the body, and updating
while loop
can be inside the body.

do-while
do-while first executes the body and then the condition check is done.
loop

To master loops and control structures in C, our C programming course offers hands-on practice
and exercises that will help you write optimized, loop-based algorithms.

for Loop
for loop in C programming is a repetition control structure that allows programmers to write a
loop that will be executed a specific number of times. for loop enables programmers to perform n
number of steps together in a single line.

Syntax:

for (initialize expression; test expression; update expression)


{
//
// body of for loop
//
}

Example:

for(int i = 0; i < n; ++i)


{
printf("Body of for loop which will execute till n");
}
In for loop, a loop variable is used to control the loop. Firstly we initialize the loop variable with
some value, then check its test condition. If the statement is true then control will move to the
body and the body of for loop will be executed. Steps will be repeated till the exit condition
becomes true. If the test condition will be false then it will stop.

 Initialization Expression: In this expression, we assign a loop variable or loop counter to


some value. for example: int i=1;
 Test Expression: In this expression, test conditions are performed. If the condition
evaluates to true then the loop body will be executed and then an update of the loop
variable is done. If the test expression becomes false then the control will exit from the
loop. for example, i<=9;

 Update Expression: After execution of the loop body loop variable is updated by some
value it could be incremented, decremented, multiplied, or divided by any value.

for loop Equivalent Flow Diagram:


Example:

// C program to illustrate for loop

#include <stdio.h>

// Driver code

int main()

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

printf( "Hello World\n");

return 0;

Output

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

While Loop

While loop does not depend upon the number of iterations. In for loop the number of iterations
was previously known to us but in the While loop, the execution is terminated on the basis of the
test condition. If the test condition will become false then it will break from the while loop else
body will be executed.

Syntax:

initialization_expression;

while (test_expression)
{
// body of the while loop

update_expression;
}

Flow Diagram for while loop:


C

// C program to illustrate

// while loop

#include <stdio.h>

// Driver code

int main()

{
// Initialization expression

int i = 2;

// Test expression

while(i < 10)

// loop body

printf( "Hello World\n");

// update expression

i++;

return 0;

Output

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

do-while Loop

The do-while loop is similar to a while loop but the only difference lies in the do-while loop test
condition which is tested at the end of the body. In the do-while loop, the loop body will execute
at least once irrespective of the test condition.

Syntax:

initialization_expression;
do
{
// body of do-while loop

update_expression;

} while (test_expression);

// C program to illustrate

// do-while loop

#include <stdio.h>
// Driver code

int main()

// Initialization expression

int i = 2;

do

// loop body

printf( "Hello World\n");

// Update expression

i++;

// Test expression

} while (i < 1);

return 0;

Output

Hello World

Above program will evaluate (i<1) as false since i = 2. But still, as it is a do-while loop the body will
be executed once.

Loop Control Statements

Loop control statements in C programming are used to change execution from its normal
sequence.

Name Description

the break statement is used to terminate the switch and loop statement. It
break
transfers the execution to the statement immediately following the loop or
statement
switch.
Name Description

continue continue statement skips the remainder body and immediately resets its
statement condition before reiterating it.

goto
goto statement transfers the control to the labeled statement.
statement

Infinite Loop

An infinite loop is executed when the test expression never becomes false and the body of the
loop is executed repeatedly. A program is stuck in an Infinite loop when the condition is always
true. Mostly this is an error that can be resolved by using Loop Control statements.

Using for loop:

// C program to demonstrate infinite

// loops using for loop

#include <stdio.h>

// Driver code

int main ()

int i;

// This is an infinite for loop

// as the condition expression

// is blank

for ( ; ; )

printf("This loop will run forever.\n");

return 0;

}
Output

This loop will run forever.


This loop will run forever.
This loop will run forever.
...

Using While loop:

// C program to demonstrate

// infinite loop using while

// loop

#include <stdio.h>

// Driver code

int main()

while (1)

printf("This loop will run forever.\n");

return 0;

Output

This loop will run forever.


This loop will run forever.
This loop will run forever.
...

Using the do-while loop:

// C program to demonstrate

// infinite loop using do-while

// loop

#include <stdio.h>

// Driver code
int main()

do

printf("This loop will run forever.\n");

} while (1);

return 0;

Output
This loop will run forever.
This loop will run forever.
This loop will run forever.
...

Uncontrol Control Statements:-

Jump Statements in C

In C, jump statements are used to jump from one part of the code to another altering the normal
flow of the program. They are used to transfer the program control to somewhere else in the
program.

Types of Jump Statements in C

There are 4 types of jump statements in C:

1. break

2. continue

3. goto

4. return

1. break in C

The break statement exits or terminates the loop or switch statement based on a certain condition,
without executing the remaining code.

Syntax of break in C

break;

Flowchart of break Statement


Uses of break in C

The break statement is used in C for the following purposes:

1. To come out of the loop.

2. To come out from the nested loops.


3. To come out of the switch case.

Note: If the break statement is used inside an inner loop in a nested loop, it will break the inner
loop without affecting the execution of the outer loop.

Example of break Statement

The statements inside the loop are executed sequentially. When the break statement is
encountered within the loop and the condition for the break statement becomes true, the
program flow breaks out of the loop, regardless of any remaining iterations.

 C

// C program to illustrate the break in c loop

#include <stdio.h>

int main()

int i;

// for loop

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

// when i = 6, the loop should end

if (i == 6) {

break;

printf("%d ", i);

printf("Loop exited.\n");

return 0;

Output

1 2 3 4 5 Loop exited.

Explanation:

 Loop Execution Starts and goes normally till i = 5.


 When i = 6, the condition for the break statement becomes true and the program control
immediately exits the loop.

 The control continues with the remaining statements outside the loop.

Note: The break statement only break a single loop per usage. If we want to exit multiple loops in
nested loops, we have to use multiple break statements for each of the loop.

The break statement is also used inside the switch statement to terminate the switch statement
after the matching case is executed.

2. Continue in C

The continue statement in C is used to skip the remaining code after the continue statement within
a loop and jump to the next iteration of the loop. When the continue statement is encountered,
the loop control immediately jumps to the next iteration, by skipping the lines of code written
after it within the loop body.

Syntax of continue in C

continue;

Note: Just like break, the continue statement also works for one loop at a time.

Flowchart of continue Statement


Example of continue Statement

 C

// C Program to illustrate the continue statement

#include <stdio.h>

int main()

int i;

// loop

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

if (i == 2) {

// continue to be executed if i = 2

printf("Skipping iteration %d\n", i);

continue;

printf("Executing iteration %d\n", i);

return 0;

Output

Executing iteration 0

Executing iteration 1

Skipping iteration 2

Executing iteration 3

Executing iteration 4

Explanation: The for loop iterates from 0 to 4. Inside the loop, we check if i is equal to 2. If the
condition is true, the continue statement is executed, and it skips the remaining code within the
loop for that iteration. If the condition is false, the code proceeds normally.
Note: While using continue in loop, we have to make sure that we put the continue after the loop
variable updation or else it will result in an infinite loop.

3. Goto Statement in C

The goto statement is used to jump to a specific point from anywhere in a function. It is used to
transfer the program control to a labeled statement within the same function.

Syntax of goto Statement

goto label;
.
.
label:
//code

Flowchart of goto Statement

Flow Diagram of goto in C

Example of goto Statement

Check if a number is odd or even using goto statement.

 C++

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

int main()

int num = 26;

checkEvenOrNot(num);

return 0;

Output

26 is even
Note: The use of goto is generally discouraged in the programmer’s community as it makes the
code complex to understand.

4. Return Statement in C

The return statement in C is used to terminate the execution of a function and return a value to the
caller. It is commonly used to provide a result back to the calling code.

return expression;

Example

 C

#include <stdio.h>

int add(int a, int b)

int sum = a + b;

return sum; // Return the sum as the result of the

// function

void printMessage()

printf("GeeksforGeeks\n");

return; // Return from the function with no value (void)

int main()

int result = add(5, 3);

printf("Result: %d\n", result);

printMessage();
return 0;

Output

Result: 8

Multiple Branching Statement:-

Switch Statement in C

Switch case statement evaluates a given expression and based on the evaluated value(matching a
certain condition), it executes the statements associated with it. Basically, it is used to perform
different actions based on different conditions(cases).

 Switch case statements follow a selection-control mechanism and allow a value to change
control of execution.

 They are a substitute for long if statements that compare a variable to several integral
values.
 The switch statement is a multiway branch statement. It provides an easy way to dispatch
execution to different parts of code based on the value of the expression.

In C, the switch case statement is used for executing one condition from multiple conditions. It is
similar to an if-else-if ladder. If you’re looking to master decision-making structures and how they
relate to data structures, the C Programming Course Online with Data Structures offers detailed
lessons on control flow and advanced programming concepts.

The switch statement consists of conditional-based cases and a default case.

Syntax of switch Statement in C

switch(expression)
{
case value1: statement_1;
break;
case value2: statement_2;
break;
.
.
.
case value_n: statement_n;
break;
default: default_statement;
}

How to use switch case Statement in C?

Before using the switch case in our program, we need to know about some rules of the switch
statement.
Rules of the switch case statement

Following are some of the rules that we need to follow while using the switch statement:

1. In a switch statement, the “case value” must be of “char” and “int” type.

2. There can be one or N number of cases.

3. The values in the case must be unique.

4. Each statement of the case can have a break statement. It is optional.

5. The default Statement is also optional.

Example

// C program to Demonstrate returning of day based numeric

// value

#include <stdio.h>

int main()

// switch variable

int var = 1;

// switch statement

switch (var)

case 1:

printf("Case 1 is Matched.");

break;

case 2:

printf("Case 2 is Matched.");

break;

case 3:

printf("Case 3 is Matched.");
break;

default:

printf("Default case is Matched.");

break;

return 0;

Output

Case 1 is Matched.

How switch Statement Work?

The working of the switch statement in C is as follows:

1. Step 1: The switch variable is evaluated.

2. Step 2: The evaluated value is matched against all the present cases.

3. Step 3A: If the matching case value is found, the associated code is executed.

4. Step 3B: If the matching code is not found, then the default case is executed if present.

5. Step 4A: If the break keyword is present in the case, then program control breaks out of
the switch statement.

6. Step 4B: If the break keyword is not present, then all the cases after the matching case are
executed.

7. Step 5: Statements after the switch statement are executed.

We can also understand the working of the switch statement in C using the flowchart.

Flowchart of Switch Statement


Flowchart of switch statement in C

Break in switch case

This keyword is used to stop the execution inside a switch block. It helps to terminate the switch
block and break out of it. When a break statement is reached, the switch terminates, and the flow
of control jumps to the next line following the switch statement.

The break statement is optional. If omitted, execution will continue on into the next case. The flow
of control will fall through to subsequent cases until a break is reached.

Example of switch case without break


C

// C Program to demonstrate the behaviour of switch case

// without break

#include <stdio.h>

int main()

int var = 2;

// switch case without break

switch (var)

case 1:

printf("Case 1 is executed.\n");

case 2:

printf("Case 2 is executed.\n");

case 3:

printf("Case 3 is executed.");

case 4:

printf("Case 4 is executed.");

return 0;

Output

Case 2 is executed.

Case 3 is executed.Case 4 is executed.

Default in switch case

The default keyword is used to specify the set of statements to execute if there is no case match.

It is optional to use the default keyword in a switch case. Even if the switch case statement does
not have a default statement, it would run without any problem.
Important Points About Switch Case Statements

1. Switch expression should result in a constant value

If the expression provided in the switch statement does not result in a constant value, it would not
be valid. Some valid expressions for switch case will be,

// Constant expressions allowed


switch(1+2+23)
switch(1*2+3%4)
// Variable expression are allowed provided
// they are assigned with fixed values
switch(a*b+c*d)
switch(a+b+c)

2. Expression value should be only of int or char type.

The switch statement can only evaluate the integer or character value. So the switch expression
should return the values of type int or char only.

3. Case Values must be Unique

In the C switch statement, duplicate case values are not allowed.

3. Nesting of switch Statements


Nesting of switch statements is allowed, which means you can have switch statements inside
another switch. However nested switch statements should be avoided as it makes the program
more complex and less readable.

4. The default block can be placed anywhere

Regardless of its placement, the default case only gets executed if none of the other case
conditions are met. So, putting it at the beginning, middle, or end doesn’t change the core logic.

Examples of switch Statement in C

Example 1: C Program to print the day of the week using a switch case.

// C program to print the day using switch

#include <stdio.h>

// Driver Code

int main()

int day = 2;

printf("The day with number %d is ", day);


switch (day)

case 1:

printf("Monday");

break;

case 2:

printf("Tuesday");

break;

case 3:

printf("Wednesday");

break;

case 4:

printf("Thursday");

break;

case 5:

printf("Friday");

break;

case 6:

printf("Saturday");

break;

case 7:

printf("Sunday");

break;

default:

printf("Invalid Input");

break;

return 0;

Output
The day with number 2 is Tuesday

Example 2: Simple Calculator using switch case in C

// C Program to create a simple calculator using switch

// statement

#include <stdio.h>

#include <stdlib.h>

// driver code

int main()

// switch variable

char choice;

// operands

int x, y;

while (1)

printf("Enter the Operator (+,-,*,/)\nEnter x to "

"exit\n");

scanf(" %c", &choice);

// for exit

if (choice == 'x')

exit(0);

printf("Enter the two numbers: ");

scanf("%d %d", &x, &y);


// switch case with operation for each operator

switch (choice)

case '+':

printf("%d + %d = %d\n", x, y, x + y);

break;

case '-':

printf("%d - %d = %d\n", x, y, x - y);

break;

case '*':

printf("%d * %d = %d\n", x, y, x * y);

break;

case '/':

printf("%d / %d = %d\n", x, y, x / y);

break;

default:

printf("Invalid Operator Input\n");

return 0;

Output

Enter the operator (+, -, *, /)


Enter x to exit
+
Enter the two numbers: 100 + 200
100 + 200 = 300

Advantages of C switch Statement

1. Easier to read than if else if.

2. Easier to debug and maintain for a large number of conditions.


3. Faster execution speed.

Disadvantages of C switch Statement

1. Switch case can only evaluate int or char type.

2. No support for logical expressions.

3. Have to keep in mind to add a break in every case.

You might also like