Module 2: Chapter 3 — Statements
True and False in C
- In C, conditional expressions decide what action a program should take.
- A condition can be either true or false.
- True: Any nonzero value (positive or negative).
- False: The value
0. - This rule makes C programs faster and more efficient.
💡 Key Concept
Conditional statements evaluate expressions that return true (non-zero) or false (zero). Based on this evaluation, different code paths are executed.
Example:
int main() {
if (5) printf("True! \n");
if (0) printf("False! \n");
if (-3) printf("Also True! \n");
return 0;
}
True!
Also True!
Selection Statements
Introduction to Decision Control / Branching Statements
- Selection or branching statements allow the program to transfer control from one part of the code to another.
- This transfer can happen with or without a condition.
- These statements help make decisions during program execution.
Types of Branching Statements
- Conditional Branch Statements
- Unconditional Branch Statements
(i) Conditional Branch Statements
These statements transfer control based on a specific condition. If the condition is true, one block executes; otherwise, another may.
- Simple if - One-way selection
- if-else - Two-way selection
- Nested if - Multi-way selection
- else-if ladder - Multi-way selection
- switch - Multi-way selection
(ii) Unconditional Branch Statements
These statements transfer control unconditionally, without checking any condition.
- goto - Jumps to a labeled statement
- break - Exits a loop or switch
- continue - Skips to the next iteration of a loop
- return - Exits a function and optionally returns a value
if Statement
- The if statement executes a block of code only when a condition evaluates to true (nonzero).
- If the condition is false (0), the if block is skipped.
- Only one of if or else executes, never both.
- Used for "one-way decision" or "single alternative" choices.
-
Syntax:
if (condition) {
// statements to execute if true
}
-
Rules:
- The condition must be enclosed in parentheses.
- Multiple statements must be enclosed in curly braces.
-
No semicolon is required after
if(semicolon creates a null statement).
(if flow chart)
Example 1: Voting Eligibility
int age;
printf("Enter the age:");
scanf("%d", &age);
if(age < = 18)
printf("The person is eligible to vote \n");
if(age < 18)
printf("The person is not eligible to vote \n");
}
Example 2: Check Even or Odd
void main() {
int n;
printf("Enter a number:");
scanf("%d", &n);
if(n % 2 = = 0)
printf("Number is even \n");
if(n % 2 ! = 0)
printf("Number is odd \n");
}
Example 3: Largest of Two Numbers
void main() {
int a, b;
printf("Enter two numbers:");
scanf("%d%d", &a, &b);
if(a > b)
printf("a is greater than b \n");
if(b > a)
printf("b is greater than a \n");
}
if-else Statement
- The if-else statement is used when there are two alternatives: one set of statements executes if the condition is true, and another set executes if it is false.
- Also called a "Two-way Decision or Selection Statement."
-
Working Principle:
- Test expression is evaluated first.
- If true → execute Statement block 1; skip Statement block 2.
- If false → execute Statement block 2; skip Statement block 1.
- After either block executes, control passes to the next statement in sequence.
-
Syntax:
if (condition) {
// Statements if true
} else {
// Statements if false
}
(if else flow chart)
Example 1: Voting Eligibility
void main() {
int age;
printf("Enter the age:");
scanf("%d", &age);
if(age >= 18)
printf("The person is eligible to vote \n");
else
printf("The person is not eligible to vote \n");
}
Example 2: Even or Odd
void main() {
int n;
printf("Enter a number:");
scanf("%d", &n);
if(n % 2 == 0)
printf("Number is even \n");
else
printf("Number is odd \n");
}
Example 3: Vowel or Consonant
void main() {
char ch;
printf("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("Character is a vowel \n");
else
printf("Character is a consonant \n");
}
Example 4: Leap Year Check
void main() {
int year;
printf("Enter any year:");
scanf("%d", &year);
if(((year % 4 == 0) && (year % 100 ! = 0)) || (year % 400 = = 0))
printf("%d is a leap year \n", year);
else
printf("%d is not a leap year \n", year);
}
Cascaded if-else (if-else-if) Statement
if-else ladder
- Also called if-else-if ladder or else-if staircase due to its appearance.
- Used when multiple conditions must be checked in sequence; executes the first true condition and bypasses the rest.
- If none of the conditions are true, the final else executes (if present); otherwise, no action occurs.
- Special case of nested-if where nesting occurs only in the else part.
- Known as a Multi-way Decision or Selection Statement, useful when actions depend on ranges of values.
-
Syntax
if (condition1)
statement1;
else if (condition2)
statement2;
else if (condition3)
statement3;
...
else
statementN;
(if-else-if-ladder flowchart)
Example: Grading System
void main() {
int marks;
printf("Enter marks: ");
scanf("%d", &marks);
if(marks >= 90)
printf("Grade: A \n");
else if(marks >= 75)
printf("Grade: B \n");
else if(marks >= 60)
printf("Grade: C \n");
else if(marks >= 50)
printf("Grade: D \n");
else
printf("Grade: F \n");
}
Switch Statement
- The switch statement is a multi-way decision statement used to select one alternative among many.
- Evaluates an expression and compares its value with multiple case values.
- Executes the statements corresponding to the first matching case.
- default case executes if no match is found; it is optional.
- break statement ends a case and exits the switch; prevents fall-through.
-
Syntax
switch (expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
(switch-case flowchart)
Important: The Break Statement
⚠️ Warning: Forgetting Break
If you forget the break statement, execution will "fall
through" to the next case, which is usually not desired!
Example 1: Display Grade
void main() {
char grade;
printf("Enter the grade: ");
scanf("%c", &grade);
switch(grade) {
case 'O': printf("Outstanding"); break;
case 'A': printf("Excellent"); break;
case 'B': printf("Good"); break;
case 'C': printf("Fair"); break;
case 'F': printf("Fail"); break;
default: printf("Invalid grade");
}
}
Example 2: Display Day of the Week
void main() {
int day;
printf("Enter any number (1-7): ");
scanf("%d", &day);
switch(day) {
case 1: printf("Sunday"); break;
case 2: printf("Monday"); break;
case 3: printf("Tuesday"); break;
case 4: printf("Wednesday"); break;
case 5: printf("Thursday"); break;
case 6: printf("Friday"); break;
case 7: printf("Saturday"); break;
default: printf("Invalid input");
}
}
When to Use Which Conditional Statement?
| Statement | Best Use Case | Advantages | Limitations |
|---|---|---|---|
| if | Single condition check | Simple, straightforward | Only handles true case |
| if-else | Two mutually exclusive paths | Handles both true and false cases | Only two choices |
| if-else ladder | Multiple conditions to check in order | Flexible, can handle ranges | Can be inefficient with many conditions |
| switch | Single variable with multiple constant values | Fast, clean, readable for many choices | Only works with integers/chars, constant cases |
Iterative Statements (Loops)
- Iterative statements, or loops, allow a set of statements to be executed repeatedly.
- Loops can run a specified number of times or until a certain condition is met.
- Also called looping constructs, repetitive statements, or loop control statements.
-
Common types of loops in C:
- for loop
- while loop
- do-while loop
for Loop (Counter-Controlled Loop)
- Executes a set of statements repeatedly for a specific number of times.
- Also called an entry-controlled loop or pretest loop.
-
Syntax:
for(initialization; test expression; increment/decrement) {
statement1;
statement2;
statement3;
}
statement x; -
Working Principle:
- Initialization: Set the starting value of loop variable.
- Test expression: Evaluated before each iteration; if true, loop executes, else control moves out.
- Increment/Decrement: Updates loop variable after each iteration.
-
Infinite Loop: Omitting the test expression creates
an infinite loop.
Example:for(i=0;;i++)
{
...
}
(flowchart-for-Loop-Flow-Diagram)
Examples:
-
Print natural numbers 1 to 10:
for(int i=1;i<=10;i++) {
printf("%d\n", i);
} -
Print numbers 1 to n:
int n; scanf("%d",&n);
for(int i=1;i<=n;i++) {
printf("%d\n", i);
}
-
Sum of 1+2+...+n:
int sum=0,n; scanf("%d",&n);
for(int i=1;i<=n;i++) {
sum+=i;
}
printf("Sum=%d", sum); -
Generate n Fibonacci numbers:
int f1=0,f2=1,f3,n,i;
scanf("%d",&n);
if(n==1)
printf("%d",f1);
else {
printf("%d %d ", f1,f2);
for(i=3;i<=n;i++) {
f3=f1+f2;
printf("%d ",f3);
f1=f2;
f2=f3;
}
} -
Print characters A to Z:
for(char ch='A';ch<='Z';ch++) {
printf("%c\t", ch);
}
-
Factorial of a number:
int fact=1,n; scanf("%d",&n);
for(int i=1;i<=n;i++) {
fact*=i;
}
printf("Factorial=%d", fact);
while Loop
- Executes a set of statements repeatedly as long as a specified condition is true.
- Condition is checked before entering the loop → called an Entry-Controlled Loop.
- If the condition is false initially, the loop body is skipped.
- Control moves to the statement immediately after the loop once the condition becomes false.
(while-Loop)
while Loop - Syntax
Statement(s);
}
Examples:
-
Print natural numbers from 1 to 10:
#include <stdio.h>
void main() {
int i=1;
while(i<=10) {
printf("%d\n", i);
i++;
}
} -
Print numbers from 1 to n:
int i=1, n;
printf("Enter n: ");
scanf("%d", &n);
while(i<=n) {
printf("%d\n", i); i++;
} -
Print numbers from n to 1:
int i=n;
while(i>=1) {
printf("%d\n", i);
i--;
}
-
Sum of first 10 natural numbers:
int i=1, sum=0;
while(i<=10) {
sum += i; i++;
}
printf("Sum=%d", sum);
-
Print characters from A to Z:
char ch='A';
while(ch<='Z') {
printf("%c\t", ch);
ch++;
} -
Factorial of a number:
int fact=1, i=1, n;
scanf("%d", &n);
while(i<=n) {
fact *= i;
i++;
}
printf("Factorial=%d", fact);
-
Check if a number is palindrome:
int num, n, rev=0, digit;
scanf("%d", &num);
n=num;
while(num! =0) {
digit=num%10;
rev=rev*10+digit;
num/=10;
}
printf("Reversed=%d", rev);
if(n==rev)
printf("Palindrome");
else
printf("Not Palindrome");
-
Find GCD and LCM of 2 numbers:
int a,b,m,n,gcd,lcm,rem;
scanf("%d %d", &a, &b);
m=a;
n=b;
while(n! =0) {
rem=m%n;
m=n;
n=rem;
}
gcd=m;
lcm=(a*b)/gcd;
printf("GCD=%d LCM=%d", gcd, lcm);
do-while Loop
- Executes a set of statements repeatedly at least once.
- The condition is tested after executing the loop body → called an Exit-Controlled Loop.
-
Unlike
forandwhileloops, which test the condition at the beginning, thedo-whileloop tests it at the end. - The loop continues as long as the test expression is true.
Syntax:
Statements;
} while (test expression);
Statement x;
Working Principle:
- The body of the loop executes once before checking the condition.
- After executing the body, the condition is evaluated to TRUE or FALSE.
- If TRUE → loop repeats; if FALSE → control exits to the statement after the loop.
(do-while-Loop)
(Flowchart-while-Loop)
Examples:
-
Print natural numbers from 1 to 10:
#include <stdio.h>
void main() {
int i = 1;
do {
printf("%d\n", i);
i++;
} while(i <= 10);
} -
Print natural numbers from 1 to n:
int i = 1, n;
printf("Enter n: ");
scanf("%d", &n);
do {
printf("%d\n", i);
i++;
} while(i <= n); -
Print numbers from n to 1:
int n, i;
printf("Enter n: ");
scanf("%d", &n);
i = n;
do {
printf("%d\n", i);
i--;
} while(i >= 1); -
Calculate sum of first 10 natural numbers:
int i = 1, sum = 0;
do {
sum += i;
i++;
} while(i <= 10);
printf("Sum = %d", sum); -
Find factorial of a given number:
int fact = 1, i = 1, n;
printf("Enter n: ");
scanf("%d", &n);
do {
fact *= i;
i++;
} while(i <= n);
printf("Factorial = %d", fact); -
Check if a number is palindrome:
int num, n, rev = 0, digit;
printf("Enter a number: ");
scanf("%d", &num);
n = num;
do {
digit = num % 10;
rev = rev * 10 + digit;
num /= 10;
} while(num != 0);
printf("Reversed = %d\n", rev);
if(n == rev)
printf("Palindrome");
else
printf("Not Palindrome");
Difference between while Loop and
do-while Loop
do {
Statements;
} while(test expression);
Statement x;
| Aspect | while Loop |
do-while Loop |
|---|---|---|
| 1. Type of Control | It is an entry-controlled loop (top-testing). | It is an exit-controlled loop (bottom-testing). |
| 2. Test Type | It is a pre-test loop (condition checked before executing). | It is a post-test loop (condition checked after executing). |
| 3. Syntax |
while(expression) {
Statements; } |
do {
Statements; } while(expression); |
| 4. Working Principle |
If the expression is true, the loop body
executes. If the expression is false, the body is skipped and control moves out of the loop. |
The body executes at least once, regardless of
the condition. After that, if the expression is true, it repeats; otherwise, it exits. |
| 5. Semicolon Usage |
The while statement does not end
with a semicolon (;).
|
The while statement in do-while
ends with a semicolon (;).
|
| 6. Example |
int i = 0, sum = 0;
while(i <= n) { sum = sum + i; i = i + 1; } |
int i = 0, sum = 0;
do { sum = sum + i; i = i + 1; } while(i <= n); |
Nested Loops
- A nested loop is a loop placed inside another loop.
-
It can be used with any looping construct —
while,do-while, orfor. -
Nested loops are most commonly used with the
forloop because it is easier to control. - The inner loop controls the number of times a specific set of statements are executed.
- The outer loop controls how many times the entire loop structure is repeated.
(Flow chart of nested for loop)
Example:
Write a C program to print the following pattern:
void main() {
int i, j;
for(i = 1; i <= 5; i++) {
for(j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
}
Output:
* *
* * *
* * * *
* * * * *
In the above example:
-
The outer loop (variable
i) controls the number of rows. -
The inner loop (variable
j) controls the number of columns (or stars printed per row). - Each time the outer loop runs once, the inner loop runs multiple times until its condition fails.
Unconditional Branch Statements: break
-
The break statement is used to terminate the
execution of the nearest enclosing loop or
switchstatement. - It is a jump statement that immediately transfers control to the statement following the loop or switch.
-
In a
switchstatement, break prevents execution of subsequent cases. -
In loops (
for,while,do-while), break exits the loop immediately, skipping remaining iterations.
(c-break-statement)
Syntax Examples:
-
While loop:
while(condition) {
if(condition) break;
...
}
// Control transfers out of the while loop -
Do-while loop:
do {
if(condition) break;
...
} while(condition);
// Control transfers out of the do-while loop -
For loop:
for(initialization; condition; increment) {
if(condition) break;
...
}
// Control transfers out of the for loop
Example Program:
Print numbers 0 to 4 using break:
void main() {
int i=0;
while(i <= 10) {
if(i==5) break;
printf("%d\n", i);
i=i+1;
}
}
Output:
1
2
3
4
Unconditional Branch Statements: continue
- The continue statement is used to skip the current iteration of a loop and continue with the next iteration.
-
It is used only inside loops (
for,while,do-while). - When continue is executed, the remaining statements in the loop body for that iteration are skipped.
(c-continue-statement)
Example Program:
Print numbers from 1 to 5, skipping 2:
void main() {
int i;
for(i=1; i<=5; i++) {
if(i==2) continue;
printf("%d ", i);
}
}
Output:
Unconditional Branch Statements: goto Statement
- The goto statement is a jump statement that transfers program control to a labeled statement unconditionally.
-
The specified label acts as a target and is identified by a valid
variable name followed by a colon (
:). - The goto statement can cause both forward and backward jumps in a program.
Syntax:
... statements ...
label:
... statements ...
(goto_statement)
Forward Jump: When control jumps to a label defined below the goto statement.
Backward Jump: When control jumps to a label defined above the goto statement.
Example Program:
Write a C program to calculate the sum of all numbers entered by the user.
void main() {
int n, i, sum = 0;
printf("Enter the number:\\n");
scanf("%d", &n);
sum = i = 0;
top: sum = sum + n;
i = i + 1;
if(i <= n) goto top;
printf("Sum of Series = %d", sum);
}
Expression Statements (skip)
-
An expression statement is simply a valid
expression followed by a semicolon (
;). -
Examples:
func();→ Function calla = b + c;→ Assignment statement-
b + f();→ A valid but unusual statement (functionf()is still evaluated) ;→ An empty or null statement
-
Even seemingly strange expressions (like
b + f();) are evaluated because the function might perform a useful action. -
Empty statements (
;) do nothing but are syntactically valid.
Example Statements:
a = b + c; /* assignment */
b + f(); /* valid but odd */
; /* null statement */
Block Statements (skip)
- Block statements (also called compound statements) are groups of related statements treated as a single unit.
-
A block starts with a left brace
{and ends with a matching right brace}. -
They are commonly used as multi-statement targets for control
structures like
if,for, andwhile. - Blocks can also appear anywhere a normal statement is valid — even as a free-standing block.
Example Program:
Demonstration of a free-standing block statement:
int main(void) {
int i;
{ /* a free-standing block statement */
i = 120;
printf("%d", i);
}
return 0;
}