Module 3 FCP
Module 3 FCP
Computing
Unit III
Control statements
By
Dr Gaanapriya V
Assistant Professor
Department of Chemical Engineering
Coimbatore Institute of Technology
1
Statements in C
Statements : smallest logical entity in c program
Compound statement
Single statement
{
int a=10; // definition
int a=10; // definition
a+5 ;//expression
a+5 ;//expression Block
a=a+10;// assignment
a=a+10;// assignment
}
2
Statements in C
Name of the statement Definition Example
Declaration and definition Declare variables, constants and int a=10; //declare+ definition
statement functions+ definition float b; // declaration
Null statement just a ; does nothing , often used as a while (i<10); // loop with
placeholder empty body
3
Statements in C
4
Decision making and Branching
C program is a set of statements which are normally executed sequentially in the order in which they
appear.
Decision making is about deciding the change of the order of execution of statements based on
certain conditions, or repeat a group of statements until certain specified conditions are met.
These statements are popularly known as decision-making statements. Since these statements
‘control’ the flow of execution , they are also known as control statements.
C language has the following statements supporting the decision – making capabilities as
if statement
switch statement
conditional operator statement
goto statement
5
Decision making and Branching
Program control
statements/constructs
Selection/Branching Iteration/Looping
6
Decision making with if statement
A powerful decision making statement and is used to control the flow of execution of statements.
Evaluate the expression first and then depending on whether the value of the expression (relation or
condition) is ‘true’(non-zero) or ‘false’(zero), it transfers the control to a particular statement.
if statement may be implemented in different forms depending on the complexity of the condition to be tested.
simple if statement
if......else statement
Nested if…else statement
else if ladder
7
Decision making with if statement
Two-way branching
Entry
True
8
Simple if statement
Statement-
statement block : single or compound block
test expression- True – statement block will be
executed
False
Otherwise, the statement block will be skipped and Statement-x
execution will jump to statement-x
True- both statement block and statement-x will be
executed in sequence
Next statement
9
Simple if statement
#include<stdio.h>
int main()
{
int x= 10; OUTPUT
x is greater than 5
if (x>5) //simple if statement Program finished
{
printf(“ x is greater than 5\n”);
}
printf(“Program finished \n”);
return 0;
}
10
Simple if statement
#include<stdio.h>
int main()
{ Enter four integer values
int a, b, c, d; 12 23 34 45
float ratio; Ratio = - 3.181818
printf(“ Enter four integer values\n”);
scanf(“%d %d %d %d”, &a, &b, &c, &d); Enter four integer values
12 23 34 34
if (c-d != 0) //execute statement block
{
ratio =float(a+b)/float(c-d);
printf(“Ratio =%f\n”, ratio);
}
return 0;
}
11
if…else statement
Syntax
if(test expression)
{
True-block statements
}
Entry
else
{ test
False-block statements expression
? False
}
Statement-X True
• If the test expression is true, then the true statement True block False Block
block will be executed immediately following the if
statement
Next statement
14
Nested if…else..if statement
The syntax is
if (test condition-1)
{
if (test condition-2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-x
15
Nested if…else..if statement
#include<stdio.h> }
int main() }
{ else if (number<0)
int number; {
printf(“Enter a number:”); printf (“ The number is negative.\n”);
scanf(“%d”, &number); }
if (number>0) else
{
{
printf(“ The number is zero.\n”);
if (number%2==0)
}
{
return 0;
printf(“The number is positive and even.\n”);
}
}
else
{
printf(“The number is positive and odd.\n”);
16
The else-if ladder
Another way of putting ifs together when multipath decisions are involved.
A multipath decision is a chain of ifs in which the statement associated with each else is an if.
This construct is known as the else if ladder. The conditions are evaluated from the top downwards.
As soon as a true condition is found, the statement associated with it is executed and the control is
transferred to the statement-x.
When all the n conditions become false, then the final else containing the default-statement will be executed.
17
The else-if ladder
Syntax:
if (condition-1)
statement-1;
else if (condition-2)
statement-2;
else if (condition-3)
statement-3;
else if (condition-n)
statement-n;
else
default-statement;
statement –x;
18
The else-if ladder
Entry
True Condit False
ion-1
False
True Condi
tion-2 False
Stateme True Condi
nt-1 Stateme tion-3 False
nt-2 True Condi
Stateme
tion-
nt-3
Stateme n Default
nt-n statement
Statement
-x
Next
19
statement
The else-if ladder
# include<stdio.h> else if(a%5 == 0)
int main( ) {
{ printf("Divisible by 5");
int a; }
printf("Enter a number..."); else
scanf("%d", &a); {
if(a%5 == 0 && a%8 == 0) printf("Divisible by none");
{ }
printf("Divisible by both 5 and 8"); return 0;
} }
else if(a%8 == 0)
{
printf("Divisible by 8");
}
20
Switch Statement
When one of the many alternatives is to be selected, we can use if statement to control the selection
The program becomes difficult to read and follow. At times, it may confuse the person who
designed it.
The switch statement tests the value of the given variable(expression) against a list of case values and
when a match is found, a block of statements associated with that case is executed.
21
Switch Statement
switch(expression)
{
case value-1:
block-1
break;
case value-2:
block-2
break;
…..
…..
default:
default-block
break;
}
statement-x;
22
Switch Statement
Value-1, value-2 are constants or constant expressions and are known as case labels. Each of these
values should be unique within a switch statement.
Block-1, block-2 ….are statement lists and may contain zero or more statement. There is no
need to put braces around these blocks. Case labels end with a colon (:)
Switch executed, value of expression is successfully compared against the values. If a case is
found whose value matches with the value of the expression, then the block statement that
follows the case will be executed.
The break statement at the end of each block signals the end of a particular case and causes an
exit from the switch statement, transferring the control to the statement-x following the
switch.
The default is an optional case. When present, it will be executed if the value of the expression does
not match with any of the case [Link] not present, it will directly go to the statement-x.
23
Switch Statement
switch
expression
Expression= value-1
block 1
block 2
Expression= value-2
default block
(no match) default
statement -x
24
Switch Statement
case 2:
#include <stdio.h> result = num1 - num2;
int main() { printf("Result = %d\n", result);
int num1, num2, choice; break;
int result;
case 3:
printf("Enter two numbers: "); result = num1 * num2;
scanf("%d %d", &num1, &num2); printf("Result = %d\n", result);
break;
printf("\nChoose an operation:\n");
printf("1. Addition\n"); case 4:
printf("2. Subtraction\n"); if(num2 != 0) {
printf("3. Multiplication\n"); result = num1 / num2;
printf("4. Division\n"); printf("Result = %d\n", result);
printf("Enter your choice (1-4): "); } else {
scanf("%d", &choice); printf("Error! Division by zero is not allowed.\n");
}
switch(choice) { break;
case 1:
result = num1 + num2; default:
printf("Result = %d\n", result); printf("Invalid choice!\n");
break; }
return 0;
} 25
Switch Statement
Case labels must be unique. No two labels can have the same value
The break statement transfers the control out of the switch statement
26
Switch Statement
The break statement is optional. That is, two or more case labels may
belong to the same statements.
The default may be placed anywhere but usually placed at the end
27
Advantages of Switch Statement
Easy to debug
28
Difference between if and switch Statement
If switch
Can evaluate the float condition, relational Cannot evaluate float, relational operators but
operators can evaluate only integer.
Program Control statements
29
goto statement
C supports the goto statement to branch unconditionally from one point to another in the
program.
The goto requires a label in order to identify the place where the branch is to be made.
The label is placed immediately before the statement where the control is to be
transferred.
The label: can be anywhere in the program either before or after the goto label; statement.
30
goto statement
goto breaks the normal sequential execution of the program. If the label: is before the
statement goto label; a loop will be formed and some statements will be executed
repeatedly, such jump is known as a backward jump.
On the other hand, if the label: is placed after the goto label; some statements will be
skipped and the jump is known as a forward jump. A goto is often used at the end of a program
to direct the control to go to the input statement, to read further data.
31
goto Statement
#include <stdio.h>
int main()
{
int num;
printf("Enter a number: ");
scanf("%d", &num);
OUTPUT
if (num % 2 == 0) Enter a number: 4
goto even; 4 is an Even number
else
goto odd;
even:
printf("%d is an Even number.\n", num);
goto end;
odd:
printf("%d is an Odd number.\n", num);
goto end;
end:
return 0;
32
}
break Statement
The syntax is :
break;
The break statement is almost always used with switch statement and if….else
statement inside the loop
33
break Statement
34
break Statement
#include <stdio.h>
int main()
{
int i;
35
continue Statement
The continue statement skips the current iteration of the loop and continues
with the next iteration
The syntax is
continue;
The continue statement is almost always used with the if...else statement
36
continue Statement
37
continue Statement
#include <stdio.h>
int main()
{ OUTPUT
int i; Numbers from 1 to 10 except 5:
printf("Numbers from 1 to 10 except 5:\n"); 1
2
for(i = 1; i <= 10; i++) { 3
4
if(i == 5) {
6
continue; // Skip the rest of the loop when i = 5 7
} 8
printf("%d\n", i); 9
} 10
return 0;
}
38
continue Statement
#include <stdio.h>
int main()
{
int i, num;
int sum = 0;
OUTPUT
printf("Enter up to 10 numbers (negative numbers will be skipped):\n"); Enter up to 10 numbers (negative numbers
for(i = 1; i <= 10; i++) will be skipped):
{ Enter number 1: 5
printf("Enter number %d: ", i); Enter number 2: -3
scanf("%d", &num);
if(num < 0)
Negative number skipped.
{ Enter number 3: 10
printf("Negative number skipped.\n"); Enter number 4: 4
continue; // Skip adding negative numbers Enter number 5: -2
} Negative number skipped.
sum = sum + num; // sum+=num;
}
Enter number 6: 1
Enter number 7: 2
printf("\n Sum of positive numbers = %d\n", sum); Enter number 8: 3
Enter number 9: 0
return 0; Enter number 10: 6
}
Sum of positive numbers = 31
39
Looping Statement
In looping, a sequence of statements are executed until some conditions for termination
of the loop are satisfied.
A program loop therefore consists of two segments, one known as the body of the
loop and the other known as the control statement.
The control statement tests certain conditions and then directs the repeated
execution of the statements contained in the body of the loop
Depending upon the position of the control statement in the loop, a control structure
may be classified either as the entry-controlled or exit controlled loop.
40
Types of Looping Statement
41
Looping Process
42
Types of Looping Statement
The test may be either to determine whether the loop has been repeated the
specified number of times or to determine whether a particular condition has
been met.
43
While loop Statement
The while loop provides a mechanism to repeat one or more statements
while a particular condition is true.
After execution of the body, the test condition is once again evaluated
and if it is true, the body is executed once again.
This process of repeated execution of the body continues until the test
condition finally becomes false and the controlled is transferred out of
the loop.
On exit, the program continues with the statement immediately after the
body of the loop.
44
while loop Statement
• The loop variable is initialized
with some value and then it has
been tested for the condition.
• If the condition returns true
then the statements inside the
body of the while loop are
executed else control comes out
of the loop.
• The value of the loop variable is
incremented/decremented then
it has been tested again for the
loop condition.
45
while loop Statement
Statement-X
46
while loop Statement
#include <stdio.h>
int main()
{
int start, end;
printf("Enter the starting number: ");
scanf("%d", &start);
printf("Enter the ending number: "); OUTPUT
scanf("%d", &end); Enter the starting number: 3
printf("\n Even numbers from %d to %d are:\n", start, end); Enter the ending number: 12
while(start <= end)
{ Even numbers from 3 to 12 are:
if(start % 2 != 0) 4
{ 6
start++; // Move to next number 8
continue; // Skip odd numbers 10
} 12
printf("%d\n", start);
start++;
}
return 0;
} 47
while loop Statement
#include <stdio.h>
int main()
{
int n, i = 1;
long long fact = 1;
while(i <= n)
{ OUTPUT
fact = fact * i; Enter a number: 5
i++; Factorial of 5 = 120
}
return 0;
}
48
while loop Statement
#include <stdio.h>
int main()
{
int num, temp, remainder, reverse = 0;
while(num != 0) {
remainder = num % 10; // get last digit
reverse = reverse * 10 + remainder; // make the reverse number
num = num / 10; // remove last digit
}
if(temp == reverse)
printf("%d is a palindrome number.\n", temp);
else
printf("%d is not a palindrome number.\n", temp);
return 0;
} 49
while loop Statement
remainder = num %
Iter num (start) reversedNum (after) num (after)
10
1 121 1 0 * 10 + 1 = 1 121 / 10 = 12
2 12 2 1 * 10 + 2 = 12 12 / 10 = 1
3 1 1 12 * 10 + 1 = 121 1 / 10 = 0
OUTPUT
Enter a number: 121
121 is a palindrome number.
50
while loop Statement
// Step 2: Calculate sum of each digit raised to the power
#include <stdio.h>
n
#include <math.h> // for using pow()
function while (temp != 0)
{
int main() remainder = temp % 10;
{ result += pow(remainder, n);
int num, temp, remainder, n = 0; temp = temp / 10;
double result = 0.0; }
In do-while loop, the test condition is evaluated at the end of the loop
The body of the loop gets executed at least one time(even if the condition is false)
There is no choice whether to execute the loop or not because the loop will be executed at
least once irrespective of whether the condition is true or false. Hence, the entry in the loop
is automatic
52
do-while loop Statement
The do-while loop is an indefinite loop as loop can execute until the user
wants to stop.
Major disadvantage is executes at least once, even if the user enters some invalid
data.
53
do-while loop Statement
Syntax
statement x;
do
{
statement block;
}
while (condition);
statement- y;
54
do-while loop Statement
#include <stdio.h>
int main()
{
int i = 1; OUTPUT:
do 1
2
{ 3
printf("\n %d", i); 4
5
i=i+1; 6
} 7
while (i<=10); 8
9
return 0; 10
}
55
do-while loop Statement
#include <stdio.h>
int main()
{
int i = 1, limit;
printf("Enter the limit: ");
scanf("%d", &limit);
printf("Even numbers from 1 to %d are:\n", limit);
do
{ OUTPUT
if (i % 2 == 0) Enter the limit: 10
printf("%d ", i); Even numbers from 1 to 10 are:
i++; 2 4 6 8 10
}
while (i <= limit);
return 0;
}
56
do-while loop Statement
#include <stdio.h> do
int main() {
fact = fact * i;
{
i++;
int n, i = 1; }
long long fact = 1; while (i <= n);
printf("Enter a number: "); printf("Factorial of %d = %lld\n", n, fact);
scanf("%d", &n); }
if (n < 0)
return 0;
{ }
printf("Factorial is not defined
for negative numbers.\n");
}
else OUTPUT
{ Enter a number: 5
Factorial of 5 = 120
57
for loop Statement
The for loop provides a mechanism to repeat a task until a particular condition is true.
For loop is usually known as a determinate or definite loop because the programmer knows
exactly how many times the loop will repeat.
The number of times the loop has to be executed can be determined mathematically by
checking the logic of the loop.
Every section of the for loop is separated from the other with a semicolon.
It is possible that one of the sections may be empty, though the semicolons still have to be there
58
for loop Statement
However, if the condition is empty, it is evaluated as true and the loop will repeat
until something else stops it.
In a for loop, condition is tested before the statements contained in the body
are executed.
If condition does not hold true, then the body of the for loop is not executed.
59
for loop Statement
statement y;
Update the loop variable
Statement y
60
for loop Statement
#include <stdio.h>
int main()
{
int n, i;
printf("Enter the limit (n): ");
OUTPUT
scanf("%d", &n); Enter the limit (n): 10
printf("Numbers from 1 to %d are:\n", n); Numbers from 1 to 10 are:
for(i = 1; i <= n; i++) 1 2 3 4 5 6 7 8 9 10
{
printf("%d ", i);
}
return 0;
}
61
for loop Statement
62
for loop Statement
#include <stdio.h>
int main()
{
int n, i;
float mark, sum = 0, average;
printf("Enter the number of students: ");
scanf("%d", &n); OUTPUT
for(i = 1; i <= n; i++) Enter the number of students: 3
{ Enter mark of student 1: 85
printf("Enter mark of student %d: ", i); Enter mark of student 2: 90
scanf("%f", &mark); Enter mark of student 3: 80
sum = sum + mark;
} Total Marks = 255.00
average = sum / n; Average Marks = 85.00
printf("\nTotal Marks = %.2f\n", sum);
printf("Average Marks = %.2f\n", average);
return 0;
}
63
Nested for loop Statement
64
Nested for loop Statement
#include <stdio.h>
int main()
{ OUTPUT
int i, j, rows; *
printf("Enter number of rows: "); **
scanf("%d", &rows); ***
for(i = 1; i <= rows; i++) { // Outer loop → rows ****
for(j = 1; j <= i; j++) { // Inner loop → stars in each row *****
printf("* ");
}
printf("\n"); // Move to next line
}
return 0;
}
65