0% found this document useful (0 votes)
7 views

CTU 07103 Programming App & Info Sec - Session 3 - Control Flow

C programming

Uploaded by

Laurent Kalugula
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)
7 views

CTU 07103 Programming App & Info Sec - Session 3 - Control Flow

C programming

Uploaded by

Laurent Kalugula
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/ 22

CTU 07103 Programming App & Info Sec

Control Flow

program to swap two numbers using a temporary variable.


#include <stdio.h>

int main() {
int num1, num2, temp;

// Input two numbers


printf("Enter first number: ");
scanf("%d", &num1);

printf("Enter second number: ");


scanf("%d", &num2);

// Swap the numbers using a temporary variable


temp = num1;
num1 = num2;
num2 = temp;

// Output the swapped values


printf("After swapping: \n");
printf("First number: %d\n", num1);
printf("Second number: %d\n", num2);

return 0;
}

program to check if a number is positive using if.


#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;
}

Page |1 RAJIV KUMAR


CTU 07103 Programming App & Info Sec
Control Flow
program to find the grade of a student using if-else-if.
#include <stdio.h>
int main() {
int marks;
printf("Enter your marks: ");
scanf("%d", &marks);
if (marks >= 90) {
printf("Grade: A\n");
} else if (marks >= 75) {
printf("Grade: B\n");
} else if (marks >= 50) {
printf("Grade: C\n");
} else {
printf("Grade: F\n");
}
return 0;
}

program to check if a number is positive and divisible by 5 using


nested if.
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num > 0) {
if (num % 5 == 0) {
printf("The number is positive and divisible by 5.\n");
} else {
printf("The number is positive but not divisible by 5.\n");
}
} else {
printf("The number is not positive.\n");
}
return 0;
}

program to display the day of the week using switch.


#include <stdio.h>
int main() {
int day;
printf("Enter day number (1-7): ");
scanf("%d", &day);
switch (day) {

Page |2 RAJIV KUMAR


CTU 07103 Programming App & Info Sec
Control Flow
case 1: printf("Monday\n"); break;
case 2: printf("Tuesday\n"); break;
case 3: printf("Wednesday\n"); break;
case 4: printf("Thursday\n"); break;
case 5: printf("Friday\n"); break;
case 6: printf("Saturday\n"); break;
case 7: printf("Sunday\n"); break;
default: printf("Invalid input.\n");
}
return 0;
}

program with nested switch statements to handle a menu.


#include <stdio.h>
int main() {
int mainMenu, subMenu;
printf("1. Fruits\n2. Drinks\nEnter choice: ");
scanf("%d", &mainMenu);
switch (mainMenu) {
case 1:
printf("1. Apple\n2. Banana\nEnter choice: ");
scanf("%d", &subMenu);
switch (subMenu) {
case 1: printf("You selected Apple.\n"); break;
case 2: printf("You selected Banana.\n"); break;
default: printf("Invalid selection.\n");
}
break;
case 2:
printf("1. Water\n2. Juice\nEnter choice: ");
scanf("%d", &subMenu);
switch (subMenu) {
case 1: printf("You selected Water.\n"); break;
case 2: printf("You selected Juice.\n"); break;
default: printf("Invalid selection.\n");
}
break;
default: printf("Invalid main menu choice.\n");
}
return 0;
}

Page |3 RAJIV KUMAR


CTU 07103 Programming App & Info Sec
Control Flow
What happens if no break is used in a switch case
If no break is used, the program executes the code for the matched case and "falls through" to
subsequent cases until a break or the end of the switch statement is reached.

Write a program to print the sum of the first n natural numbers using a for loop.
#include <stdio.h>
int main() {
int n, sum = 0;
printf("Enter the value of n: ");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
sum += i;
}
printf("Sum of first %d natural numbers: %d\n", n, sum);
return 0;
}

program to find the largest of three numbers using nested if.


#include <stdio.h>
int main() {
int a, b, c;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);
if (a > b) {
if (a > c) {
printf("Largest number is: %d\n", a);
} else {
printf("Largest number is: %d\n", c);
}
} else {
if (b > c) {
printf("Largest number is: %d\n", b);
} else {
printf("Largest number is: %d\n", c);
}
}
return 0;
}

Page |4 RAJIV KUMAR


CTU 07103 Programming App & Info Sec
Control Flow
program to display the Fibonacci series up to n terms using a for loop.
#include <stdio.h>
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}

int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Factorial of %d is %d\n", num, factorial(num));
return 0;
}

