0% found this document useful (0 votes)
23 views33 pages

Lecture 5 Control Statements

The document provides an overview of control statements in C programming, detailing simple and compound statements, flow control, and various types of selection and iteration constructs. It explains how to use if, if-else, switch statements, and demonstrates their application through example programs. Additionally, it covers the representation of true and false values, operator semantics, and nested if statements.
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)
23 views33 pages

Lecture 5 Control Statements

The document provides an overview of control statements in C programming, detailing simple and compound statements, flow control, and various types of selection and iteration constructs. It explains how to use if, if-else, switch statements, and demonstrates their application through example programs. Additionally, it covers the representation of true and false values, operator semantics, and nested if statements.
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
You are on page 1/ 33

Computer Programming

CSC01
B. Tech. (Semester I, Section: H )
2023-24 (Odd Semester)

Dr. Abhijit Sharma


Assistant Professor
Department of Computer Science & Engineering
NIT Durgapur
CSC01

Control Statements

CSC01: Control Statements


[email protected]
Statements
A statement is the smallest logical entity that can independently exist in
a C program.

Based upon the number of constituent statements, statements in C


language are classified as follows:

1. Simple statements
2. Compound statements

CSC01: Control Statements


[email protected]
Statements
1. Simple statements: A simple statement consists of a single statement.
It is terminated with a semicolon.
a. int variable=10; //definition statement
b. variable+5; //expression statement
c. variable=variable+10; //assignment statement

2. Compound statements: A compound statement consists of a sequence


of simple statements enclosed within a pair of braces.
{ // a compound statement consisting of three simple statements
int variable=10;
variable=variable*2;
variable+=5;
}

CSC01: Control Statements


[email protected]
Flow Control Statements
• The order in which the program statements are executed is known as
‘flow of program control’ or just ‘flow of control’.
• By default, the program control flows sequentially from top to bottom.
• Many practical situations like decision making, repetitive execution of a
certain task, etc. require deviation or alteration from the default flow of
program control.
• The default flow of control can be altered by using flow control
statements.

CSC01: Control Statements


[email protected]
Control Statements

• Control statements embody the decision logic that tells the executing
program what action to carry out next depending on the values of
certain variables or expression statements.

CSC01: Control Statements


[email protected]
Program Control Statements/Constructs in ‘C’

Program Control
Statements/Constructs

Selection/Branching Iteration/Looping

do-
for while
Conditional Type Unconditional Type while

if if-else if-else-if switch break continue goto

CSC01: Control Statements


[email protected]
Selection Statements

• A selection statement is a control statement that allows choosing


between two or more execution paths in a program.
• The selection statements in C are the if statement, the if-else statement,
and the switch statement.

CSC01: Control Statements


[email protected]
Specifying Test Condition
• If an expression, involving the relational operator, is true, it is given a value of 1. If
an expression is false, it is given a value of 0. Similarly, if a numeric expression is
used as a test expression, any non-zero value (including negative) will be
considered as true, while a zero value will be considered as false.
• Space can be given between operand and operator (relational or logical) but space is
not allowed between any compound operator like <=, >=, ==, !=. It is also compiler
error to reverse them.
• a == b and a = b are not similar, as == is a test for equality, a = b is an assignment
operator. Therefore, the equality operator has to be used carefully.
• The relational operators have lower precedence than all arithmetic operators.

CSC01: Control Statements


[email protected]
Operators
To Specify Symbol Used To Specify Symbol Used
less than <
Equal to ==
greater than >
Not equal to !=
less than or <=
equal to >= Logical AND &&
greater than or
equal to Logical OR ||

Negation !

CSC01: Control Statements


[email protected]
Operator Semantics
Operators Associativity
() ++ (postfix) -- (postfix) left to right
+ (unary) - (unary) right to left
++ (prefix) -- (prefix) * / % left to right
+- left to right
< <= > >= left to right
== != left to right
&& left to right
|| left to right
?: right to left
=+=-=*=/= right to left
, (comma operator) left to right

CSC01: Control Statements


[email protected]
Understanding How True and False is Represented in C

