Unit 2(Control Flow)
Simple sequential programs Conditional Statements (if, if-else, switch), Loops (for, while,
do-while) Break and Continue.
Control Flow :
Control flow statements manage the execution flow of the program. They are divided into
three categories: Selection statements, Loops, and Jump/Transfer statements.
Control Flow
Selection Iterative Jump/Transfer
Statements Statements(Loops)
Statements
If while break
If else for continue
Else if do while goto
ladder return
Nested if
switch
Selection Statements(Conditional Statements):
Selection statements allow the program to choose different paths of execution based on
conditions.
if statement The if statement tests a condition and executes a block of code if the condition is
true. Otherwise the block will be skipped
Syntax:
if (condition) {
// code to be executed if condition is true
}
Code:
#include <stdio.h>
int main() {
int num = 10;
if (num > 5) {
printf("The number is greater than 5\n");
}
printf(("Outside of if\n");
return 0;
}
if else statement:
The if-else statement executes one block of code if the condition is true, and another
block(else) if it is false.
Syntax:
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
Flowchart:
Code:
#include <stdio.h>
int main()
{
int num;
// Input from the user
printf("Enter an integer: ");
scanf("%d", &num);
// Check if the number is even or odd
if (num % 2 == 0)
{
printf("%d is even.\n", num);
}
else
{
printf("%d is odd.\n", num);
}
return 0;
}
Note : Please refer leap year or not program as well
else if ladder:
It is used in the scenario where there are multiple cases to be performed for different
conditions. In if-else-if ladder statement, if a condition is true then the statements defined in
the if block will be executed, otherwise if some other condition is true then the statements
defined in the else-if block will be executed, at the last if none of the condition is true then
the statements defined in the else block will be executed. There are multiple else-if blocks
possible.
Syntax:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if all conditions are false
}
Code:
#include <stdio.h>
int main() {
// Variable declaration
float telugu, hindi, english, maths, science, social, total, percentage;
char grade;
// Maximum total marks
float maxMarks = 600.0;
// Input marks for each subject
printf("Enter the marks obtained in Telugu: ");
scanf("%f", &telugu);
printf("Enter the marks obtained in Hindi: ");
scanf("%f", &hindi);
printf("Enter the marks obtained in English: ");
scanf("%f", &english);
printf("Enter the marks obtained in Maths: ");
scanf("%f", &maths);
printf("Enter the marks obtained in Science: ");
scanf("%f", &science);
printf("Enter the marks obtained in Social: ");
scanf("%f", &social);
// Calculate total marks obtained
total = telugu + hindi + english + maths + science + social;
// Calculate percentage
percentage = (total / maxMarks) * 100;
// Output total and percentage
printf("Total Marks Obtained: %.2f\n", total);
printf("Percentage: %.2f%%\n", percentage);
// Calculate grade using else-if ladder
if (percentage >= 90) {
grade = 'A';
} else if (percentage >= 80) {
grade = 'B';
} else if (percentage >= 70) {
grade = 'C';
} else if (percentage >= 60) {
grade = 'D';
} else if (percentage >= 50) {
grade = 'E';
} else {
grade = 'F'; // Fail
}
// Output the grade
printf("Grade: %c\n", grade);
return 0;
}
Switch Statement:
The switch statement in C is an alternate to if-else-if ladder statement which allows us to
execute multiple operations for the different possibles values of a single variable called
switch variable. Here, We can define various statements in the multiple cases for the different
values of a single variable.
Syntax:
switch(expression)
{
case value1: statement_1;
break;
case value2: statement_2;
break;
.
.
.
case value_n: statement_n;
break;
default: default_statement;
}
Code:
// C program to print the day using switch
#include <stdio.h>
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;
}
Note : Please write sample input and outputs for every program
fall-through in a switch statement occurs when the control flows from one case to the next
without hitting a break statement. This allows multiple cases to execute the same block of
code or to have consecutive cases without breaks.
Example:
#include <stdio.h>
int main() {
int day = 5;
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
printf("Weekday\n");
break;
case 6:
case 7:
printf("Weekend\n");
break;
default:
printf("Invalid day\n");
}
return 0;
}
Looping Statement/Iterative Statements:
Looping statements in C are used to execute a block of code repeatedly as long as a specified
condition is met. This repetition continues until the condition becomes false.
The three primary types of loops in C are:
1. while loop
2. do-while loop
3. for loop
While Loop:
The while loop is a Entry Controlled Loop/pre-condition loop that checks a condition
before executing the body of the loop. If the condition is true, the loop executes the code
block. The condition is checked again after the code block is executed, and the loop continues
until the condition becomes false.
Syntax:
initialization
while (condition) {
// Loop body
// Code to be executed as long as the condition is true
}
Code:
#include <stdio.h>
int main() {
int i = 1; // Initialization
// while loop to print numbers from 1 to 10
while (i <= 10) {
printf("%d ", i);
i++; // Increment the value of i
}
return 0;
}
#include <stdio.h>
int main() {
int n, i = 1;
unsigned long long int factorial = 1;
// Input a number
printf("Enter a positive integer: ");
scanf("%d", &n);
// while loop to calculate the factorial
while (i <= n) {
factorial *= i; // Multiply factorial by i
i++; // Increment i
}
// Output the factorial
printf("Factorial of %d = %llu\n", n, factorial);
return 0;
}
C Program to find the given number is prime or not by counting factors method.
#include<stdio.h>
int main()
{
int n,count=0,i=1;
printf("Enter a number:\n");
scanf("%d",&n);
while(i<=n)
{
if(n%i==0)
count++;
i++;
}
if(count==2)
printf("%d is prime number\n",n);
else
printf("%d is not a prime number\n",n);
return 0;
}
C Program to find the given number is prime or not using
#include<stdio.h>
int main()
{
int number,flag=1,i;
printf("Enter a number:\n");
scanf("%d",&number);
if(number<=1)
printf("%d is not a prime number",number);
else
{
i=2;
while(i<number)
{
if(number%i==0)
{
flag=0;
printf("%d is divisible by %d\n",number,i);
break;
}
i++;
}
if(flag==1)
printf("%d is prime number",number);
else
printf("%d is not a prime number",number);
}
}
Note: Please Practise following codes
Armstrong Number
Factorial
Palindrome Number or Not
For Loop:
The for loop in C Language provides a functionality/feature to repeat a set of statements a
defined number of times. The for loop is in itself a form of an entry-controlled loop.
Unlike the while loop and do…while loop, the for loop contains the initialization, condition,
and updating statements as part of its syntax. It is mainly used to traverse arrays, vectors, and
other data structures.
Syntax
for(initialization; check/test expression; updation)
{
// body consisting of multiple statements
}
Printing 1 to 10 numbers in c
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
printf("%d\n", i);
}
return 0;
}
Calculating sum of N Natural Numbers
#include <stdio.h>
int main() {
int n, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
sum += i; // sum = sum + i
}
printf("Sum of first %d natural numbers is: %d\n", n, sum);
return 0;
}
Factorial of a number using for loop
#include <stdio.h>
int main() {
int n;
unsigned long long factorial = 1;
printf("Enter a positive integer: ");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
factorial *= i; // factorial = factorial * i
}
printf("Factorial of %d is: %llu\n", n, factorial);
return 0;
}
Printing Multiplication Table
#include<stdio.h>
int main()
{
int n, m, i;
// Input values for 'n' and 'm'
printf("Enter n (number for the multiplication table):\n");
scanf("%d", &n);
printf("Enter m (limit of the multiplication table):\n");
scanf("%d", &m);
// Display the multiplication table
printf("The multiplication table is:\n");
// Loop to generate and print the table
for (i = 1; i <= m; i++) {
printf("%d * %d = %d\n", i, n, i * n);
}
return 0;
}
Palindrome of a number using for loop
#include <stdio.h>
int main() {
int num, reversed = 0, remainder, original;
// Input a number
printf("Enter an integer: ");
scanf("%d", &num);
original = num; // Store the original number
// For loop to reverse the number
for (; num != 0; num /= 10) {
remainder = num % 10;
reversed = reversed * 10 + remainder;
}
// Check if the original number is equal to its reversed version
if (original == reversed) {
printf("%d is a palindrome.\n", original);
} else {
printf("%d is not a palindrome.\n", original);
}
return 0;
}
Jump or Transfer Statements in C: or Loop Control Statements
Jump or transfer statements in C are used to alter the normal flow of program execution by
skipping or terminating certain parts of the code. The key jump statements are `break`,
`continue`, `return`, and `exit` and goto.
1. `break` Statement
The `break` statement is primarily used to:
- Exit loops (`for`, `while`, `do-while`) before the loop completes all iterations.
- Exit a `switch` statement once a matching case is found.
Example 1: Using `break` in a Loop
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Loop will terminate when i equals 5
}
printf("%d ", i);
}
return 0;
}
Output: 1 2 3 4
- The loop exits as soon as `i == 5`.
Example 2: Using break in a `switch` statement
#include <stdio.h>
int main() {
int choice = 2;
switch (choice) {
case 1:
printf("Case 1\n");
break;
case 2:
printf("Case 2\n");
break;
default:
printf("Default Case\n");
}
return 0;
}
Output: `Case 2`
- The `break` exits the `switch` after executing the case body, preventing fall-through to the
next case.
2. `continue` Statement
The `continue` statement skips the current iteration of the loop and moves to the next
iteration. Unlike `break`, it does not terminate the loop entirely.
Example: Using `continue` in a Loop
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip printing when i equals 3
}
printf("%d ", i);
}
return 0;
}
Output: `1 2 4 5`
- When `i == 3`, the `continue` statement skips the rest of the loop body for that iteration, and
the next iteration starts.
The `return` statement is used to:
- Exit a function and return control to the calling function.
- Optionally, return a value from a function (in functions with a non-`void` return type).
Example: Using `return` in a Function
#include <stdio.h>
// Function to add two numbers
int add(int a, int b) {
return a + b; // Returns the sum of a and b
}
int main() {
int sum = add(5, 3);
printf("Sum: %d\n", sum);
return 0;
}
Output: Sum: 8
The `return` statement in the `add` function returns the result of the addition.
4. exit() Function
The `exit()` function is used to terminate the program execution immediately. It is typically
used for error handling or when the program needs to terminate due to some condition.
Example: Using `exit()` in a Program
#include <stdio.h>
#include <stdlib.h> // Required for exit()
int main() {
int x = -1;
if (x < 0) {
printf("Error: Negative value. Exiting program.\n");
exit(1); // Exit the program with a non-zero status indicating an error
}
printf("This line will not be executed if exit is called.\n");
return 0;
}
Output: `Error: Negative value. Exiting program.`
- The `exit(1)` call immediately terminates the program, and the subsequent code is not
executed.
Goto:
The goto statement allows you to jump to a specific labeled point in the program.
Syntax:
goto label;
program:
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
goto end; // Jump to the 'end' label when i equals 3
}
printf("%d ", i);
}
end:
printf("Loop exited using goto.\n");
return 0;
}
#include <stdio.h>
int main() {
int num;
// Label to jump back if a negative number is entered
input:
printf("Enter a number: ");
scanf("%d", &num);
// Check if the number is negative
if (num < 0) {
printf("You entered a negative number.\n");
printf("Please enter a positive number.\n");
goto input; // Go back to the input label to ask for the number again
}
else {
// If the number is positive, check if it's even or odd
if (num % 2 == 0) {
printf("%d is positive and even.\n", num);
} else {
printf("%d is positive and odd.\n", num);
}
}
return 0;
}
Nested Loops
A nested loop in C refers to a loop inside another loop. The outer loop controls the number
of iterations of the inner loop. Each time the outer loop runs once, the inner loop runs its
entire cycle
for (initialization; condition; increment) {
for (initialization; condition; increment) {
// Inner loop statements
}
// Outer loop statements
}
Nested loops can be used with any loop type: for, while, or do-while.
Uses:
• The inner loop executes fully for each iteration of the outer loop.
• Nested loops are commonly used for matrix operations, patterns, and repetitive tasks.
#include <stdio.h>
int main() {
int rows = 5;
// Outer loop for each row
for (int i = 1; i <= rows; i++) {
// Inner loop for each column
for (int j = 1; j <= rows; j++) {
printf("* ");
}
printf("\n"); // Move to the next line after printing one row
}
return 0;
}
#include <stdio.h>
int main() {
int rows = 5;
// Outer loop for each row
for (int i = 1; i <= rows; i++) {
// Inner loop for printing stars in each row
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}
Print primes in certain range
Print primes In low and high interval
#include <stdio.h>
int main() {
int lower, upper,i,num;
// Input the interval
printf("Enter the lower bound: ");
scanf("%d", &lower);
printf("Enter the upper bound: ");
scanf("%d", &upper);
printf("Prime numbers between %d and %d are:\n", lower, upper);
for (num = lower; num <= upper; num++)
{
if (num <= 1) continue; // Skip 0 and 1
int isPrime = 1; // Assume num is prime
for (i = 2; i <= num/2; i++)
{
if (num % i == 0)
{
isPrime = 0; // Not a prime number
break; // No need to check further
}
}
if (isPrime) {
printf("%d ", num);
}
}
printf("\n");
return 0;
}