infinite loop with example.


• An infinite loop is a loop that runs endlessly because its condition is always true. Example:

int main() {
while (1) {
printf("This is an infinite loop.\n");
}
return 0;
}

Page |5 RAJIV KUMAR


CTU 07103 Programming App & Info Sec
Control Flow

do-while loop differ from the while loop in C


• Difference: The primary difference between the do-while loop and the while loop is when the
condition is checked.
o while loop: The condition is checked before executing the loop body. If the condition is
false initially, the loop body will not execute even once.
o do-while loop: The condition is checked after executing the loop body. Therefore, the
loop body will always execute at least once, regardless of whether the condition is true
or false.
Example:
#include <stdio.h>

int main() {
int i = 5;

// while loop
while (i < 5) {
printf("This will not print because the condition is false.\n");
i++;
}

i = 5;
// do-while loop
do {
printf("This will print at least once.\n");
i++;
} while (i < 5);

return 0;
}

nested loop in C, and when is it used


• Definition: A nested loop is a loop inside another loop. In C, a for, while, or do-while loop can be
nested inside another loop. Nested loops are typically used when you need to perform
operations on multi-dimensional data structures like matrices, or when you need to perform
repetitive tasks that require multiple iterations.
Example:
#include <stdio.h>

int main() {
int i, j;

// Nested for loop to print a multiplication table


for (i = 1; i <= 3; i++) {
for (j = 1; j <= 3; j++) {

Page |6 RAJIV KUMAR


CTU 07103 Programming App & Info Sec
Control Flow
printf("%d\t", i * j);
}
printf("\n");
}

return 0;
}

loop control statements in C, and what are their purposes



Definition: Loop control statements in C are used to alter the flow of execution inside loops.
They allow you to skip certain iterations, terminate the loop early, or control the iteration step.
The three main loop control statements are:
1. break: Terminates the loop immediately and exits from it.
2. continue: Skips the remaining code in the current iteration and proceeds to the next
iteration of the loop.
3. goto: Unconditionally jumps to a specified label in the program (though generally
discouraged in structured programming).
Example of break and continue:
#include <stdio.h>

int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break; // Breaks the loop when i equals 3
}
printf("%d ", i);
}
printf("\n");

for (int i = 1; i <= 5; i++) {


if (i == 3) {
continue; // Skips the current iteration when i equals 3
}
printf("%d ", i);
}
return 0;
}

infinite loop in C and provide an example



Definition: An infinite loop in C is a loop that never terminates because its loop condition is
always true. These loops are often used in situations where a program is running continuously
(e.g., server applications), but they can also be a result of logical errors.
Example:
#include <stdio.h>

int main() {

Page |7 RAJIV KUMAR


CTU 07103 Programming App & Info Sec
Control Flow
while (1) {
printf("This is an infinite loop.\n");
}

return 0;
}

When would you use a break statement in a loop.


• Definition: The break statement is used to immediately exit a loop when a certain condition is
met. It is often used when you need to stop the loop early based on some condition, such as
when a target value is found or an error occurs.
Example:
#include <stdio.h>

int main() {
int target = 4;

// Loop to find a target value


for (int i = 1; i <= 10; i++) {
if (i == target) {
printf("Target %d found at index %d\n", target, i);
break; // Exit the loop when target is found
}
}

return 0;
}

purpose of the continue statement in a loop


• Purpose: The continue statement is used in loops to skip the rest of the code in the current
iteration and move directly to the next iteration of the loop. It is useful when you want to skip
certain conditions or computations without terminating the loop.
Example:
#include <stdio.h>

int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip the iteration when i is 3
}
printf("%d ", i);
}
return 0;
}

Page |8 RAJIV KUMAR


CTU 07103 Programming App & Info Sec
Control Flow

simple if construct checking if a number is positive in C.


Example:
#include <stdio.h>

int main() {
int number;

// Ask for user input


printf("Enter a number: ");
scanf("%d", &number);

// Check if the number is positive


if (number > 0) {
printf("The number is positive.\n");
}

return 0;
}

switch construct simplify complex conditional statements compared


to multiple if-else if statements
• Explanation: The switch construct simplifies complex conditional statements by providing a
more structured and efficient way to check multiple possible values of a variable. Instead of
writing multiple if-else if conditions, you can use a switch statement to match the variable to
different cases, making the code cleaner and more readable. It is also generally faster than
multiple if-else if chains for checking a single variable's value.
Example:
#include <stdio.h>

