0% found this document useful (0 votes)
5 views65 pages

Module 3 FCP

The document outlines control statements in C programming, detailing various types including declaration, expression, null, labeled, and flow control statements. It explains decision-making constructs such as if, if-else, nested if, switch, and goto statements, emphasizing their roles in controlling program execution flow. Additionally, it compares the advantages of switch statements over if-else statements and provides code examples for better understanding.

Uploaded by

crazychan1407
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views65 pages

Module 3 FCP

The document outlines control statements in C programming, detailing various types including declaration, expression, null, labeled, and flow control statements. It explains decision-making constructs such as if, if-else, nested if, switch, and goto statements, emphasizing their roles in controlling program execution flow. Additionally, it compares the advantages of switch statements over if-else statements and provides code examples for better understanding.

Uploaded by

crazychan1407
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

23CH112 -Fundamentals of

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

Non-executable statements Executable statements

Represents the instructions to be performed


Tell the compiler to build the program
during the execution of the 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

Expression statement Performs an action (calculation, a=a+ 10;


function, call) printf(“ Hello”);

Null statement just a ; does nothing , often used as a while (i<10); // loop with
placeholder empty body

Labeled statements Labels used along with goto and switch


case. Three kinds of label
Identifier label statement A user defined label followed by a colon lab: printf(“C Lab”);
Case label statement Used inside switch for specific choices case 1: printf(“Choice 1”);
Default label statement Used in switch when no case matches default: printf(“Choice n”);

3
Statements in C

Name of the statement Definition Example


Flow control statements Control the execution flow of the
program
Branching (selection statement) if, if-else, nested if, switch if(x>0)
printf(“Positive”);
else
printf(“ Negative”);
Iteration (Looping statement) for, while, do-while for(int i=0; i< 5; i++)
printf(“%d\n”,i);
Jump statements break, continue, goto, return For (int i=0 ;i<5 ; i++)
{
if (i==3) break; // exit loop
printf(“%d\n”,i);

4
Decision making and Branching
C program is a set of statements which are normally executed sequentially in the order in which they
appear.

This happens when no options or no repetitions of certain calculations are necessary.

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

Conditional type Unconditional type do-


for while
while
if if-else if-else-if switch break continue goto

6
Decision making with if statement
A powerful decision making statement and is used to control the flow of execution of statements.

It is basically a two-way decision statement and is used in conjunction with an expression.

It takes the following form if (test expression)

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

test expression False


?

True

8
Simple if statement

The general form of a simple if statement is Entry


if (test expression)
{
test
statement –block;
expression
} ?
statement –x; True

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

• Otherwise, the false statement block will be executed. In


either case, either true block or false block will be Statement-X
executed not both. In both the case control is transferred
to statement-x subsequently.
12
if…else statement
#include<stdio.h>
int main()
{
char ch;
printf(“\n Enter any character:”);
scanf(“%c”,&ch);
if (ch ==„a‟||ch == „e‟ ||ch == „i‟ ||ch == „o‟ ||ch == „u‟ || ch ==„A‟ || ch ==„E‟ || ch ==
„I‟ ||ch ==„O‟ ||ch == „U‟)
{
printf(“\n %c is a vowel”, ch);
}
else
{ OUTPUT
printf(“\n %c is not a vowel”, ch); Enter any character: v
} v is not a vowel
return 0;
}
== comparison operator to be used not the = assignment operator
13
Nested if…else..if statement
Entry
test
• When a series of decisions are involved, we conditi
have to use more than one if..else statement in False
nested form. on 1?
True
test
conditi
• Condition-1 is false, statement 3 will be on 2?
executed; otherwise it continues to perform False True
the second test.
Statement-3 Statement-2 Statement-1

• If the condition-2 is true, the statement 1 will


be executed. Otherwise the statement -2 will
be evaluated and then the control is
transferred to the statement-x
Statement-x

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

However, complexity of such program dramatically increases as number of alternatives increases.

The program becomes difficult to read and follow. At times, it may confuse the person who
designed it.

C has built-in multi-way decision statement known as a switch statement.

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

The switch expression must be an integer type

Case labels must be constants or constant expressions

Case labels must be unique. No two labels can have the same value

Case labels must end with colon

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 label is optional. If present, it will be executed when the


expression does not find a matching case label.

There can be at most one default label.

The default may be placed anywhere but usually placed at the end

It is permitted to nest switch statements.

27
Advantages of Switch Statement

Easy to debug

Easy to read and understand

Ease of maintenance as compared with its equivalent if-else statements

Like if-else statements, switch statements can also be nested

Executes faster than its equivalent if-else construct

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.

A label is any valid variable name, and must be followed by a colon.

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

Break statement ends the loop immediately when it is encountered.

The syntax is :
break;

The break statement is almost always used with switch statement and if….else
statement inside the loop

When a break statement is encountered inside a block or loop, control


automatically passes to the first statement after the loop or block

33
break Statement

34
break Statement

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

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


{ 1
if (i == 5) 2
break; // exit the loop when i equals 5 3
printf("%d\n", i); 4
} Loop stopped when i = 5

printf("Loop stopped when i = %d\n", i);


return 0;
}

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