a = 1, b = 2, and c = 3 (a = 3)
(a < 2) (3 = a)
(a + 1 == b) (a - 1)
1==a (!(a))
a + b >=c (0 * c)
c <= (a + b) (c - a - b)
(a > 0) (c–2*–30)
(a) (0+b)
(–a) (c–a+b)
CSC01: Control Statements
[email protected]
Understanding How True and False is Represented in C

a=2, b=3 a=0, b=3;


r= a && b++; r= a && b++;
r=1, a=2, and b=4 r=0, a=0, and b=3

r = a || b++; r = a || b++;
r=1, a=2, and b=3 r=1, a=0, and b=4
CSC01: Control Statements
[email protected]
Selection Statements
• Selection is used to take a decision between one or two or more
alternatives.
• Decision in a program is concerned with choosing to execute one set
of statement over the others.
• Selection is also known as branching.

• When dealing with selection statements, there are generally three


versions: one-way, two-way, and multi-way.

CSC01: Control Statements


[email protected]
One-way decisions using if statement
Flowchart for if construct
if(TestExpr)
T F
stmtT; TestExpr

stmtT

CSC01: Control Statements


[email protected]
One-way decisions using if statement
Write a program that checks if a given number is positive and prints a
message if it is.

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

printf("Enter a number: ");


scanf("%d", &num);

if (num > 0) {
printf("The number is positive.\n");
}
return 0;
}
CSC01: Control Statements
[email protected]
One-way decisions using if statement
Write a program that determines whether a given year is a leap year
and prints a message if it is.

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

printf("Enter a year: ");


scanf("%d", &year);

if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {


printf("%d is a leap year.\n", year);
}
return 0;
}
CSC01: Control Statements
[email protected]
One-way decisions using if statement
Write a program that checks if a given number is even and prints a
message if it is.

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

printf("Enter a number: ");


scanf("%d", &num);

if (num % 2 == 0) {
printf("The number is even.\n");
}
return 0;
}
CSC01: Control Statements
[email protected]
Two-way decisions using if-else statement
The form of a two-way decision Flowchart of if-else construct
is as follows:

if(TestExpr)
stmtT;
else
stmtF;

CSC01: Control Statements


[email protected]
Two-way decisions using if-else statement
Write a program that compares two numbers and determines which one is greater.

#include <stdio.h>
int main() {
int num1, num2;

printf("Enter two numbers: ");


scanf("%d %d", &num1, &num2);

if (num1 > num2) {


printf("%d is greater than %d.\n", num1, num2);
} else {
printf("%d is greater than or equal to %d.\n", num2, num1);
}
return 0;
}
CSC01: Control Statements
[email protected]
Two-way decisions using if-else statement
Write a program that checks if a person is eligible to vote based on their age.

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

printf("Enter your age: ");


scanf("%d", &age);

if (age >= 18) {


printf("You are eligible to vote.\n");
} else {
printf("You are not eligible to vote.\n");
}
return 0;
} CSC01: Control Statements
[email protected]
Two-way decisions using if-else statement
Write a program that checks if a given number is even or odd.

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

printf("Enter a number: ");


scanf("%d", &num);

if (num % 2 == 0) {
printf("The number is even.\n");
} else {
printf("The number is odd.\n");
}
return 0;
} CSC01: Control Statements
[email protected]
Multi way Decisions
if(TestExpr1)
stmtT1;
else if(TestExpr2)
stmtT2;
else if(TestExpr3)
stmtT3;
.. .
else if(TestExprN)
stmtTN;
else
stmtF;

if-else-if ladder
CSC01: Control Statements
[email protected]
Multi way Decisions
Write a program that checks whether a number given by the user is zero,
positive, or negative.
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);

if (num > 0) {
printf("The number is positive.\n");
} else if (num < 0) {
printf("The number is negative.\n");
} else {
printf("The number is zero.\n");
}
return 0;
CSC01: Control Statements
} [email protected]
Multi way Decisions
Write a program that calculates and prints a student's grade based on
their exam score.
#include <stdio.h> } else if (score >= 70) {
printf("Grade: B\n");
int main() { } else if (score >= 60) {
int score; printf("Grade: C\n");
} else {
printf("Enter your exam score: "); printf("Grade: F\n");
scanf("%d", &score); }