int main() {
int number;

printf("Enter a number between 1 and 3: ");


scanf("%d", &number);

// Using switch to check the number


switch (number) {
case 1:
printf("You entered one.\n");
break;
case 2:
printf("You entered two.\n");
break;
case 3:
printf("You entered three.\n");

Page |9 RAJIV KUMAR


CTU 07103 Programming App & Info Sec
Control Flow
break;
default:
printf("Invalid input.\n");
}

return 0;
}

example of a simple if construct checking if a number is positive in C.


Example
#include <stdio.h>

int main() {
int number;

// Ask for user input


printf("Enter a number: ");
scanf("%d", &number);

// Check if the number is positive


if (number > 0) {
printf("The number is positive.\n");
}

return 0;
}

implement a nested for loop to print a 3x3 grid of numbers


Example:
#include <stdio.h>

int main() {
// Nested for loop to print a 3x3 grid of numbers
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
printf("%d ", i * j); // Printing product of i and j
}
printf("\n");
}

return 0;
}

if-else construct can be used to check if a number is even or odd.

P a g e | 10 RAJIV KUMAR
CTU 07103 Programming App & Info Sec
Control Flow
• Explanation: The if-else construct can be used to check if a number is even or odd by dividing
the number by 2. If the remainder is 0, the number is even; otherwise, it is odd. The % (modulus)
operator is used to determine the remainder.
Example:
#include <stdio.h>

int main() {
int number;

// Ask the user to input a number


printf("Enter a number: ");
scanf("%d", &number);

// Check if the number is even or odd


if (number % 2 == 0) {
printf("The number is even.\n");
} else {
printf("The number is odd.\n");
}

return 0;
}

What happens if you forget to include a break statement in a switch


case
• Explanation: If you forget to include a break statement in a switch case, the program will "fall
through" to the next case. This means that the code for the next case will execute as well, even if
its condition doesn't match. This can lead to unexpected behavior unless intentionally done
(using fall-through logic).
Example:
#include <stdio.h>

int main() {
int number = 2;

switch (number) {
case 1:
printf("One\n");
case 2:
printf("Two\n");
case 3:
printf("Three\n");
default:
printf("Invalid number\n");
}

return 0;

P a g e | 11 RAJIV KUMAR
CTU 07103 Programming App & Info Sec
Control Flow
}

while loop to print numbers from 10 down to 1 in C


• Explanation: You can use a while loop to print numbers in descending order by starting from 10
and decrementing the counter after each iteration.
Example:
#include <stdio.h>

int main() {
int i = 10;

// While loop to print numbers from 10 to 1


while (i >= 1) {
printf("%d\n", i);
i--; // Decrement the value of i
}

return 0;
}

default case in a switch construct


• Explanation: The default case in a switch construct is used to handle situations where none of
the case labels match the value of the expression. It is optional but useful for handling
unexpected or invalid input. If no default case is provided and no case matches, the switch
statement does nothing.
Example:
#include <stdio.h>

int main() {
int number = 5;

switch (number) {
case 1:
printf("One\n");
break;
case 2:
printf("Two\n");
break;
default:
printf("Invalid number\n");
}

return 0;
}

P a g e | 12 RAJIV KUMAR
CTU 07103 Programming App & Info Sec
Control Flow

concept of a nested loop with an example.


• Explanation: A nested loop is a loop inside another loop. The outer loop executes its block of
code once, and for each iteration of the outer loop, the inner loop runs completely. Nested loops
are useful when working with multi-dimensional data structures like matrices or grids.
Example:
#include <stdio.h>

int main() {
// Nested for loop to print a 3x3 grid of numbers
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
printf("%d ", i * j); // Printing product of i and j
}
printf("\n"); // Move to the next line after each row
}

return 0;
}

purpose and usage of the else if construct in controlling program flow


with an example.
The else if construct in C is used to evaluate multiple conditions in a sequential manner. It allows a
program to check for various possibilities and execute specific blocks of code depending on which
condition evaluates to true. This construct improves code readability and efficiency, as it avoids writing
multiple independent if statements.
Purpose of else if:
1. To handle multiple conditions sequentially in a structured way.
2. To execute the appropriate block of code when a specific condition is met.
3. To ensure that once a condition evaluates to true, the remaining conditions are skipped,
optimizing execution time.
Usage:
The else if construct starts with an initial if condition, followed by one or more else if conditions, and
optionally ends with a default else block. If none of the conditions are true, the else block (if provided) is
executed.
Example Code:
#include <stdio.h>