Setting and initialization of a condition variable

Execution of the statements in the loop

Test for a specified value of the condition variable for


execution of the loop

Incrementing or updating the condition variable

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.

An entry-controlled loop statement. The test-condition is evaluated


and if the condition is true, then the body of the loop is executed.

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

Syntax for while loop


statement x; Update the condition
expression
while (condition)
{ Condition

statement block; Statement block


TRUE
FALSE
}
Statement-Y
statement y;

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;

printf("Enter a number: ");


scanf("%d", &n);

while(i <= n)
{ OUTPUT
fact = fact * i; Enter a number: 5
i++; Factorial of 5 = 120
}

printf("Factorial of %d = %lld\n", n, fact);

return 0;
}

48
while loop Statement
#include <stdio.h>
int main()
{
int num, temp, remainder, reverse = 0;

printf("Enter a number: ");


scanf("%d", &num);

temp = num; // store the original number

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.

Enter a number: 123


123 is not 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; }

printf("Enter a number: "); // Step 3: Compare and print result


scanf("%d", &num); if ((int)result == num)
printf("%d is an Armstrong number.\n", num);
temp = num; else
printf("%d is not an Armstrong number.\n", num);
// Step 1: Count number of digits
while (temp != 0) return 0;
{ }
temp = temp / 10;
n++; OUTPUT
} Enter a number: 153
temp = num; // reset temp to original 153 is an Armstrong number.
number Enter a number: 123
123 is not an Armstrong number. 51
do-while loop Statement

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)

Test condition is enclosed in parentheses and followed by a semicolon. The statements in


the statement block are enclosed within curly brackets.

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

There is only one choice: to continue or to exit.

The do-while loop is an indefinite loop as loop can execute until the user
wants to stop.

It is known as bottom-checking loop, since the control expression is placed


after the body of the loop.

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.

The for loop is widely used to execute a single or a group of statements a


limited number of times.

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

Syntax of for loop Initialization of loop


variable
for(initialization; condition;
increment/decrement/update) Controlling FALSE
{ condition for
loop variable
statement block;
} Statement block

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

#include <stdio.h> OUTPUT


Enter a number: 5
int main() Multiplication table of 5:
{ 5*1=5
int n, i; 5 * 2 = 10
printf("Enter a number: "); 5 * 3 = 15
5 * 4 = 20
scanf("%d", &n);
5 * 5 = 25
printf("Multiplication table of %d:\n", n); 5 * 6 = 30
for(i = 1; i <= 10; i++) 5 * 7 = 35
{ 5 *8 = 40
printf("%d x %d = %d\n", n, i, n * i); 5 * 9 = 45
5*10 = 50
}
return 0;
}

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

Syntax of nested for loop


for(initialization; condition;
increment/decrement/update)
{
for(initialization; condition;
increment/decrement/update)
{
statement block;
}
}
statement y;

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

You might also like