if (score >= 90) { return 0;


printf("Grade: Ex\n"); }
} else if (score >= 80) {
printf("Grade: A\n");
CSC01: Control Statements
[email protected]
Nested if
Construct 1 Construct 2
When any if statement is written
under another if statement, this if(TestExprA) if(TestExprA)
cluster is called a nested if. if(TestExprB) if(TestExprB)
stmtBT; stmtBT;
else else
stmtBF; stmtBF;
else else
stmtAF; if(TestExprC)
stmtCT;
else
stmtCF;

CSC01: Control Statements


[email protected]
A program to find the largest among three numbers
#include <stdio.h>
int main()
{
int a, b, c;
printf(“\nEnter the three numbers”);
scanf(“%d %d %d”, &a, &b, &c);
if(a > b)
if(a > c)
printf(“%d”, a);
else
printf(“%d”, c);
else
if(b > c)
printf(“%d”, b);
else
printf(“%d”, c);
return 0;
}
CSC01: Control Statements
[email protected]
The Switch Statement
The general format of a switch statement is
switch(expr)
{
case constant1: stmtList1;
break;
case constant2: stmtList2;
break;
case constant3: stmtList3;
break;
………………………….
………………………….
default: stmtListn;
}
CSC01: Control Statements
[email protected]
▪ The switch statement enables you to choose one course of action from a set of
possible actions, based on the result of an integer expression.
▪ The case labels can be in any order and must be constants.
▪ No two case labels can have the same value.
▪ The default is optional and can be put anywhere in the switch construct.
▪ The case constants must be integer or character constants.
▪ The expression must evaluate to an integral type.
▪ The break statement is optional. If a break statement is omitted in any case of
a switch statement, the program flow is followed through the next case label.
▪ The case cannot exist by itself, outside of a switch.

CSC01: Control Statements


[email protected]
This program acts as a simple calculator that performs addition, subtraction,
multiplication, or division based on the user's choice.

#include <stdio.h> case '*':


result = num1 * num2;
int main() {
char operator; break;
double num1, num2, result; case '/':
if (num2 != 0) {
printf("Enter an operator (+, -, *, /): "); result = num1 / num2;
scanf(" %c", &operator); } else {
printf("Error: Division by zero!\n");
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2); return 1; // Exit with an error code
}
switch (operator) { break;
case '+': default:
result = num1 + num2; printf("Error: Invalid operator!\n");
break;
case '-': return 1; // Exit with an error code
result = num1 - num2; }
break; printf("Result: %.2lf\n", result);
return 0;
}
CSC01: Control Statements
[email protected]
This program takes an integer input (1-7) representing a day of the week and prints the
corresponding day's name.

#include <stdio.h> case 4:


int main() { printf("Wednesday\n");
int day; break;
printf("Enter a number (1-7) to represent a day of the week: "); case 5:
scanf("%d", &day); printf("Thursday\n");
switch (day) { break;
case 1: case 6:
printf("Sunday\n"); printf("Friday\n");
break; break;
case 2: case 7:
printf("Monday\n"); printf("Saturday\n");
break; break;
case 3: default:
printf("Tuesday\n"); printf("Invalid input! Please enter a number between 1 and
break; 7.\n");
}
return 0;
}
CSC01: Control Statements
[email protected]
This program takes a numeric grade and classifies it into a letter grade using a switch
statement.

#include <stdio.h> switch (grade) {


case 10:
case 9:
int main() {
printf("Grade: A\n");
int score; break;
case 8:
printf("Enter your exam score (0-100): ");
printf("Grade: B\n");
break;
scanf("%d", &score); case 7:
printf("Grade: C\n");
if (score < 0 || score > 100) { break;
case 6:
printf("Invalid input! Please enter a score between 0 and 100.\n");
printf("Grade: D\n");
return 1; // Exit with an error code break;
} default:
printf("Grade: F\n");
}
int grade = score / 10;

CSC01: Control Statements return 0;


[email protected] }
Switch Vs. Nested if

• The switch differs from the else-if in that switch can test only
for equality, whereas the if conditional expression can be of a
test expression involving any type of relational operators and/or
logical operators.

• A switch statement is usually more efficient than nested ifs.

• The switch statement can always be replaced with a series of


else-if statements.

CSC01: Control Statements


[email protected]

You might also like