int main() {
int score;

printf("Enter your score: ");


scanf("%d", &score);

P a g e | 13 RAJIV KUMAR
CTU 07103 Programming App & Info Sec
Control Flow
if (score >= 90) {
printf("Grade: A\n");
} else if (score >= 80) {
printf("Grade: B\n");
} else if (score >= 70) {
printf("Grade: C\n");
} else if (score >= 60) {
printf("Grade: D\n");
} else {
printf("Grade: F\n");
}

return 0;
}

nested if construct is beneficial with example


A nested if construct is beneficial when a decision-making process depends on multiple related
conditions that require hierarchical or dependent checks. It allows you to perform additional checks
within a broader condition.
Scenario:
Consider an application where you need to classify employees based on their department and
experience level. The first condition checks the department, and the second checks the experience level
within the department.
Example Code:
#include <stdio.h>

int main() {
char department;
int experience;

printf("Enter department (A/B): ");


scanf(" %c", &department);

if (department == 'A') {
printf("Enter years of experience: ");
scanf("%d", &experience);

if (experience >= 5) {
printf("You are a Senior in Department A.\n");
} else {
printf("You are a Junior in Department A.\n");
}
} else if (department == 'B') {
printf("Enter years of experience: ");
scanf("%d", &experience);

if (experience >= 3) {

P a g e | 14 RAJIV KUMAR
CTU 07103 Programming App & Info Sec
Control Flow
printf("You are a Senior in Department B.\n");
} else {
printf("You are a Junior in Department B.\n");
}
} else {
printf("Invalid department.\n");
}

return 0;
}

differences between while and do-while loops in C with examples


The while and do-while loops in C are both used for repetitive execution of a block of code, but they
differ in how they check the loop condition.
Key Differences:
Feature while Loop do-while Loop
Condition The condition is checked before executing The condition is checked after
Checking the loop body. executing the loop body.
Execution The loop body may not execute if the The loop body is guaranteed to execute
Guarantee condition is initially false. at least once.
Syntax while (condition) { ... } do { ... } while (condition);
Example Code for while:
#include <stdio.h>

int main() {
int counter = 0;

while (counter < 3) {


printf("This is iteration %d of the while loop.\n", counter + 1);
counter++;
}

return 0;
}

Example Code for do-while:


#include <stdio.h>

int main() {
int counter = 0;

do {
printf("This is iteration %d of the do-while loop.\n", counter + 1);
counter++;
} while (counter < 3);

P a g e | 15 RAJIV KUMAR
CTU 07103 Programming App & Info Sec
Control Flow
return 0;
}

loop control statements (break and continue) in C programming with


examples.
Loop control statements, such as break and continue, are used to alter the normal flow of execution in
loops. These statements make the program more flexible and allow fine-tuned control of loops.
1. break Statement:
The break statement is used to terminate the loop immediately when a certain condition is met. It is
typically used when further iterations are unnecessary.
Example of break:
#include <stdio.h>

int main() {
int i;
for (i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i equals 5
}
printf("%d ", i);
}
return 0;
}

2. continue Statement:
The continue statement skips the current iteration of the loop and moves to the next iteration. It is
useful when specific conditions require skipping parts of the loop body.
Example of continue:
#include <stdio.h>

int main() {
int i;
for (i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
printf("%d ", i);
}
return 0;
}

switch construct in C. Provide an example and describe when it is


more useful than if-else if.

P a g e | 16 RAJIV KUMAR
CTU 07103 Programming App & Info Sec
Control Flow
The switch construct in C is a decision-making control statement that allows a variable to be tested for
equality against a list of constants. It simplifies code by replacing multiple if-else if statements when
testing a single variable for multiple possible values.
Syntax of switch:
switch (expression) {
case constant1:
// Code block
break;
case constant2:
// Code block
break;
...
default:
// Default code block
}

Example Code:
#include <stdio.h>

int main() {
int day;

printf("Enter a number (1-7) for the day of the week: ");


scanf("%d", &day);

switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
case 6:
printf("Saturday\n");
break;
case 7:
printf("Sunday\n");
break;
default:

P a g e | 17 RAJIV KUMAR
CTU 07103 Programming App & Info Sec
Control Flow
printf("Invalid input!\n");
}

return 0;
}

When is switch More Useful?


1. Single Variable with Multiple Values: When testing the same variable for multiple constant
values, a switch is more readable and easier to maintain compared to multiple if-else if
statements.
2. Performance: The switch statement can be optimized by the compiler to use jump tables,
making it faster than if-else if for a large number of cases.

do-while loop used to ensure user input validation until correct input
is provided
The do-while loop is ideal for input validation because it ensures that the user is prompted at least once
and continues to prompt until valid input is provided.
Example Code:
#include <stdio.h>

int main() {
int number;

do {
printf("Enter a number between 1 and 10: ");
scanf("%d", &number);

if (number < 1 || number > 10) {


printf("Invalid input. Please try again.\n");
}
} while (number < 1 || number > 10);

printf("You entered a valid number: %d\n", number);

return 0;
}

for loop in C
The for loop in C is a control flow statement that is used for iterating over a sequence of values. It is
particularly useful when the number of iterations is known beforehand.
Syntax of for Loop:
for (initialization; condition; increment/decrement) {
// Code block to be executed

P a g e | 18 RAJIV KUMAR
CTU 07103 Programming App & Info Sec
Control Flow
}

Components:
1. Initialization: A variable is initialized before the loop starts. This is executed only once.
2. Condition: The loop runs as long as this condition is true. It is checked before every iteration.
3. Increment/Decrement: Updates the loop variable after each iteration.
Example Code:
#include <stdio.h>

int main() {
int i;

for (i = 1; i <= 5; i++) {


printf("Iteration %d\n", i);
}

return 0;
}

switch construct handles multiple case values leading to the same


outcome, with an example.
The switch construct in C can handle multiple case values leading to the same outcome by grouping case
labels together without providing separate break statements. This is particularly useful for scenarios
where the same logic applies to multiple cases.
Example Code:
#include <stdio.h>

int main() {
int grade;

printf("Enter your grade (1-5): ");


scanf("%d", &grade);

switch (grade) {
case 1:
case 2:
printf("Poor performance.\n");
break;
case 3:
printf("Average performance.\n");
break;
case 4:
case 5:
printf("Excellent performance.\n");
break;
default:

P a g e | 19 RAJIV KUMAR
CTU 07103 Programming App & Info Sec
Control Flow
printf("Invalid grade entered.\n");
}

return 0;
}

nested loops to print a multiplication table up to 10x10 in C, with an


example
Nested loops are useful for performing operations where one loop iterates through rows, and another
loop iterates through columns. This technique is ideal for printing a multiplication table.
Example Code:
#include <stdio.h>

int main() {
int i, j;

printf("Multiplication Table (10x10):\n");

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


for (j = 1; j <= 10; j++) {
printf("%4d", i * j); // Print product with spacing
}
printf("\n"); // Move to the next row
}

return 0;
}

loop control statements and their usage to manage loop execution,


Include break and continue statements in loop
Loop control statements manage the execution of loops by altering the normal flow. They make it
possible to:
1. Exit a loop prematurely (break).
2. Skip the remaining part of the current iteration and proceed to the next (continue).
1. break Statement:
The break statement terminates the loop and transfers control to the next statement after the loop.
Example of break:
#include <stdio.h>

int main() {
int i;
for (i = 1; i <= 10; i++) {
if (i == 5) {

P a g e | 20 RAJIV KUMAR
CTU 07103 Programming App & Info Sec
Control Flow
break; // Exit the loop when i equals 5
}
printf("%d ", i);
}
return 0;
}

2. continue Statement:
The continue statement skips the remaining part of the current iteration and moves to the next iteration.
Example of continue:
#include <stdio.h>

int main() {
int i;
for (i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
printf("%d ", i);
}
return 0;
}

infinite loop in C
An infinite loop is a loop that runs indefinitely because its terminating condition is never met. This can be
achieved using:
1. A while loop with a condition that always evaluates to true.
2. A for loop with no condition.
1. Using a while Loop:
#include <stdio.h>

int main() {
while (1) { // Condition is always true
printf("This is an infinite loop.\n");
}
return 0;
}

2. Using a for Loop:


c
Copy code
#include <stdio.h>

int main() {
for (;;) { // No initialization, condition, or increment

P a g e | 21 RAJIV KUMAR
CTU 07103 Programming App & Info Sec
Control Flow
printf("This is an infinite loop.\n");
}
return 0;
}

Example of Infinite Loop with break:


#include <stdio.h>

int main() {
int input;
while (1) {
printf("Enter a number (0 to exit): ");
scanf("%d", &input);

if (input == 0) {
break; // Exit loop when input is 0
}
printf("You entered: %d\n", input);
}
return 0;
}

P a g e | 22 RAJIV KUMAR

You might also like